Exemple #1
0
void Verifier::recv_plain_answers() {
  for (int beta = 0; beta < batch_size; beta++) {

    FILE *fp = NULL;

    // if optimized format is used, fetch everything at once
    if (optimize_answers) {
      char f_name[BUFLEN];
      snprintf(f_name, BUFLEN - 1, "answers_%d", beta + 1);
      recv_file(f_name);
      continue;
    }

    // else, fetch one by one
    string consistency_answer_str = "f_consistency_answer_b_%d";
    snprintf(scratch_str, BUFLEN - 1, consistency_answer_str.c_str(), beta);
    recv_file(scratch_str);
    for (int rho = 0; rho < num_repetitions; rho++) {
      // NOTE: assumes X is a single digit!
      string answer_str = "qX_qquery_answer_b_%d_r_%d";
      for (uint32_t i = 0; i < num_lin_pcp_queries; i++) {
        answer_str[1] = '0' + i;
        snprintf(scratch_str, BUFLEN - 1, answer_str.c_str(), beta,
                 rho);
        recv_file(scratch_str);
      }
    }

    if (fp != NULL)
      fclose(fp);
  }
}
Exemple #2
0
/** get file from ftp server **/
void do_get_cli(char recv_buf[], char send_buf[], char file_buf[],
                int server_sockfd, int file_sockfd)
{
    int ret;
    struct cmd_type_header* cmd_hdr = (struct cmd_type_header*)send_buf;
    struct cmd_result_header* result_hdr = (struct cmd_result_header*)recv_buf;

    printf("** send GET cmd\n");

    memset(recv_buf, 0, BUF_SIZE);
    ret = check_file_for_recv(cmd_hdr->cmd_argv, recv_buf);

    if (ret < 0)
        printf("get: %s", recv_buf);
    else
    {
        send(server_sockfd, send_buf, BUF_SIZE, 0);

        memset(recv_buf, 0, BUF_SIZE);
        recv(server_sockfd, recv_buf, BUF_SIZE, 0);

        printf("%s", result_hdr->ret_result);

        if (result_hdr->ret_status == SUCCESS)
        {
            recv_file(cmd_hdr->cmd_argv, file_sockfd, file_buf);
        }
    }
}
Exemple #3
0
void			read_client(t_serv *serv, int cs)
{
  char			str[4096];
  pid_t			pid;

  pid = fork();
  if (pid == 0)
    {
      while (1)
	{
	  memset(str, 0, 4096);
	  if (read(cs, str, 4096) != 0)
	    {
	      if (strcmp(EXIT, str) == 0)
		client_disconnect(serv, cs);
	      if (strcmp(str, GET) == 0)
		send_file(cs);
	      else if (strcmp(str, PUT) == 0)
		recv_file(cs);
	      else
		function_exec(serv, str, cs);
	    }
	}
    }
  return ;
}
//download a file from server
void fileDownload(uchar *fileName, int socket)
{
    FILE *fp;
    uchar buffer[BUFFER_SIZE];
    //ssize_t RecvBytes;
    int size;
	bzero(buffer,BUFFER_SIZE);
	printf("fileName=%s\n",fileName);
	if((fp=fopen(fileName,"wb"))==NULL)
	{
		printf("File Open Error!\n");
		exit(1);
	}
    //printf("Cleint. RECV\n");
    while(1)
	{
	    if(recv_file(buffer, &size, socket)==0)
	    {
	        printf("buffer=%s\tsize=%d\n",buffer,size);
	        system("clear");
	        printf("download successfully\n");
	        //printf("size=%d\n",size);
	        fwrite(buffer,size * sizeof(unsigned char),1,fp);
	        break;
	    }
	    printf("size=%d\n",size);
        fwrite(buffer,size * sizeof(unsigned char),1,fp);
        bzero(buffer,BUFFER_SIZE);

	}
	fclose(fp);
}
Exemple #5
0
void Verifier::recv_comm_answers() {
#if NONINTERACTIVE == 1
  for (int beta = 0; beta < batch_size; beta++) {
    string answer_str = "f_answers_G1_b_%d";
    snprintf(scratch_str, BUFLEN - 1, answer_str.c_str(), beta);
    recv_file(scratch_str);
    answer_str = "f_answers_G2_b_%d";
    snprintf(scratch_str, BUFLEN - 1, answer_str.c_str(), beta);
    recv_file(scratch_str);
  }
#else
  for (int beta = 0; beta < batch_size; beta++) {
    string commitment_answer_str = "f_commitment_answer_b_%d";
    snprintf(scratch_str, BUFLEN - 1, commitment_answer_str.c_str(), beta);
    recv_file(scratch_str);
  }
#endif
}
Exemple #6
0
/* FIXME doc */
static void *compile_file(void *state)
{
    thread_state_t *thread_state = (thread_state_t *)state;

    process_file_t *file = NULL;

    /* Set a timeout on the socket */
    if (set_timeout(thread_state->cli_fd) < 0)
        goto exit_thread;

    file = process_file_new();

    if (recv_argv(thread_state->cli_fd,
                  &thread_state->argc, &thread_state->argv) < 0)
        goto exit_thread;

    if (recv_file(thread_state->cli_fd, file->input_name) < 0)
        goto exit_thread;

    update_argv_file(thread_state->argc,
                     thread_state->argv,
                     file->input_name,
                     file->output_name);

    /* TODO : put it somewhere else */
    for (int i = 0; i < thread_state->argc; ++i)
        printf("%s ", thread_state->argv[i]);
    printf("\n");
    /* END TODO */

    file->result = compile_without_preprocess(thread_state->argc,
                                              thread_state->argv);
    if (!file->result)
        goto exit_thread;

    if (send_compile_result(thread_state->cli_fd, file->result) == -1)
    {
        printf("[multi deamon] Can not send compile result\n");
        goto exit_thread;
    }

    if (!file->result->status)
    {
        if (send_file(thread_state->cli_fd, file->output_name) < 0)
        {
            printf("[multi deamon] Can not send compiled file\n");
            goto exit_thread;
        }
    }

exit_thread:
    if (file)
        process_file_free(&file);

    return end_thread(&thread_state);
}
Exemple #7
0
int client::download()
{
    int res = 0;

    char file_name[BUFFSIZE] = {0};
    if(m_cmd.size() < 2)
    {
        do
        {
            cout << "file name: ";
            cout.flush();

            cin.getline(file_name, BUFFSIZE);

        }while(file_name[0] == '\0');
    }
    else
    {
        strncpy(file_name, m_cmd[1], BUFFSIZE);
    }

    m_buff.clear();

    // Add the pack type.
    m_buff.push_back(PT_DWREQ);

    // Add the filename.
    add_buff(file_name, strlen(file_name));

    // Add checkcode.
    m_analyser.load_data(m_buff);
    m_buff.push_back(m_analyser.check());

    if(-1 == send_data())
    {
        ;// Send error.
    }

    char pack_type = acceptable();
    if( is_pack_type(PT_OK, pack_type) )
    {
        if(-1 == recv_file_info() )
        {
            return -1;// Recv error.
        }

        res = recv_file();
    }
    else if( is_pack_type(PT_FNOEXIST, pack_type) )
    {
        cout << "file not exist" << endl;;
    }

    return res;
}
Exemple #8
0
int pasv_handler(int work_sockfd, char* ip, int port, char* fileName, int retr_stor) {
	int sockfd;
	struct sockaddr_in addr;
	int ok_flag;
	
	if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
		printf("Error socket(): %s(%d)\n", strerror(errno), errno);
		ok_flag = 1;
	}
	
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = port;
	if (inet_pton(AF_INET, ip, &addr.sin_addr) <= 0) {
		printf("Error inet_pton(): %s(%d)\n", strerror(errno), errno);
		ok_flag = 1;
	}
	
	if (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		printf("Error connect(): %s(%d)\n", strerror(errno), errno);
		ok_flag = 1;
	}
	
	if (ok_flag == 1) {
		close(sockfd);
		waiting_for(work_sockfd, "");
		return 1;
	}
	
	if (retr_stor == 0) {
		char *tmp_str = waiting_for(work_sockfd, "");
		char num[256];
		strcpy(num, split(tmp_str, " ", 2)[0]);
		if (strcmp(num, "150") != 0) {
			return 1;
		}
		
		if (recv_file(work_sockfd, sockfd, fileName) == 1) {
			close(sockfd);
			return 1;
		}
	} else {
		if (send_file(work_sockfd, sockfd, fileName) == 1) {
			close(sockfd);
			return 1;
		}
	}
	
	close(sockfd);
	
	return 0;
}
Exemple #9
0
int main()
{
    monitor_t m;
    init_monitor(&m);

    pthread_create(&m.id, NULL, monitor_thread, &m);

    recv_file(&m);

    pthread_join(m.id, NULL);

    return 0;
}
Exemple #10
0
void do_put(char recv_buf[], char send_buf[], char file_buf[],
            char current_dir[], char processed_path[],
            int client_sockfd, int file_sockfd)
{
    printf("## PUT cmd ##\n");
    int ret;
    struct cmd_type_header* cmd_hdr = (struct cmd_type_header*)recv_buf;

    ret = check_put(cmd_hdr->cmd_argv, send_buf, current_dir, processed_path);
    send(client_sockfd, send_buf, BUF_SIZE, 0);
    if (ret == 0)
    {
        recv_file(processed_path, file_sockfd, file_buf);
    }
}
Exemple #11
0
int main(int argc, char** argv) {
    FILE* db = fopen(".nitdb", "r");
    if(db == NULL) {
        FILE* temp = fopen(".nitdb", "w");
        fclose(temp);
    }
    int socket_fd = 0, conn_fd =0;
    struct sockaddr_in server_addr;
    socket_fd = socket(PF_INET, SOCK_STREAM, 0);
    if(socket_fd == -1) 
        err_handler("Failed to get socked file descriptor");
    /* Zero the IPV6 compatibility bits */
    memset(&server_addr, '0', sizeof(server_addr));
    memset(&buf, '\0', sizeof(buf));
    memset(&cmd_buf, '\0', sizeof(cmd_buf));

    server_addr.sin_family = AF_INET;
    /* Standardize endian-ness */
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT_NUM);
    if(bind(socket_fd, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1)
        err_handler("Failed to bind port");
    if(listen(socket_fd, 10) == -1)
        err_handler("Failed to listen on port");

    while(1) {
        conn_fd = accept(socket_fd, (struct sockaddr*) NULL, NULL);
        printf("ACCEPTED");
        /* Recieve opcode */
        while(recv(conn_fd, cmd_buf, BUF_SIZE, NO_FLAGS) > 0) 
        {
            send(conn_fd, ACK, strlen(ACK), NO_FLAGS);
            memset(buf, '\0', sizeof(buf));
            if(recv(conn_fd, buf, BUF_SIZE, NO_FLAGS) <= 0) {
                close(conn_fd);
                break;
            }
            send(conn_fd, ACK, strlen(ACK), NO_FLAGS);
            /* Take action */
            if(strcmp(cmd_buf, OP_SEND_FILE) == 0)
                recv_file(conn_fd);
            if(strcmp(cmd_buf, OP_GET_FILE) == 0) 
                send_file(conn_fd);
        }
        close(conn_fd);
    }
    return 0;
}
Exemple #12
0
void do_server(char const *port)
{
	struct addrinfo *ai = get_bind_addrinfo(port);
	assert(ai);
	int lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if (lfd == -1) {
		perror("socket");
		goto out_addrinfo;
	}
	int optval = 1;
	if (-1 == setsockopt(
		lfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
	{
		perror("setsockopt");
		goto out_socket;
	}
	if (-1 == bind(lfd, ai->ai_addr, ai->ai_addrlen)) {
		perror("bind");
		goto out_socket;
	}
	if (-1 == listen(lfd, 5)) {
		perror("listen");
		goto out_socket;
	}
	while (true) {
		struct sockaddr_storage remaddr;
		socklen_t sin_size = sizeof(remaddr);
		int newfd = accept(lfd, (struct sockaddr *)&remaddr, &sin_size);
		if (-1 == newfd) {
			perror("accept");
			continue;
		}
#if 0
		if (-1 == shutdown(newfd, SHUT_WR)) {
			perror("shutdown");
		}
#endif
		while (recv_file(newfd));
		if (-1 == close(newfd)) {
			perror("close");
			break;
		}
	}
out_addrinfo:
	freeaddrinfo(ai);
out_socket:
	verify(-1 != close(lfd));
}
//接收一个目录,没有则创建,有则清空
void recv_dir(char *dir_path)
{
	int file_count;
	int ret;
	DIR * dir;
	struct dirent *dir_info;
	char *file_path = NULL;
	//判断文件夹是否存在
	if((dir = opendir(dir_path)) != NULL)
	{
		//若存在则清空文件
		file_path = (char *)malloc(sizeof(char)*FILE_PATH_LEN);
		while((dir_info = readdir(dir)) != NULL)
		{
			if(strcmp(dir_info->d_name,".")!=0&&strcmp(dir_info->d_name,"..")!=0)
			{
				memset(file_path,'\0',sizeof(char)*FILE_PATH_LEN);
				strcpy(file_path,dir_path);
				strcat(file_path,dir_info->d_name);
				remove(file_path);
			}
		}
		free(file_path);
	}
	else
	{
		//若不存在则创建该文件夹
		if(mkdir(dir_path,0775) == -1)
		{
			fprintf(stderr,"mkdir %s failed\n",dir_path);
			return ;
		}
	}
	//接收文件个数
	ret = recv_time_out(cli_serial_num,(char *)&file_count,sizeof(int));
	if(ret == -1)
	{
		fprintf(stderr,"recv error\n");
		return ;
	}
	//根据文件个数循环调用recv_file
	for(;file_count >0;file_count--)
	{
		recv_file(dir_path);
	}
}
int
main(int argc, char **argv)
{
	int rv;

	UploadLogInit();
	parse_args(argc, argv);

	net_init();

	log("%s: listening on port %d for image data from %s (max of %llu bytes)",
	    path, portnum, inet_ntoa(clientip), maxsize);

	rv = recv_file();
	close(sock);

	exit(rv);
}
Exemple #15
0
int port_handler(int work_sockfd, int listenfd, int port, char* fileName, int retr_stor) {
	int connfd;
	char buffer[8192];
	int recv_len, write_len;
	FILE *fp;
	
	if (retr_stor == 0) {
		char *tmp_str = waiting_for(work_sockfd, "");
		char num[256];
		strcpy(num, split(tmp_str, " ", 2)[0]);
		if (strcmp(num, "150") != 0) {
			close(listenfd);
			return 1;
		}
	
	}
	
	if ((connfd = accept(listenfd, NULL, NULL)) == -1) {
		printf("Error accept(): %s(%d)\n", strerror(errno), errno);
		waiting_for(work_sockfd, "");
		close(listenfd);
		return 1;
	}
	
	if (retr_stor == 0) {
		if (recv_file(work_sockfd, connfd, fileName) == 1) {
			close(connfd);
			close(listenfd);
			return 1;
		}
	} else {
		if (send_file(work_sockfd, connfd, fileName) == 1) {
			close(connfd);
			close(listenfd);
			return 1;
		}
	}
		
	close(connfd);
	close(listenfd);
	
	return STATUS_OK;
}
/*************************************************************************
	int DownloadFile(int server_fd,char* filename)
	func   :  recieve file from server
	return :
*************************************************************************/
int DownloadFile(int server_fd,char* filename)
{
	int bytes_recv = 0;
	char response_type[20];
	char response_argu[20];
	FILE* file_to_recv;
	int server_send_fd;

	memset(buffer,'\0',BUF_SIZE);			//clear the buffer before use
	sprintf(buffer,"request;downloadfile;%s;%s|",current_directory,filename);
	if(send(server_fd,buffer,strlen(buffer),0)==-1)
		printf("GetConnection send package error! \n");

	memset(buffer,'\0',BUF_SIZE);			//clear the buffer before use
	if(recv(server_fd,buffer,BUF_SIZE,0)>0){	
		response_analysis(buffer,response_type,response_argu);
		if(strncmp(response_type,"ack",3)==0){
			printf("file exist now begin to download\n");
			server_send_fd = get_data_connection();		//get data channel connection to server
			if((file_to_recv=fopen(filename,"w"))==NULL){
				printf("can not open the file to recv! \n");
				return -1;
			}
			if((bytes_recv = recv_file(server_send_fd,file_to_recv)) == -1){
				printf("recieve package error \n");
				return -1;
			}
			printf("%d bytes recieved \n",bytes_recv);
			close_data_connection(server_send_fd);		//close data channel connection to server
			return 1;
		}
		else{
			printf("file not exist \n");
			return 0;
		}
	}
	else{
		printf("server has been shutdown\n");
		return -1;
	}
}
Exemple #17
0
//此线程用于接收来自汇聚节点的文件
void *start_server1()
{
        int     sockfd;


        sockfd = init_socket_client("/root/onesafe/code/jun/conf9");
        if(sockfd < 0)
        {
                printf("init_socket_client error\n");
        }

        while(1)
        {
                if(recv_file(sockfd) < 0)
                {
                        printf("send_file error\n");
                }

                sleep(3);
        }

}
Exemple #18
0
static int	get_response(int sockfd, char *dst, t_param *param)
{
	uint32_t	magic;

	if (!(recv_data(sockfd, &magic, sizeof(magic))))
	{
		param->to_deco = 1;
		printf(RECV_MAGIC_CONF_FAIL "\n");
		return (0);
	}
	if (magic != MAGIC_CONF_SUCCESS)
	{
		printf(MAGIC_CONF_INVALID "\n");
		return (0);
	}
	if (!(recv_file(sockfd, dst)))
	{
		printf(RECV_FILE_FAIL "\n");
		return (0);
	}
	return (1);
}
Exemple #19
0
/**
 * Called when a new thread is created.
 * Receives the init packet and then the data packets.
 * Exits when done or if communication with client is lost.
 **/
void * do_threading(void * ptr) {
    int                     sock_num = (int) ptr;
    struct sockaddr_in      cli_addr;
    FILE *                  p_file = malloc(sizeof(FILE));
    init_pkt_t *            p_init_pkt = malloc(INIT_PKT_SZ);
    
    //debug_max("-------- new thread -----------\n");
    /* Receive the init packet */
    // Keep trying to receive the init pointer
    // How many times should we try this?
    int init_res = RES_NO_DATA;
    while (init_res != RES_SUCCESS) {
        init_res = recv_init(sock_num, &cli_addr, &p_init_pkt, &p_file);
        //debug_max("do_threading()/recv_init: init_res = %i\n", init_res);
        
        if (init_res == RES_NO_DATA) {
            debug_errors("do_threading(): did not receive init packet from client; exiting\n");
            return NULL;
        } else if (init_res == RES_FILE_ERR) {
            debug_errors("do_threading(): could not open file for writing; exiting\n");
            return NULL;
        }
    
    }
    if (init_res != RES_SUCCESS) {
        debug_errors("do_threading(): could not get the init packet; exiting\n");
        return NULL;
    }
    
    /* Receive the data packets */
    recv_file(sock_num, &cli_addr, p_init_pkt->hdr.file_len, p_init_pkt->hdr.buffer_sz, p_file);
    
    fclose(p_file);
    free(p_init_pkt);
    
    //debug_max("do_threading(): finished with this client\n");
    
    return NULL;
}
Exemple #20
0
/* FIXME doc */
static int client_retrieve_data()
{
    if ((config->result = recv_compile_result(config->socket_fd)) == NULL)
    {
        ERROR_MSG("Error: Can not receive compiler state from the server\n");
        close(config->socket_fd);

        return -1;
    }

    if (!config->result->status)
    {
        if (recv_file(config->socket_fd, config->file->output_file) < 0)
        {
            ERROR_MSG("Error: Can not receive compiled file from the server\n");
            close(config->socket_fd);

            return -1;
        }
    }

    return 0;
}
Exemple #21
0
int main(int argc, char ** argv )
{
	int i,ret;
	int fd,sockfd;
	tftp_t req = {0};  //用于发送读写请求
	tftp_t ack = {0};
	int reqlen = 0;
	struct sockaddr_in server = {0}; //服务器端地址
	struct sockaddr_in sender = {0};
	int addrlen = sizeof(sender);

	if( argc < 4 )   //参数不够
	{
		fprintf(stderr,"usage: tftp <server IP> <get|put> <file name>\n");
		return -1;
	}
	
	//设置服务器地址
	server.sin_family = AF_INET;
	server.sin_port = htons(SERVER_PORT);
	server.sin_addr.s_addr = inet_addr(argv[1]);
	if( INADDR_NONE == server.sin_addr.s_addr)
	{
		fprintf(stderr,"IP addr invalid");
		return -1;
	}
	//创建套接字	
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if( sockfd < 0 )
	{
		perror("socket");
		return -1;
	}
	
	if( 0 == strcmp(argv[2], "get") )  //下载文件,覆盖现有文件
	{
		fd = open(argv[3], O_WRONLY | O_CREAT | O_TRUNC, 0644); 
		if( fd < 0 )
		{
			perror("open");
			goto ERROR_OUT;
		}
		reqlen = fill_request( &req, RRQ, argv[3], "octet" );

		ret = send_request(sockfd, &server, &req, reqlen); //发送请求
		if( ret < 0 )
			goto ERROR_OUT;
		
		ret = recv_file(sockfd, fd, &server, argv[2]); //接收文件
		if( 0 != ret )
			goto ERROR_OUT;
	}
	else if( 0 == strcmp(argv[2], "put") ) //上传文件
	{
		fd = open(argv[3], O_RDONLY );
		if( fd < 0 )
		{
			perror("open");
			goto ERROR_OUT;
		}
		reqlen=fill_request( &req,WRQ,argv[3],"octet");

		for(i=1;i<=3; i++ )
		{
			ret = send_request(sockfd, &server, &req, reqlen); //发送请求
			if( ret < 0 )
				goto ERROR_OUT;

			addrlen = sizeof(sender);
			recvfrom(sockfd, &ack, sizeof(ack),0,(SAP)&sender,&addrlen); 

			if( sender.sin_addr.s_addr == server.sin_addr.s_addr )
			{
				if( ntohs(ack.opcode) == ACK  &&  0 == ntohs(ack.be.block) )
					break;   //收到0号确认,服务器启用新端口,新地址放在sender

				if( ntohs(ack.opcode) == ERROR )
				{
					fprintf(stderr,"ERROR code %d: %s\n",
								 ntohs(ack.be.error), ack.data);
					goto ERROR_OUT;
				}
			}
			if( 3 == i )
				goto ERROR_OUT;
		}

		ret = send_file(sockfd, fd, &sender, argv[2]);  
		if( 0 != ret )
			goto ERROR_OUT;
	}
	else
	{
		fprintf(stderr,"usage: client <server IP> <get|put> <filename>\n");
		return -1;	
	}

	close(fd);
	close(sockfd);
	return 0;

ERROR_OUT:
	if( sockfd > 0 )
		close(sockfd);
	if ( fd > 0 )
		close(fd);
	return -1;
} //end of main()
Exemple #22
0
int main(int argc, char *argv[])
{
	const char *portname = "/dev/ttyUSB0";
	const char *pending_cmd = NULL;
	int ret = -1;
	int arg = 1;
	int fd;

	if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
		usage(argv[0]);

	if (!strcmp(argv[arg], "-d")) {
		arg++;
		if (argv[arg] != NULL)
			portname = argv[arg];
		else
			invarg(argc, argv, arg);
		arg++;
	}

	fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
	if (fd < 0) {
		fprintf(stderr, "open %s: ", portname);
		perror("");
		return 1;
	}

	setup(fd);

	send_cmd_check_k(fd, "    *T");

	for (; arg < argc; arg++) {
		if (!strcmp(argv[arg], "-f")) {
			arg++;
			if (argv[arg] == NULL)
				invarg(argc, argv, argc);
			if (pending_cmd == NULL)
				// assume game upload
				pending_cmd = "*g";

			ret = send_file(fd, argv[arg], pending_cmd);
			if (ret)
				return ret;

			pending_cmd = NULL;
			continue;
		}
		if (argv[arg + 1] && !strcmp(argv[arg + 1], "-f")) {
			/* we'll avoid sending command if there are
			 * problems with specified file */
			pending_cmd = argv[arg];
			continue;
		}
		/* custom OS commands */
		if (!strcmp(argv[arg], "*xd")) {
			unsigned int addr, size;
			if (arg + 3 >= argc)
				invarg(argc, argv, argc);
			addr = strtoul(argv[++arg], NULL, 0);
			size = strtoul(argv[++arg], NULL, 0);
			ret = recv_file(fd, argv[++arg], addr, size);
			if (ret)
				return ret;

			continue;
		}

		/* passthrough */
		ret = send_cmd_check_k(fd, argv[arg]);
	}

	return ret;
}
Exemple #23
0
//创建新SOCKET,打开/创建文件,具体文件传输由recv_file()和send_file()实现
int service( tftp_t * req, struct sockaddr_in * peer)
{
	int sockfd;
	int fd;
	int ret;

	int opcode = ntohs(req->opcode);
	char * filename = (char*)&(req->be);
	char * mode = NULL;

	mode = filename;
	while(*mode++); //暂时统一按octet模式
	
	//用新的SOCKET与客户端传递数据
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if( sockfd < 0 )
	{
		perror("socket");
		return -1;
	}	
	
	if(RRQ==opcode)   //客户读请求,下载
	{
		if( access(filename, F_OK))  //文件不存在
		{
			send_error(sockfd,peer,ENOTFOUND);
			goto ERROR_OUT;
		}

		fd = open(filename,O_RDONLY); //读方式打开
		if( fd < 0 )
		{
			perror("open");
			send_error(sockfd, peer, EACCESS);
			goto ERROR_OUT;
		}

		ret = send_file(sockfd, fd, peer, mode); //开始发送数据
		if( ret < 0 )
			goto ERROR_OUT;
	}
	else if( WRQ == opcode )  //客户端写请求,上传
	{
		fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644); 
		if( fd < 0 )
		{
			perror("open");
			send_error(sockfd, peer, EEXISTS); //文件已存在
			goto ERROR_OUT;
		}
		
		send_ack(sockfd, peer, 0);    //发送0号确认
		
		ret = recv_file(sockfd, fd, peer, mode); //接收文件数据
		if( ret < 0 )
			goto ERROR_OUT;
	}
	else    //非法操作码
	{
		send_error(sockfd,peer,EBADOP);
		goto ERROR_OUT;
	}

	close(fd);	
	close(sockfd);
	return 0;

ERROR_OUT:
	if( fd > 0 )
		close(fd);
	if( sockfd > 0 )
		close(sockfd);
	return -1;
}
Exemple #24
0
void main()
{
	int sfd = tcp_connect();
	int epfd = epoll_create(1);
	struct epoll_event evs[2];
	memset(evs,0,sizeof(struct epoll_event));
	epfd_add(sfd,epfd);  
	epfd_add(0,epfd);                        //注册epoll
	char buf[1024];
	char filename[20] = {0};
	char *pname;
	int ret;
	int n;
	int i;
	loginServer(sfd);
	while(1)
	{
		memset(evs,0,sizeof(struct epoll_event));
		n = epoll_wait(epfd,evs,2,-1);
		if(n > 0)
		{
			for(i = 0; i < n; i++)
			{
				if(evs[i].data.fd == 0)
				{
					memset(buf,0,sizeof(buf));
					ret = read(0,buf,sizeof(buf));
					if(ret == 0)//ctrl+d
					{
						printf("bye\n");
						close(sfd);
						exit(0);
					}
					send(sfd,buf,strlen(buf)-1,0);
					if(strncmp("puts",buf,4) == 0)
					{
						memset(filename,0,sizeof(filename));
						strcpy(filename,buf+4);
						pname = filename;
						while(*pname == ' ') pname++;
						send_file(sfd,pname);
					}
				}
				if(evs[i].data.fd == sfd)
				{
					if(strncmp("gets",buf,4) == 0)
					{
						memset(buf,0,sizeof(buf));
						recv(sfd,buf,1,0);
						if(buf[0] == '1')
						{
							 recv_file(sfd);
						}
						else if(buf[0] == '2')
						{
							 mmaprecefile(sfd);
						}
						else
							printf("file not exist\n");
					}
					else
					{
						memset(buf,0,sizeof(buf));
						ret =recv(sfd,buf,sizeof(buf),0);
						if(ret == 0)
						{
							printf("bye sfd\n");
							close(sfd);
							exit(-1);
						}
						system("clear");
						printf("%s\n",buf);
					}
				}
			}
		}
	}
	close(sfd);
	return;
}
Exemple #25
0
int main()
{
	char HOME[128];
	int client_len;
	struct sockaddr_in client_address;
	int result;
	fd_set readfds, testfds;

	struct sigaction act;
	act.sa_handler = sigint_handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGINT, &act, 0);

	get_home_dir(HOME);
	printf("HOME:%s\n", HOME);

	//global variable server_sockfd will be set.
	create_server_socket();

	FD_ZERO(&readfds);
	FD_SET(server_sockfd, &readfds);

	while(1) {
		char buf[128];
		int fd;
		int nread;
	
		testfds = readfds;

		printf("server waiting\n");
		result = select(FD_SETSIZE, &testfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0);

		if(result < 1) {
			perror("ftp_server");
			exit(1);
		}

		for(fd = 0; fd < FD_SETSIZE; fd++) {
			if(FD_ISSET(fd, &testfds)) {
				if(fd == server_sockfd) {//有新来的客户链接
					client_len = sizeof(client_address);
					client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
					FD_SET(client_sockfd, &readfds);
					client[client_sockfd].cmd_sockfd = client_sockfd;
					client[client_sockfd].sin_addr.s_addr = client_address.sin_addr.s_addr;
					sprintf(client[client_sockfd].cwd, "/");
					printf("adding client on fd %d\n", client_sockfd);
					sprintf(buf, "220 (wxftp 1.0)\r\n");
					write(client_sockfd, buf, strlen(buf));
				} else {//客户链接发来数据
					ioctl(fd, FIONREAD, &nread);
					if(nread == 0) {//无数据可读,表示客户已主动断开链接
						close(fd);
						memset(&client[fd], 0, sizeof(struct Client));
						FD_CLR(fd, &readfds);
						printf("removing client on fd %d\n", fd);
					} else {//读取数据并当作命令来处理。
						read(fd, buf, nread);
						buf[nread] = '\0';
						printf("serving client on fd %d: %s\n", fd, buf);
						if(strncmp(buf, "USER", 4) == 0) {
							sscanf(&buf[4], "%s", client[fd].user);
							//printf("user %s\n", client[fd].user);
							sprintf(buf, "331 Password required for %s.\r\n", client[fd].user);
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "PASS", 4) == 0) {
							sscanf(&buf[4], "%s", client[fd].pass);
							if (authenticate(client[fd].user, client[fd].pass) == 0) {
								client[fd].authorized = 1;
								sprintf(buf, "230 Login successful.\r\n");
							} else {
								client[fd].authorized = 0;
								sprintf(buf, "530 Login or Password incorrect.\r\n");
							}
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "SYST", 4) == 0) {
							sprintf(buf, "215 Linux.\r\n");
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "FEAT", 4) == 0) {
							sprintf(buf, "550 Not support.\r\n");
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "PWD", 3) == 0) {
							sprintf(buf, "257 \"%s\" is current directory.\r\n", client[fd].cwd);
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "CWD", 3) == 0) {
							char dir[128];
							sscanf(&buf[3], "%s", dir);
							if (strncmp(dir, "..", 2) == 0) {
								if(strlen(client[fd].cwd) == 1) {
									sprintf(buf, "250 \"/\" is current directory.\r\n");
								} else {
									int i;
									char *cwd = client[fd].cwd;
									int len = strlen(cwd);
									for(i = len - 1; i >= 0; i--) {
										if(cwd[i] == '/' && i != len - 1) {
											cwd[i+1] = '\0';
											break;
										}
									}
									sprintf(buf, "250 CWD command successful. \"%s\" is current directory.\r\n", client[fd].cwd);
								}
							} else if(file_exist(client[fd].cwd, dir) == 0) {
								//client[fd].cwd = ;
								char *cwd = client[fd].cwd;
								int len = strlen(cwd);
								if(cwd[len-1] == '/') {
									sprintf(&client[fd].cwd[len], "%s", dir);
								} else {
									sprintf(&client[fd].cwd[len], "/%s", dir);
								}
								sprintf(buf,"250 CWD command successful. \"%s\" is current directory.\r\n",client[fd].cwd );
							} else {
								sprintf(buf,"550 CWD failed. \"%s\": no such file or directory.\r\n", dir);
							}
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "CDUP", 4) == 0) {
							if(strlen(client[fd].cwd) == 1) {
								sprintf(buf, "250 \"/\" is current directory.\r\n");
							} else {
								//make some change to client[fd].cwd
								int i;
								char *cwd = client[fd].cwd;
								int len = strlen(cwd);
								printf("%s: %d\n", cwd, len);
								for(i = len - 1; i >= 0; i--) {
									printf("%d: %c\n", i, client[fd].cwd[i]);
									if(client[fd].cwd[i] == '/' && i != len - 1) {
										client[fd].cwd[i+1] = '\0';
										break;
									}
								}
								sprintf(buf, "250 \"%s\" is current directory.\r\n",client[fd].cwd);
							}
							write(fd, buf, strlen(buf));
						} else if (strncmp(buf, "MKD", 3) == 0) {
							char dir[128];
							sscanf(&buf[3], "%s", dir);
							if (file_exist(client[fd].cwd, dir) == 0) {
								sprintf(buf, "550 Command failed. %s exists.\r\n", dir);
								write(fd, buf, strlen(buf));
							} else {
								make_dir(client[fd].cwd, dir);
								sprintf(buf, "250 Command ok. %s made.\r\n", dir);
								write(fd, buf, strlen(buf));
							}
						} else if (strncmp(buf, "RMD", 3) == 0) {
							char dir[128];
							sscanf(&buf[3], "%s", dir);
							if (file_exist(client[fd].cwd, dir) == 0) {
								remove_dir(client[fd].cwd, dir);
								sprintf(buf, "250 Command ok. %s removed.\r\n", dir);
								write(fd, buf, strlen(buf));
							} else {
								sprintf(buf, "550 Command failed. %s doesn't exist.\r\n", dir);
								write(fd, buf, strlen(buf));
							}
						} else if (strncmp(buf, "RNFR", 4) == 0) {
							char dir[128];
							sscanf(&buf[4], "%s", dir);
							if (file_exist(client[fd].cwd, dir) == 0) {
								sscanf(&buf[4], "%s", client[fd].rnfr);
								sprintf(buf, "350 File exists, ready for destination name.\r\n");
								write(fd, buf, strlen(buf));
							} else {
								sprintf(buf, "550 File/directory not found.\r\n");
								write(fd, buf, strlen(buf));
							}
						} else if (strncmp(buf, "RNTO", 4) == 0) {
							char dir[128];
							sscanf(&buf[4], "%s", dir);
							if (file_exist(client[fd].cwd, dir) == 0) {
								sprintf(buf, "550 Comman failed. %s exists.\r\n", dir);
								write(fd, buf, strlen(buf));
							} else {
								rename_dir(client[fd].cwd, client[fd].rnfr, dir);
								sprintf(buf, "250 File rename successfully.\r\n");
								write(fd, buf, strlen(buf));
							}
						} else if(strncmp(buf, "TYPE", 4) == 0) {
							char type[10];
							sscanf(&buf[4], "%s", type);
							sprintf(buf, "200 Type set to %s.\r\n", type);
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "PASV", 4) == 0) {
							int port = rand() % 1000 + 8000;
							client[fd].data_port = port;
							client[fd].mode = kDataConnModePassive;
							struct sockaddr_in name;
							int name_len = sizeof(struct sockaddr_in);
							getsockname(fd, (struct sockaddr*)&name, &name_len);
							printf("server ip address is : %s\n port: %d\n", inet_ntoa(name.sin_addr), port);
							sprintf(buf, "227 Entering Passive Mode (210,25,132,182,%d,%d)\r\n", port / 256, port % 256);
							write(fd, buf, strlen(buf));
							int sockfd = data_conn_passive(port);
							printf("PASV sockfd: %d\n", sockfd);
							client[fd].data_sockfd = sockfd;
						} else if(strncmp(buf, "PORT", 4) == 0) {
							int ip[4], port[2];
							sscanf(&buf[4], "%d,%d,%d,%d,%d,%d", &ip[0], &ip[1], &ip[2], &ip[3], &port[0], &port[1]);
							sprintf(client[fd].data_ip, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
							client[fd].data_port = port[0] * 256 + port[1];
							client[fd].mode = kDataConnModeActive;
							printf("IP:%s, Port:%d\n", client[fd].data_ip, client[fd].data_port);
							sprintf(buf, "200 Port command successful.\r\n");
							write(fd, buf, strlen(buf));
						} else if(strncmp(buf, "LIST", 4) == 0 || strncmp(buf, "NLST", 4) == 0) {
							int sockfd;
							if(client[fd].mode == kDataConnModeActive) {
								sockfd = data_conn_active(&client[fd].sin_addr, client[fd].data_port);
							} else if (client[fd].mode == kDataConnModePassive) {
								//sockfd = data_conn_passive(client[fd].data_port);
								sockfd = client[fd].data_sockfd;
							}
							int result = 0;
							if (sockfd != -1) {
								sprintf(buf,"150 Opening data connection for directory list.\r\n");
								write(fd, buf, strlen(buf));
								if(send_list(sockfd, client[fd].cwd) == 0) {
									sprintf(buf, "226 Transfer ok.\r\n");
								} else {
									sprintf(buf, "550 Error encountered.\r\n");
								}
								write(fd, buf, strlen(buf));
								close(sockfd);
							} else {
								printf("CREATE DATA_CONN FAILE.\n");
							}
						} else if (strncmp(buf, "RETR", 4) == 0) {
							char filename[64];
							sscanf(&buf[4], "%s", filename);
							if(file_exist(client[fd].cwd, filename) != 0) {
								sprintf(buf, "550 \"%s\": no such file.\r\n", filename);
								write(fd, buf, strlen(buf));
							} else {
								int sockfd;
								if(client[fd].mode == kDataConnModeActive) {
									sockfd = data_conn_active(&client[fd].sin_addr, client[fd].data_port);
								} else if (client[fd].mode == kDataConnModePassive) {
									sockfd = data_conn_passive(client[fd].data_port);
								}
								int result = 0;
								if (sockfd != -1) {
									sprintf(buf, "150 Opening data connection for %s\r\n", filename);
									write(fd, buf, strlen(buf));
									char filedir[128];
									int len = strlen(client[fd].cwd);
									if(client[fd].cwd[len-1] == '/') {
										sprintf(filedir, "%s%s%s", HOME, client[fd].cwd, filename);
									} else {
										sprintf(filedir, "%s%s/%s", HOME, client[fd].cwd, filename);
									}	
									result = send_file(sockfd, filedir);
									printf("send result: %d\n", result);
									if (result != -1) {
										close(sockfd);
										sprintf(buf, "226 File sent ok.\r\n");
										write(fd, buf, strlen(buf));
									}
								}
							}
						} else if (strncmp(buf, "STOR", 4) == 0) {
							char filename[64];
							sscanf(&buf[4], "%s", filename);
							int sockfd;
							if(client[fd].mode == kDataConnModeActive) {
								sockfd = data_conn_active(&client[fd].sin_addr, client[fd].data_port);
							} else if (client[fd].mode == kDataConnModePassive) {
								sockfd = data_conn_passive(client[fd].data_port);
							}
							int result = 0;
							if (sockfd != -1) {
								sprintf(buf, "150 Opening data connection for %s\r\n", filename);
								write(fd, buf, strlen(buf));
								char filedir[128];
								int len = strlen(client[fd].cwd);
								if(client[fd].cwd[len-1] == '/') {
									sprintf(filedir, "%s%s%s", HOME, client[fd].cwd, filename);
								} else {
									sprintf(filedir, "%s%s/%s", HOME, client[fd].cwd, filename);
								}	
								result = recv_file(sockfd, /*filename*/filedir);
								printf("recv result: %d\n", result);
								if (result != -1) {
									close(sockfd);
									sprintf(buf, "226 File received ok.\r\n");
									write(fd, buf, strlen(buf));
								}
							}
						} else if (strncmp(buf, "QUIT", 4) == 0) {
							sprintf(buf, "221 Goodbye.\r\n");
							write(fd, buf, strlen(buf));
							close(fd);
							memset(&client[fd], 0, sizeof(struct Client));
							FD_CLR(fd, &readfds);
							printf("removing client on fd %d\n", fd);
						} else {
							sprintf(buf, "550 Unknown command.\r\n");
							write(fd, buf, strlen(buf));
						}
					}
				}
			}
		}
	}
	return 0;
}
//执行接受操作
void recv_package()
{
	int i;
	int ret;
	int package_size = 0;
	int message_flag = 0;
	char recv_sig_buf = 0;

	//等待连续3次sig_start
	for(i=0; i<3; i++)
	{
		ret = recv_time_out(cli_serial_num,&recv_sig_buf,sizeof(char));
		if(ret == -1)
		{
			fprintf(stderr,"recv error\n");
			return ;
		}
		if(recv_sig_buf == sig_start)
		{
			recv_sig_buf = 0;
		}
		else
		{
			i = -1;
			recv_sig_buf = 0;
		}
	}

	//接收命令
	ret = recv_time_out(cli_serial_num,&recv_sig_buf,sizeof(char));
	if(ret == -1)
	{
		fprintf(stderr,"recv error\n");
		return ;
	}
	if(recv_sig_buf != CMD_RECV_MESSAGE)
	{
		fprintf(stderr,"recv %x\n",recv_sig_buf);
	}

	switch(recv_sig_buf)
	{
		case CMD_CONTACTS:
			fprintf(stderr,"wait recv contact\n");
			//接收通讯录
			recv_file("/tmp/ass/");
			break;
		case CMD_INSERT_CONTACT:
			break;
		case CMD_DELETE_CONTACT:
			break;
		case CMD_UPDATE_CONTACT:
			break;
		case CMD_MESSAGE:
			//接收短信的结构体至message_pack
			memset(&message_pack,'\0',sizeof(message_pack_t));
			fprintf(stderr,"wait recv message package_size\n");
			//接收package_size若超出结构体大小。则返回;否则接收
			ret = recv_time_out(cli_serial_num,(char *)&package_size,sizeof(int));
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			if(package_size > sizeof(message_pack_t))
			{
				fprintf(stderr,"package_size:%d\n",package_size);
				return ;
			}
			fprintf(stderr,"package_size: %d\n",package_size);
			ret = recv_time_out(cli_serial_num,(char *)&message_pack,package_size);
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			break;
		case CMD_SEND_MESSAGE:
			break;
		case CMD_APPINFO:
			fprintf(stderr,"wait recv appinfo\n");
			//接收应用信息appinfo.db3至指定路径
			recv_file("/tmp/ass/");		
			fprintf(stderr,"wait recv appicon\n");
			//接收应用图标
			recv_dir("/tmp/ass/icon/");
			break;
		case CMD_IMAGE:
			//接收图片信息至image_pack
			memset(&image_pack,'\0',sizeof(image_pack_t));
			fprintf(stderr,"wait recv image package_size\n");
			//接收package_size若超出结构体大小。则返回;否则接收
			ret = recv_time_out(cli_serial_num,(char *)&package_size,sizeof(int));
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			if(package_size > sizeof(image_pack_t))
			{
				fprintf(stderr,"error package_size:%d\n",package_size);
				return ;
			}
			fprintf(stderr,"package_size: %d\n",package_size);
			ret = recv_time_out(cli_serial_num,(char *)&image_pack,package_size);
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			//接收缩略图
			fprintf(stderr,"wait recv imageThumbnail\n");
			recv_dir("/tmp/ass/imageThumbnail/");
			break;
		case CMD_AUDIO:
			//接收音频信息至audio_pack
			memset(&audio_pack,'\0',sizeof(audio_pack_t));
			fprintf(stderr,"wait recv audio package_size\n");
			//接收package_size若超出结构体大小。则返回;否则接收
			ret = recv_time_out(cli_serial_num,(char *)&package_size,sizeof(int));
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			if(package_size > sizeof(audio_pack_t))
			{
				fprintf(stderr,"error package_size:%d\n",package_size);
				return ;
			}
			fprintf(stderr,"package_size: %d\n",package_size);
			ret = recv_time_out(cli_serial_num,(char *)&audio_pack,package_size);
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			break;
		case CMD_VIDEO:
			//接收视频信息至video_pack
			memset(&video_pack,'\0',sizeof(video_pack_t));
			fprintf(stderr,"wait recv video package_size\n");
			//接收package_size若超出结构体大小。则返回;否则接收
			ret = recv_time_out(cli_serial_num,(char *)&package_size,sizeof(int));
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			if(package_size > sizeof(video_pack_t))
			{
				fprintf(stderr,"error package_size:%d\n",package_size);
				return ;
			}
			fprintf(stderr,"package_size: %d\n",package_size);
			ret = recv_time_out(cli_serial_num,(char *)&video_pack,package_size);
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}
			fprintf(stderr,"%d\n",video_pack.count);
			//接收缩略图
			fprintf(stderr,"wait recv videoThumbnail\n");
			recv_dir("/tmp/ass/videoThumbnail/");
			break;
		case CMD_RECV_MESSAGE:
			//接收新短信标志
			ret = recv_time_out(cli_serial_num,(char *)&message_flag,sizeof(int));
			if(ret == -1)
			{
				fprintf(stderr,"recv error\n");
				return ;
			}

			//若未收到短信,则将信号清空
			if(message_flag == 0)
			{
				//若未收到短信,则清空标志
				recv_sig_buf = 0;
			}
			else
			{
				//若收到短信,则接收new_message结构体
				fprintf(stderr,"wait new message\n");
				memset(&new_message,'\0',sizeof(message_t));
				ret = recv_time_out(cli_serial_num,(char *)&new_message,sizeof(message_t));
				if(ret == -1)
				{
					fprintf(stderr,"recv error\n");
					return ;
				}
				fprintf(stderr,"new message:\n%s\n%s\n%s\n",new_message.message_name,new_message.message_date,new_message.message_body);
			}
			break;
		default:
			break;
	}
	//仅允许覆盖0x00与CMD_RECV_MESSAGE
	if(recv_cmd_flag == 0x00 || recv_cmd_flag == CMD_RECV_MESSAGE)
	{
		pthread_mutex_lock(&recv_flag_mutex);
		if(recv_sig_buf != 0x00)
		{
			fprintf(stderr,"recv_flag_lock\n");
		}
		recv_cmd_flag = recv_sig_buf;
		pthread_mutex_unlock(&recv_flag_mutex);
		if(recv_sig_buf != 0x00)
		{
			fprintf(stderr,"recv_flag_unlock\n");
		}
	}
	recv_sig_buf = 0;
}
Exemple #27
0
int serve(int *clientSocket, http_message *message)

