#include "server.h" struct accept { int newfd; struct sockaddr_in sa; struct in_addr jabber_addr; unsigned short jabber_port; }; struct client { char * user; int client_fd, jabber_fd, keep_alive; time_t last_action; struct client * next, * previous; }; struct cat { int in_fd, out_fd, jabber, keep_alive; struct client * client; }; struct client * clients = (struct client *)NULL; pthread_mutex_t mutexsum; int main (int argc, char ** argv) { struct in_addr remote_addr, local_addr; unsigned short remote_port, local_port; int listen_fd; ParseArgs (argc, argv, &remote_addr, &remote_port, &local_addr, &local_port); Initialise (); // Create server socket before becoming a daemon so // there is still a chance to print an error message. listen_fd = CreateServerSocket (local_addr, local_port); if ( listen_fd < 0 ) pbomb ("Unable to create server socket"); //Daemonise (); MainLoop (listen_fd, remote_addr, remote_port); // never returns exit (EXIT_SUCCESS); } // ParseArgs() // Parse the command line arguments to extract the remote // and local adresses and port numbers, ra, rp, la & lp. // Exit the program gracefully upon error. void ParseArgs (int argc, char ** argv, struct in_addr * ra, unsigned short * rp, struct in_addr * la, unsigned short * lp) { // argv[0] = program name // argv[1] = remote_addr // argv[2] = remote_port // argv[3] = local_addr (optional) // argv[4] = local_port (optional) char * p = strrchr (argv[0], '/'); strncpy (g_program_name, (p == NULL) ? argv[0] : p + 1, sizeof (g_program_name) - 1); if ( (argc < 3) || (argc > 5) ) { fprintf (stderr, "usage: %s remote_addr remote_port [local_addr] [local_port]\n", argv[0]); exit (EXIT_FAILURE); } if ( NameToAddr (argv[1], ra) ) hbomb ("Unable to resolve \"%s\" to an ip address", argv[1]); if ( NameToPort (argv[2], rp, "tcp") ) quit ("Unable to resolve \"%s\" to a port number", argv[2]); if ( argc < 4 ) la->s_addr = htonl (INADDR_ANY); else if ( NameToAddr (argv[3], la) ) hbomb ("Unable to resolve \"%s\" to an ip address", argv[3]); if ( argc < 5 ) memcpy (lp, rp, sizeof (*lp)); else if ( NameToPort (argv[4], lp, "tcp") ) quit ("Unable to resolve \"%s\" to a port number", argv[4]); } // Initialise() // Setup syslog, signal handlers, and other intialisation. void Initialise (void) { openlog (g_program_name, LOG_PID, LOG_USER); syslog (LOG_INFO, "%s started", g_program_name); chdir ("/"); // Change working directory to the root. umask (0); // Clear our file mode creation mask set_signal_handler (SIGCHLD, sig_child); signal (SIGPIPE, SIG_IGN); } // sig_child() // Handles SIGCHLD from exiting child processes. void sig_child (int signo) { pid_t pid; (void) signo; // suppress compiler warning for ( ; ; ) { pid = waitpid (WAIT_ANY, NULL, WNOHANG); if ( pid > 0 ) syslog (LOG_INFO, "Caught SIGCHLD from pid %d", pid); else break; } if ( (pid < 0) && (errno != ECHILD) ) syslog (LOG_ERR, "waitpid(): %m"), exit (EXIT_FAILURE); return; } // CreateServerSocket() // Create a socket, bind it to the specified address // and port, and set it to listen for client connections. // Returns < 0 on failure to bind, bombs on error otherwise, // returns the fd of the new socket on success. int CreateServerSocket (struct in_addr addr, unsigned short port) { int err, fd; const int on = 1; struct sockaddr_in sa; // Create a socket and get its descriptor. fd = socket (AF_INET, SOCK_STREAM, 0); if ( fd < 0 ) syslog (LOG_ERR, "socket(): %m"), exit (EXIT_FAILURE); // Set SO_REUSEADDR socket option if ( setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0 ) syslog (LOG_ERR, "setsockopt(fd%d, SO_REUSEADDR): %m", fd); // Load a sa structure with the specified address and port sa.sin_family = AF_INET; sa.sin_port = htons (port); //sa.sin_addr = addr; sa.sin_addr.s_addr = htonl(INADDR_ANY); memset (sa.sin_zero, 0, sizeof (sa.sin_zero)); // Bind our socket to the address and port specified err = bind (fd, (struct sockaddr *) &sa, sizeof (sa)); if ( err < 0 ) { syslog (LOG_ERR, "bind(): %m"); return err; } // Tell socket to listen and queue up to 5 incoming connections. if ( listen (fd, 5) < 0 ) syslog (LOG_ERR, "listen(): %m"), exit (EXIT_FAILURE); return fd; } // MainLoop() // Classic concurrent server model. // Wait for a client to connect, fork a child process // to do the business with the client, parent process // continues to wait for the next connection. // This function does not return. void MainLoop (int listen_fd, struct in_addr rem_addr, unsigned short rem_port) { struct accept * accept; pthread_t accept_thread, clear_list_thread; pthread_mutex_init(&mutexsum, NULL); pthread_create(&clear_list_thread, NULL, (void *) &ClearList, (void *)NULL ); for ( ; ; ) { accept = AcceptClientConnection (listen_fd); accept->jabber_addr = rem_addr; accept->jabber_port = rem_port; pthread_create(&accept_thread, NULL, (void *) &VerifyClient, (void *) accept); } pthread_mutex_destroy(&mutexsum); pthread_exit(NULL); } void ClearList(void) { struct client * current, * previous = (struct client *)NULL; int last_action = (int)NULL; for ( ; ; ) { pthread_mutex_lock(&mutexsum); current = clients; while ( current != (struct client *)NULL ) { last_action = time(NULL) - current->last_action; if ( last_action > 10 ) { shutdown(current->client_fd, SHUT_RDWR); close(current->client_fd); current->client_fd = (int)NULL; } if ( last_action > 20 ) { shutdown(current->jabber_fd, SHUT_RDWR); close(current->jabber_fd); current->jabber_fd = (int)NULL; } if ( last_action > 30 ) { if ( current->previous == (struct client *)NULL ) { if ( current->next == (struct client *)NULL ) clients = (struct client *)NULL; else { clients = current->next; clients->previous = (struct client *)NULL; } } else if ( current->next != (struct client *)NULL ) { current->previous->next = current->next; current->next->previous = current->previous; } else current->previous->next = (struct client *)NULL; previous = current; current = current->next; free(previous); } else current = current->next; } pthread_mutex_unlock(&mutexsum); sleep(2); } } // AcceptClientConnection() // waits for a tcp connect to the socket listen_fd, which // must already be bound and set to listen on a local port. // Bombs on error, returns the fd of the new socket on success. struct accept * AcceptClientConnection (int listen_fd) { int newfd; struct sockaddr_in sa; socklen_t socklen; syslog (LOG_INFO, "AcceptClientConnection(fd%d)", listen_fd); // Accept the connection and create a new socket for it. socklen = sizeof (sa); memset (&sa, 0, socklen); do { newfd = accept (listen_fd, (struct sockaddr *) &sa, &socklen); } while ( (newfd < 0) && (errno == EINTR) ); syslog (LOG_INFO, "Accepted client connection on new socket fd%d", newfd); if ( newfd < 0 ) syslog (LOG_ERR, "accept(): %m"), exit (EXIT_FAILURE); if ( socklen != sizeof (sa) ) syslog (LOG_ERR, "accept() screwed up!"), exit (EXIT_FAILURE); struct accept * new_accept = (struct accept *) malloc(sizeof(struct accept)); new_accept->newfd = newfd; new_accept->sa = sa; return (new_accept); } void VerifyClient(void * accept) { int jabber_fd = (int)NULL; struct accept * client = (struct accept *) accept; struct client * user = (struct client *)NULL; struct cat * info_1, * info_2; pthread_t client_server_thread, server_client_thread; unsigned int addr = 0; char buf[250]; addr = ntohl(client->sa.sin_addr.s_addr); sprintf(buf,"%d.%d.%d.%d", (addr >> 24), (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF); //printf("New connection: %s\n", buf); //if ( strcmp(buf, "200.189.113.134") == 0 || strcmp(buf, "200.189.113.135") == 0 ) /*if ( strcmp(buf, "127.0.0.1") == 0 ) { user = Handshake(&client->newfd); jabber_fd = user->jabber_fd; }*/ if ( jabber_fd == (int)NULL ) { jabber_fd = ConnectToServer(client->jabber_addr, client->jabber_port); if ( user != (struct client *)NULL ) user->jabber_fd = jabber_fd; } info_1 = (struct cat *) malloc(sizeof(struct cat)); info_2 = (struct cat *) malloc(sizeof(struct cat)); info_1->out_fd = jabber_fd; info_1->in_fd = client->newfd; info_1->jabber = (int)NULL; info_1->keep_alive = (int)NULL; info_1->client = user; //pthread_create(&client_server_thread, NULL, (void *) &Cat, (void *)info_1 ); info_2->in_fd = jabber_fd; info_2->out_fd = client->newfd; info_2->jabber = jabber_fd; info_2->keep_alive = (int)NULL; if ( user != (struct client *)NULL ) info_2->keep_alive = 1; info_2->client = (struct client *)NULL; //pthread_create(&client_server_thread, NULL, (void *) &Cat, (void *)info_2 ); int pid; pid = fork(); if ( pid == 0 ) { int pid_helper; pid_helper = fork(); if ( pid_helper == 0 ) { Cat(info_1); exit(0); } else { Cat(info_2); wait(0); } } pthread_exit(0); } struct client * Handshake(int * newfd) { float is_new_client;// = (float) NULL; int bytes_rcvd, bytes_sent, i; unsigned char * const buf = (char *) malloc (sizeof(char) * 5); char * user = (char *) malloc(128 * sizeof(char)), * pass = (char *) malloc(128 * sizeof(char)); //struct client * clients = (struct client *)NULL; struct client * new_client = (struct client *)NULL; bzero(buf, 5); sprintf(buf, "user"); for ( i = 0; i < sizeof(buf); i += bytes_sent ) { bytes_sent = send (*newfd, buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } bzero(user, 128); if ( (bytes_rcvd = recv (*newfd, user, 128, 0)) < 1 ) pthread_exit(0); bzero(buf, 5); sprintf(buf, "pass"); for ( i = 0; i < sizeof(buf); i += bytes_sent ) { bytes_sent = send (*newfd, buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } bzero(pass, 128); if ( (bytes_rcvd = recv (*newfd, pass, 128, 0)) < 1 ) pthread_exit(0); pthread_mutex_lock (&mutexsum); if ( clients == (struct client *)NULL ) { clients = (struct client *) malloc(sizeof(struct client)); new_client = clients; new_client->previous = (struct client *)NULL; is_new_client = 1; } else { new_client = clients; while ( ((is_new_client = (float)strcmp(new_client->user, user)) != 0) && (new_client->next != (struct client *)NULL) ) new_client = new_client->next; if ( is_new_client != 0 ) { new_client->next = (struct client *) malloc(sizeof(struct client)); new_client->next->previous = new_client; new_client = new_client->next; } } if ( is_new_client != 0 ) { new_client->user = user; new_client->client_fd = (int)NULL; new_client->jabber_fd = (int)NULL; new_client->keep_alive = 1; new_client->next = (struct client *)NULL; } if ( is_new_client != 0 || new_client->jabber_fd == (int)NULL ) { bzero(buf, 5); sprintf(buf, "new"); for ( i = 0; i < sizeof(buf); i += bytes_sent ) { bytes_sent = send (*newfd, buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } } else { bzero(buf, 5); sprintf(buf, "rec"); for ( i = 0; i < sizeof(buf); i += bytes_sent ) { bytes_sent = send (*newfd, buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } } new_client->client_fd = *newfd; new_client->last_action = time(NULL); pthread_mutex_unlock(&mutexsum); return new_client; } // ConnectToServer() // attempts a tcp connect to the server specified // by addr and port. Bombs on failure to connect, // returns the fd of the new socket on success. int ConnectToServer (struct in_addr addr, unsigned short port) { // TODO: have a timeout for connect() - see Unix socket FAQ 6.2 int fd, err; struct sockaddr_in sa; // Create a socket and get its descriptor. fd = socket (AF_INET, SOCK_STREAM, 0); if ( fd < 0 ) syslog (LOG_ERR, "socket(): %m"), pthread_exit(0);//exit (EXIT_FAILURE); sa.sin_family = AF_INET; sa.sin_port = htons (port); sa.sin_addr = addr; memset (sa.sin_zero, 0, sizeof (sa.sin_zero)); err = connect (fd, (struct sockaddr *) &sa, sizeof (sa)); if (err < 0) { syslog (LOG_ERR, "Unable to connect socket fd%d to server: %m", fd); //exit (EXIT_FAILURE); pthread_exit(0); } syslog (LOG_INFO, "Connected socket fd%d to server", fd); return fd; } // Cat() // read data from in_fd and write it to out_fd until // the connection is closed by one of the peers. // Data is copied using a dynamically allocated buffer. //void Cat (int in_fd, int out_fd) //void Cat (int in_fd, int out_fd) void Cat (void * info) { unsigned char * const buf = (char *) malloc (sizeof(char) * BUF_SIZE); int bytes_rcvd, bytes_sent = (int) NULL, i, in_fd, out_fd; struct cat * user = (struct cat *) info; in_fd = user->in_fd; out_fd = user->out_fd; syslog (LOG_INFO, "Cat(fd%d, fd%d)", in_fd, out_fd); if ( buf == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); do { bzero(buf, BUF_SIZE); bytes_rcvd = recv (in_fd, buf, BUF_SIZE, 0); /* puts("\n"); puts(buf); puts("\n"); */ for ( i = 0; i < bytes_rcvd; i += bytes_sent ) { bytes_sent = send (out_fd, buf + i, bytes_rcvd - i, 0); if ( bytes_sent < 0 ) break; } } while ( (bytes_rcvd > 0) && (bytes_sent > 0) ); if ( (bytes_rcvd < 0) && (errno != ECONNRESET) ) syslog (LOG_ERR, "recv(): %m"), exit (EXIT_FAILURE); if ( (bytes_sent < 0) && (errno != EPIPE) ) syslog (LOG_ERR, "send(): %m"), exit (EXIT_FAILURE); if ( user->jabber && !user->keep_alive ) { shutdown(user->jabber, SHUT_RDWR); close(user->jabber); } pthread_exit(0); free (buf); } // NameToAddress() // Convert name to an ip address. // Returns 0 on success, -1 on failure. int NameToAddr (const char * name, struct in_addr * p_inaddr) { struct hostent * he; // First, attempt to convert from string ip format // TODO: use inet_aton() instead p_inaddr->s_addr = inet_addr (name); if ( p_inaddr->s_addr != -1U ) // Success return 0; // Next, attempt to read from /etc/hosts or do a DNS lookup he = gethostbyname (name); if ( he != NULL ) // Success { memcpy (p_inaddr, he->h_addr, sizeof (struct in_addr)); return 0; } return -1; // Failed to resolve name to an ip address } // NameToPort() // Convert name to a port number. Name can either be a port name // (in which case proto must also be set to either "tcp" or "udp") // or name can be the ascii representation of the port number. // Returns 0 on success, -1 on failure. int NameToPort (const char * name, unsigned short * port, const char * proto) { unsigned long lport; char * errpos; struct servent * se; // First, attempt to convert string to integer lport = strtoul (name, &errpos, 0); if ( (*errpos == 0) && (lport <= 65535) ) // Success { *port = lport; return 0; } // Next, attempt to read the string from /etc/services se = getservbyname (name, proto); if ( se != NULL) // Success { *port = ntohs (se->s_port); return 0; } return -1; // Failed to resolve port name to a number } // quit() // Print an error message to stderr // and syslog, then exit the program. void quit (const char * fmt, ...) // quit with msg { va_list ap; fflush (stdout); fprintf (stderr, "%s: ", g_program_name); va_start (ap, fmt); vfprintf (stderr, fmt, ap); va_end (ap); fputc ('\n', stderr); syslog (LOG_ERR, "I quit!"); exit (EXIT_FAILURE); } // pbomb() // Print an error message to stderr // and syslog, then exit the program. // pbomb() additionally include the // string representation of errno. void pbomb (const char * fmt, ...) // bomb with perror { va_list ap; int errno_save = errno; char buf[100]; fflush (stdout); fprintf (stderr, "%s: ", g_program_name); va_start (ap, fmt); vsnprintf (buf, sizeof (buf), fmt, ap); va_end (ap); errno = errno_save; perror (buf); syslog (LOG_ERR, "Bang!: %s: %m", buf); exit (EXIT_FAILURE); } // hbomb() // Print an error message to stderr // and syslog, then exit the program. // hbomb() additionally include the // string representation of h_errno. void hbomb (const char * fmt, ...) // bomb with herror { va_list ap; int h_errno_save = h_errno; char buf[100]; fflush (stdout); fprintf (stderr, "%s: ", g_program_name); va_start (ap, fmt); vsnprintf (buf, sizeof (buf), fmt, ap); va_end (ap); h_errno = h_errno_save; herror (buf); syslog (LOG_ERR, "Bang!: %s: %s", buf, hstrerror (h_errno)); exit (EXIT_FAILURE); } // set_signal_handler() // Sets a signal handler function. // Similar to signal() but this method // is more portable between platforms. void set_signal_handler (int signum, signal_handler_t sa_handler_func) { struct sigaction act; act.sa_handler = sa_handler_func; sigemptyset (&(act.sa_mask)); act.sa_flags = 0; if ( sigaction (signum, &act, NULL) < 0 ) { syslog (LOG_ERR, "Error setting handler for signal %d: %m", signum); exit (EXIT_FAILURE); } }