#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; // Typedef for a signal handler function. typedef void (*signal_handler_t) (int); // Global variables char g_program_name[100]; // Initialised from argv[0] in ParseArgs() struct allowed_ip * allowed_ips = (struct allowed_ip *)NULL; int quantity_of_fd = 0; // quantity of file descriptor static struct connections * connections = (struct connections *)NULL; pthread_mutex_t mutexsum; // structs struct allowed_ip { char * ip; struct allowed_ip * next; }; struct accept { int * fd; struct sockaddr_in sa; struct in_addr jabber_addr; unsigned short jabber_port; pthread_t accept_thread; }; struct client { char * user, * pass; int * jabber_fd, * read_fd; time_t last_access; }; struct connections { struct client * client; struct connections * next; }; struct read_write { int * jabber, client, type; pthread_t read, write; }; void recursive (int, struct in_addr, unsigned short); int getPermission(char *); void ParseArgs (int, char **, struct in_addr *, unsigned short *, struct in_addr *, unsigned short *); void Initialise (void); void sig_child (int); int CreateServerSocket (struct in_addr, unsigned short); void Daemonise (void); void MainLoop (int, struct in_addr, unsigned short); void ClearList(void); struct accept * AcceptClientConnection (int); void VerifyClient(void *); struct client * Handshake (struct accept *, struct read_write *); void * withConnections(void * (*func)(), ...); //struct client * LookFor (char *, char *); //void * LookFor (struct connections *, char *, char *); void * LookFor (char *, char *); void Reading (void *); void Writing (void *); int ConnectToServer (struct in_addr, unsigned short); 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); int main (int argc, char ** argv) { struct in_addr remote_addr, local_addr; unsigned short remote_port, local_port; int listen_fd; //pthread_t clear_list_thread; 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 (); //pthread_mutex_init(&mutexsum, NULL); //pthread_create(&clear_list_thread, NULL, (void *) &ClearList, (void *)NULL ); //MainLoop (listen_fd, remote_addr, remote_port); // never returns recursive(listen_fd, remote_addr, remote_port); //pthread_mutex_destroy(&mutexsum); exit (EXIT_SUCCESS); } void recursive (int listen_fd, struct in_addr rem_addr, unsigned short rem_port) { //while ( 1 ) // sleep(1); //exit(0); pid_t helper_pid; syslog (LOG_INFO, "recursive()"); signal (SIGCHLD, SIG_IGN); helper_pid = fork (); if ( helper_pid == -1 ) syslog (LOG_ERR, "fork() on recursive(): %m"), exit (EXIT_FAILURE); if ( helper_pid ) /* parent */ { //syslog (LOG_INFO, "Forked child pid %d to help with MainLoop", helper_pid); wait(0); /* wait for helper to exit */ } else /* child (helper) */ { MainLoop (listen_fd, rem_addr, rem_port); syslog (LOG_INFO, "exiting"); exit (0); /* helper exits here */ } recursive(listen_fd, rem_addr, rem_port); } // 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]); } int getPermission(char * ip) { struct allowed_ip * allow_ip = allowed_ips; int allow = 0; while ( !allow && allow_ip != (struct allowed_ip *)NULL ) { //printf("strcmp(%s, %s)\n\n", ip, allow_ip->ip); if ( strcmp(ip, allow_ip->ip) == 0 ) allow = 1; else allow_ip = allow_ip->next; } return allow; } // Initialise() // Setup syslog, signal handlers, and other intialisation. void Initialise (void) { FILE * allowed_ips_fd; struct allowed_ip * allow_ip; if ( !(allowed_ips_fd = fopen("webjabber.cfg", "r")) ) syslog (LOG_ERR, "Impossivel abrir o arquivo 'webjabber.cfg'"), exit (EXIT_FAILURE); while ( !feof(allowed_ips_fd) ) { char * line = (char *) malloc(16 * sizeof(char)); bzero(line, 16); fgets(line, 16, allowed_ips_fd); if ( strlen(line) ) { if ( line[strlen(line) - 1] == '\n' ) line[strlen(line) - 1] = '\0'; if ( allowed_ips == (struct allowed_ip *)NULL ) allow_ip = allowed_ips = (struct allowed_ip *) malloc(sizeof(struct allowed_ip)); else { allow_ip = allowed_ips; while ( allow_ip->next != (struct allowed_ip *)NULL ) allow_ip = allow_ip->next; allow_ip->next = (struct allowed_ip *) malloc(sizeof(struct allowed_ip)); allow_ip = allow_ip->next; } allow_ip->next = (struct allowed_ip *)NULL; allow_ip->ip = line; } } char * initial_path = (char *) malloc(128 * sizeof(char)); getcwd(initial_path, 128); openlog (g_program_name, LOG_PID, LOG_USER); syslog (LOG_INFO, "%s started in path [#%d] %s", g_program_name, strlen(initial_path), initial_path); 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; } // Daemonise(): Put the program in the background, set PPID=1, create a new // session and process group, without a controlling tty. void Daemonise (void) { pid_t pid; /* Close stdin, stdout & stderr */ /* TODO: open /dev/null and dup the fd to stdin, stdout & stderr * close(STDIN_FILENO); * close(STDOUT_FILENO); * close(STDERR_FILENO); * */ syslog (LOG_INFO, "%s daemonising", g_program_name); /* Fork the process to put it in the background. */ pid = fork (); if (pid == -1) syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); /* parent terminates here, so shell thinks the command is done. */ if (pid) exit (0); syslog (LOG_INFO, "%s in background", g_program_name); /* 1st child continues to run in the background with PPID=1 */ /* Become leader of a new session and a new process group, * with no controlling tty. */ setsid (); /* Fork again to guarantee the process will not be able to aquire a * controlling tty. */ /*signal (SIGHUP, SIG_IGN); *//* required according to Stevens' UNP2 p333 */ pid = fork (); if (pid == -1) syslog (LOG_ERR, "fork(): %m"), exit (EXIT_FAILURE); if (pid) /* 1st child terminates */ exit (0); /* 2nd child continues, no longer a session or group leader */ syslog (LOG_INFO, "%s daemonised", g_program_name); } // 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) { //pid_t helper_pid; pthread_t clear_list_thread; syslog (LOG_INFO, "MainLoop :: listen_fd(fd%d)", listen_fd); //signal (SIGCHLD, SIG_IGN); pthread_mutex_init(&mutexsum, NULL); pthread_create(&clear_list_thread, NULL, (void *) &ClearList, (void *)NULL ); while ( quantity_of_fd < 50 ) { struct accept * client; syslog (LOG_INFO, "[timestamp = %d] quantity_of_fd = %d", time(NULL), quantity_of_fd); client = AcceptClientConnection (listen_fd); client->jabber_addr = rem_addr; client->jabber_port = rem_port; pthread_create(&client->accept_thread, NULL, (void *) &VerifyClient, (void *) client); } pthread_mutex_destroy(&mutexsum); } void ClearList(void) { for ( ; ; ) { pthread_mutex_lock(&mutexsum); struct connections * connection = connections; while ( connection != (struct connections *)NULL ) { if ( *(connection->client->jabber_fd) != (int)NULL && time(NULL) - connection->client->last_access > 70 ) { shutdown(*(connection->client->jabber_fd), SHUT_RDWR); close(*(connection->client->jabber_fd)); *(connection->client->jabber_fd) = (int)NULL; } connection = connection->next; } pthread_mutex_unlock(&mutexsum); sleep(5); } } // 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. //int AcceptClientConnection (int listen_fd) struct accept * AcceptClientConnection (int listen_fd) { int * newfd = (int *) malloc(sizeof(int)); if ( newfd == NULL ) { syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); } 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); quantity_of_fd++; const int on = 1; if ( setsockopt (*(newfd), SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0 ) syslog (LOG_ERR, "setsockopt(fd%d, SO_REUSEADDR): %m", *(newfd)); struct accept * accepted = (struct accept *) malloc(sizeof(struct accept)); if ( accepted == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); accepted->fd = newfd; accepted->sa = sa; return (accepted); } void VerifyClient(void * accepted) { //puts("\n\n:::::::::::::::: VERIFYCLIENT :::::::::::::::::::::\n"); unsigned int addr = 0; char ip[250]; int * jabber_fd = (int *)NULL; const int on = 1; struct accept * accept = (struct accept *) accepted; struct client * client = (struct client *)NULL; struct read_write * read_write = (struct read_write *) malloc(sizeof(struct read_write)); if ( read_write == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); read_write->type = 0; // ip from client addr = ntohl(accept->sa.sin_addr.s_addr); sprintf(ip, "%d.%d.%d.%d", (addr >> 24), (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF); //printf("\nNew connection [#%d]: %s\n", *(accept->fd), ip); if ( getPermission(ip) ) if ( (client = Handshake(accept, read_write)) == (struct client *)NULL ) { close(*(accept->fd)); pthread_kill(accept->accept_thread, 0); } else { jabber_fd = client->jabber_fd; } else { jabber_fd = (int *) malloc(sizeof(int)); if ( jabber_fd == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); *(jabber_fd) = (int)NULL; } //puts("\n\n:::::::::::::::: JABBER IN VERIFYCLIENT #1 :::::::::::::::::::::\n"); if ( *(jabber_fd) == (int)NULL ) *(jabber_fd) = ConnectToServer(accept->jabber_addr, accept->jabber_port); //puts("\n\n:::::::::::::::: JABBER IN VERIFYCLIENT #2 :::::::::::::::::::::\n"); // Set SO_REUSEADDR socket option //if ( setsockopt (*(jabber_fd), SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0 ) // syslog (LOG_ERR, "setsockopt(fd%d, SO_REUSEADDR) #2: %m", *(jabber_fd)); //if ( client != (struct client *)NULL ) // client->jabber_fd = jabber_fd; read_write->jabber = jabber_fd; read_write->client = *(accept->fd); //pthread_t cat_thread; //fcntl(read_write->client, F_SETFL, fcntl(read_write->client, F_GETFL, 0) | O_NDELAY); //puts("\n\n:::::::::::::::: THREADS :::::::::::::::::::::\n"); //pthread_create(&read_write->write, NULL, (void *) &Writing, (void *)read_write ); pthread_create(&read_write->read, NULL, (void *) &Reading, (void *)read_write ); //pthread_exit(0); pthread_kill(accept->accept_thread, 0); } struct client * Handshake(struct accept * accept, struct read_write * read_write) { //puts("\n\n:::::::::::::::: HANDSHAKE :::::::::::::::::::::\n"); struct client * client = (struct client *)NULL; unsigned char * const buf = (char *) malloc (sizeof(char) * 5); if ( buf == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); char * str = (char *) malloc(128 * sizeof(char)), * user = (char *)NULL, * pass = (char *)NULL, * pass_pos = (char *)NULL, * type = (char *)NULL, * type_pos = (char *)NULL; if ( str == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); int bytes_rcvd, bytes_sent, i; bzero(str, 128); if ( (bytes_rcvd = recv (*(accept->fd), str, 128, 0)) < 1 ) { //puts("error :: str"); close(*(accept->fd)); return client; } pass_pos = strstr(str, "##") + 2; i = strlen(str) - strlen(pass_pos) - 1; user = (char *) malloc(i * sizeof(char)); if ( user == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); bzero(user, i); strncpy(user, str, i - 1); type_pos = strstr(pass_pos, "##") + 2; i = strlen(pass_pos) - strlen(type_pos) - 1; pass = (char *) malloc(i * sizeof(char)); if ( pass == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); bzero(pass, i); strncpy(pass, pass_pos, i - 1); i = strlen(type_pos) + 1; type = (char *) malloc(i * sizeof(char)); if ( type == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); bzero(type, i); strcpy(type, type_pos); printf(" str[%2d]: %s\n", strlen(str), str); printf("user[%2d]: %s\n", strlen(user), user); printf("pass[%2d]: %s\n", strlen(pass), pass); printf("type[%2d]: %s\n", strlen(type), type); printf(" fd[%2d]: client\n", *(accept->fd)); //if ( (client = LookFor (user, pass)) != (struct client *)NULL ) if ( (client = (struct client *) withConnections(LookFor, user, pass)) != (struct client *)NULL ) { //puts("\n\n:::::::::::::::: INFO #0 :::::::::::::::::::::\n"); bzero(buf, 5); //if ( *(client->read_fd) != (int)NULL ) //{ // shutdown(*(client->read_fd), SHUT_RDWR); // close(*(client->read_fd)); //} //*(client->read_fd) = *(accept->fd); //puts("\n\n:::::::::::::::: INFO #1 :::::::::::::::::::::\n"); if ( *(client->jabber_fd) == (int)NULL ) { //puts("\n\n:::::::::::::::: JABBER IN HANDSHAKE #1 :::::::::::::::::::::\n"); *(client->jabber_fd) = ConnectToServer(accept->jabber_addr, accept->jabber_port); sprintf(buf, "new "); //puts("\n\n:::::::::::::::: JABBER IN HANDSHAKE #2 :::::::::::::::::::::\n"); } else sprintf(buf, "rec "); //puts("\n\n:::::::::::::::: INFO #2 :::::::::::::::::::::\n"); //printf("connection: %s\n\n\n", buf); for ( i = 0; i < sizeof(buf); i += bytes_sent ) { bytes_sent = send (*(accept->fd), buf + i, sizeof(buf) - i, 0); if ( bytes_sent < 0 ) break; } //puts("\n\n:::::::::::::::: INFO #3 :::::::::::::::::::::\n"); if ( strcmp(type, "read") == 0 ) read_write->type = 1; else if ( strcmp(type, "write") == 0 ) read_write->type = 2; //puts("\n\n:::::::::::::::: INFO #4 :::::::::::::::::::::\n"); } //free(str); free(buf); return client; } void * withConnections(void * (*func)(), ...) { //static struct connections * connections = (struct connections *)NULL; if ( (*func) == LookFor ) { va_list ap; char * user, * pass; void * _return; va_start(ap, (*func)); user = va_arg(ap, char *); pass = va_arg(ap, char *); va_end(ap); pthread_mutex_lock(&mutexsum); _return = (*func)(user, pass); pthread_mutex_unlock(&mutexsum); return _return; } else { } } //struct client * LookFor (char * user, char * pass) //void * LookFor (struct connections * connections, char * user, char * pass) void * LookFor (char * user, char * pass) { //puts("\n\n:::::::::::::::: LOOKFOR :::::::::::::::::::::\n"); //static struct connections * connections = (struct connections *)NULL; //pthread_mutex_lock(&mutexsum); if ( connections == (struct connections *)NULL ) { //puts("\n\n:::::::::::::::: FIRST CONNECTION :::::::::::::::::::::\n"); connections = (struct connections *) malloc(sizeof(struct connections)); if ( connections == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); connections->client = (struct client *) malloc(sizeof(struct client)); if ( connections->client == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); connections->client->user = user; connections->client->pass = pass; connections->client->read_fd = (int *) malloc(sizeof(int)); if ( connections->client->read_fd == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); connections->client->jabber_fd = (int *) malloc(sizeof(int)); if ( connections->client->jabber_fd == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); *(connections->client->read_fd) = (int)NULL; *(connections->client->jabber_fd) = (int)NULL; connections->client->last_access = time(NULL); connections->next = (struct connections *)NULL; //pthread_mutex_unlock(&mutexsum); return connections->client; } else { //puts("\n\n:::::::::::::::: HAS CONNECTION :::::::::::::::::::::\n"); struct connections * connection = connections, * last; while ( connection != (struct connections *)NULL ) { //puts(":::::::::::::::: PROCURANDO :::::::::::::::::::::"); if ( strcmp(connection->client->user, user) == 0 ) if ( strcmp(connection->client->pass, pass) == 0 ) { //pthread_mutex_unlock(&mutexsum); //puts(":::::::::::::::: ACHOU #1 :::::::::::::::::::::"); connection->client->last_access = time(NULL); return connection->client; } else { //pthread_mutex_unlock(&mutexsum); //puts(":::::::::::::::: ACHOU #2 :::::::::::::::::::::"); return (struct client *)NULL; } last = connection; connection = connection->next; } //puts(":::::::::::::::: ACHOU #3 :::::::::::::::::::::"); last->next = (struct connections *) malloc(sizeof(struct connections)); if ( last->next == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); connection = last->next; connection->client = (struct client *) malloc(sizeof(struct client)); if ( connection->client == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); connection->client->user = user; connection->client->pass = pass; connection->client->jabber_fd = (int *) malloc(sizeof(int)); if ( connection->client->jabber_fd == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); *(connection->client->jabber_fd) = (int)NULL; connection->client->last_access = time(NULL); connection->next = (struct connections *)NULL; //pthread_mutex_unlock(&mutexsum); return connection->client; } } void Reading (void * read_write) { unsigned char * const buf_2_jabber = (char *) malloc (sizeof(char) * BUF_SIZE); unsigned char * const buf_2_client = (char *) malloc (sizeof(char) * BUF_SIZE); bzero(buf_2_jabber, BUF_SIZE); bzero(buf_2_client, BUF_SIZE); if ( buf_2_jabber == NULL || buf_2_client == NULL ) syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); struct read_write * read = (struct read_write *) read_write; int jabber_fd = *(read->jabber), client_fd = read->client; fcntl(jabber_fd, F_SETFL, fcntl(jabber_fd, F_GETFL, 0) | O_NDELAY); fcntl(client_fd, F_SETFL, fcntl(client_fd, F_GETFL, 0) | O_NDELAY); int bytes_rcvd_jabber = (int) NULL, bytes_sent_jabber = (int) NULL, bytes_rcvd_client = (int) NULL, bytes_sent_client = (int) NULL, i, do_auth = 0; // @TODO: verificar alocacao buffer //if ( buf == NULL ) // syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); do { bzero(buf_2_jabber, BUF_SIZE); bytes_rcvd_client = recv (client_fd, buf_2_jabber, BUF_SIZE, 0); if ( (bytes_rcvd_client != 0) && (strlen(buf_2_client) > 0) ) { for ( i = 0; i < bytes_rcvd_jabber; i += bytes_sent_client ) { bytes_sent_client = send (client_fd, buf_2_client + i, bytes_rcvd_jabber - i, 0); if ( bytes_sent_client < 0 ) break; } } if ( strlen(buf_2_jabber) > 0 ) { printf("(client/jabber[#%d])[%d]:\n{\n%s.......\n}\n", jabber_fd, strlen(buf_2_jabber), buf_2_jabber); if ( strstr(buf_2_jabber, "type == 1 ) bytes_rcvd_jabber = recv (jabber_fd, buf_2_client, BUF_SIZE, 0); else bytes_rcvd_jabber = -1; if ( (bytes_rcvd_jabber != 0) && (strlen(buf_2_jabber) > 0) ) { for ( i = 0; i < bytes_rcvd_client; i += bytes_sent_jabber ) { bytes_sent_jabber = send (jabber_fd, buf_2_jabber + i, bytes_rcvd_client - i, 0); if ( bytes_sent_jabber < 0 ) break; } } if ( strlen(buf_2_client) > 0 ) { if ( do_auth && strstr(buf_2_jabber, "client, SHUT_RDWR); close (read->client); } /* void Reading (void * read_write) { struct read_write * read = (struct read_write *) read_write; //printf("read->type: %d\n\n\n", read->type); if ( !read->type || read->type == 1 ) { unsigned char * const buf = (char *) malloc (sizeof(char) * BUF_SIZE); if ( buf == NULL ) { puts("\n\nmalloc() : buf #2\n\n\n"); exit (EXIT_FAILURE); } int bytes_rcvd, bytes_sent = (int) NULL, i; int in_fd = *(read->jabber), out_fd = read->client; //syslog (LOG_INFO, "Reading(fd%d, fd%d)", in_fd, out_fd); // @TODO: verificar alocacao buffer //if ( buf == NULL ) // syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); do { //puts("\n\n:::::::::::::::: DO - READ :::::::::::::::::::::\n"); bzero(buf, BUF_SIZE); bytes_rcvd = recv (in_fd, buf, BUF_SIZE, 0); if ( strlen(buf) > 0 ) { // descomentar para ver oq esta passado de informacao printf("Reading(#%d/jabber,#%d/client)[%d]:\n{\n%s.......\n}\n", in_fd, out_fd, strlen(buf), buf); for ( i = 0; i < bytes_rcvd && *(read->jabber) != (int)NULL; 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) ); printf("\n[Reading] FINALIZANDO TREAD CLIENTE COM FD #%d\n\n", out_fd); pthread_cancel(read->write); //if ( bytes_rcvd < 1 ) // *(read->jabber) = (int)NULL; printf("\n\nFIM Reading [#%d#%d]\nbytes_rcvd = %d : bytes_sent = %d\n\n\n", in_fd, out_fd, bytes_rcvd, bytes_sent); free (buf); } else while ( 1 ) usleep(500); //pthread_kill(read->write, 0); shutdown(read->client, SHUT_RDWR); close (read->client); //pthread_exit(0); } */ void Writing (void * read_write) { struct read_write * write = (struct read_write *) read_write; //printf("write->type: %d\n\n\n", write->type); //if ( !write->type || write->type == 2 ) //{ unsigned char * const buf = (char *) malloc (sizeof(char) * (BUF_SIZE + 1)); if ( buf == NULL ) { syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); } int bytes_rcvd, bytes_sent = (int) NULL, i; int in_fd = write->client, out_fd = *(write->jabber); //syslog (LOG_INFO, "Writing(fd%d, fd%d)", in_fd, out_fd); // @TODO: verificar alocacao buffer //if ( buf == NULL ) // syslog (LOG_ERR, "malloc(): %m"), exit (EXIT_FAILURE); do { //puts("\n\n:::::::::::::::: DO - WRITE :::::::::::::::::::::"); bzero(buf, BUF_SIZE + 1); //puts(":::::::::::::::: WRITE - RECV :::::::::::::::::::::"); bytes_rcvd = recv (in_fd, buf, BUF_SIZE, 0); //puts(":::::::::::::::: WRITE - IF #1 :::::::::::::::::::::"); if ( strlen(buf) > 0 ) { // descomentar para ver oq esta passado de informacao //printf("Writing(#%d/client,#%d/jabber)[%d]:\n{\n%s.......\n}\n", in_fd, out_fd, strlen(buf), buf); for ( i = 0; i < bytes_rcvd && *(write->jabber) != (int)NULL; i += bytes_sent ) { bytes_sent = send (out_fd, buf + i, bytes_rcvd - i, 0); if ( bytes_sent < 0 ) break; } } //puts(":::::::::::::::: WRITE - IF #2 :::::::::::::::::::::\n"); } while ( (bytes_rcvd > 0) && (bytes_sent > 0) ); //printf("\n[Writing] FINALIZANDO TREAD CLIENTE COM FD #%d\n\n", in_fd); pthread_cancel(write->read); //if ( bytes_sent < 1 ) // *(write->jabber) = (int)NULL; //printf("\n\nFIM Writing [#%d#%d]\nbytes_rcvd = %d : bytes_sent = %d\n\n\n", in_fd, out_fd, bytes_rcvd, bytes_sent); free (buf); //} //else // while ( 1 ) usleep(500); //pthread_kill(write->read, 0); shutdown(write->client, SHUT_RDWR); close (write->client); //pthread_exit(0); } // 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"), 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); } quantity_of_fd++; syslog (LOG_INFO, "Connected socket fd%d to server", fd); return fd; } // 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); } }