コード例 #1
0
ファイル: client.c プロジェクト: jtresman/networking
int main(int argc, char **argv){
    
    char *conf, buf[MAXLINE];

    if (argc != 2) {
        fprintf(stderr, "Please Specify a Config File.");
        exit(0);
    }

    conf = argv[1];
    
    getConfig(conf);

    servers[0].fd = open_clientfd(servers[0].host, servers[0].port);
    servers[1].fd = open_clientfd(servers[1].host, servers[1].port);
    servers[2].fd = open_clientfd(servers[2].host, servers[2].port);
    servers[3].fd = open_clientfd(servers[3].host, servers[3].port);

    printf("Please Enter A Command: \n");

    while (fgets(buf, MAXLINE, stdin) != NULL) {
        // printf("The line was: %s\n", buf);
        processRequest(buf);
        printf("Please Enter a Command: \n");
    }

    close(servers[0].fd);
    close(servers[1].fd);
    close(servers[2].fd);
    close(servers[3].fd);

    exit(0);
}
コード例 #2
0
ファイル: proxy.c プロジェクト: yuguess/ProxyLabNew
/* 
 * forward_request - send request from client to its destination server 
 */
int forward_request(int client_fd, Request *request, Response *response) {
    rio_t   server_rio;
    int server_fd;
    char hostname[MAXLINE];
    int  port = 80;

    extract_hostname_port(request->host_str, hostname, &port);

    #ifdef DEBUG
    printf("extract hostname:%s\n", hostname);
    printf("extract port:%d\n", port);
    #endif
    if ((server_fd = open_clientfd(hostname, port)) < 0) {
        sleep(2);
        if ((server_fd = open_clientfd(hostname, port)) < 0) {
            sleep(2);
            if ((server_fd = open_clientfd(hostname, port)) < 0) {
                proxy_error(strcat(hostname, " connection refuesed"));
                close(server_fd);
                return -1;
            }
        }
    }

    rio_readinitb(&server_rio, server_fd);
    #ifdef DEBUG
    printf("request_str:%s", request->request_str); 
    #endif
    
    rio_writen(server_fd, request->request_str, strlen(request->request_str));
    rio_writen(server_fd, request->host_str, strlen(request->host_str));
    /* send cookie to server */
    if (request->cookie_size != 0) {
        rio_writen(server_fd, request->cookie, request->cookie_size);
    }
    /* send user-agent info to server */
    if (request->user_agent_size != 0) {
        rio_writen(server_fd, request->user_agent, request->user_agent_size);
    }
    rio_writen(server_fd, "\r\n", strlen("\r\n"));
    
    if (forward_response(client_fd, server_fd, response) < 0) {
        close(server_fd);
        return -1;
    }
    close(server_fd);
    return 1;
}
コード例 #3
0
ファイル: csapp.c プロジェクト: abapst/15213-labs
/****************************************************
 * Wrappers for reentrant protocol-independent helpers
 ****************************************************/
int Open_clientfd(char *hostname, char *port) 
{
    int rc;
    if ((rc = open_clientfd(hostname, port)) == -1) 
	unix_error("Open_clientfd error");
    return rc;
}
コード例 #4
0
ファイル: main.c プロジェクト: xiangshouding/old.c
/**
 * callback func
 */
void * subtask (void * arg) {
    task_arg * ta = (task_arg *) arg;
    int clientfd;
    char buffer[STD_BUFF_SIZE] = "";
    char head[STD_BUFF_SIZE] = "";
    clientfd = open_clientfd(ta->host, ta->port, TIME_OUT);
    if (clientfd < 0) {
        pthread_exit((void *) 0);
        return ((void *) 0); 
    }

    memset(head, '\0', strlen(head));
    sprintf(head, "HEAD / HTTP/1.0\r\n\r\n");
    send(clientfd, head, strlen(head) + 1);

    memset(buffer, '\0', strlen(buffer));

    recv(clientfd, buffer, 2048, 0);

    pthread_mutex_lock(f_lock);
    fprintf(stdout, "running thread 0x%x\n", (unsigned int)pthread_self());
    fprintf(stdout, "hostname %s\n port %d\n", ta->host, ta->port);
    fprintf(stdout, "recv data(%d)\n ", strlen(buffer));
    if (ta->flt->is_set) {
        filter_by_re(buffer, ta->flt->re, NULL);
    } else {
        fprintf(stdout, "%s\n", buffer);
    }
    pthread_mutex_unlock(f_lock);

    close(clientfd);

    pthread_exit((void *) 0);
    return ((void *) 0); 
}
コード例 #5
0
ファイル: proxy.c プロジェクト: fxiang/proxylab
int forward_request(int client_fd, Request *request, Response *response) {
    rio_t   server_rio;
    int server_fd;
    char hostname[MAXLINE];
    int  port = 80;

    port = extract_port_number(request->request_str);
    extract_hostname(request->host_str, hostname);

    #ifdef DEBUG
    printf("hostname:%s\n", hostname);
    printf("port:%d\n", port);
    #endif

    if ((server_fd = open_clientfd(hostname, port)) < 0) {
       fprintf(stderr, "Warning connection refused !\n"); 
       return -1;
    }

    rio_readinitb(&server_rio, server_fd);
    #ifdef DEBUG
    printf("request_str:%s", request->request_str); 
    #endif
    
    rio_writen(server_fd, request->request_str, strlen(request->request_str));
    rio_writen(server_fd, request->host_str, strlen(request->host_str));
    rio_writen(server_fd, "\r\n", strlen("\r\n"));
    
    forward_response(client_fd, server_fd, response);
    Close(server_fd);
    return 1;
}
コード例 #6
0
void send_newinfo(){
    // as the first seeder, communicate with the chord ring, and set the tracker info
    char buf[MAXLINE];
    char cmd[MAXLINE];
    char in[MAXLINE];
    printf("Please input the filename that you want to upload:\n");
    int dummy = scanf("%s", in);
    strcpy(filename,in);

    // send the filename and its own ip and port info
    strcpy(cmd,"NewTracker");
    clientfd = open_clientfd(NodeIP, NodePort);
    if (clientfd == -1) {
        printf("The IP and port you entered is not in the ring.\n");
        exit(1);
    }
    sprintf(buf,"%s %s %d %s\r\n",cmd,myIP,myport,filename);
    Rio_writen(clientfd, buf, strlen(buf));
    memset(buf, 0, strlen(buf));
    close(clientfd);

    for (int i = 0; i < 10; i++) {
    	if (filenames[i] == NULL) {
    		filenames[i] = strdup(filename);
    		break;
    	}
    }
}
コード例 #7
0
ファイル: webhelper.c プロジェクト: doublequan/CSAPP
int web_open_clientfd(char *hostname, char *port) 
{
    int rc;

    if ((rc = open_clientfd(hostname, port)) < 0) 
	web_error("Open_clientfd error");
    return rc;
}
コード例 #8
0
ファイル: csapp.c プロジェクト: FDUJiChao/wdan-ics
/******************************************
 * Wrappers for the client/server helper routines 
 ******************************************/
