#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Buffer size, in bytes, used for copying in the Cat() function. const size_t BUF_SIZE = 4096; // Global variables char g_program_name[100]; // Initialised from argv[0] in ParseArgs() // Typedef for a signal handler function. typedef void (* signal_handler_t) (int); // Prototypes for functions in this file. void ParseArgs (int, char **, struct in_addr *, struct in_addr *, struct in_addr *, struct in_addr *); void Initialise (void); void sig_child (int); int CreateServerSocket (int); void Daemonise (void); void MainLoop (int);//, struct in_addr *, struct in_addr *, struct in_addr *, struct in_addr *); void ClearList(void); void Proxy (int, int); struct accept * AcceptClientConnection (int); void VerifyClient(void *); struct client * Handshake(int); int ConnectToServer (struct in_addr, unsigned short); //void Cat (int, int); void Cat (void *); int NameToAddr (const char *, struct in_addr *); int NameToPort (const char *, unsigned short *, const char *); #ifdef __GNUC__ void quit (const char *, ...) __attribute__ ((format (printf, 1, 2))); void pbomb (const char *, ...) __attribute__ ((format (printf, 1, 2))); void hbomb (const char *, ...) __attribute__ ((format (printf, 1, 2))); #else void quit (const char *, ...); void pbomb (const char *, ...); void hbomb (const char *, ...); #endif void set_signal_handler (int, signal_handler_t); #define __PORT__ 9000 #define __MOITA_FOI_SOLICITADA__ "moita" #define __OK__ "ok" struct accept { int newfd; struct sockaddr_in sa; }; struct main_loop { int listen_fd, ra_1, ra_2, ra_3, ra_4; }; struct client { char * user; int client_fd; int jabber_fd; int keep_alive; time_t last_action; struct client * next; struct client * previous; }; struct cat { int in_fd, out_fd; int 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_1, remote_addr_2, remote_addr_3, remote_addr_4; int listen_fd_1, listen_fd_2, listen_fd_3, listen_fd_4, listen_fd_5; pthread_t port_9001, port_9002, port_9003, port_9004, port_9005; //ParseArgs (argc, argv, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // Create server socket before becoming a daemon so // there is still a chance to print an error message. listen_fd_1 = CreateServerSocket (9001); listen_fd_2 = CreateServerSocket (9002); listen_fd_3 = CreateServerSocket (9003); listen_fd_4 = CreateServerSocket (9004); listen_fd_5 = CreateServerSocket (9005); if ( listen_fd_1 < 0 ) pbomb ("Unable to create server socket #1"); if ( listen_fd_2 < 0 ) pbomb ("Unable to create server socket #2"); if ( listen_fd_3 < 0 ) pbomb ("Unable to create server socket #3"); if ( listen_fd_4 < 0 ) pbomb ("Unable to create server socket #4"); if ( listen_fd_5 < 0 ) pbomb ("Unable to create server socket #5"); //Daemonise (); //pthread_create(&port_900, NULL, (void *) &MainLoop, (void *) accept); MainLoop (listen_fd_1);//, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // never returns //MainLoop (listen_fd, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // never returns //MainLoop (listen_fd, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // never returns //MainLoop (listen_fd, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // never returns //MainLoop (listen_fd, &remote_addr_1, &remote_addr_2, &remote_addr_3, &remote_addr_4); // never returns syslog (LOG_ERR, "fim MainLoop(): %m"); 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_1, struct in_addr * ra_2, struct in_addr * ra_3, struct in_addr * ra_4) { // 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 < 5) || (argc > 5) ) { fprintf (stderr, "usage: %s remote_addr_1 remote_addr_2 remote_addr_3 remote_addr_4\n", argv[0]); exit (EXIT_FAILURE); } if ( NameToAddr (argv[1], ra_1) ) hbomb ("Unable to resolve \"%s\" to an ip address", argv[1]); if ( NameToAddr (argv[2], ra_2) ) hbomb ("Unable to resolve \"%s\" to an ip address", argv[2]); if ( NameToAddr (argv[3], ra_3) ) hbomb ("Unable to resolve \"%s\" to an ip address", argv[3]); if ( NameToAddr (argv[4], ra_4) ) hbomb ("Unable to resolve \"%s\" to an ip address", 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); } // 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 (int 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_addr.s_addr = htonl(INADDR_ANY); sa.sin_port = htons (port); 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 accept * client; unsigned int addr = 0; char buf[250]; int bytes_rcvd, bytes_sent, usando_moita = 0, size_of_buffer, i; time_t inicio = time(NULL); for ( ; ; ) { client = AcceptClientConnection (listen_fd); 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 :: %d\n", buf, ntohs(client->sa.sin_port)); bzero(buf, 250); if ( (bytes_rcvd = recv(client->newfd, buf, 128, 0)) < 1 ) printf("error in recv #1\n"); else { if ( strcmp(buf, __MOITA_FOI_SOLICITADA__) == 0 ) if ( !usando_moita ) { bzero(buf, 250); sprintf(buf, __OK__); size_of_buffer = sizeof(buf); for ( i = 0; i < size_of_buffer; i += bytes_sent ) { bytes_sent = send (client->newfd, buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } } } } } // 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"), pthread_exit(0); if ( socklen != sizeof (sa) ) syslog (LOG_ERR, "accept() screwed up!"), pthread_exit(0); 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; pthread_t cat_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, "10.15.20.42") == 0 )//|| strcmp(buf, "10.15.20.202") == 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 = (struct cat *) malloc(sizeof(struct cat)); info->out_fd = jabber_fd; info->in_fd = client->newfd; info->jabber = (int)NULL; info->keep_alive = (int)NULL; info->client = user; pthread_create(&cat_thread, NULL, (void *) &Cat, (void *)info ); 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->jabber_fd = (int)NULL; new_client->keep_alive = 1; new_client->next = (struct client *)NULL; } bzero(buf, 5); if ( is_new_client != 0 || new_client->jabber_fd == (int)NULL ) sprintf(buf, "new"); else sprintf(buf, "rec"); send (newfd, buf, 3, 0); 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_in = (char *) malloc (sizeof(char) * BUF_SIZE); unsigned char * const buf_out = (char *) malloc (sizeof(char) * BUF_SIZE); int bytes_rcvd_in = (int) NULL, bytes_sent_in = (int) NULL, bytes_rcvd_out = (int) NULL, bytes_sent_out = (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_in == NULL || buf_out == NULL ) syslog (LOG_ERR, "malloc(): %m"), pthread_exit(0); fcntl(in_fd, F_SETFL, fcntl(in_fd, F_GETFL, 0) | O_NDELAY); fcntl(out_fd, F_SETFL, fcntl(out_fd, F_GETFL, 0) | O_NDELAY); bzero(buf_in, BUF_SIZE); bzero(buf_out, BUF_SIZE); do { bzero(buf_in, BUF_SIZE); if ( (bytes_rcvd_in = recv (in_fd, buf_in, BUF_SIZE, 0)) != 0 && strlen(buf_out) > 0 ) { for ( i = 0; i < bytes_rcvd_out; i += bytes_sent_in ) { bytes_sent_in = send (in_fd, buf_out + i, bytes_rcvd_out - i, 0); if ( bytes_sent_in < 0 ) break; } } bzero(buf_out, BUF_SIZE); if ( (bytes_rcvd_out = recv (out_fd, buf_out, BUF_SIZE, 0)) != 0 && strlen(buf_in) > 0 ) { //printf("\n%s\n", buf_in); for ( i = 0; i < bytes_rcvd_in; i += bytes_sent_out ) { bytes_sent_out = send (out_fd, buf_in + i, bytes_rcvd_in - i, 0); if ( bytes_sent_out < 0 ) break; } } usleep(500); } while ( (bytes_rcvd_in != 0) && (bytes_rcvd_out != 0) ); if ( ((bytes_rcvd_in < 0) || (bytes_rcvd_out < 0)) && (errno != ECONNRESET) ) syslog (LOG_ERR, "recv(): %m"), pthread_exit(0); if ( ((bytes_sent_in < 0) || (bytes_sent_out < 0)) && (errno != EPIPE) ) syslog (LOG_ERR, "send(): %m"), pthread_exit(0); if ( user->jabber && !user->keep_alive ) { shutdown(user->jabber, SHUT_RDWR); close(user->jabber); } pthread_exit(0); free (buf_in); free (buf_out); } // 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); } }