Beispiel #1
0
int main(int argc, char *argv[])
{

        if(argc!=3)
        {
                printf("gatlinject <ip:port> <num socket>\n");
                exit(1);
        }

        struct sockaddr_in target = str2sa((char *) argv[1]); // convert target information
        int maxconn = atoi(argv[2]); //number of sockets to connect to the target

        // internal variables definition
        int i, count, datacount;

        char message[] = "hello\n\n";
        int messagelength = strlen(message);

        char buffer[1500];
        int buffersize = strlen(buffer);

        struct statistics stats;
        memset(&stats,0x0,6 * sizeof(int));
        pthread_t Statsthread;


        // time
        struct timeval start;
        struct timeval current;
        float elapsedtime;

        // catch SIGINT to exit in a clean way
        struct sigaction sa;
        memset(&sa, 0, sizeof(struct sigaction *));
        sa.sa_handler = interrupt;
        sa.sa_flags = 0;
        sigemptyset (&(sa.sa_mask));
        if(sigaction (SIGINT, &sa, NULL)!= 0)
        {
                perror("sigaction failed");
                exit(1);
        }

        // the epoll file descriptor
        int epfd;

        // epoll structure that will contain the current network socket and event when epoll wakes up
        static struct epoll_event *events;
        static struct epoll_event event_mask;

        // create the special epoll file descriptor
        epfd = epoll_create(maxconn);

        // allocate enough memory to store all the events in the "events" structure
        if (NULL == (events = calloc(maxconn, sizeof(struct epoll_event))))
        {
                perror("calloc events");
                exit(1);
        };

        // create and connect as much as needed
        for(i=0;i<maxconn;i++)
                if(create_and_connect(target, (int *) epfd) != 0)
                {
                        perror("create and connect");
                        exit(1);
                }
                else
                        stats.nbsock++;

        // start the thread that prints the statistics
        if( 0!= pthread_create (&Statsthread, NULL, (void *)printstats, &stats) ){
                perror("stats thread");
                exit(1);
        }

        gettimeofday(&start, NULL);

        do
        {
                /* wait for events on the file descriptors added into epfd
                 *
                 * if one of the socket that's contained into epfd is available for reading, writing,
                 * is closed or have an error, this socket will be return in events[i].data.fd
                 * and events[i].events will be set to the corresponding event
                 *
                 * count contain the number of returned events
                 */
                count = epoll_wait(epfd, events, maxconn, 1000);

                for(i=0;i<count;i++)
                {
                        if (events[i].events & EPOLLOUT) //socket is ready for writing
                        {
                                // verify the socket is connected and doesn't return an error
                                if(socket_check(events[i].data.fd) != 0)
                                {
                                        perror("write socket_check");
                                        continue;
                                }
                                else
                                {
                                        if((datacount = send(events[i].data.fd, message, messagelength, 0)) < 0)
                                        {
                                                stats.error++;
                                                perror("send failed");
                                                continue;
                                        }
                                        else
                                        {
                                                /* we just wrote on this socket, we don't want to write on it anymore
                                                 * but we still want to read on it, so we modify the event mask to
                                                 * remove EPOLLOUT from the events list
                                                 */
                                                event_mask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET;
                                                event_mask.data.fd = events[i].data.fd;

                                                if(epoll_ctl(epfd, EPOLL_CTL_MOD, events[i].data.fd, &event_mask) != 0)
                                                {
                                                        perror("epoll_ctl, modify socket\n");
                                                        exit(1);
                                                }

                                                stats.reqsent++;
                                                stats.bytessent += datacount;
                                        }
                                }
                        }

                        if (events[i].events & EPOLLIN) //socket is ready for writing
                        {
                                // verify the socket is connected and doesn't return an error
                                if(socket_check(events[i].data.fd) != 0)
                                {
                                        perror("read socket_check");
                                        continue;
                                }
                                else 
                                {
                                        memset(buffer,0x0,buffersize);

                                        if((datacount = recv(events[i].data.fd, buffer, buffersize, 0)) < 0)
                                        {
                                                stats.error++;
                                                perror("recv failed");
                                                continue;
                                        }
                                        else
                                        {
                                                stats.bytesrecv += datacount;
                                                stats.reprecv++;

                                        }
                                }
                        }

                        if (events[i].events & (EPOLLRDHUP | EPOLLHUP)) //socket closed, delete and create a new one
                        {
                                // socket is closed, remove the socket from epoll and create a new one
                                epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, NULL);

                                if(close(events[i].data.fd)!=0)
                                {
                                        perror("close");
                                        continue;
                                }
                                else
                                        stats.nbsock--;

                                if(create_and_connect(target, (int *) epfd) != 0)
                                {
                                        perror("create and connect");
                                        continue;
                                }
                                else
                                        stats.nbsock++;
                        }
                        if (events[i].events & EPOLLERR)
                        {
                                perror("epoll");
                                continue;
                        }
                }
        } while(!stop);

        gettimeofday(&current, NULL);

        elapsedtime = (current.tv_sec * 1000000 + current.tv_usec) -  (start.tv_sec * 1000000 + start.tv_usec);

        printf("\n\nTime: %4.6f\nRequests sent: %d\nBytes sent: %d\nReponses received: %d\nBytes received: %d\nRates out: %4.6freq/s, %4.6fbytes/s\nRates in : %4.6frep/s, %4.6fbytes/s\nErrors: %d\n", elapsedtime/1000000, stats.reqsent, stats.bytessent, stats.reprecv, stats.bytesrecv, stats.reqsent/(elapsedtime/1000000), stats.bytessent/(elapsedtime/1000000), stats.reprecv/(elapsedtime/1000000), stats.bytesrecv/(elapsedtime/1000000), stats.error);

        return 0;
}
int main (int argc, const char* argv[]) {

    // Check if the user has not given enough parameters
    if (argc != 3) {
        printf("Invalid command. Usage: \"%s [address] [port]\"\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // Init structs and other variables
    struct addrinfo* results;
    int sockfd, nbytes;
    char buf[MAXDATASIZE];

    // Try to get addrinfo, exiting on error
    printf("Getting address information...\n");
    results = get_address_info(argv[1], argv[2]);
    if (!results) {
        fprintf(stderr, "Implement assignment 1!\n");
	exit(EXIT_FAILURE);
    }

    // Get IP addresses
    printf("Printing IP addresses for %s...\n", argv[1]);
    char* addr = print_addresses(results);
    if (!addr) {
        fprintf(stderr, "Implement assignment 2!\n");
        exit(EXIT_FAILURE);
    }
    printf("%s", addr);
    free(addr);

    // Bind and connect socket
    printf("Connecting to server...\n");
    sockfd = create_and_connect(results);
    if (!sockfd) {
        fprintf(stderr, "Implement assignment 3!\n");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // We don't need this struct anymore
    freeaddrinfo(results);

    // Receive data
    printf("Receiving data...\n");
    nbytes = receive_data(sockfd, buf);
    if (!nbytes) {
        fprintf(stderr, "Implement assignment 4!\n");
        exit(EXIT_FAILURE);
    }
    buf[nbytes] = '\0';
    printf("Received: %s\n", buf);

    // Send data
    printf("Sending data...\n");
    nbytes = send_data(sockfd, buf);
    if (!nbytes) {
        fprintf(stderr, "Implement assignment 5!\n");
        exit(EXIT_FAILURE);
    }
    buf[nbytes] = '\0';
    printf("Sent: %s\n", buf);

    // Receive confirmation
    if ((nbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
        perror("recv error");
        exit(EXIT_FAILURE);
    }
    buf[nbytes] = '\0';
    printf("Received: %s\n", buf);

    // Close the socket after the sending and receiving is done
    close(sockfd);

    return 0;
}
Beispiel #3
0
void main(int argc, char* argv[])
{
	char *url, **headers;
	headers = malloc((argc / 2) * sizeof(char *));
	
    if (parse_args(&cfg, headers, argc, argv)) {
        usage();
        exit(1);
    }

    char **h;
	char header_name[32];
	char header_value[200];
	char header[1024];
	char header_tmp[232];
  event_ptr * ptr;
  
	if (cfg.file) {
		FILE *fp;
		char buf[MAX_LINE];  /*缓冲区*/
		int n, len ;
		fp = fopen(cfg.file, "r");
		if (fp == NULL) {
			printf("file not exist :%s\n", cfg.file);
			exit(1);
		}
		n = 0;
		int epfd;
		static struct epoll_event *events;

		// create the special epoll file descriptor
		epfd = epoll_create(cfg.threads);

		// allocate enough memory to store all the events in the "events" structure
		if (NULL == (events = calloc(cfg.threads, sizeof(struct epoll_event))))
		{
		  perror("calloc events");
		  exit(1);
		};
		int rn = 0;	
master_worker:		
		while(fgets(buf, MAX_LINE, fp) != NULL) {
			len = strlen(buf);
			buf[len-1] = '\0'; /* 去掉换行符 */
			  if(strlen(buf) >= 7 && create_and_connect(buf, &epfd) != 0)
			  {
				 fprintf (stderr, "create and connect : %s\n", buf);
			  }			
			++n;
			++rn;
			if(rn > cfg.threads) goto epoll_worker;
		}
		if (rn == 0) exit(0);
		

epoll_worker:
	
	sprintf(header, "GET %s HTTP/1.1\r\n", cfg.path);
	rn = 0;
	for (h = headers; *h; h++) {
		char *p = strchr(*h, ':');
		if (p && p[1] == ' ') {
			bzero(header_name, 32);
			bzero(header_value, 200);
			bzero(header_tmp, 232);
			strncpy(header_name, *h, strlen(*h) - strlen(p));
			strcpy(header_value, p + 2);
			sprintf(header_tmp, "%s: %s\r\n", header_name, header_value);
			stringlink(header, header_tmp);
			//printf("p=%p(%d), %s => %s\n", p, strlen(p), header_name, header_value);
		}
	}
	stringlink(header, "\r\n");
	int header_len = strlen(header);
	char *hhh  = malloc( header_len * sizeof(char) + 1);
	strcpy(hhh, header);

	printf("%s", hhh);
	
   char buffer[2049];
   int buffersize = 2048;
   int count, i, datacount;	
   int http_status;
  char *http_servername = NULL;
   char *http_title = NULL;
   	while(1) {
			count = epoll_wait(epfd, events, cfg.threads, 500);
			if(count == 0) break;
		for(i=0;i<count;i++) {	
 		ptr = events[i].data.ptr;
		//printf("count=%d,fd=%d ,ip=%s, events[i].events=%d\n", count, ptr->fd, ptr->addr, events[i].events);
	  if ((events[i].events & (EPOLLHUP |  EPOLLERR)) || strlen(ptr->addr) == 0)
	    {

          epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL);

	      //fprintf (stderr, "epoll error %d\n", ptr->fd);
	      continue;
	    }				
         if (events[i].events & EPOLLOUT) //socket is ready for writing
         {
            // verify the socket is connected and doesn't return an error
            if(socket_check(ptr->fd) != 0)
            {
               perror("write socket_check");
               continue;
            }
            else
            {
              
              int total = header_len;
              while(1) {
              	datacount = send(ptr->fd, hhh, header_len, 0);
              	if(datacount < 0) {
              		if (errno == EINTR || errno == EAGAIN) {
              			usleep(1000);
              			continue;
              		} 
              	}
              	if (datacount == total) {
                  events[i].events = EPOLLIN  | EPOLLHUP | EPOLLERR;

                  if(epoll_ctl(epfd, EPOLL_CTL_MOD, ptr->fd, events) != 0)
                  {
                     perror("epoll_ctl, modify socket");
                     continue;
                  }
                  break;           	
              	}
              	total -= datacount;
              	hhh += datacount;
              }

            }
         }

         if (events[i].events & (EPOLLIN )) //socket is ready for reading
         {
            // verify the socket is connected and doesn't return an error
            if(socket_check(ptr->fd) != 0)
            {
               fprintf (stderr, " [ %s->%d] read socket_check : [%d]%s\n", ptr->addr, ptr->fd, errno, strerror(errno));
               //epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL);
               continue;

            }
            else 
            {
               memset(buffer,0x0,buffersize);

               int n = 0;
               while (1) {
               datacount = read(ptr->fd, buffer +n , buffersize);
		      	if(datacount == -1) {
		      		++ptr->rein;
		      		if (ptr->rein > 5) {
		      			epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL);
		      			break;
		      		}
		      		if (errno == EAGAIN) {
		      			usleep(1000);
		      			continue;
		      		}
		      	

		      	}else if(datacount == 0) {
		      		break;
		      	}
              //printf("%s=%d=%d\n", buffer, n, datacount);
		      	               
                n += datacount;
              }


              /*            
               if((datacount = recv(ptr->fd, buffer, buffersize, 0)) < 0 )
               {
               	  ++ptr->rein;
                  fprintf (stderr, "[ %s->%d] recv failed : %s\n", ptr->addr, ptr->fd, strerror(errno));
                  if(ptr->rein > 5) {
                  	epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL);
                  }
                  continue;
               }
              */  
				printf("%s\n", buffer);
               char *http_status = substring(buffer, 9, 3);
               http_servername = substr(buffer, "Server: ", "\r\n");
               http_title = substr(buffer, "<title>", "</title>");
               fprintf (stdout, "%s\t%s\t%s\t%s\n", ptr->addr, http_status, http_servername, http_title);
               if(http_status != NULL) free(http_status);
               if(http_servername != NULL) free(http_servername);
               if(http_title != NULL) free(http_title); 

               epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL);
               //usleep(10000);
            }
         }

         }			
		}
		goto master_worker;
	}
	
    //printf("headers: %s\npath: %s\nport: %d\n", *headers, cfg.path, cfg.port);
}