int Open_clientfd(char *hostname, int port) {
	int rc;
	//Permit to try more than one time.
	int max=5;
	while ((max>0)&&((rc = open_clientfd(hostname, port)) < 0)) {
		sleep(1);
		max--;
	}
	return rc;
}
コード例 #9
0
ファイル: csapp.c プロジェクト: jack-lijing/unix
int Open_clientfd(char *hostname, int port)
{
	int rt;
	rt = open_clientfd(hostname, port);
	if ( rt == -1 )
		unix_error("Open_clientfd unix error");
	if ( rt == -2)
		unix_error("Open_clientfd DNS error");
	return rt;
}
コード例 #10
0
/******************************************
 * Wrappers for the client/server helper routines 
 ******************************************/
int Open_clientfd(char *hostname, int port) {
	int rc;

	if ((rc = open_clientfd(hostname, port)) < 0) {
		if (rc == -1)
			unix_error("Open_clientfd Unix error");
		else
			dns_error("Open_clientfd DNS error");
	}
	return rc;
}
コード例 #11
0
ファイル: proxy.c プロジェクト: samzcmu/proxy
/* open_serverfd_h is a wrapper for open_clientfd and handles errors. */
int open_serverfd_h(struct client_request *request, int clientfd)
{
	int serverfd;
	
	serverfd = open_clientfd(request->host, request->server_port);
	if (serverfd >= 0)
		return serverfd;
	if (serverfd == -1)  /* socket_error */
		close_connection(request, clientfd, -1);
	if (serverfd == -2)  /* DNS error */
		clienterror(clientfd, "http address", "404", "Not found",
					"Proxy could not find server");
	close_connection(request, clientfd, -1);
	abort(); /* flow should never reach here */
}
コード例 #12
0
ファイル: proxy.c プロジェクト: HELLOWORLDxN/CSAPP-3
void *proxy(void *vargp) {
	Pthread_detach(Pthread_self());

	int serverfd;
	int clientfd = *(int *)vargp;
	free(vargp);

	rio_t rio;
	rio_readinitb(&rio, clientfd);

	struct status_line status;

	char buf[MAXLINE];
	int flag;

#ifdef PROXY_CACHE
	char objectbuf[MAX_OBJECT_SIZE];
#endif

	if ((flag = rio_readlineb(&rio, buf, MAXLINE)) > 0) {
		if (parseline(buf, &status) < 0)
			fprintf(stderr, "parseline error: '%s'\n", buf);
#ifdef PROXY_CACHE
		else if (cacheable(&status) &&
				(flag = cache_find(status.line, objectbuf))) {
			if (rio_writen(clientfd, objectbuf, flag) < 0)
				log(cache_write);
		}
#endif
		else if ((serverfd =
					open_clientfd(status.hostname, status.port)) < 0)
			log(open_clientfd);
		else {
			if ((flag = send_request(&rio, buf,
							&status, serverfd, clientfd)) < 0)
				log(send_request);
			else if (interrelate(serverfd, clientfd, buf, flag
#ifdef PROXY_CACHE
						,objectbuf, &status
#endif
						) < 0)
				log(interrelate);
			close(serverfd);
		}
	}
	close(clientfd);
	return NULL;
}
コード例 #13
0
ファイル: proxy.c プロジェクト: Viredery/web_proxy
void doit(int fd)
{
	int clientfd, port, size = 0;
	ssize_t linecounter;
	rio_t client_rio, server_rio;
	char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE], serveraddr[MAXLINE], path[MAXLINE], message[MAXLINE];
	//read the HTTP request
	rio_readinitb(&client_rio, fd);
	rio_readlineb(&client_rio, buf, MAXLINE);
	sscanf(buf, "%s %s %s", method, uri, version);
	if(strcasecmp(method, "GET") != 0)
	{
		clienterror(fd, method, "501", "Not Implemented", "Proxy does not implement this method");
		return;
	}
	read_requesthdrs(&client_rio);
	//parse it to determine the name of the end server
	port = parse_uri(uri, serveraddr, path);
	//filter
	if(is_blocked_address(serveraddr))
	{
		clienterror(fd, serveraddr, "403", "Forbidden", "Proxy does not access this server");
		return;
	}
 	//open a connection to the end server
	if((clientfd = open_clientfd(serveraddr, port)) < 0)
	{
		clienterror(fd, serveraddr, "404", "Not Found", "Proxy does not found this server");
		return;
	}
	//send it the request
	sprintf(message, "GET %s HTTP/1.0\r\n", path);
	rio_writen(clientfd, message, strlen(message));
	sprintf(message, "HOST: %s\r\n\r\n", serveraddr);
	rio_writen(clientfd, message, strlen(message));
	//receive the reply, and forward the reply to the browser if the request is not blocked.
	rio_readinitb(&server_rio, clientfd);
	while((linecounter = rio_readlineb(&server_rio, message, MAXLINE)) != 0)
	{
		rio_writen(fd, message, linecounter);
		size += linecounter;
	}
	//log
	sem_wait(&mutex);
	log_report(serveraddr, size);
	sem_post(&mutex);
}
コード例 #14
0
ファイル: client.c プロジェクト: jtresman/networking
//Verify the Username is Corret
int verifyUser(){

    int i = 0;

    int servfd = 0;

    char command[MAXLINE];
    char res[3];

    sprintf(command, "VERIFY %s %s\n", userName, passwd);


    printf("Verifing User! %s %s\n", userName, passwd );

    while ((servfd = open_clientfd("localhost", servers[i].port)) < 0 && i<NUM_SERVERS){

        i++;

    }

    if (servfd > 0){
        write(servfd, command, strlen(command));

        readline(servfd, res, 2);

        // printf("We read: %s %d\n", res, strncmp(res, "1", 1));

        if(strncmp(res, "1", 1) == 0){
            printf("User Verified!\n");
            return 1;
        }  else {

            printf("User Not Verified! Please Check Your Credentials\n");

        }
    } else {
        printf("We could not connect to any server to verify user!\n");
        exit(0);
    }

    close(servfd);

    return 0;
}
コード例 #15
0
ファイル: csapp.c プロジェクト: zihaol1/15-712-simple-proxy
/******************************************
 * Wrappers for the client/server helper routines 
 ******************************************/
