void receive_file(struct packet* hp, struct packet* data, int sfd, FILE* f) { int x; int i = 0, j = 0; if((x = recv(sfd, data, size_packet, 0)) <= 0) er("recv()", x); j++; hp = ntohp(data); //printpacket(hp, HP); while(hp->type == DATA) { i += fwrite(hp->buffer, 1, hp->datalen, f); if((x = recv(sfd, data, size_packet, 0)) <= 0) er("recv()", x); j++; hp = ntohp(data); //printpacket(hp, HP); } fprintf(stderr, "\t%d data packet(s) received.\n", --j); // j decremented because the last packet is EOT. fprintf(stderr, "\t%d byte(s) written.\n", i); if(hp->type == EOT) return; else { fprintf(stderr, "Error occured while downloading remote file.\n"); exit(2); } fflush(stderr); }
void* serve_client(void* info) { int sfd_client, connection_id, x; struct packet* data = (struct packet*) malloc(size_packet); struct packet* shp; char lpwd[LENBUFFER]; struct client_info* ci = (struct client_info*) info; sfd_client = ci->sfd; connection_id = ci->cid; while(1) { if((x = recv(sfd_client, data, size_packet, 0)) == 0) { fprintf(stderr, "client closed/terminated. closing connection.\n"); break; } shp = ntohp(data); if(shp->type == TERM) break; if(shp->conid == -1) shp->conid = connection_id; if(shp->type == REQU) { switch(shp->comid) { case PWD: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_pwd(shp, data, sfd_client, lpwd); break; case CD: if((x = chdir(shp->buffer)) == -1) fprintf(stderr, "Wrong path.\n"); command_cd(shp, data, sfd_client, x == -1 ? "fail" : "success"); break; case MKDIR: command_mkdir(shp, data, sfd_client); break; case LS: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_ls(shp, data, sfd_client, lpwd); break; case GET: command_get(shp, data, sfd_client); break; case PUT: command_put(shp, data, sfd_client); break; case RGET: if(!getcwd(lpwd, sizeof lpwd)) er("getcwd()", 0); command_rget(shp, data, sfd_client); send_EOT(shp, data, sfd_client); if((x = chdir(lpwd)) == -1) fprintf(stderr, "Wrong path.\n"); default: // print error break; } /* //send info and then proceed to complete the request shp->type = INFO; strcpy(path, shp->buffer); sprintf(shp->buffer, "File found. Processing..."); data = htonp(shp); if((x = send(sfd_client, data, size_packet, 0)) != size_packet) er("send()", x); send_file(path, sfd_client, shp); send_TERM(sfd_client, shp); */ } else { //show error, send TERM and break fprintf(stderr, "packet incomprihensible. closing connection.\n"); send_TERM(shp, data, sfd_client); break; } } close(sfd_client); fflush(stdout); }