/* Receive data through socket * @param socket: file descriptor of server * @param fdout: file descriptor to write * * @return: -1 on error. Positive integer otherwise */ int receive_data(int socket, int fdout) { int aux; int dir, files; while (TRUE) { aux = receive_file(socket, fdout); if (aux == END) { read_from(socket, &dir, sizeof(int)); read_from(socket, &files, sizeof(int)); if ((DIR_R == dir) && (FILES_R == files)) { dprintf(fdout, "\nTransferencia realizada con exito.\n"); dprintf(fdout, "\nSe han transferido: - %d de %d carpetas\n", \ DIR_R, dir); dprintf(fdout, " - %d de %d archivos\n", \ FILES_R, files); } else { dprintf(fdout, \ "\nAlgunos archivos no se pudieron transferir.\n"); dprintf(fdout, "\nSe han transferido: - %d carpetas\n", DIR_R); dprintf(fdout, " - %d archivos\n", FILES_R); } break; } else if (aux < 0) { dprintf(fdout, "\nSe ha producido un error en la transferencia.\n"); return -1; } } return 0; }
/* server reader */ THREAD_PROC server_thread(void *arg) { EZS *E = (EZS*) arg; char rbuf[4096]; int nb; FILE *sp; THREAD_DETACH; fprintf(stderr, "server_reader\n"); ssl_session = ezs_get_session(E); if (ssl_session) { fprintf(stderr, "saving session\n"); sp = fopen("session.pem", "w"); fputs(ssl_session, sp); fclose(sp); } while ((nb=ezs_read(E, rbuf, 4095))>0) { rbuf[nb] = '\0'; printf("recv %d bytes: %s\n", nb, rbuf); if (!strncmp(rbuf, "#file ", 6)) { if (!receive_file(E, rbuf+6)) break; } } report_err(E, "read"); }
void get(){ // Send command // send_pack(GET, command.arguments, sock); // receive positive/negative acknowledgement (whether the file exists or not) // if(recv(sock, packet_str, PACK_SIZE, 0) < 0){ error("recv"); } parse_packet(packet_str, packet); if(!(int)packet.command_code){ fprintf(stderr, "The specified does not exist\n"); return; } /* send port number for data connection to server */ send_data_port(); // make socket and accept server's Data Connection (active)// makeDataConnection(); fprintf(stderr, "get() : data connection accepted\n"); // recieve file // receive_file(); fprintf(stdout, "get() : complete file received\n"); fflush(stdout); // close the data connection // close(request->serverSocket); }
/* Has one FileIn parameter. */ int do_internal_rhbz914931 (int count) { int r; if (count <= 0 || count > 1000) { reply_with_error ("count out of range"); return -1; } r = receive_file (crash_cb, &count); if (r == -1) { /* write error */ int err = errno; cancel_receive (); errno = err; reply_with_error ("write error"); return -1; } if (r == -2) { /* cancellation from library */ /* This error is ignored by the library since it initiated the * cancel. Nevertheless we must send an error reply here. */ reply_with_error ("file upload cancelled"); return -1; } return 0; }
static void handle_request(int opcode, int master_sd, char *addr, char *buffer, struct sockaddr_in *client) { char *filename; uint16_t blksize; filename = buffer; if (!in_path(filename)) { send_error(client, TFTP_ERR_ACCES_VIOLATION, (char *)"Requested file outside of working dir.", master_sd); return; } buffer += strnlen(buffer, 508) + 1; if (strncmp(buffer, "octet", 5) != 0) { send_error(client, TFTP_ERR_UNDEFINED, (char *)"Transfer mode not supported.", master_sd); return; } buffer += 6; blksize = get_blksize(buffer, filename); if (opcode == TFTP_RRQ) send_file(filename, client, addr, master_sd, blksize); else receive_file(filename, client, addr, master_sd, blksize); }
int main(int argc, char *argv[]) { int sock; struct sockaddr_in addr; int port = get_port(argc, argv); char server_address_string[16]; char buf[BUF_SIZE]; char repeat = 1; int id; set_address(argc, argv, server_address_string, LENGTH_OF(server_address_string)); srand(time(NULL)); id = rand(); sock = socket(AF_INET, SOCK_STREAM, 0); if(WRONG_SOC(sock)) { perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_port = htons(port); /* addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); */ addr.sin_addr.s_addr = inet_addr(server_address_string); if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("connect"); exit(2); } printf("%s:%d, ID: %d\n", server_address_string, port, id); send(sock, &id, sizeof(id), EMPTY_FLAGS); while(repeat) { printf("-> "); read_stdin(buf, LENGTH_OF(buf)); if(strlen(buf) == 0) continue; if(!strncmp(buf, "close", LENGTH_OF(buf))) repeat = 0; send_to(sock, buf); // download file if its exists if(strstr(buf, "download") && receive_int(sock)) { receive_file(sock); printf("%s\n", FILE_DOWNLOADED_MSG); continue; } // prints info or error mesages receive_and_print_msg(sock); } close(sock); return 0; }
/* Has one FileIn parameter. */ int do_base64_in (const char *file) { int err, r; FILE *fp; CLEANUP_FREE char *cmd = NULL; int fd; if (asprintf_nowarn (&cmd, "%s -d -i > %R", str_base64, file) == -1) { err = errno; cancel_receive (); errno = err; reply_with_perror ("asprintf"); return -1; } if (verbose) fprintf (stderr, "%s\n", cmd); fp = popen (cmd, "w"); if (fp == NULL) { err = errno; cancel_receive (); errno = err; reply_with_perror ("%s", cmd); return -1; } /* The semantics of fwrite are too undefined, so write to the * file descriptor directly instead. */ fd = fileno (fp); r = receive_file (write_cb, &fd); if (r == -1) { /* write error */ cancel_receive (); reply_with_error ("write error on file: %s", file); pclose (fp); return -1; } if (r == -2) { /* cancellation from library */ /* This error is ignored by the library since it initiated the * cancel. Nevertheless we must send an error reply here. */ reply_with_error ("file upload cancelled"); pclose (fp); return -1; } if (pclose (fp) != 0) { reply_with_error ("base64 subcommand failed on file: %s", file); return -1; } return 0; }
int main(int argc, char **argv) { if(2 != argc) { print_error_usage(); return -1; } if(0 != parse_args(argv[1])) { print_error_usage(); return -1; } printf("\n> FTP Structure:\n"); print_ftp_struct(); printf("\n> Opening TCP control connection...\n"); if(0 != open_tcp_control_connection()) { printf("Could not open tcp control connection\n"); return -1; } printf("\n> Receiving TCP control data...\n"); if(0 != receive_tcp_control_data()) { printf("Could not receive tcp control data\n"); return -1; } printf("\n> Opening TCP receiver connection...\n"); if(0 != open_tcp_receiver_connection()) { printf("Could not open tcp receiver connection\n"); close(ctrl_ftp.socket_fd); return -1; } printf("\n> Receiving file...\n"); if(0 != receive_file()) { printf("Could not receive file data\n"); close(ctrl_ftp.socket_fd); close(recv_ftp.socket_fd); return -1; } else { printf("File received successfully\n"); } close(ctrl_ftp.socket_fd); close(recv_ftp.socket_fd); printf("\n> Sockets closed. Terminating...\n"); return 0; }
/* Send a cancellation flag back to the library. */ int cancel_receive (void) { XDR xdr; char fbuf[4]; uint32_t flag = GUESTFS_CANCEL_FLAG; xdrmem_create (&xdr, fbuf, sizeof fbuf, XDR_ENCODE); xdr_u_int (&xdr, &flag); xdr_destroy (&xdr); if (xwrite (sock, fbuf, sizeof fbuf) == -1) { perror ("write to socket"); return -1; } /* Keep receiving chunks and discarding, until library sees cancel. */ return receive_file (NULL, NULL); }
int cmd_get(void *info, t_msg *msg) { t_handle *handle; char path[PATH_SIZE]; int size; handle = (t_handle*)info; memset(path, 0, PATH_SIZE); add_log("Client %d execute command get %s\n", 0, handle->cli_num, msg->arg); strcat(path, handle->path); strcat(path, "/"); strcat(path, msg->arg); if (get_file_info(handle, &size, path) < 0) if (write(handle->cli_fd, "0", 1) < 0) return (_error("Can't write on client %d: %m\n", -1, handle->cli_num)); if (receive_file(handle, path, size, msg) < 0) return (IWARNING); return (ISUCCESS); }
/* Has one FileIn parameter. */ int do_debug_upload (const char *filename, int mode) { /* Not chrooted - this command lets you upload a file to anywhere * in the appliance. */ int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY|O_CLOEXEC, mode); if (fd == -1) { int err = errno; cancel_receive (); errno = err; reply_with_perror ("%s", filename); return -1; } int r = receive_file (write_cb, &fd); if (r == -1) { /* write error */ int err = errno; cancel_receive (); errno = err; reply_with_error ("write error: %s", filename); close (fd); return -1; } if (r == -2) { /* cancellation from library */ /* This error is ignored by the library since it initiated the * cancel. Nevertheless we must send an error reply here. */ reply_with_error ("file upload cancelled"); close (fd); return -1; } if (close (fd) == -1) { reply_with_perror ("close: %s", filename); return -1; } return 0; }
int main(int argc, char **argv) { struct ifi_info *ifihead; int sockfd; if (argc != 2) err_quit("usage: client <FileName>"); read_input_file(argv[1]); // Print information about the IP address and network masks ifihead = Get_ifi_info_plus(AF_INET, 1); prifinfo_plus(ifihead); // Create a socket that connects to the server sockfd = create_socket(); receive_file(sockfd); return 0; }
int cmd_put(void *info, t_msg *msg) { t_handle *handle; int ret; int size; char name[BUF_SIZE]; handle = (t_handle*)info; memset(name, 0, BUF_SIZE); add_log("Client %d execute command put %s\n", 0, handle->cli_num, msg->arg); if ((ret = receive_file_info(handle, &size, name)) < 0) return (ret); if (write(handle->cli_fd, "OK", 2) < 0) return (_error("Can't write on client %d: %m\n", -1, handle->cli_num)); if ((ret = receive_file(handle, size, name)) < 0) return (ret); if (write(handle->cli_fd, "OK", 2) < 0) return (_error("Can't write on client %d: %m\n", -1, handle->cli_num)); add_log("Client %d create file %s of size %d\n", 0, handle->cli_num, msg->arg , size); return (ISUCCESS); }
int process_STOR(struct session* ses, const char* data) { if (strlen(data) > 0) { char file[MAX_PATH]; if (relative_to_absolute_path(ses->current_dir, data, file)) if (open_data_connection(ses) != -1) { char buf[BUF_LEN]; snprintf (buf, BUF_LEN, "Opening BINARY mode data connection for %s.", data); respond (ses, 150, buf); if (receive_file(ses, file) != -1) respond (ses, 226, "Transfer complete."); else respond (ses, 550, "Transfer failed."); close_data_connection (ses); return 0; } } respond (ses, 553, "Could not create file."); return 0; }
int server_response(int fd) { int len; char *resp; len = 0; while (!len && ioctl(fd, FIONREAD, &len) >= 0) usleep(3000); if ((resp = malloc(sizeof(char) * (len + 1))) == NULL) { printf("Unable to malloc response\n"); return (-1); } len = read(fd, resp, len); resp[len] = '\0'; printf("%s", resp); if (strncmp(resp, "777 : ", 6) == 0) receive_file(fd, &resp[6]); else if (strncmp(resp, "778 : ", 6) == 0) send_file(fd, &resp[6]); free(resp); return (0); }
void command_get(int sfd_client, struct packet* chp, char* filename) { FILE* f = fopen(filename, "wb"); if(!f) { fprintf(stderr, "File could not be opened for writing. Aborting...\n"); return; } clear_packet(chp); chp->type = REQU; chp->comid = GET; strcpy(chp->buffer, filename); send_packet(sfd_client, chp); recv_packet(sfd_client, chp); //printpacket(chp, HP); if(chp->type == INFO && chp->comid == GET && strlen(chp->buffer)) { printf("\t%s\n", chp->buffer); receive_file(sfd_client, chp, f); fclose(f); } else fprintf(stderr, "Error getting remote file : <%s>\n", filename); }
bool Server::accept_connection() { while (1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size); if (new_fd == -1) { error("accept"); return false; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *) &their_addr), s, sizeof s); cout << "server: got connection from " << s << endl; if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener cout << "waiting for HTTP request" << endl; char buf_req[MAXREQUESTSIZE]; char buf_rest[MAXREQUESTSIZE]; while (true) { // request line detection char received_chunk[MAXDATASIZE]; memset(received_chunk, 0, MAXDATASIZE); receive_data(received_chunk, MAXDATASIZE); // receive request line // cout << "\treceived 1 : \"" << received_chunk << "\"" << endl; string s = received_chunk; int pos = s.find("\r\n", 0); if (pos != string::npos) { string s1, s2; s1 = s.substr(0, pos); s2 = s.substr(pos); strcpy(buf_req, s1.c_str()); strcpy(buf_rest, s2.c_str()); // cout << "\tbuf_req: \"" << buf_req << "\"" << endl; // cout << "\tbuf_rest: \"" << buf_rest << "\"" << endl; break; } else { strcat(buf_req, received_chunk); } } // find out whether the received request is GET or POST vector<string> v; FileHandler::split(buf_req, ' ', v); if (v[0].compare("GET") == 0) { // GET request detected cout << "GET request detected" << endl; cout << "###################################" << endl << buf_req; string file = WORKINGDIRECTORY + v[1]; while (true) { string s(buf_rest); // cout << "\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the GET request, discard the rest string headers; headers = s.substr(0, pos); strcat(buf_rest, headers.c_str()); cout << s << "###################################" << endl; break; } char received_chunk[MAXDATASIZE]; memset(received_chunk, 0, MAXDATASIZE); receive_data(received_chunk, MAXDATASIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } cout << "server: requesting file: " << file << endl; //Check for file existence //File exists if (FileHandler::fexists(file)) { cout << "Exists" << file << endl; //Send File ifstream file_stream; FileHandler::open_file_to_read(&file_stream, file); if (!file_stream.is_open()) { error("Could not open file"); return false; } int file_size = FileHandler::get_file_size(&file_stream); cout << "sending actual file..." << endl; const char* message = construct_message(200).c_str(); send_data(message); send_file(file_size, &file_stream); cout << "file was sent successfully" << endl; } //File doesn't exist else { cout << "Doesn't Exist" << endl; string not_found = construct_message(404); if (send(new_fd, not_found.c_str(), strlen(not_found.c_str()), 0) == -1) error("send"); } } else if (v[0].compare("POST") == 0) { // POST request detected cout << "POST request detected" << endl; cout << "###################################" << endl << buf_req; string file_name = WORKINGDIRECTORY+v[1]; string file_size; bool valid_request = false; char file[MAXREQUESTSIZE]; ///////////////////////////////////////////////// //Getting headers while (true) { string s(buf_rest); // cout << s.length()<<"\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the POST request, get the length from the headers and receive the file string headers; headers = s.substr(0, pos); cout<<"ABO:\""<<headers<<"\""<<endl; char header_char_arr [MAXREQUESTSIZE]; strcpy(header_char_arr,headers.c_str()); // extract Content-length from the headers, else report a bad request v.clear(); cout << "\theaders: " << header_char_arr << endl; FileHandler::split_string(header_char_arr, "\r\n", v); for (int i = 0; i < v.size();i++) { vector<string> v2; FileHandler::split(v[i],':',v2); if (v2.size() > 0 && v2[0].compare("Content-Length") == 0) { // found Content-length header, request is valid file_size = v2[1]; valid_request = true; break; } } if (!valid_request) { string message = construct_message(400); send_data(message.c_str()); } else { //Begining of file string temp = ""; cout<<"LL:"<<pos<<" "<<s<<endl; temp = s.substr(pos + 4); cout<<"TEMP:\""<<temp<<"\""<<endl; strcpy(file, temp.c_str()); // strcat(buf_rest, headers.c_str()); int size_int = atoi(file_size.c_str()); cout << "\tsize: " << size_int << endl; cout << s << "###################################" << endl; // int size_written = FileHandler::create_file_from_buf(file_name, file, strlen(file),size_int); FileHandler::concat_to_existing_file(file_name,file,strlen(temp.c_str())); // cout<<":::"<<size_int<<"::"<<size_written<<endl; cout<<"FILE: "<<sizeof(file)<<" Written: "<<strlen(temp.c_str())<<" size int: "<<size_int<<endl; if((receive_file(file_name, size_int-strlen(temp.c_str()))) == false) { cout << "server: An error has occurred and the client may have disconnected" << endl; } cout<<"EEEEEEEEEEEEEEEEEEEEEE"<<endl; string message = construct_message(200); send_data(message.c_str()); } break; } char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } ///////////////////////////////////////////////// } else { //neither // return 400 bad request } close(new_fd); return true; } close(new_fd); // parent doesn't need this } }
/* Takes optional arguments, consult optargs_bitmask. */ int do_tar_in (const char *dir, const char *compress) { const char *filter; int err, r; FILE *fp; CLEANUP_FREE char *cmd = NULL; char error_file[] = "/tmp/tarXXXXXX"; int fd, chown_supported; chown_supported = is_chown_supported (dir); if (chown_supported == -1) return -1; if ((optargs_bitmask & GUESTFS_TAR_IN_COMPRESS_BITMASK)) { if (STREQ (compress, "compress")) filter = " --compress"; else if (STREQ (compress, "gzip")) filter = " --gzip"; else if (STREQ (compress, "bzip2")) filter = " --bzip2"; else if (STREQ (compress, "xz")) filter = " --xz"; else if (STREQ (compress, "lzop")) filter = " --lzop"; else { reply_with_error ("unknown compression type: %s", compress); return -1; } } else filter = ""; fd = mkstemp (error_file); if (fd == -1) { reply_with_perror ("mkstemp"); return -1; } close (fd); /* "tar -C /sysroot%s -xf -" but we have to quote the dir. */ if (asprintf_nowarn (&cmd, "%s -C %R%s -xf - %s2> %s", str_tar, dir, filter, chown_supported ? "" : "--no-same-owner ", error_file) == -1) { err = errno; r = cancel_receive (); errno = err; reply_with_perror ("asprintf"); unlink (error_file); return -1; } if (verbose) fprintf (stderr, "%s\n", cmd); fp = popen (cmd, "w"); if (fp == NULL) { err = errno; r = cancel_receive (); errno = err; reply_with_perror ("%s", cmd); unlink (error_file); return -1; } /* The semantics of fwrite are too undefined, so write to the * file descriptor directly instead. */ fd = fileno (fp); r = receive_file (write_cb, &fd); if (r == -1) { /* write error */ cancel_receive (); CLEANUP_FREE char *errstr = read_error_file (error_file); reply_with_error ("write error on directory: %s: %s", dir, errstr); unlink (error_file); pclose (fp); return -1; } if (r == -2) { /* cancellation from library */ /* This error is ignored by the library since it initiated the * cancel. Nevertheless we must send an error reply here. */ reply_with_error ("file upload cancelled"); pclose (fp); unlink (error_file); return -1; } if (pclose (fp) != 0) { CLEANUP_FREE char *errstr = read_error_file (error_file); reply_with_error ("tar subcommand failed on directory: %s: %s", dir, errstr); unlink (error_file); return -1; } unlink (error_file); return 0; }
void send_receive_command() { int n; char buffer[1024]; bzero(buffer,256); n = read(nsockfd,buffer,255); // printf("yaha tu agaya _%s_\n",buffer); //if (n < 0) { // printf("Mujhe toh mil gaya\n"); // error("ERROR reading from socket"); } //printf("Here is the message: %s\n",buffer); //printf("Length of buffer = %d\n", (int)strlen(buffer)); if (strstr(buffer,"IndexGet") != NULL) { if (strstr(buffer, "ShortList") != NULL) { char pch1[1024],pch2[1024]; /* strtok(buffer," "); strtok(NULL, " "); pch1 = strtok(NULL, " "); strcat(pch1,strtok(NULL, " ")); pch2 = strtok(NULL, " "); strcat(pch2,strtok(NULL, " ")); printf("%s----%s\n",pch1,pch2);*/ printf("%s\n",buffer); int i,space_count=0; char c; int pch1_count=0,pch2_count=0; for(i=0;i<strlen(buffer);i++) { c=buffer[i]; if(c==' ') { space_count++; if(space_count==2 || space_count==4) continue; } if(space_count==2 || space_count==3) pch1[pch1_count++]=c; if(space_count==4 || space_count==5) pch2[pch2_count++]=c; } pch1[pch1_count]='\0'; pch2[pch2_count]='\0'; send_latest_files(pch1,pch2); } else if (strstr(buffer, "LongList") != NULL) { send_all_files(); } else if (strstr(buffer, "RegEx") != NULL) { char *pch; char buffer_backup[1024]; strcpy(buffer_backup, buffer); pch = strtok (buffer_backup, " "); int i=2; while(i--) pch = strtok(NULL, " "); send_regex_files(pch); } } else if (strstr(buffer, "FileHash") != NULL) { if (strstr(buffer, "Verify") != NULL) { char *pch; char buffer_backup[1024]; strcpy(buffer_backup, buffer); pch = strtok (buffer_backup, " "); int i=2; while(i--) pch = strtok(NULL, " "); filehash_verify(pch); } else if (strstr(buffer, "CheckAll") != NULL) { filehash_checkall(); } } else if (strstr(buffer, "FileDownload") != NULL) { // file_download(); char *pch; char buffer_backup[1024],file_path[1024]; strcpy(buffer_backup, buffer); pch = strtok (buffer_backup, " "); pch = strtok(NULL, " "); pch = strtok (pch, "\n"); strcpy(file_path,SERVER); strcat(file_path,pch); printf("%s\n",file_path); char permission[10]; printf("Provide Permission to Client for Download write y or n\n"); scanf("%s",permission); write(nsockfd,permission, strlen(permission)); if(permission[0]=='y') send_file(file_path); } else if (strstr(buffer, "FileUpload") != NULL) { char *pch; char buffer_backup[1024],file_path[1024]; strcpy(buffer_backup, buffer); pch = strtok (buffer_backup, " "); pch = strtok(NULL, " "); pch = strtok (pch, "\n"); strcpy(file_path,SERVER); strcat(file_path,pch); printf("%s\n",file_path); receive_file(file_path); } }
int main(int argc, char *argv[]) { //Read Command Line and set values if (argc != 5) { printf("usage: %s <client name> <server ip> <server port #> <list of files from “shared files directory”>\n", argv[0]); exit(1); } c_name = argv[1]; server_ip = argv[2]; server_port = atoi(argv[3]); file_list=argv[4]; // 1. Create socket and connect to server int sock,csock,clientsock; int clientAddrSize = sizeof(struct sockaddr_in); struct sockaddr_in clientAddr; sock = tcp_connect(server_ip,server_port); srand((unsigned)time(0)); int ran_num=rand() % 2000; client_port=5000+ran_num; csock = tcp_listen(client_port); //2.send client name and file list to server char buffer[MAXBUFSIZE]; bzero(buffer,MAXBUFSIZE); filelist(c_name,file_list,buffer,client_port); printf("client %s is sending file_list\n",c_name); send(sock,buffer,sizeof(buffer),0); bzero(buffer,MAXBUFSIZE); recv(sock,buffer,MAXBUFSIZE,0); printf("%s\n",buffer); char buf[MAXBUFSIZE]; char recvbuf[MAXBUFSIZE]; while (1) { fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(csock, &rfds); tv.tv_sec = 0; tv.tv_usec = 100000; //printf("loop\n"); if (select(csock + 1, &rfds, NULL, NULL, &tv)) { printf("in select 1\n"); /* if someone is trying to connect, accept() the connection */ clientsock = accept(csock, (struct sockaddr*) &clientAddr, (socklen_t*) &clientAddrSize); FD_ZERO(&rfds); FD_SET(clientsock, &rfds); tv.tv_sec = 0; tv.tv_usec = 100000; if (select(clientsock + 1, &rfds, NULL, NULL, &tv)) { bzero(buffer,MAXBUFSIZE); bzero(buf,MAXBUFSIZE); printf("in select 2\n"); recv(clientsock,buffer,MAXBUFSIZE,0); strncpy(buf,buffer,3); if(!strcmp(buf,"Get")){ send_file(buffer+4,clientsock); } } close(clientsock); } /* Read command line and store in buffer*/ bzero(buf,MAXBUFSIZE); bzero(buffer,MAXBUFSIZE); // printf("> "); fd_set fds; struct timeval ttv; int ioflag = 0; ttv.tv_sec = 5; ttv.tv_usec = 0; FD_ZERO(&fds); FD_SET(0,&fds); //stdin select(0+1,&fds,NULL,NULL,&ttv); if(FD_ISSET(0,&fds)){ fgets(buf, MAXBUFSIZE, stdin); ioflag = 1; } if(!ioflag){ //bounce back to start of loop on user io timeout continue; } if (strlen(buf) > 0) { buf[strlen(buf) - 1] = '\0'; if(!strcmp(buf,"Exit")){ sprintf(buffer,"%s.%s.",c_name,buf); send(sock,buffer,sizeof(buffer),0); close(sock); exit(EXIT_SUCCESS); } else if(!strcmp(buf,"List")){ sprintf(buffer,"%s.%s.",c_name,buf); send(sock,buffer,sizeof(buffer),0); } else if(!strcmp(buf,"SendMyFilesList")){ bzero(buffer,MAXBUFSIZE); filelist(c_name,file_list,buffer,client_port); send(sock,buffer,sizeof(buffer),0); } else if(!strcmp(buf,"")){ continue; } else{ strncpy(buffer,buf,3); if(!strcmp(buffer,"Get")){ bzero(buffer,MAXBUFSIZE); sprintf(buffer,"%s.Get.%s",c_name,buf+4); send(sock,buffer,sizeof(buffer),0); } else{ printf("Invalid Command: Exit/List/SendMyFilesList/Get <file>\n"); continue; } } } bzero(recvbuf,MAXBUFSIZE); bzero(buf,MAXBUFSIZE); recv(sock,recvbuf,MAXBUFSIZE,0); int fdot = strcspn(recvbuf, "."); strncpy(buf, recvbuf, fdot); if(!strcmp(buf,"Server: receive file_list successfully")){ printf("%s\n",recvbuf); } else if(!strcmp(buf,"filelist")){ printf("Received list of files from server\nFile name || File size KB || File owner\n%s",recvbuf+fdot+1); } else if(!strcmp(buf,"ip")){ int sdot = strcspn(recvbuf+fdot+1,"|"); char client_ip[MAXBUFSIZE]; char filename[MAXBUFSIZE]; char file_buf[MAXBUFSIZE]; char cport[MAXBUFSIZE]; int cp; bzero(filename,MAXBUFSIZE); strncpy(filename,recvbuf+fdot+1,sdot); if(!strcmp(recvbuf+fdot+sdot+2,"File requested is not available")){ printf("Server: File requested is not available\n"); continue; } int adot = strcspn(recvbuf+fdot+sdot+2,"."); bzero(cport,MAXBUFSIZE); strncpy(cport,recvbuf+fdot+sdot+2,adot); cp=atoi(cport); bzero(client_ip,MAXBUFSIZE); strcpy(client_ip,recvbuf+fdot+sdot+adot+3); int currentsock = tcp_connect(client_ip,cp); sprintf(file_buf,"Get %s",filename); send(currentsock,file_buf,sizeof(file_buf),0); receive_file(filename,currentsock); close(currentsock); } } close(sock); }
int main() { struct sockaddr_in server; struct sockaddr_in dest; int socket_fd, client_fd,num; socklen_t size; SSL_CTX *ctx; /******* START SSL ***************/ /* http://mooon.blog.51cto.com/1246491/909932 */ /* SSL Libraries Init */ SSL_library_init(); /* add all SSL algorithms */ OpenSSL_add_all_algorithms(); /* add all SSL ciphers */ OpenSSL_add_all_ciphers(); /* add all digests */ OpenSSL_add_all_digests(); /* load all SSL errors */ SSL_load_error_strings(); /* Build SSL_CTX -> SSL Content Text * SSLv2_server_method() or SSLv3_server_method() relative to SSL V2 * and SSL V3 */ ctx = SSL_CTX_new(SSLv23_server_method()); if(ctx == NULL){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the server certificate into the SSL_CTX structure */ if(SSL_CTX_use_certificate_file(ctx,RSA_SERVER_CERT,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the private-key corresponding to the server certificate */ if(SSL_CTX_use_PrivateKey_file(ctx,RSA_SERVER_KEY,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Check if the server certificate and private-key matches */ if(!SSL_CTX_check_private_key(ctx)){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /*********** END SSL ****************/ int yes =1; /* Open a socket to listen */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } /* init memory for server and dest */ memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; //same to PF_INET server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; /* BIND SOCKET */ if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } /* START LISTENING */ if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { SSL *ssl; size = sizeof(struct sockaddr_in); /* Waiting for client to connect */ if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); continue; //exit(EXIT_FAILURE); } else{ printf("Server got connection from client %s, port %d, socket %d\n", inet_ntoa(dest.sin_addr),ntohs(dest.sin_port),client_fd); } /* /connection complete */ /* create a new ssl based on ctx */ ssl = SSL_new(ctx); /* add socket : client_fd to SSL */ SSL_set_fd(ssl,client_fd); /* Build up SSL connection */ if(SSL_accept(ssl) == -1){ perror("accept"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } /******* START PROCESSING DATA *************/ /* read header - then do action based on header parsing */ char header_buf[HEADER_SIZE]; int len = HEADER_SIZE; if ((num = recv_all(ssl, (unsigned char *)header_buf, &len))== -1) { printf("Read header failed\n"); perror("recv"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } char *hr = NULL; hr = malloc(3); SSL_read(ssl, hr, sizeof(hr)); if(strcmp("100",hr)){ printf("Header receiving failed\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } else{ printf("Header received successfully\n"); } /* unpack header string */ header h; if (unpack_header_string(header_buf, &h) == -1) { fprintf(stderr, "[SERVER] Could not unpack header information from client\n"); h.action = FAIL_ERROR; //exit(EXIT_FAILURE); } if (h.action == FAIL_ERROR) { printf("Header action is FAIL ERROR\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } //inform client header unpacked successfully SSL_write(ssl,"100",strlen("100")); printf("Header unpacked successfully\n"); // header part end // if client requests to uplaod file if (h.action == ADD_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Adding file %s\n", target); receive_file(ssl, target, h.file_size); free(target); } else if (h.action == FETCH_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Fetching file %s\n", target); FILE *fp; if (!(fp = fopen(target, "r"))) { perror("fopen"); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } free(target); // get file's protection rating to compare to // client's requested circumference int protectionRating = getProtectionRating(h.file_name); header h_send; if (protectionRating >= h.circ) { h_send.action = ADD_FILE; } else { h_send.action = FAIL_ERROR; // client will fail out } h_send.file_size = get_file_size(fp); h_send.file_name = h.file_name; h_send.certificate = " "; send_header(ssl, h_send); if (protectionRating >= h.circ) send_file(ssl, fp); fclose(fp); } else if (h.action == UPLOAD_CERT) { char target[MAXSIZE]; sprintf(target, "%s/%s_crt.pem", SERVER_CERT_DIR, h.file_name); printf("Receiving cert and storing: %s\n", target); receive_file(ssl, target, h.file_size); }// if client requests to list files else if (h.action == LIST_FILE) { char **files; size_t count; unsigned int i; count = file_list(SERVER_FILE_DIR, &files); for (i = 0; i < count; i++) { char *send_str = NULL; send_str = malloc(MAXSIZE); int protectionRating = getProtectionRating(files[i]); if (protectionRating >= h.circ) { sprintf(send_str, "Protected (c = %i): %s",protectionRating,files[i]); } else { sprintf(send_str, "Unprotected (c = %i): %s",protectionRating,files[i]); } send_message(ssl, send_str); free(send_str); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } /* if client requires to vouch a file * https://gitorious.org/random_play/random_play/source/b9f19d4d9e8d4a9ba0ef55a6b0e2113d1c6a5587:openssl_sign.c */ else if (h.action == VOUCH_FILE){ // vouch for this file const char *clearTextFileName = h.file_name; int isCertFile = isNameCertFile(clearTextFileName); // vouch using this certificate char *certificate_file_name = h.certificate; char *cert_loc = NULL; cert_loc = malloc(MAXSIZE); sprintf(cert_loc, "%s/%s", SERVER_CERT_DIR, certificate_file_name); if (!check_if_file_exists(cert_loc)) { char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Unable to locate %s certificate on the server. Please upload using -a\n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; // should notify client here somehow } else{ char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Located %s certificate on the server. \n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); } free(cert_loc); char *target = NULL; target = malloc(MAXSIZE); if (isCertFile) { sprintf(target, "%s/%s", SERVER_CERT_DIR, h.file_name); } else { sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); } unsigned char *md5Value = NULL; md5Value = malloc(MD5_DIGEST_LENGTH); if(hashFile(md5Value, (const char *)target)!=0){ printf("Couldn't open file"); free(target); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } free(target); send_message(ssl, (char *)md5Value); unsigned char signature[MAXSIZE]; SSL_read(ssl, signature, 128); char *sig_name = NULL; sig_name = malloc(MAXSIZE); // keep certificate signatures with certificates if (isCertFile) { sprintf(sig_name, "%s/%s_%s.sig", SERVER_CERT_DIR, clearTextFileName, certificate_file_name); } else { sprintf(sig_name, "%s/%s_%s.sig", SERVER_SIG_DIR, clearTextFileName, certificate_file_name); } if (writeSig(signature, sig_name) != 0) { fprintf(stderr, "Could not save signature file\n"); free(sig_name); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } else{ printf("Sig loc: %s\n", sig_name); SSL_write(ssl,"100",strlen("100")); } free(sig_name); } else if (h.action == VERIFY_FILE){ // test verification of signature files char signatoryCertName[MAXSIZE]; sprintf( signatoryCertName, "%s_crt.pem", h.certificate ); const char *clearText = h.file_name; if(!verifySig(signatoryCertName,clearText)){ printf("Verify failed\n"); } } else if (h.action == FIND_ISSUER){ char certPath[MAXSIZE]; sprintf( certPath, "%s", h.certificate ); } else if (h.action == TEST_RINGOFTRUST) { ringOfTrust(h.file_name); } /********** END DATA PROCESSING **************/ free(h.certificate); free(h.file_name); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); } //Outer While /* Close listening socket */ close(socket_fd); /* Release CTX */ SSL_CTX_free(ctx); return 0; } //End of main
int main(int argc, char*argv[]) { socklen_t len; /* Length of the client address */ int sk; /* Passive socket */ int optval; /* Socket options */ struct sockaddr_in my_addr, cl_addr; /* Server and client addressed */ char cl_paddr[INET_ADDRSTRLEN]; /* Client IP addresses */ uint16_t cl_port; /* Client port */ int ret; int cl_sk; /* Client socket */ int srv_port; /* Server port number */ struct sockaddr_in srv_addr; /* Server address */ printf("simple server, v. 0.1\n"); // Command line arguments check if (argc!=2) { printf ("Error inserting parameters. Usage: \n\t %s (port) \n\n", argv[0]); return 1; } // Port number validity check if (atoi(argv[1]) <= 0 || atoi(argv[1]) > 65535) { printf ("Port number is not valid\n"); return 1; } srv_port = atoi(argv[1]); printf ("server: Port: %d \n",srv_port); memset(&srv_addr, 0, sizeof(srv_addr)); srv_addr.sin_family = AF_INET; srv_addr.sin_port = htons(srv_port); ret = inet_pton(AF_INET, SRV_ADDR, &srv_addr.sin_addr); if(ret <= 0) { printf("\n Wrong server address\n"); return 1; } /* New socket creation */ sk = socket(AF_INET, SOCK_STREAM, 0); if(sk == -1){ printf("\nError creating the socket\n"); return 1; } optval = 1; ret = setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(ret == -1) { printf("\nError setting SO_REUSEADDR\n"); return 1; } /* The socket is binded with the IP address and the port number */ memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = htonl(INADDR_ANY); my_addr.sin_port = htons(srv_port); ret = bind(sk, (SA *) &my_addr, sizeof(my_addr)); if(ret == -1) { printf("\nError binding the socket\n"); return 1; } /* Creation of backlog queue */ ret = listen(sk, BACKLOG_SIZE); if(ret == -1) { printf("\nError creating the backlog queue, size %d\n", BACKLOG_SIZE); return 1; } printf("Waiting for connections ...\n"); while(1) { /* Accept a request arrived at sk, which is served by cl_sk */ len = sizeof(cl_addr); cl_sk = accept(sk, (SA *) &cl_addr, &len); if(cl_sk == -1) { printf("\nError during connession\n"); return 1; } inet_ntop(AF_INET, &cl_addr.sin_addr, cl_paddr, sizeof(cl_paddr)); cl_port = ntohs(cl_addr.sin_port); printf("\nConnession with client %s established on port %d\n", SRV_ADDR, srv_port); if(receive_file(cl_sk)) { printf("Error receiving the file\n"); return 1; } printf ("\nConnection terminated\n"); close(cl_sk); return 0; } close(sk); return 0; }
/* Has one FileIn parameter. */ int do_ntfsclone_in (const char *device) { int err, r; FILE *fp; char *cmd; char error_file[] = "/tmp/ntfscloneXXXXXX"; int fd; fd = mkstemp (error_file); if (fd == -1) { reply_with_perror ("mkstemp"); return -1; } close (fd); /* Construct the command. */ if (asprintf_nowarn (&cmd, "ntfsclone -O %s --restore-image - 2> %s", device, error_file) == -1) { err = errno; r = cancel_receive (); errno = err; reply_with_perror ("asprintf"); unlink (error_file); return -1; } if (verbose) fprintf (stderr, "%s\n", cmd); fp = popen (cmd, "w"); if (fp == NULL) { err = errno; r = cancel_receive (); errno = err; reply_with_perror ("%s", cmd); unlink (error_file); free (cmd); return -1; } free (cmd); /* The semantics of fwrite are too undefined, so write to the * file descriptor directly instead. */ fd = fileno (fp); r = receive_file (write_cb, &fd); if (r == -1) { /* write error */ cancel_receive (); char *errstr = read_error_file (error_file); reply_with_error ("write error on device: %s: %s", device, errstr); free (errstr); unlink (error_file); pclose (fp); return -1; } if (r == -2) { /* cancellation from library */ /* This error is ignored by the library since it initiated the * cancel. Nevertheless we must send an error reply here. */ reply_with_error ("ntfsclone cancelled"); pclose (fp); unlink (error_file); return -1; } if (pclose (fp) != 0) { char *errstr = read_error_file (error_file); reply_with_error ("ntfsclone subcommand failed on device: %s: %s", device, errstr); free (errstr); unlink (error_file); return -1; } unlink (error_file); return 0; }
static void cmd_STOR_func(ClientInfo *client) { char dest_path[PATH_MAX]; gen_filepath(client, dest_path); receive_file(client, dest_path); }
int autoupgrade_client(struct async *as, struct conf *conf) { int a=0; int ret=-1; char *cp=NULL; char *copy=NULL; char *script_path=NULL; char script_name[32]=""; char package_name[32]=""; char write_str[256]=""; const char *args[2]; struct iobuf *rbuf=NULL; struct asfd *asfd; asfd=as->asfd; if(!conf->autoupgrade_dir) { logp("autoupgrade_dir not set!\n"); goto end; } if(!conf->autoupgrade_os) { logp("autoupgrade_os not set!\n"); goto end; } if(!(copy=strdup(conf->autoupgrade_dir))) { log_out_of_memory(__func__); goto end; } strip_trailing_slashes(©); if((cp=strchr(copy, '/'))) *cp='\0'; if(mkpath(&(conf->autoupgrade_dir), copy)) goto end; // Let the server know we are ready. snprintf(write_str, sizeof(write_str), "autoupgrade:%s", conf->autoupgrade_os); if(asfd->write_str(asfd, CMD_GEN, write_str)) goto end; if(!(a=asfd->simple_loop(asfd, conf, NULL, __func__, autoupgrade_func))) { ret=0; // No autoupgrade. goto end; } else if(a<0) // Error. #ifdef HAVE_WIN32 win32_enable_backup_privileges(); snprintf(script_name, sizeof(script_name), "script.bat"); snprintf(package_name, sizeof(package_name), "package.exe"); #else snprintf(script_name, sizeof(script_name), "script"); snprintf(package_name, sizeof(package_name), "package"); #endif if(receive_file(asfd, conf->autoupgrade_dir, script_name, conf)) { logp("Problem receiving %s/%s\n", conf->autoupgrade_dir, script_name); goto end; } if(receive_file(asfd, conf->autoupgrade_dir, package_name, conf)) { logp("Problem receiving %s/%s\n", conf->autoupgrade_dir, package_name); goto end; } if(!(script_path=prepend_s(conf->autoupgrade_dir, script_name))) goto end; chmod(script_path, 0755); /* Run the script here. */ a=0; args[a++]=script_path; args[a++]=NULL; ret=run_script(asfd, args, NULL, conf, 0 /* do not wait */, 1 /* use logp */, 1 /* use logw */); /* To get round Windows problems to do with installing over files that the current process is running from, I am forking the child, then immediately exiting the parent process. */ printf("\n"); logp("The server tried to upgrade your client.\n"); logp("You will need to try your command again.\n"); asfd_free(&as->asfd); exit(0); end: if(copy) free(copy); if(script_path) free(script_path); iobuf_free(rbuf); return ret; }
bool Client::interact() { printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure vector<string>::iterator it = splitted_request.begin(); string get = "get"; string post = "post"; string request = ""; string file_name = ""; if ((*it).compare(get) == 0) { ++it; string temp = (*it).c_str(); if ((*it)[0] == '/') { request += "GET "; file_name = temp; } else { request += "GET "; file_name = '/' + temp; } request += file_name + " HTTP/1.0\r\n"; if (send(sockfd, request.c_str(), strlen(request.c_str()), 0) == -1) error("send"); request = "\r\n"; if (send(sockfd, request.c_str(), strlen(request.c_str()), 0) == -1) error("send"); ////////////// char buf_req[MAXREQUESTSIZE]; char buf_rest[MAXREQUESTSIZE]; while (true) { // response line detection char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive request line // cout << "\treceived 1 : \"" << received_chunk << "\"" << endl; string s = received_chunk; int pos = s.find("\r\n", 0); if (pos != string::npos) { string s1, s2; s1 = s.substr(0, pos); s2 = s.substr(pos); strcpy(buf_req, s1.c_str()); strcpy(buf_rest, s2.c_str()); // cout << "\tbuf_req: \"" << buf_req << "\"" << endl; // cout << "\tbuf_rest: \"" << buf_rest << "\"" << endl; break; } else { strcat(buf_req, received_chunk); } } cout << "" << endl; cout << "###################################" << endl << buf_req; vector<string> v; FileHandler::split(buf_req, ' ', v); //Response is OK cout << v[1] << endl; if (v[1].compare("200") == 0) { char file[MAXREQUESTSIZE]; //Getting headers while (true) { string s(buf_rest); // cout << "\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the GET request, discard the rest string headers; headers = s.substr(0, pos); //Begining of file string temp = ""; temp = s.substr(pos + 4); strcpy(file, temp.c_str()); strcat(buf_rest, headers.c_str()); cout << s << "###################################" << endl; FileHandler::create_file_from_buf(WORKINGDIRECTORY+file_name, file, strlen(file)); break; } char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } receive_file(WORKINGDIRECTORY+file_name); } else if (v[1].compare("404") == 0) { // file not found cout<<buf_req<<endl; } else if (v[1].compare("400") == 0) { // bad request cout<<buf_req<<endl; } } else if ((*it).compare(post) == 0) { ++it; string temp = (*it).c_str(); if ((*it)[0] == '/') { request += "POST "; file_name = temp; } else { request += "POST "; file_name = '/' + temp; } request += file_name + " HTTP/1.0\r\n"; ifstream fs; FileHandler::open_file_to_read(&fs,WORKINGDIRECTORY+file_name); int file_size = FileHandler::get_file_size(&fs); string size_str;//string which will contain the result stringstream convert; // stringstream used for the conversion convert << file_size;//add the value of Number to the characters in the stream size_str = convert.str(); // cout<<"SIZE: "<<size_str<<":::"<<file_size<<endl; request += "Content-Length: " + size_str + "\r\n"; request += "\r\n"; send_data(request.c_str()); send_file(file_size,&fs); //receive response char response[MAXREQUESTSIZE]; receive_data(response,MAXREQUESTSIZE); cout<<response<<endl; } else { cout << "client: Undefined request, please use the following formats" << endl; cout << "client:\tget <file-name> <host-name> (<port-number>)" << endl; cout << "client:\tpost <file-name> <host-name> (<port-number>)" << endl; cout << "client:\twhere <host-name> and <port-number> are optional parameters" << endl; } return true; }
int main() { //printf("%d\n", SEND_FILE); struct sockaddr_in server; struct sockaddr_in dest; int status,socket_fd, client_fd,num; socklen_t size; //char buffer[1024]; char *buff; // memset(buffer,0,sizeof(buffer)); int yes =1; if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { size = sizeof(struct sockaddr_in); if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); exit(EXIT_FAILURE); } printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr)); char header[1024]; // read header - then do action based on header parsing if ((num = recv(client_fd, header, 1024,0))== -1) { perror("recv"); exit(EXIT_FAILURE); } else if (num == 0) { printf("Connection closed\n"); //So I can now wait for another client continue; } // printf("%s\n", buffer); while(TRUE){ // if client requests to uplaod file if (strcmp(header, "send") == 0) { char *file_name = "written.txt"; // TODO get file_name from header receive_file(client_fd, file_name); } else if (strcmp(header, "list") == 0) { char **files; size_t count; unsigned int i; count = file_list("./", &files); printf("There are %zu files in the directory,transmitting file list.\n", count); for (i = 0; i < count; i++) { send_message(client_fd,files[i]); sleep(1); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } break; } } //Outer While close(socket_fd); return 0; } //End of main