int Open_clientfd(char *hostname, int port, char *origin_request_line, char *origin_host_header) 
{
    int rc;

    if ((rc = open_clientfd(hostname, port)) < 0) {
        if (rc == -1)
            unix_error("Open_clientfd Unix error");
        else {
            dns_error("Open_clientfd DNS error");
            fprintf(stderr, "Original Request Line: %s", origin_request_line);
            fprintf(stderr, "Original Host Header: %s", origin_host_header);
            fprintf(stderr, "Parsed Host: %s\n", hostname);
            fprintf(stderr, "Parsed Port: %d\n", port);
            fprintf(stderr, "Ok, That's fine.\n");
            fprintf(stderr, "Our proxy will send customized response.\n\n");
        }
    }
    return rc;
}
コード例 #16
0
void query(){
    char buf[MAXLINE];
    char in[MAXLINE];
    char cmd[MAXLINE];
	char ip[MAXLINE], ports[MAXLINE], keyy[MAXLINE];
    rio_t client;
    
    printf("Please intput the filename:\n");
    int dummy = scanf("%s",in);
    strcpy(filename,in);
    
    //decide re-download
    for (int i = 0; i < 10; i++) {
        if(filenames[i] != NULL && strcmp(filenames[i],in)==0){
            rep_flag=1;
            break;
        }
    }
    
    unsigned key = hashFunction(filename);
    sprintf(buf, "Query q q %u\r\n", key);
    clientfd = open_clientfd(NodeIP, NodePort);
    if (clientfd == -1) {
        printf("The IP and port you entered is not in the ring.\n");
        exit(1);
    }
    Rio_writen(clientfd, buf, strlen(buf));
    memset(buf, 0, sizeof(buf));
    
    Rio_readinitb(&client, clientfd);
    while(1) {
        Rio_readlineb(&client,buf,MAXLINE);
        if (strcmp(buf, "finish\r\n") == 0) {
            break;
        }
        sscanf(buf, "%s %s %s %s", cmd, ip, ports, keyy);
        if (strcmp(cmd, "ResQuery") == 0) {
            //NodeIP = strdup(ip);
            NodePort = atoi(ports);
        }
    }
    close(clientfd);
}
コード例 #17
0
ファイル: access_client.c プロジェクト: fallenworld/Access
int main(int argc, char* argv[])
{
    int ret = 0;
    /* check arguments */
    if (argc != 3)
    {
        puts("Usage : access_client server_address key");
        return 1;
    }
    for (;;)
    {
        /* connect to the server*/
        printf("Connecting to the server %s\n", argv[1]);
        int fd = open_clientfd(argv[1]);
        if (fd < 0)
        {
            puts("Connect failed, reconnect later");
            sleep(2);
            continue;
        }
        puts("Connect server successfully");
        /* authentic */
        puts("Being authenticated by the server...");
        ret = authenticate(fd, argv[2]);
        if (ret < 0)
        {
            puts("Server disconncted, reconnect later");
            sleep(2);
            continue;
        }
        else if (ret == 1)
        {
            puts("Key is not correct");
            exit(1);
        }
        else if (ret == 0)
        {
            handle_connection(fd);
        }
    }
    return 0;
}
コード例 #18
0
ファイル: proxy.c プロジェクト: swananan/Wu-CSAPP
int connect_server(char *hostname,int port,char *query_path)
{
    char buf[MAXLINE];
    int proxy_clientfd;
    proxy_clientfd=open_clientfd(hostname,port);
    
    if(proxy_clientfd<0)
        return proxy_clientfd;
    
    //按照http协议,向服务器发送请求 见书P635
    sprintf(buf,"GET %s HTTP/1.0\r\n",query_path);
    Rio_writen(proxy_clientfd,buf,strlen(buf));
    sprintf(buf,"Host: %s\r\n",hostname);
    Rio_writen(proxy_clientfd,buf,strlen(buf));
    Rio_writen(proxy_clientfd,user_agent,strlen(user_agent));
    Rio_writen(proxy_clientfd,accept_str,strlen(accept_str));
    Rio_writen(proxy_clientfd,connection,strlen(connection));
    Rio_writen(proxy_clientfd,"\r\n",strlen("\r\n"));
    return proxy_clientfd;
}
コード例 #19
0
ファイル: client.c プロジェクト: leonshao/network
int main(int argc, char** argv) {
	int clientfd, port;
	char *hostname;

	if (argc != 3) {
		printf("Usage: %s hostname/ip port\n", argv[0]);
		return EXIT_FAILURE;
	}

	hostname = argv[1];
	port = atoi(argv[2]);
	if ((clientfd = open_clientfd(hostname, port)) < 0) {
		return EXIT_FAILURE;
	}

	send_and_recv(clientfd);

	close(clientfd);

	return EXIT_SUCCESS;
}
コード例 #20
0
ファイル: proxy.c プロジェクト: yihanwan/15513
/* 
 * proxy as a client to connect server,
 * return clientfd, if clientfd < 0, means failed 
 */