{
	int bytecount = 0;
//	SLOG(INFO, "A new HTTP request has been received <%s>.", message->request_uri);

	if (message->request_uri)
	{
		if (strncmp(message->request_uri, URI_FILE, strlen(URI_FILE)) == 0)
		{
			std::string uri(message->request_uri);
			std::string app, filepath;
			
			std::size_t found = uri.find_first_of('/',strlen(URI_FILE));
			if(found)
			{
				app = uri.substr(strlen(URI_FILE),found - strlen(URI_FILE));
				filepath = uri.substr(found+1);			
			}

			if (message->method == 1)		// GET
			{

				bytecount = serve_file(clientSocket, message, filepath.c_str());

			}
			else if (message->method == 3)	// POST
			{

				bytecount = recv_file(clientSocket, message, filepath.c_str());
				if(bytecount>0)
				{
					onCMDEvent(app, filepath);
				}

			}
			else

			{

				bytecount = serve_error(clientSocket, "400 Bad Request");

			}

		}

		else if (strncmp(message->request_uri, URI_SIGCHECK, strlen(URI_SIGCHECK)) == 0)

		{

			char *filepath = message->request_uri + strlen(URI_SIGCHECK);



		//	bytecount = serve_sigcheck(clientSocket, message, filepath);

		}

		else if (strncmp(message->request_uri, URI_PING, strlen(URI_PING)) == 0)

		{

			bytecount = serve_ping(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_RUN, strlen(URI_RUN)) == 0)

		{

			char *filepath = message->request_uri + strlen(URI_RUN);



			bytecount = serve_run(clientSocket, message, filepath);

		}

		else if (strncmp(message->request_uri, URI_OPEN, strlen(URI_OPEN)) == 0)

		{

			char *filepath = message->request_uri + strlen(URI_OPEN);



			bytecount = serve_open(clientSocket, message, filepath);

		}

		else if (strncmp(message->request_uri, URI_EXPLORER, strlen(URI_EXPLORER)) == 0)

		{

	//		bytecount = serve_explorer(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_CLEANTEMP, strlen(URI_CLEANTEMP)) == 0)

		{

			bytecount = serve_cleantemp(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_START, strlen(URI_START)) == 0)

		{

		//	bytecount = serve_start(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_STOP, strlen(URI_STOP)) == 0)

		{

		//	bytecount = serve_stop(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_SCREENSHOT, strlen(URI_SCREENSHOT)) == 0)

		{

		//	bytecount = serve_screenshot(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_EVENTS, strlen(URI_EVENTS)) == 0)

		{

		//	bytecount = serve_events(clientSocket, message);

		}

		else if (strncmp(message->request_uri, URI_DATA_POLLUTION, strlen(URI_DATA_POLLUTION)) == 0)

		{

			bytecount = serve_data_pollution(clientSocket, message);

		}	

		else

		{

			//LOG(WARN,"Bad request: %s\n", message->request_uri);

			bytecount = serve_error(clientSocket, "400 Bad Request");

		}

	}

	else

	{

		// TODO empty request URI

		bytecount = serve_error(clientSocket, "400 Bad Request");

	}



	//LOG(INFO,"Sent bytes %d\n", bytecount);



	return bytecount;

}
Exemple #28
0
int main(int argc, char *argv[]) {
    int server_port = 2121;

    if (argc < 2) {
        printf("usage: %s <addr> [2121]\n", argv[0]);
        exit(0);
    }
    if (argc == 3) {
        server_port = atoi(argv[2]);
    }
    int client = new_client(ntohl(inet_addr(argv[1])), server_port);
    if (client < 0) {
        err(1, "can not connect to %s %d", argv[1], server_port);
        err(1, "exit ...");
        exit(1);
    }
    int i, n;
    char buf[BUF_SIZE+1];
    char tmpbuf[BUF_SIZE+1];
    char cmdbuf[BUF_SIZE+1];
    int data_client = -1;
    struct sockaddr_in data_client_addr;
    uint32_t addr;
    uint16_t port;
    char path[BUF_SIZE];
    int code = -1;
    enum CLIENT_STATE state = ST_NONE;
    char filename[BUF_SIZE], line[BUF_SIZE];

    while ((n=recv(client, buf, sizeof(buf), MSG_PEEK)) > 0) {
        if (!running) break;
        for (i=0; i<n; i++) {
            if (buf[i] == '\n') break;
        }
        if (buf[i] != '\n') {
            err(1, "no line break found");
            break;
        }
        n = recv(client, buf, i+1, 0);
        buf[n] = 0;
        printf("%s", buf);
        fflush(stdout);
        parse_number(buf, &code);
        if (code < RPL_ERR_UNKWNCMD && state != ST_NONE) {
            switch(state) {
                case ST_PASVLIST:
                case ST_PASVGET:
                case ST_PASVPUT:
                    if (code == RPL_PASVOK) {
                        strcpy(tmpbuf, buf);
                        tmpbuf[0] = tmpbuf[1] = tmpbuf[2] = tmpbuf[3] = ' ';
                        parse_addr_port(tmpbuf, &addr, &port);
                        switch(state) {
                            case ST_PASVLIST:
                                send_str(client, "LIST\r\n");
                                break;
                            case ST_PASVGET:
                                send_str(client, "RETR %s\r\n", filename);
                                break;
                            case ST_PASVPUT:
                                send_str(client, "STOR %s\r\n", filename);
                                break;
                        }
                        data_client = new_client(addr, port);
                        state++;
                    } else {
                        state = ST_NONE;
                    }
                    break;
                case ST_PASVLIST2:
                case ST_PASVGET2:
                case ST_PASVPUT2:
                    if (data_client < 0) {
                        err(1, "data client not created");
                    } else {
                        if (state == ST_PASVLIST2) {
                            recv_file(data_client, stdout);
                        } else if (state == ST_PASVGET2) {
                            recv_path(data_client, filename, 0);
                        } else if (state == ST_PASVPUT2) {
                            FILE *f = fopen(filename, "rb");
                            if (f) {
                                send_file(data_client, f);
                                fclose(f);
                            } else {
                                err(1, "err open file %s", filename);
                            }
                        }
                        info(1, "closing data socket ... %d", close(data_client));
                        data_client = -1;
                        state = ST_NONE;
                    }
                    break;
                default:
                    state = ST_NONE;
                    break;
            }
            if (code < RPL_ERR_UNKWNCMD)
                continue;
        }
        if (code >= RPL_ERR_UNKWNCMD) state = ST_NONE;

        int valid = 0;
        while (!valid) {
            valid = 1;
            printf("ftp >>> ");
            if (!fgets(line, BUF_SIZE, stdin)){
                running = 0;
                break;
            }
            int len = strlen(line);
            len --;
            while (line[len] == '\n' || line[len] == '\r') len--;
            len ++;
            line[len] = 0;
            enum USER_CMD cmd = parse_input_cmd(line, len);
            switch(cmd) {
                case USER_USER:
                case USER_PASS:
                case USER_TYPE:
                case USER_MKD:
                case USER_DELE:
                case USER_RNFR:
                case USER_RNTO:
                case USER_RMD:
                    send_str(client, "%s\r\n", line);
                    break;
                case USER_LS:
                    send_str(client, "PASV\r\n");
                    state = ST_PASVLIST;
                    break;
                case USER_CD:
                    send_str(client, "CWD %s\r\n", &line[3]);
                    break;
                case USER_PWD:
                    send_str(client, "PWD\r\n");
                    break;
                case USER_CDUP:
                    send_str(client, "CDUP\r\n");
                    break;
                case USER_HELP:
                    for (i=0; i<sizeof(USER_CMD_LIST)/sizeof(USER_CMD_LIST[0]); i++) {
                        printf("%s\n", USER_CMD_LIST[i].name);
                    }
                    valid = 0;
                    break;
                case USER_BYE:
                    send_str(client, "QUIT\r\n");
                    running = 0;
                    break;
                case USER_LCD:
                    chdir(&line[4]);
                    valid = 0;
                    break;
                case USER_LLS:
                    getcwd(path, sizeof(path));
                    printf("%s\n", path);

                    sprintf(cmdbuf, "ls -l %s", path);
                    FILE *p2 = popen(cmdbuf, "r");
                    int n;
                    while ((n=fread(tmpbuf, 1, BUF_SIZE, p2)) > 0 ) {
                        fwrite(tmpbuf, 1, n, stdout);
                    }
                    pclose(p2);

                    valid = 0;
                    break;
                case USER_LPWD:
                    getcwd(path, sizeof(path));
                    printf("%s\n", path);
                    valid = 0;
                    break;
                case USER_GET:
                    send_str(client, "PASV\r\n");
                    strcpy(filename, &line[4]);
                    state = ST_PASVGET;
                    break;
                case USER_PUT:
                    send_str(client, "PASV\r\n");
                    strcpy(filename, &line[4]);
                    state = ST_PASVPUT;
                    break;
                default:
                    warn(1, "unknown user cmd");
                    valid = 0;
                    break;
            }
        }
        if (!running) break;
    }
    int st = close(client);
    info(1, "FTP client close socket ... %d", st);
    info(1, "FTP client shutdown");
    if (data_client > 0) {
        st = close(data_client);
        info(1, "FTP client close data socket ... %d", st);
        info(1, "FTP client data socket shutdown");
    }
    return 0;
}
Exemple #29
0
static int client(const char *filepath, 
                  struct in_addr *srv_inetaddr, int port)
{
        int sock, ret = EXIT_FAILURE;
        union {
                struct sockaddr_sv serval;
                struct sockaddr_in inet;
                struct sockaddr saddr;
        } cliaddr, srvaddr;
        socklen_t addrlen = 0;
        unsigned char digest[SHA_DIGEST_LENGTH];
        unsigned short srv_inetport = (unsigned short)port;
        int family = AF_SERVAL;

        memset(&cliaddr, 0, sizeof(cliaddr));
        memset(&srvaddr, 0, sizeof(srvaddr));

        if (srv_inetaddr) {
                family = AF_INET;
                cliaddr.inet.sin_family = family;
                cliaddr.inet.sin_port = htons(6767);
                srvaddr.inet.sin_family = family;
                srvaddr.inet.sin_port = htons(srv_inetport);
                memcpy(&srvaddr.inet.sin_addr, srv_inetaddr, 
                       sizeof(*srv_inetaddr));
                addrlen = sizeof(cliaddr.inet);
        } else {
                cliaddr.serval.sv_family = family;
                cliaddr.serval.sv_srvid.s_sid32[0] = htonl(getpid());
                srvaddr.serval.sv_family = AF_SERVAL;
                memcpy(&srvaddr.serval.sv_srvid, 
                       &server_srvid, sizeof(server_srvid));
                addrlen = sizeof(cliaddr.serval);
                /* srvaddr.sv_flags = SV_WANT_FAILOVER; */
        }
        
        sock = socket_sv(family, SOCK_STREAM, 0);
        
        set_reuse_ok(sock);
        
        if (family == AF_SERVAL) {
                ret = bind_sv(sock, &cliaddr.saddr, addrlen);
                
                if (ret < 0) {
                        fprintf(stderr, "error client binding socket: %s\n", 
                                strerror_sv(errno));
                        goto out;
                }
        }
        
        if (family == AF_INET) {
                char buf[18];
                printf("Connecting to service %s:%u\n",
                       inet_ntop(family, srv_inetaddr, buf, 18), 
                       srv_inetport);
        } else {
                printf("Connecting to service id %s\n", 
                       service_id_to_str(&srvaddr.serval.sv_srvid));
        }
        ret = connect_sv(sock, &srvaddr.saddr, addrlen);
    
        if (ret < 0) {
                fprintf(stderr, "ERROR connecting: %s\n",
                        strerror_sv(errno));
                goto out;
        }
#if defined(SERVAL_NATIVE)
        {
                struct {
                        struct sockaddr_sv sv;
                        struct sockaddr_in in;
                } saddr;
                socklen_t addrlen = sizeof(saddr.in);
                char ipaddr[18];

                memset(&saddr, 0, sizeof(saddr));
                
                ret = getsockname(sock, (struct sockaddr *)&saddr, &addrlen);

                if (ret == -1) {
                        fprintf(stderr, "Could not get sock name : %s\n",
                                strerror(errno));
                } else {
                        printf("sock name is %s @ %s\n",
                               service_id_to_str(&saddr.sv.sv_srvid),
                               inet_ntop(AF_INET, &saddr.in.sin_addr, 
                                         ipaddr, 18));
                }

                memset(&saddr, 0, sizeof(saddr));
                
                ret = getpeername(sock, (struct sockaddr *)&saddr, &addrlen);

                if (ret == -1) {
                        fprintf(stderr, "Could not get peer name : %s\n",
                                strerror(errno));
                } else {
                        printf("peer name is %s @ %s\n",
                               service_id_to_str(&saddr.sv.sv_srvid),
                               inet_ntop(AF_INET, &saddr.in.sin_addr, 
                                         ipaddr, 18));
                }
        } 
#endif
        printf("Connected successfully!\n");
        
        ret = recv_file(sock, filepath, digest);
        
        if (ret == EXIT_SUCCESS) {
                printf("SHA1 digest is [%s]\n", digest_to_str(digest));
        } else {
                printf("Receive failed\n");
        }
out:
        fprintf(stderr, "Closing socket...\n");
        close_sv(sock);

        return ret;
}
Exemple #30
0
int __cdecl main(int argc, char **argv) 
{
	WSADATA			wsa_data;
    struct addrinfo *result					= NULL,
                    *ptr					= NULL,
                    hints;
	SOCKET			conn_socket				= INVALID_SOCKET;
	char			input[MAX_INPUT_LENGTH],
					msg_buf[MAX_INPUT_LENGTH],
					*command,
					*filename,
					*next_token				= NULL,
					control_message[MAX_INPUT_LENGTH];
	int				quit					= FALSE,
					return_code;

	init_crc();

	printf("UFTP Client v0.8\n");
	printf("--------------------------\n\n");

	if(argc != 2)
	{
		printf("Usage: uftp.exe [ip address of the UFTP Server]\n\n");
		return 1;
	}

	printf("Connecting to UFTP Server %s:%s.", argv[1], CONNECT_PORT);

    // Initialize Winsock
    return_code = WSAStartup(MAKEWORD(2,2), &wsa_data);
    if(return_code != 0) 
	{
        printf("WSAStartup failed: %d\n", return_code);
        return 1;
    }
	printf(".");

    // Resolve the server address and port
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    return_code = getaddrinfo(argv[1], CONNECT_PORT, &hints, &result);
    if(return_code != 0) 
	{
        printf("getaddrinfo failed: %d\n", return_code);
        WSACleanup();
        return 1;
    }
	printf(".");

    // Attempt to connect to an address until one succeeds
    for(ptr = result; ptr != NULL; ptr = ptr->ai_next) 
	{
        // Create a conn_socket for connecting to server
        conn_socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if(conn_socket == INVALID_SOCKET) 
		{
            printf("Error at conn_socket(): %ld\n", WSAGetLastError());
            freeaddrinfo(result);
            WSACleanup();
            return 1;
        }
		printf(".");

        // Connect to server.
        return_code = connect(conn_socket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if(return_code == SOCKET_ERROR) 
		{
            closesocket(conn_socket);
            conn_socket = INVALID_SOCKET;
            continue;
        }
		printf(".");
        break;
    }
    freeaddrinfo(result);
    if(conn_socket == INVALID_SOCKET) 
	{
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }	
	printf(".DONE!\n\n");
	printf("COMMANDS:\n");
	printf("\t DIR  - Display directory listing.\n");
	printf("\t GET  - Download remote file.\n");
	printf("\t QUIT - Disconnect from server and exit.\n\n");

	memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
	control_message[0] = CONTROL_MESSAGE_SEND_HELLO;
	return_code = send(conn_socket, control_message, (int)strlen(control_message), 0);
	if(return_code == SOCKET_ERROR)
	{
		printf("failed to send hello: %d\n", WSAGetLastError());
		quit = TRUE;
	}
	else
	{
		memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
		return_code = recv(conn_socket, control_message, MAX_INPUT_LENGTH-1, 0);
		if(return_code == SOCKET_ERROR)
		{
			printf("failed to receive hello: %d\n", WSAGetLastError());
			quit = TRUE;
		}
	}

	switch(control_message[0])
	{
	case CONTROL_MESSAGE_HELLO_RESPONSE:
		printf("UFTP Server ready for commands:\n\n");
		quit = FALSE;
		break;

	case CONTROL_MESSAGE_SERVER_BUSY:
		printf("Server is too bust, try again later...\n\n");
		quit = TRUE;
		break;

	default:
		printf("Unknown server, may not be a UFTP Server.\n\n");
		quit = TRUE;
		break;
	}

	// interact with the server
	while(!quit)
	{
		memset(input, 0, sizeof(MAX_INPUT_LENGTH));
		printf(">");
		gets_s(input, MAX_INPUT_LENGTH);

		//process input
		command = strtok_s(input, DELIMIT_TOKENS, &next_token);
		filename = strtok_s(NULL, DELIMIT_TOKENS, &next_token);

		if(_strcmpi(command, "get") == 0)
		{
			sprintf_s(control_message, MAX_INPUT_LENGTH, "  %s", filename);
			control_message[0] = CONTROL_MESSAGE_GET_FILE;
			return_code = send(conn_socket, control_message, (int)strlen(control_message)+1, 0);
			if(return_code == SOCKET_ERROR)
			{
				printf("failed to send command: %d\n", WSAGetLastError());
				quit = TRUE;
				break;
			}

			if(!recv_file(conn_socket, filename))
			{
				printf("failed to get file: %d\n", WSAGetLastError());
				quit = TRUE;
				continue;
			}
		}
		else if(_strcmpi(command, "dir") == 0)
		{
			memset(control_message, 0, sizeof(MAX_INPUT_LENGTH));
			control_message[0] = CONTROL_MESSAGE_DISPLAY_DIR;
			return_code = send(conn_socket, control_message, (int)strlen(control_message), 0);
			if(return_code == SOCKET_ERROR)
			{
				printf("failed to send command: %d\n", WSAGetLastError());
				quit = TRUE;
				break;
			}

			do
			{				
				memset(msg_buf, 0, sizeof(MAX_INPUT_LENGTH));
				return_code = recv(conn_socket, msg_buf, MAX_INPUT_LENGTH-1, 0);
				if(return_code == SOCKET_ERROR)
				{
					printf("failed to list dir: %d\n", WSAGetLastError());
					quit = TRUE;
					break;
				}				

				printf("%s", msg_buf);

				if(strstr(msg_buf, END_OF_DYNAMIC_DATA) != NULL)
					break;

			} while(_strcmpi(msg_buf, END_OF_DYNAMIC_DATA) != 0);

			printf("\n");
		}
		else if(_strcmpi(command, "quit") == 0)
		{
			quit = TRUE;
		}
		else
		{
			printf("unknown command: %s\n", command);
		}
	}

    // shutdown the connection since no more data will be sent
    return_code = shutdown(conn_socket, SD_SEND);
    if(return_code == SOCKET_ERROR) 
	{
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(conn_socket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do 
	{
        return_code = recv(conn_socket, msg_buf, MAX_INPUT_LENGTH-1, 0);
    } while( return_code > 0 );

    // cleanup
    closesocket(conn_socket);
    WSACleanup();

    return 0;
}