int transfer(char *host, char *port) { int sfd; // server socket fileop_t *f; // contains all operations for a file sfd = inetConnect(host, port, SOCK_STREAM); if (sfd == -1) { errnoMsg(LOG_ERR, "Unable to connect to the server."); return -1; } // initiate sync (sync-id, resource, number of files) errMsg(LOG_INFO, "Number of files: %d", HASH_COUNT(files)); switch (initiateSync(sfd, HASH_COUNT(files))) { case -1: // error return -1; case -2: // there's nothing to synchronize return 0; default: break; } // iterate over files in correct order HASH_SORT(files, sortByOrder); for (f = files; f != NULL; f = (fileop_t*) (f->hh.next)) { if (transferFile(sfd, f) == -1) { errMsg(LOG_ERR, "Transfer of file %s has failed.", f->relpath); return -1; } } // wait for ACK SyncFinish *conf; conf = (SyncFinish *) recvMessage(sfd, SyncFinishType, NULL); if (conf == NULL) { errMsg(LOG_ERR, "Could not get transfer confirmation."); return -1; } return 0; }
/** *@description send requested file to sock *@param sockFd int socket Id *@param request Request http_request struct *@return if failed, return negative number, otherwise, nonnegative */ int sendRequestedFile(int sockFd, Request * httpRequest) { char ok_line[] = "HTTP/1.0 200 OK\r\n"; char badReq_line[] = "HTTP/1.0 400 Bad Request\r\n"; char badReq_content[] = "<html><head></head><body><h1>400 Bad Request</h1></body></html>"; char notFound_line[] = "HTTP/1.0 404 Not Found\r\n"; char notFound_content[] = "<html><head></head><body><h1>404 Not Found</h1></body></html>"; char suffix_line[] = "\r\n"; char writeBuffer[MAX_WRITE_BUFFER]; char * responseLine; char *filePath = (httpRequest->requestLine).path; int fileSize; if (!checkFileExist(filePath)) { printf("file %s doesn't exist\n", filePath); } short isResolved = httpRequest->isResolved; if ( isResolved ) { fileSize = getFileSize(filePath); if (fileSize < 0) { printf("request file %s not found, so send 404 response\n", filePath); if (send(sockFd, notFound_line, strlen(notFound_line), 0) < 0) { return -1; } //send content length memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %lu\r\n","Content-Length",strlen(notFound_content)); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send persistent header memset(writeBuffer, '\0', sizeof(writeBuffer)); if (httpRequest->isAlive == persistent) { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "keep-alive"); } else { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "close"); } if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send content-type header memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Content-Type", "text/html"); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send Date memset(writeBuffer, '\0', sizeof(writeBuffer)); time_t current = time(0); time_t expire = current + 60; struct tm currentTm = *gmtime(¤t); struct tm expireTm = * gmtime(&expire); char timeStr[128]; memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", ¤tTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Date", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } memset(writeBuffer, '\0', sizeof(writeBuffer)); memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", &expireTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Expires", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send suffix line if (send(sockFd, suffix_line, strlen(suffix_line), 0) < 0) { return -1; } //send content if (send(sockFd, notFound_content, strlen(notFound_content), 0) < 0) { return -1; } return 0; } else { printf("start to send request file of size %d bytes...\n", fileSize); //send 200 OK status line if (send(sockFd, ok_line, strlen(ok_line), 0) < 0) { return -1; } //send content-length header memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %d\r\n", "Content-Length", fileSize); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send persistent header memset(writeBuffer, '\0', sizeof(writeBuffer)); if (httpRequest->isAlive == persistent) { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "keep-alive"); } else { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "close"); } if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send content-type header memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Content-Type", "text/html"); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send Date memset(writeBuffer, '\0', sizeof(writeBuffer)); time_t current = time(0); time_t expire = current + 60; struct tm currentTm = *gmtime(¤t); struct tm expireTm = * gmtime(&expire); char timeStr[128]; memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", ¤tTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Date", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } memset(writeBuffer, '\0', sizeof(writeBuffer)); memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", &expireTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Expires", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send suffix line if (send(sockFd, suffix_line, strlen(suffix_line), 0) < 0) { return -1; } //send request body if (transferFile(filePath, sockFd) == 0) { printf("send file %s of %d bytes successfully\n", filePath, fileSize); } else { return -1; } } } else { printf("start to send 400 bad request\n"); if (send(sockFd, badReq_line, strlen(badReq_line), 0) < 0 ) { return -1; } //send content length memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %lu\r\n","Content-Length",strlen(badReq_content)); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send persistent header memset(writeBuffer, '\0', sizeof(writeBuffer)); if (httpRequest->isAlive == persistent) { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "keep-alive"); } else { snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Connection", "close"); } if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send content-type header memset(writeBuffer, '\0', sizeof(writeBuffer)); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Content-Type", "text/html"); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send Date memset(writeBuffer, '\0', sizeof(writeBuffer)); time_t current = time(0); time_t expire = current + 60; struct tm currentTm = *gmtime(¤t); struct tm expireTm = * gmtime(&expire); char timeStr[128]; memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", ¤tTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Date", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } memset(writeBuffer, '\0', sizeof(writeBuffer)); memset(timeStr, '\0', sizeof(timeStr)); strftime(timeStr, sizeof(timeStr), "%a, %d %b %Y %H:%M:%S %Z", &expireTm); snprintf(writeBuffer, sizeof(writeBuffer), "%s: %s\r\n", "Expires", timeStr); if (send(sockFd, writeBuffer, strlen(writeBuffer), 0) < 0) { return -1; } //send suffix line if (send(sockFd, suffix_line, strlen(suffix_line), 0) < 0) { return -1; } //send content if (send(sockFd, notFound_content, strlen(notFound_content), 0) < 0) { return -1; } return 0; } return 1; }
int main(int argc, char **argv) { int servSock; int clientSock; struct sockaddr_in servAddr; struct sockaddr_in clientAddr; unsigned short servPort; unsigned int clientLen; char *servIP; char fileBuffer[FILEBUFSIZE]; if(argc < 2) { handleError("Usage: ./a.out < mode > < addl. parameters >\n"); } //CLIENT MODE if(atoi(argv[1]) == 0) { if(argc != 5) { handleError("Usage: ./a.out <0> <serverName> <serverPort> <fileToTransfer>\n"); } FILE *transferMe = fopen(argv[4],"r"); if(transferMe == NULL) { handleError("Failed to open specified file!"); } servIP = argv[2]; servPort = atoi(argv[3]); if((clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { handleError("socket creation failed"); } memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = resolveName(servIP); servAddr.sin_port = htons(servPort); if(connect(clientSock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { handleError("connection failed"); } printf("\nTransferring"); int bytesRead; while(!feof(transferMe)) { bytesRead = fread(fileBuffer, 1, FILEBUFSIZE, transferMe); send(clientSock, fileBuffer, bytesRead, 0); printf("."); } printf("\nFile transfer complete!\n"); } //SERVER MODE else if(atoi(argv[1]) == 1) { char fileIndex[10]; // this holds the current file index in string form if(argc != 4) { handleError("Usage: ./a.out <1> <serverPort> <fileToCreate>\n"); } servPort = atoi(argv[2]); FILE *fileToWrite; char *fileBaseName = argv[3]; char fileNameBuffer[64]; signal(SIGINT,exit_with_stats); if((servSock= socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { handleError("socket creation failed"); } memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(servPort); if(bind(servSock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) { handleError("binding socket failed"); } if(listen(servSock, MAXPENDING) < 0) { handleError("listen() failed"); } while(1) { clientLen = sizeof(clientAddr); if((clientSock = accept(servSock, (struct sockaddr *) &clientAddr, &clientLen)) < 0) { handleError("accept() failed"); } strcpy(fileNameBuffer,fileBaseName); sprintf(fileIndex, "%d",filesTransferred); strcat(fileNameBuffer,fileIndex); fileToWrite = fopen(fileNameBuffer,"w"); transferFile(fileBuffer, fileToWrite, clientSock); fclose(fileToWrite); } } else { handleError("Unrecognized mode, bailing out!"); } return 0; }
void executeCommand(char *command) { char BYE[] = "bye"; char GET[] = "get"; char PUT[] = "put"; char DIR[] = "dir"; char LS[] = "ls"; char DELETE[] = "delete"; char MKDIR[] = "mkdir"; char RMDIR[] = "rmdir"; char CD[] = "cd"; char HELP[] = "help"; char * first_arg , * second_arg ; int i; printf("\n\n=======New Command Entered======\n"); if(command == NULL) { printf("The client did not enter any valid command or went down unexpectedly going to waiting mode\n"); serveClients(); } printf("\n Raw command=%s \n\n", command); first_arg = strtok(command, DELIM); second_arg = strtok(NULL, DELIM); if(first_arg == NULL) { printf("The client did not enter any valid command or went down unexpectedly going to waiting mode\n"); serveClients(); } printf("first %s, second %s\n", first_arg, second_arg); if(!strcmp(first_arg, GET)) { printf("The user entered GET command\n"); strcpy(response, "You just entered GET command\n"); if(second_arg != NULL) { transferFile(second_arg); for(i=0 ; i<4095 ; i++) { response[i] = '\0'; } send(connected, response,strlen(response), 0); for(i=0 ; i<4095 ; i++) { response[i] = '\0'; } } else strcpy(response, "Bad command for get : Usage >> get <dir_name>\n"); } else if(!strcmp(first_arg, PUT)) { if(second_arg != NULL) { printf("The user entered PUT command\n"); file_bytes_recieved = recv(connected, file_recv_data, 4096, 0); file_recv_data[file_bytes_recieved] = '\0'; writeToFile(second_arg, file_recv_data); //second_arg=filename; file_recv_data=actual recieved data printf("recieved %d bytes\n", file_bytes_recieved); strcpy(response, "Data bytes recieved successfully at the server.\n"); } else strcpy(response, "Bad command for put : Usage >> put <dir_name>\n"); } else if(!strcmp(first_arg, LS) || !strcmp(first_arg, DIR)) { printf("The user entered LS command\n"); int link[2]; pid_t pid; char output_of_ls[4096]; if (pipe(link)==-1) die("pipe"); if ((pid = fork()) == -1) die("fork"); if(pid == 0) { dup2 (link[1], STDOUT_FILENO); close(link[0]); if(second_arg != NULL) execl("/bin/ls", "/bin/ls", "-r", second_arg, "-l", (char *) 0); else execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0); } else { close(link[1]); int i; for(i=0 ; i<4095 ; i++) { output_of_ls[i] = '\0'; response[i] = '\0'; } printf("The value of output_of_ls after flush: %s \n", output_of_ls); read(link[0], output_of_ls, sizeof(output_of_ls)); printf("Output: (%s)\n", output_of_ls); strcpy(response, ""); strcpy(response, output_of_ls); wait(NULL); } } else if(!strcmp(first_arg, DELETE)) { printf("The user entered DELETE command\n"); int link[2]; pid_t pid; char output_of_delete[4]; if (pipe(link)==-1) die("pipe"); if ((pid = fork()) == -1) die("fork"); if(pid == 0) { dup2 (link[1], STDOUT_FILENO); close(link[0]); if(second_arg != NULL) execl("/bin/rm", "/bin/rm", "-rf", "", second_arg, (char *) 0); else strcpy(response, "Bad command for delete : Usage >> delete <filename>\n"); } else { close(link[1]); read(link[0], output_of_delete, sizeof(output_of_delete)); printf("Output: (%s)\n", output_of_delete); strcpy(response, ""); strcpy(response, output_of_delete); wait(NULL); } } else if(!strcmp(first_arg, MKDIR)) { printf("The user entered MKDIR command\n"); int link[2]; pid_t pid; char output_of_mkdir[4096]; if (pipe(link)==-1) die("pipe"); if ((pid = fork()) == -1) die("fork"); if(pid == 0) { dup2 (link[1], STDOUT_FILENO); close(link[0]); if(second_arg != NULL) execl("/bin/mkdir", "/bin/mkdir", "", "", second_arg, (char *) 0); else strcpy(response, "Bad command for mkdir : Usage >> mkdir <dir_name>\n"); } else { close(link[1]); read(link[0], output_of_mkdir, sizeof(output_of_mkdir)); printf("Output: (%s)\n", output_of_mkdir); strcpy(response, ""); wait(NULL); } } else if(!strcmp(first_arg, RMDIR)) { printf("The user entered RMDIR command\n"); int link[2]; pid_t pid; char output_of_rmdir[4]; if (pipe(link)==-1) die("pipe"); if ((pid = fork()) == -1) die("fork"); if(pid == 0) { dup2 (link[1], STDOUT_FILENO); close(link[0]); if(second_arg != NULL) { execl("/bin/rm", "/bin/rm", "-rf", "", second_arg, (char *) 0); } else strcpy(response, "Bad command for mkdir : Usage >> mkdir <dir_name>\n"); } else { close(link[1]); read(link[0], output_of_rmdir, sizeof(output_of_rmdir)); printf("Output: (%s)\n", output_of_rmdir); strcpy(response, ""); wait(NULL); } } else if(!strcmp(first_arg, CD)) { printf("The user entered CD command\n"); int link[2]; pid_t pid; char output_of_cd[4096]; if (pipe(link)==-1) die("pipe"); if ((pid = fork()) == -1) die("fork"); if(pid == 0) { dup2 (link[1], STDOUT_FILENO); close(link[0]); if(second_arg != NULL) { int result =chdir(second_arg); if(result != -1) {strcat(response, "PWD changed to "); strcat(response, second_arg); strcat(response, "\n"); } else { perror("Couldn't execute\n"); strcat(response, "Bad directory name\n"); } } else strcpy(response, "Bad command for mkdir : Usage >> mkdir <dir_name>\n"); } else { close(link[1]); read(link[0], output_of_cd, sizeof(output_of_cd)); printf("Output: (%s)\n", output_of_cd); strcpy(response, ""); wait(NULL); } } else if(!strcmp(first_arg, BYE)) { printf("The user entered BYE command\n"); //free(first_arg); //free(second_arg); printf("reaching here\n"); //closeSocket(); //close(connected); serveClients(); //exit(0); } else if(!strcmp(first_arg, HELP)) { printf("The user entered BYE command\n"); strcpy(response, "Supported commands: ls, dir, get, put, delete <filename>, mkdir <dirname>, rmdir <dirname>, cd <dirname>, bye.\n"); } else { printf("Invalid command entered\n"); strcpy(response, "Bad command : type 'help' for more info.\n"); } }
int main(int argc, const char * argv[]) { const char *server; const char *port; const char *user; const char *image_url; const char *message; programName = argv[0]; smc_parsecommandline(argc, argv, showUsage, &server, &port, &user, &message, &image_url, &verbose); INFO("main()", "Using the following options: server=\"%s\", port=\"%s\", user=\"%s\", img_url=\"%s\", message=\"%s\"", server, port, user, image_url, message); INFO("main()", "connecting to server=\"%s\", port=\"%s\"", server, port); int sfd = 0; if (connectToServer(server, port, &sfd) != SUCCESS) { fprintf(stderr, "%s: connectToServer() failed for server %s and port %s: %s\n", programName, server, port, strerror(errno)); exit(errno); } INFO("main()", "open file descriptor for writing %s", ""); errno = SUCCESS; FILE *toServer = fdopen(sfd, "w"); if (toServer == NULL) { fprintf(stderr, "%s: fdOpen() to write to server failed: %s\n", programName, strerror(errno)); close(sfd); exit(errno); } INFO("main()", "sending data to server %s", server); if (sendData(toServer, "user="******"%s: sendData() for param user=<user> failed: %s\n", programName, strerror(errno)); shutdown(sfd, SHUT_RDWR); fclose(toServer); exit(errno); } if (image_url != NULL) { INFO("main()", "found image, sending to server %s", server); if (sendData(toServer, "img=", image_url) == ERROR) { fprintf(stderr, "%s: sendData() for param img=<image_url> failed: %s\n", programName, strerror(errno)); shutdown(sfd, SHUT_RDWR); fclose(toServer); exit(errno); } } INFO("main()", "send message to server %s", server); if (sendData(toServer, "", message) == ERROR) { fprintf(stderr, "%s: sendData() for message failed: %s\n", programName, strerror(errno)); shutdown(sfd, SHUT_RDWR); fclose(toServer); exit(errno); } /* fclose schließt auch sfd, daher vorher ein dup */ INFO("main()", "creating backup of file descriptor %s", ""); int backupOfSfd = dup(sfd); INFO("main()", "closing connection to server %s", server); if (shutdown(sfd, SHUT_WR) != SUCCESS) { fprintf(stderr, "%s: shutDown() SHUT_WR for server connection failed: %s\n", programName, strerror(errno)); fclose(toServer); exit(EXIT_FAILURE); } INFO("main()", "closing file descriptor %s", ""); fclose(toServer); INFO("main()", "closed writing channel to server %s", server); INFO("main()", "open stream from server %s", server); FILE *fromServer = fdopen(backupOfSfd, "r"); if (fromServer == NULL) { fprintf(stderr, "%s: fdOpen() to read from server failed: %s\n", programName, strerror(errno)); close(backupOfSfd); exit(errno); } INFO("main()", "opened reading channel from server %s", server); /* read line for status=... */ /* if status returned from server != 0 then exit using the status */ int status = ERROR; INFO("main()", "start checking server response %s", ""); if (checkServerResponseStatus(fromServer, &status) != SUCCESS || status != SUCCESS) { fprintf(stderr, "%s: reading server response failed with error %d\n", programName, status); fclose(fromServer); close(backupOfSfd); exit(status); } INFO("main()", "server returned status %d", status); INFO("main()", "start receiving files from server %s", server); int canTransferFile = SUCCESS; while (canTransferFile != DONE) { canTransferFile = transferFile(fromServer); if (canTransferFile == ERROR) { fprintf(stderr, "%s: transferFile() failed: %s\n", programName, strerror(errno)); fclose(fromServer); close(backupOfSfd); exit(EXIT_FAILURE); } } INFO("main()", "received all data, closing connection to server %s", server); fclose(fromServer); close(backupOfSfd); INFO("main()", "closed connection to server %s", server); INFO("main()", "bye %s!", user); exit(status); }