int connect_server(char *hostname, char *port, char *query){
    char buf[MAXLINE];
    int clientfd = open_clientfd(hostname, port);

    /* connection failed */
    if(clientfd < 0)
        return clientfd;

    /* send http request */
    sprintf(buf, "GET %s HTTP/1.0\r\n", query);
    Rio_writen(clientfd, buf, strlen(buf));
    sprintf(buf, "Host: %s\r\n", hostname);
    Rio_writen(clientfd, buf, strlen(buf));
    Rio_writen(clientfd, user_agent_hdr, strlen(user_agent_hdr));
    Rio_writen(clientfd, accept_hdr, strlen(accept_hdr));
	Rio_writen(clientfd, accept_encoding_hdr, strlen(accept_encoding_hdr));
    Rio_writen(clientfd, connection_hdr, strlen(connection_hdr));
	Rio_writen(clientfd, proxy_connection_hdr, strlen(proxy_connection_hdr));
    Rio_writen(clientfd, "\r\n", strlen("\r\n"));
    return clientfd;
}
コード例 #21
0
ファイル: client.c プロジェクト: jtresman/networking
//LIST
void listFiles(){

    char command[MAXLINE];
    char buf[MAXLINE];

    int i = 0;
    int servfd;

    sprintf(command, "LIST %s %s\n", userName, passwd);

    //Find an avalible Server
    while ((servfd = open_clientfd("localhost", servers[i].port)) < 0 && i<NUM_SERVERS){
        i++;
    }

    if (servfd < 0){
        printf("No Servers avalible!\n");
        return;
    }

    write(servfd, command, strlen(command));

    while(readline(servfd, buf, MAXLINE)){

        // printf("Line %s\n", buf );

        if(strncmp(buf, "Done", 4) == 0){
            // printf("Done Reading!\n");
            break;
        } else if(strncmp(buf, "Error", 5) == 0){
            printf("%s\n", buf);
            break;
        } else {
            printf("%s", buf);
        }
    }

    close(servfd);
}
コード例 #22
0
ファイル: reduceFunction.cpp プロジェクト: Jiaran/MapReduce
void reduceFunction::getMapInfo(){
for(std::map<int,mapNode>::iterator it=mapAddress.begin(); it!=mapAddress.end(); ++it){
	int fd;
	//int cound=0;
	while(true){
		fd=open_clientfd(it->second.mapIp, it->second.mapPort);
		if(fd<0){
			/*if(cound==3){
	NodeInfo newNode("8080", "10.0.2.15");
	changeInfo(1, newNode);
			}*/
			printf("Node is missing.\n"); 
			sleep(1);
			//cound++;
			continue;	
      		}
		else{
			//break;

			std::cout<<"geting map info"<<std::endl;
			char buf_s[80];
			sprintf(buf_s,"GETMAP %d\n",it->first);
	      		Rio_writep(fd, buf_s, strlen(buf_s));
			char buf_r[80];
			char * saveptr=NULL;
			int numBytes;
			rio_t t;
			Rio_readinitb( &t,fd);
			bool finished=false;
			std::map<std::string, int> tempMap;
			while(numBytes = Rio_readlineb(&t, buf_r, MAXLINE)>0){
	  			if(numBytes<=0){
						std::cout<<"close fd"<<std::endl;
						break;
	  			}
				printf("numBytes is %d\n", numBytes);
	  			char* r1 = strtok_r(buf_r, "*",&saveptr);

				char r_name[80];
				strcpy(r_name,r1);
				std::string s_name(r_name);
				if(s_name=="FINISH"){
					finished=true;
					break;
				}
				char* r2 = strtok_r(NULL, "*",&saveptr);
				int r_num=atoi(r2);
				tempMap[s_name]+=r_num;
				//std::cout<<r_num<<std::endl;
			}
			if(finished){
				for(std::map<std::string,int>::iterator tempit=tempMap.begin(); tempit!=tempMap.end(); ++tempit){
					myMap[tempit->first]=tempit->second;
				}
				break;
			}
			continue;
		}
	}
		
	}
}
コード例 #23
0
ファイル: client.c プロジェクト: jtresman/networking
//GET 
void getFile(char * filename){

    unsigned char * buf;
    char path[PATH_MAX];
    char command[MAXLINE];

    int fd, i, len;
    int servfd = -1;

    //Add Path onto File Name
    strcat(path, "./");
    strcat(path, filename);


    //Send Command to Reposive Server
    while ((servfd = open_clientfd("localhost", servers[i].port)) < 0 && i<NUM_SERVERS){
        i++;
    }

    if (servfd < 0){
        printf("No Servers avalible!\n");
        exit(0);
    }

    sprintf(command, "GET %s %s %s\n", userName, passwd, filename);

    write(servers[i].fd, command, strlen(command));

    //Open File for Writing
    fd = open(filename, O_RDWR | O_CREAT, S_IRWXU);
    if (fd == -1) {
        printf("Error opening file!\n");
        exit(1);
    } 

    buf = (unsigned char *)malloc(sizeof(unsigned char)*15);

    //Read the File Length
    readline(servers[i].fd, buf, MAXLINE);
    if(strncmp(buf, "Error", 5) == 0){
        printf("%s", buf);
        free(buf);
        close(fd);
        return;
    }

    len = atoi(buf);

    //Read File from server
    buf = (unsigned char *) realloc(buf, sizeof(unsigned char)*len);

    read(servers[i].fd, buf, len);

    if(strncmp(buf, "Error", 5) == 0){
        printf("%s", buf);
        free(buf);
        close(fd);
        return;
    }

    //Write Line to File
    write(fd, buf, len);

    //Close File
    close(fd);
}
コード例 #24
0
ファイル: chatclient.c プロジェクト: panxiuqing/Learn-Program
int main(int argc, char *argv[])
{
  WINDOW *send_win, *people_win;
  win_s send, people;
  int ch;

  int port, i = 0;
  char *host, *name;
  pthread_t read_pid;
  pt_s pt;
  if (argc != 4) {
    fprintf(stderr, "usage: %s <host> <port> <nickname>\n", argv[0]);
    return 0;
  }
  host = argv[1];
  port = atoi(argv[2]);
  for (i = 0; i < strlen(argv[3]); i++) {
      pt.wbuf[i] = argv[3][i];
  }

  fprintf(stdout, "OK in 46\n");

  // setlocale(LC_ALL, "zh_CN.UTF-8");
  initscr();
  raw();
  echo();
  keypad(stdscr, TRUE);

  if(has_colors() == FALSE) {
    endwin();
    printf("Your terminal does not support color\n");
    return 1;
  }
  start_color();
  init_pair(1, COLOR_GREEN, COLOR_BLACK);
  init_pair(2, COLOR_YELLOW, COLOR_BLACK);
  init_pair(3, COLOR_BLUE, COLOR_BLACK);
  init_pair(4, COLOR_CYAN, COLOR_BLACK);

  send.height = 5;
  send.width = COLS - 20;
  send.startx = 0;
  send.starty = LINES - 5;

  refresh();
  
  send_win = create_newwin(send, "SEND");

  refresh();
  pt.clientfd = open_clientfd(host, port);
  Rio_readinitb(&(pt.rio), pt.clientfd);
  pt.wbuf[strlen(argv[3])] = '\n';
  Rio_writen(pt.clientfd, pt.wbuf, strlen(pt.wbuf));
  pt.wbuf[strlen(argv[3])] = ':';
  
  pthread_create(&read_pid, NULL, read_thread, &pt);

  int name_len = strlen(argv[3]) + 1;
  while (mvwgetnstr(send_win, 0, 0, pt.wbuf + name_len, MAXLINE - name_len) != ERR) {
    pt.wbuf[strlen(pt.wbuf)] = '\n';
    Rio_writen(pt.clientfd, pt.wbuf, strlen(pt.wbuf));
    bzero(pt.wbuf + name_len, MAXLINE - name_len);
    werase(send_win);
  }

  endwin();
  return 0;
}
コード例 #25
0
ファイル: tiny.c プロジェクト: mallochine/fics-proxy
void doit(int clientfd) 
{
    //
    // Code to deal with the client
    //
    char buf[MAXLINE];
    rio_t client_rio;

    puts("INFO: Preparing JARVIS to receive from the client");
    Rio_readinitb(&client_rio, clientfd);

    //
    // Code to deal with FICS
    // 
    int serverfd = 0;
    rio_t server_rio;

    puts("INFO: Preparing JARVIS to receive from FICS");
    Rio_readinitb(&server_rio, serverfd);

    puts("INFO: Opening connection to FICS...");
    serverfd = open_clientfd("freechess.org", 5000);

    if (serverfd < 0) {
        puts("ERROR: Couldn't open connection to FICS!");
        return;
    }
    else
        puts("INFO: Connection to FICS was successful!");

    puts("INFO: Authenticating with FICS using login_key.txt...");
    authenticateClient(clientfd, serverfd);

    //
    // Code to deal with FICS <-> client back and forth
    //
    int numReadFromFICS = 0;
    int numReadFromClient = 0;

    puts("INFO: Creating threads to route traffic between FICS and client...");

    pthread_t fromClientId;
    pthread_t fromFICSId;

    route clientToFICS = {clientfd, serverfd};
    route FICSToClient = {serverfd, clientfd};

    // fromFICSId thread routes traffic from FICS to Client.
    // fromClientId thread routes traffic from Client to FICS.
    pthread_create(&fromFICSId, NULL, route_to, &FICSToClient);
    pthread_create(&fromClientId, NULL, routeClientToFICS, &clientToFICS);

//    pthread_join(fromFICSId, NULL);
    pthread_join(fromClientId, NULL);

    pthread_detach(fromClientId);
    pthread_detach(fromFICSId);

    Close(serverfd);

    printf("INFO: exiting doit\n");
}
コード例 #26
0
ファイル: agent.c プロジェクト: rebryant/Cloud-BDD
void init_agent(bool iscli, char *controller_name, unsigned controller_port,
		bool try_self_route, bool try_local_router) {
    operator_table = word_keyvalue_new();
    deferred_operand_table = word_keyvalue_new();
    size_t i;
    for (i = 0; i < NSTATA; i++)
	agent_stat_counter[i] = 0;

    chunk_ptr msg;
    bool eof;
    isclient = iscli;
    self_route = try_self_route;
    controller_fd = open_clientfd(controller_name, controller_port);
    if (controller_fd < 0)
	err(true, 
	    "Cannot create connection to controller at %s:%u",
	    controller_name, controller_port);
    else {
#if RPT >= 2
	report(2, "Connection to controller has descriptor %d", controller_fd);
#endif
    }
    msg = isclient ? msg_new_register_client() : msg_new_register_worker();
    bool sok = chunk_write(controller_fd, msg);
#if RPT >= 3
    report(3, "Sent %s registration to controller",
	   isclient ? "client" : "worker");
#endif
    chunk_free(msg);
    if (!sok)
	err(true, "Could not send registration message to controller");
    /* Get acknowledgement from controller */
    bool first = true;
    /* Anticipated number of routers 
      (Will be updated when get first message from controller) */
    nrouters = 1;
    chunk_ptr amsg = NULL;
    unsigned ridx = 0;;
    while (ridx < nrouters) {
	msg = chunk_read_unbuffered(controller_fd, &eof);
	if (eof) {
	    err(true,
		"Unexpected EOF from controller while getting router map");
	}
	word_t h = chunk_get_word(msg, 0);
	unsigned code = msg_get_header_code(h);
	switch (code) {
	case MSG_ACK_AGENT:
	    if (first) {
		own_agent = msg_get_header_agent(h);
		amsg = msg_new_register_agent(own_agent);
		nworkers = msg_get_header_workercount(h);
		nrouters = msg_get_header_wordcount(h);
		router_fd_array = calloc_or_fail(nrouters, sizeof(int),
						 "init_agent");
#if RPT >= 3
		report(3,
"Ack from controller.  Agent Id %u.  %d workers.  %d routers.",
		       own_agent, nworkers, nrouters);
#endif
		first = false;
	    }
	    int i;
	    for (i = 1; i < msg->length; i++) {
		word_t h = chunk_get_word(msg, i);
		int fd;
		unsigned ip = msg_get_header_ip(h);
		unsigned port = msg_get_header_port(h);
#if RPT >= 4
		report(4, "Attempting to add router %u with ip 0x%x, port %d",
		       ridx, ip, port);
#endif
		fd = open_clientfd_ip(ip, port);
		if (fd < 0) {
		    err(true, "Couldn't add router with ip 0x%x, port %d",
			ip, port);
		} else {
		    router_fd_array[ridx++] = fd;
#if RPT >= 3
		    report(3, "Added router %u with ip 0x%x, port %d, fd %d",
			   ridx, ip, port, fd);
#endif
		    if (!chunk_write(fd, amsg)) {
			err(true, 
"Couldn't send agent registration message to router with ip 0x%x, port %u",
			    ip, port);
		    }

                    if (try_local_router && local_router_fd == -1 &&
			match_self_ip(ip))
                    {
                        local_router_fd = fd;
#if RPT >= 5
                        report(5,
"Router with fd %d designated as local router and prioritized for sending packets",
			       fd);
#endif
                    }
		}
	    }
	    chunk_free(msg);
	    break;
	case MSG_NACK:
	    err(true, "Connection request refused.");
	    break;
	default:
	    err(false,
"Unexpected message code %u while getting router information", code);
	    chunk_free(msg);
	    break;
	}
    }
    chunk_free(amsg);
#if RPT >= 2
    report(2, "All %d routers connected", nrouters);
#endif
    if (isclient) {
	add_quit_helper(quit_agent);
	add_cmd("kill", do_agent_kill,
		"              | Shutdown system");
	add_cmd("flush", do_agent_flush,   
		"              | Flush system");
	add_cmd("collect", do_agent_gc,
		"              | Initiate garbage collection");
    } else {
	/* Worker must notify controller that it's ready */
	chunk_ptr rmsg = msg_new_worker_ready(own_agent);
	if (chunk_write(controller_fd, rmsg)) {
#if RPT >= 3
	    report(3, "Notified controller that worker is ready");
#endif
	} else {
	    err(true, "Couldn't notify controller that worker is ready");
	}
	chunk_free(rmsg);
    }
}
コード例 #27
0
ファイル: proxy.c プロジェクト: stale2000/Computer-Systems
/*
 *  * doit - handle one HTTP request/response transaction
 *
 */
