/* net.c: networking module for the newsfetch program */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include <arpa/inet.h>

#include "newsfetch.h"

extern int h_errno;

#ifdef SUN
	void herror(char *error);
#endif

/* here we establish and handle the socket connection to the nntp server */
int connect_server(char *server_name, int port, int exit_flag)
{
	int s, one = 1;
	struct sockaddr_in sa;
	struct hostent *hp;
	struct in_addr saddr;

	/* if there is no server name specified at all */
	if (server_name == NULL) {
		if (exit_flag)
			return -1;
		else
			exit_now(-1);
	}

	/* if an address was used and it cannot be found */
	if (isdigit(*server_name)) {
		saddr.s_addr = inet_addr(server_name);
		if (saddr.s_addr > 0)
			hp = gethostbyaddr((char *) &saddr, 
				sizeof(struct in_addr), AF_INET);
		else
			hp = gethostbyname(server_name);

		if (hp == NULL) {
			herror("servername");
			if (exit_flag)
				return -1;
			else
				exit_now(-1);
		}

	/* if a name was used and was not found */
	} else if ((hp = gethostbyname(server_name)) == NULL) {
		herror("gethostbyname");
		if (exit_flag)
			return -1;
		else
			exit_now(-1);

	}


	/*fprintf(stderr, "Trying to connect %s...", server_name); */
	printf("Trying to connect %s...", server_name);
	fflush(stdout);
	/* a note, the bove 2 lines used to be fprintf and fflush(stderr)
	   this is another error i need to keep an eye out for */

	bcopy((char *) hp->h_addr, (char *) &sa.sin_addr, hp->h_length);
	sa.sin_family = hp->h_addrtype;
	sa.sin_port = htons(port);

	if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
		fprintf(stderr, "\n");
		perror("socket");
		if (exit_flag)
			return -1;
		else
			exit_now(-1);
	}
	if (connect(s, (struct sockaddr *) &sa, sizeof sa) < 0) {
		fprintf(stderr, "\n");
		perror("connect");
		if (exit_flag)
			return -1;
		else
			exit_now(-1);
	}
	fprintf(stderr, "connected\n");

	if ((setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(int))) < 0) {
		perror("error setting socket option");
	}
	fflush(stderr);
	return s;
}

/* hmmm - i think the name gives this away */
void create_fd(int socketid, FILE ** sfp)
{

	if ((sfp[0] = fdopen(socketid, "w")) == NULL) {
		perror("fdopen");
		close(socketid);
		exit_now(1);
	}
	if ((sfp[1] = fdopen(socketid, "r")) == NULL) {
		perror("fdopen");
		close(socketid);
		exit_now(1);
	}
}

/* not that i particularly give a crap about SUN, but i'll
   leave this in - it does not seem to be causing a problem */
#ifdef SUN
void herror(char *error)
{
	fprintf(stderr, "%s : error\n", error);
}
#endif