void* doit(void* pt1) 
{
	//signal(SIGPIPE, SIG_IGN);
	pt_helper* pt = (pt_helper*)pt1;
	int fd = pt->connfd;
    int serverFile, amountRead;
    char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE],
		request[MAXLINE];
    char *host, *website, *filename;
	int port;
    rio_t rio, tmprio;
  
	counter++;

	website = uri;
	
    /* Read request line and headers */
    Rio_readinitb(&rio, fd);
    Rio_readlineb(&rio, buf, MAXLINE);
    sscanf(buf, "%s %s %s", method, uri, version);
	//some error checking.
	if(strcasecmp(method, "GET"))
	{
		clienterror(fd, method, "501", "Not Implemented",
			"FoxyProxy does not implement this method");
		Close(pt->connfd);
		free(pt);
		return NULL;
	}
	
	port = parse_website(&website,&filename,&host);
	int n; int found=0;
	for(n = 0; n < CACHEL; n++)
	{
		if(names[n] != NULL){
//		printf("blah blah %s\n",names[n]);
//		printf("foo foo %s\n",website);
		}
		if(names[n] != NULL && !strcmp(website, names[n]))
		{
			found = 1;
			break;
		}
	}
	if(found)
	{
		P(&mut);
		readLock++;
		if(readLock == 1)
		{
			P(&writeLock);
		}
		V(&mut);
	
		times[n] = counter;//time(NULL);
		rio_writen(fd, pages[n], sizes[n]);
		//close(serverFile);
		printf("cached!\n");
		
		P(&mut);
		readLock--;
		if(readLock == 0)
		{
			V(&writeLock);
		}
		V(&mut);
		

		Close(pt->connfd);
		free(pt);
		return NULL;
	}

	serverFile = open_clientfd(host, port);

	//add in request print stuff here
	strcpy(request, method);
	strcat(request, " ");
	strcat(request, filename);
	strcat(request, " HTTP/1.0\r\n");
	strcat(request, HTTPHDR);
	
	rio_writen(serverFile, request, strlen(request));
	//XXX
	//printf(request);
	
	send_requesthdrs(&rio, serverFile, host);

	rio_readinitb(&tmprio, serverFile);
	
	char* buf2 = (char*)malloc(MAX_OBJECT_SIZE);
	int totalRead = 0;
	while ( (amountRead = rio_readnb(&tmprio, buf, MAXBUF)) > 0 )
	{
		rio_writen(fd, buf, amountRead);
		if(totalRead+amountRead <= MAX_OBJECT_SIZE)
		{
			memcpy(buf2+totalRead,buf,amountRead);
		}
		totalRead+=amountRead;
	}

	amountRead = totalRead;
		
	//TODO lock cache
	//FIXME how to delete enough stuff?
	if(amountRead <= MAX_OBJECT_SIZE)
	{
	//	printf("Lock: %d\n", writeLock);
		P(&writeLock);
	//	printf("Lock2: %d\n", writeLock);

		if(amountRead + cachesize <= MAX_CACHE_SIZE)
		{
			time_t lowtime = counter;//time(NULL);
			int leastrecent = -1;
			int n;
			for(n = 0; n < CACHEL; n++)
			{
				if(times[n] < lowtime)
				{
					leastrecent = n;
					lowtime = times[n];
				}
				if(pages[n] == NULL)
				{
					leastrecent = n;
					break;
				}
			}
			n = leastrecent;
			if(pages[n] != NULL)
			{
				free(pages[n]);
				pages[n] = NULL;
				free(names[n]);
				names[n] = NULL;
			}
			void* page = (void*)malloc(amountRead);
			memcpy(page, buf2, amountRead);
			printf("page: \n");
			printf("%s",page);
			char* website_cpy = (char*)malloc(strlen(website)+1);
			strncpy(website_cpy,website,strlen(website));
			website_cpy[strlen(website)]='\0';
			pages[n] = page;
			times[n] = counter;//time(NULL);
			cachesize-=sizes[n];
			sizes[n] = amountRead;
			cachesize+=amountRead;
			names[n] = website_cpy;
		}
		else
		{
			while(cachesize + amountRead > MAX_CACHE_SIZE)
			{
				time_t lowtime = counter;//time(NULL);
				int leastrecent = -1;
				int n;
				for(n = 0; n < CACHEL; n++)
				{
					if(times[n] < lowtime && pages[n] != NULL)
					{
						leastrecent = n;
						lowtime = times[n];
					}
				}
				
				n = leastrecent; 

				free(pages[n]);
				pages[n] = NULL;
				free(names[n]);
				names[n] = NULL;
				cachesize -= sizes[n];
				sizes[n] = 0;
				times[n] = 0;
			}
			int n;
			for(n = 0; n < CACHEL; n++)
			{
				if(pages[n] == NULL) break;
			}
			void* page = (void*)malloc(amountRead);
			memcpy(page, buf2, amountRead);
			pages[n] = page;
			char* website_cpy = (char*)malloc(strlen(website));
			strncpy(website_cpy,website,strlen(website));
			times[n] = counter;//time(NULL);
			names[n] = website_cpy;
			sizes[n] = amountRead;
			cachesize += amountRead;
		}
		V(&writeLock);
	//TODO unlock cache
	}
	free(buf2);
	close(serverFile);
	Close(pt->connfd);
	free(pt);
	return NULL;
}
コード例 #28
0
int main(int argc, char *argv[]){

  int target_port,local_port;
  char *target_ip,*local_ip;
  if(argc !=5){
	  printf("please enter arguments in format:./name target_ip,target_port,local_ip,local_port\n");
  }
  target_ip = argv[1]; // reserver ip information for future extension
  target_port = atoi(argv[2]);
  local_ip =argv[3];
  local_port = atoi(argv[4]);
  // printf("the target ip is :%s\nthe target port is:%d\n",target_ip,target_port);

  //start listening
  int args[2];
  args[0] = local_port;
  args[1] = target_port;
  pthread_t hear;
  Pthread_create(&hear,NULL,start_listen,(void*)args);
  Pthread_detach(hear);

  //create connectionfd with server
  int targetfd;
  targetfd = open_clientfd(target_ip,target_port);
  if(targetfd < 0){
    printf("targetfd error!\n");
    return EXIT_FAILURE;
   }
 
  char *cmd, *signature;
  //hand shake start

  //_____________send client hello infromation to server with protocol infromation_______________
  char content[MAXLINE];
  sprintf(content, "ClientHello,sslv2.0");
  rio_writen(targetfd,content,strlen(content));
  //receive response from server, confirm protocol
  int len;
  char answer[MAXLINE];
  len = rio_readp(targetfd,answer,MAXLINE);
  printf("content received from server is: %s\n",answer);
  if(strstr(answer,"ServerHello")!=NULL){
    printf("hello ends\n");
  }

  //______________________DH exchange___________________________
  int dh_g = 3;
  int dh_b = 7;
  int dh_a = 0;
  int *g_ptr = &dh_g;
  int *a_ptr = &dh_a;
  int *b_ptr = &dh_b;
  DH_change_client (targetfd, g_ptr, a_ptr,b_ptr);
  printf("After DH function: g is %d,a is %d,b is %d\n", dh_g, dh_a, dh_b);

 //receive ditial singature from server and authenticate
  len = rio_readp(targetfd,answer,MAXLINE);
    for(int i = 0;i<strlen(answer)-1;i++){
    answer[i] = answer[i]+dh_a;
  }
  cmd = strtok_r(answer,",",&signature);
  printf("signature is %s\n",signature);
  if(strcmp(signature,target_ip) == 0){
    printf("digital signature verified\n");
  }


  //create private key-public key pair and send public key to server uisng DH method
  int p = 11;
  int q = 19;
  int public_n;
  int public_e;
  int private_n;
  int private_d;
  int *public_n_ptr = &public_n;
  int *private_n_ptr = &private_n;
  int *public_e_ptr = &public_e;
  int *private_d_ptr = &private_d;
    
  RSA_generate(p,q,public_n_ptr,private_n_ptr,public_e_ptr,private_d_ptr);
  printf("public <n,e> = <%d,%d>\n", public_n, public_e);
  printf("private <n,d> = <%d,%d>\n", private_n, private_d);
  
  
   memset(content,0,sizeof(content));
  sprintf(content,"ClientKeyExchange,RSA %d %d,TLSv1",p,q);
  for (int i = 0; i<strlen(content);i++){
    content[i] = content[i]+dh_a;
  }
  rio_writen(targetfd,content,strlen(content));


  //__________________first talk______________________
  //receive infromation from server and decryption by RSA method
  memset(answer, 0, sizeof(answer));
  len = rio_readp(targetfd,answer,MAXLINE);
  char count_buffer[MAXLINE];
  memset(count_buffer, 0, sizeof(count_buffer));
  len = rio_readp(targetfd, count_buffer, MAXLINE);
  int word_count = atoi(count_buffer);
  printf("word count is: %d\n", word_count);
  char *decrypt = NULL;
  long long *ip2 = (long long *)answer;
  decrypt = decryption(ip2, word_count, private_n);
  printf("After decryption:%s\n", decrypt);



  //______________second talk_______________________
  memset(content,0,sizeof(content));
  sprintf(content,"ClientFinish");
  //encryption
  int ans_len = strlen(content);
  long long *ip = NULL;
  word_count = 0;
  int *word_count_ptr = &word_count;
  ip = encryption(content,ans_len, word_count_ptr, public_e, public_n);
  printf("Before encryption: %s\n", content);
  printf("After encryption,send:");
  char *ch = (char*)ip;
  printf("%s\n", ch);
//send content
  rio_writen(targetfd,ch,sizeof(ch)*word_count);
  //send word count
  memset(content, 0, sizeof(content));
  sprintf(content, "%d", word_count);
  printf("word count: %s\n", content);
  rio_writen(targetfd, content, sizeof(content));
  memset(content, 0, sizeof(content));
  printf("===============hand shake ends==================\n");
 
 
  printf("please input your message now\n\n");
  //start talking
  while (1){
    //send information to server
    printf("Client:");
    memset(content, 0, sizeof(content));
    scanf("%s", content);
    ans_len = strlen(content);
    ip = NULL;
    word_count = 0;
    word_count_ptr = &word_count;
    ip = encryption(content, ans_len, word_count_ptr, public_e, public_n);;
    char *ch = (char*)ip;
    //send content
    rio_writen(targetfd, ch, sizeof(ch)*word_count);
    //send word count
    memset(content, 0, sizeof(content));
    sprintf(content, "%d", word_count);
    rio_writen(targetfd, content, sizeof(content));
    memset(content, 0, sizeof(content));
    
    
    //receive information from server
    printf("Server:");
    memset(answer, 0, sizeof(answer));
    len = rio_readp(targetfd, answer, MAXLINE);
    if (strcmp(answer, "You end the talk. Sever disconnect.") == 0){
      printf("%s\n", answer);
      break;
    }
    memset(count_buffer, 0, sizeof(count_buffer));
    len = rio_readp(targetfd, count_buffer, MAXLINE);
    word_count = atoi(count_buffer);
    decrypt = NULL;
    ip2 = (long long *)answer;
    decrypt = decryption(ip2, word_count, private_n);
    printf("%s\n", decrypt);
  }
  close (targetfd);
  return EXIT_SUCCESS;
}
コード例 #29
0
ファイル: client.c プロジェクト: shengbolou/server-client
int main(){
  int clientfd = open_clientfd("elnux1.cs.umass.edu",48579);
  if(clientfd < 0){
    printf("%s\n", "connection error");
  }
  else{
    printf("%s\n","connected");

    FILE* file = Fdopen(clientfd,"a+");
    //send spire id
    printf("%s\n", "Sending Spire ID...." );
    fprintf(file, "28530995");
    //get question
    char* line = NULL;
    int count;
    getline(&line,&count,file);
    //print out question: the question is IDX
    printf("%s", "the question is");
    printf("%s\n", line);
    //get str and idx
    char *str;
    int idx;
    count= sscanf(line, "IDX%ms%d", &str, &idx);
    if(count == EOF){
      printf("%s\n", "sscanf error");
    }
    //calculate the answer
    char result = IDX(str,idx);
    //finish using str and line, free str and line
    free(str);
    free(line);
    line = NULL;

    //write the answer to server
    printf("sending answer: %c\n", result);
    fprintf(file, "%c\n", result);
    //receive msg from server, get line again
    getline(&line,&count,file);
    //print out msg
    printf("%s\n", line);
    //free the line and set line to NULL
    free(line);
    line=NULL;

    //write bonus to server
    fprintf(file, "%s\n", "HW9");

    //get bonus result
    getline(&line,&count,file);
    printf("%s\n", "The result is ");
    printf("%s\n", line);
    //free line and set it to NULL
    free(line);
    line = NULL;

    //close  file and clientfd
    Fclose(file);
    close(clientfd);
    printf("%s\n", "disconnect from server");
  }

}
コード例 #30
0
ファイル: main.c プロジェクト: DCPagan/cs352proxy
int main(int argc, char **argv){
	char *c;
	unsigned short port;
	thread_param tp;
	pthread_t eth_tid, tap_tid;
	
	char *remote_host;
	int remote_port;
	char *local_interface;

	if(argc != 4 || argc != 3){
		printf("Error\n\t Usage for first proxy:\n\t\t cs352proxy <port> <local interface> \n\t Usage for second proxy: \n\t\t cs352proxy <remote host> <remote port> <local interface>\n");
	return -1;
	}

	switch(argc){
		// 1st proxy
		case 3:
			for(c=argv[1]; isdigit(*c)||*c=='\0'; c++);
			if(*c=='\0'){
				tp.ethfd=atoi(argv[1]);
				if(tp.ethfd<1024||tp.ethfd>65535){
					perror("ERROR: port must be from "
						"1024-65535.\n");
					exit(1);
				}
				port=(unsigned short)tp.ethfd;
			}
			else{
				perror("ERROR: port parameter "
					"not a decimal number.\n");
				exit(1);
			}
			if((tp.ethfd=open_listenfd(port))<0){
				perror("error opening ethernet device\n");
				exit(1);
			}
			if((tp.tapfd=allocate_tunnel(argv[2], IFF_TAP|IFF_NO_PI))<0){
				perror("error opening tap device\n");
				exit(1);
			}

			/**
			  * 1st thread listens to TCP socket
			  * 2nd thread listens to tap device
			  */

			Pthread_create(&eth_tid, NULL, eth_thread, &tp);
			Pthread_create(&tap_tid, NULL, tap_thread, &tp);
			Pthread_join(eth_tid, NULL);
			Pthread_join(tap_tid, NULL);
			close(tp.ethfd);
			close(tp.tapfd);
			break;

		// 2nd proxy
		case 4:
			for(c=argv[2]; isdigit(*c)||*c=='\0'; c++);
			if(*c=='\0'){
				tp.ethfd=atoi(argv[2]);
				if(tp.ethfd<1024||tp.ethfd>65535){
					perror("ERROR: port must be from "
						"1024-65535.\n");
					exit(1);
				}
				port=(unsigned short)tp.ethfd;
			}
			else{
				perror("ERROR: port parameter "
					"not a decimal number.\n");
				exit(1);
			}
			if((tp.ethfd=open_clientfd(argv[1], port))<0){
				perror("error opening ethernet device\n");
				exit(1);
			}
			if((tp.tapfd=allocate_tunnel(argv[3], IFF_TAP|IFF_NO_PI))<0){
				perror("error opening tap device\n");
				exit(1);
			}

			/**
			  * 1st thread listens to TCP socket
			  * 2nd thread listens to tap device
			  */

			Pthread_create(&eth_tid, NULL, eth_thread, &tp);
			Pthread_create(&tap_tid, NULL, tap_thread, &tp);
			Pthread_join(eth_tid, NULL);
			Pthread_join(tap_tid, NULL);
			close(tp.ethfd);
			close(tp.tapfd);
			break;
		default:
			perror("ERROR: invalid parameters.\n");
			exit(1);
	}
	return 0;
}