From d9de77e42783d061ab72f272fc7df7b4fe10e551 Mon Sep 17 00:00:00 2001 From: elvis Date: Sat, 7 May 2022 17:28:41 +0200 Subject: [PATCH] style and fixed bug allocating too much memory in append file --- lib/api/api.c | 589 +++++++++++++++++++++++---------------------- lib/api/api.h | 134 +++++++++-- src/client.c | 204 ++++++++-------- src/server.c | 138 +++++------ src/serverWorker.c | 52 ++-- src/serverWorker.h | 18 +- 6 files changed, 628 insertions(+), 507 deletions(-) diff --git a/lib/api/api.c b/lib/api/api.c index 7a35d69..94ef7c3 100644 --- a/lib/api/api.c +++ b/lib/api/api.c @@ -1,46 +1,41 @@ #define _POSIX_C_SOURCE 200809L - +#include +#include +#include +#include #include #include #include #include #include -#include -#include -#include #include -#include #include #include -#include -#include +#include "api.h" +#include "conn.h" -#define SOCKNAMEMAX 256 // should be at least 108 +#define SOCKNAMEMAX 256 /* should be at least 108 */ -#define MEOK "20" //OK -// #define ME "21" // not used -// #define ME "22" // not used -#define MEFP "25" // file purged +#define MEOK "20" /*OK */ +// #define ME "21" /* not used */ +// #define ME "22" /* not used */ +#define MEFP "25" /* file purged */ -// #define ME "40" // not used -// #define ME "41" // not used -#define MESD "42" // shutting down -#define MENT "45" // requested file action not taken +// #define ME "40" /* not used */ +// #define ME "41" /* not used */ +#define MESD "42" /* shutting down */ +#define MENT "45" /* requested file action not taken */ -#define MESY "50" // syntax error -// #define ME "51" // not used -// #define ME "52" // not used -#define MESE "55" // server error - -#define debughere(str) \ - fprintf(stdout, "\nIn function: %s\n", __func__); \ - fprintf(stdout, "\t%s\n", str); \ - fflush(stdout); \ +#define MESY "50" /* syntax error */ +// #define ME "51" /* not used */ +// #define ME "52" /* not used */ +#define MESE "55" /* server error */ // ----------------------------------------------------------------------------- -/* structs */ +// structs + typedef struct files_s { char *filename; int locked; @@ -49,17 +44,17 @@ typedef struct files_s { typedef struct openfiles_s { int numOfFiles; - files_t *f; // list of files - int validwDir; // 1 if wDir is allocated - char *wDir; // for files sent from the server after openFile - int validrDir; // 1 if rDir is allocated - char *rDir; // for files read from the server - char *createdAndLocked; // path of the last file that was created and locked - int print; // whether to print - FILE *out; // where to print + files_t *f; /* list of files that are currently opened */ + int validwDir; /* true if wDir is allocated */ + char *wDir; /* for files sent from the server after openFile */ + int validrDir; /* true if rDir is allocated */ + char *rDir; /* for files read from the server */ + char *createdAndLocked; /* path of the last file that was created and locked */ + int print; /* whether to print */ + FILE *out; /* where to print */ } openfiles_t; - +/* struct for the files sent from the server */ typedef struct recivedFile_s { int64_t pathlen; char *path; @@ -68,38 +63,38 @@ typedef struct recivedFile_s { } recivedFile_t; typedef struct response_s { - char ME[2]; // response - int meerrno; // errno if sent - int64_t numfiles; // number of files if sent - recivedFile_t *rf; // array of files + char ME[2]; /* response */ + int meerrno; /* errno sent by server */ + int64_t numfiles; /* number of files if sent */ + recivedFile_t *rf; /* array of files */ } response_t; // ----------------------------------------------------------------------------- -/* variabili globali */ -static long fd_skt; // descriptor of the socket -static char socketName[SOCKNAMEMAX] = ""; // name of the socket +// global variables +static long fd_skt; /* descriptor of the socket */ +static char socketName[SOCKNAMEMAX] = ""; /* name of the socket */ static openfiles_t *openedFiles = NULL; // ----------------------------------------------------------------------------- -/* funzioni ausiliarie */ +// helper functions -// closes every file opened by the client +/* closes every file opened by the client */ int closeEveryFile(); -// closes and frees memory -int removeOpenFile(const char *pathname); -// adds element -int addOpenFile(const char *pathname, const int flags); -// checks if the file is open already -int isOpen(const char *pathname, const int flags); -// reads everything the server sent into the variable passed to the function -// expected is 1 if a file could be sent (if no server errors occurs) -int reciveData(response_t *res, int expected); -// saves the files in the specified directory -int storeFilesInDirectory(const char *dirname, int n, recivedFile_t *rf); -// frees memory inside response_t element -void freeResponse(response_t *res); -// creates the global variable -int createOpenedFiles(void); +/* closes and frees memory */ +int removeOpenFile(const char *); +/* adds element */ +int addOpenFile(const char *, const int); +/* checks if the file is open already */ +int isOpen(const char *, const int); +/* reads everything the server sent into the variable passed to the function + * expected == 1 if a file should be sent (if no server errors occurs) */ +int reciveData(response_t *, int expected); +/* saves the files in the specified directory */ +int storeFilesInDirectory(const char *, int n, recivedFile_t *); +/* frees memory inside response_t element */ +void freeResponse(response_t *); +/* initiates the global variables */ +int createOpenedFiles(); // ----------------------------------------------------------------------------- @@ -111,7 +106,7 @@ int openConnection(const char* sockname, int msec, const struct timespec abstime if(!openedFiles) { if(createOpenedFiles()<0) { - perror("createOpenedfiles"); + perror("openConnection: createOpenedfiles"); return -1; } } @@ -120,22 +115,22 @@ int openConnection(const char* sockname, int msec, const struct timespec abstime struct timespec ts; ts.tv_sec = msec/1000; ts.tv_nsec = (msec % 1000) * 1000000; - struct timeval t1, t2; // for gettimeofday - long long start, end; // to calculate the time elapsed + struct timeval t1, t2; /* for gettimeofday */ + long long start, end; /* to calculate the time elapsed */ long long elapsedTime; - // select socket + /* select socket */ strncpy(sa.sun_path, sockname, sizeof(sa.sun_path)-1); sa.sun_family = AF_UNIX; if ((fd_skt = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { errno = EINVAL; - perror("socket"); + perror("openConnection: socket"); return -1; } if(gettimeofday(&t1, NULL) != 0) { - perror("gettimeofday"); + perror("openConnection: gettimeofday"); return -1; } @@ -146,7 +141,7 @@ int openConnection(const char* sockname, int msec, const struct timespec abstime end = (long long) t2.tv_sec * 1000000000 + t2.tv_usec * 1000; elapsedTime = (end - start); - // return if more time has elapsed than allowed + /* return if more time has elapsed than allowed */ if (elapsedTime > (abstime.tv_sec * 1000000000) + abstime.tv_nsec) { errno = ETIMEDOUT; return -1; @@ -164,20 +159,20 @@ int closeConnection(const char* sockname) { errno = EINVAL; return -1; } - // if closing a different socket -> error + /* if closing a different socket -> error */ if(strncmp(socketName, "", sizeof(socketName)) != 0 && strncmp(socketName, sockname, sizeof(socketName)) != 0) { errno = EINVAL; return -1; } - // close every file + /* close every file */ if (closeEveryFile() == -1) { - perror("closeEveryFile"); + perror("closeConnection: closeEveryFile"); return -1; } - // close socket + /* close socket */ if (close(fd_skt) == -1) { - // return errno from close + /* return errno from close */ return -1; } @@ -202,50 +197,52 @@ int openFile(const char* pathname, int flags) { errno = ENOTCONN; return -1; } - if(isOpen(pathname, flags) == 1) { // already open + if(isOpen(pathname, flags) == 1) { /* already open */ return 0; } - // invio al server la stringa "openFile|$(pathname)|$(flags)" + /* sent to server the string "openFile|$(pathname)|$(flags)" */ int leng_flags = snprintf(NULL, 0, "%d", flags); long len = strlen("openFile")+1+strlen(pathname)+1+leng_flags+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("openFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "openFile|%s|%d", pathname, flags); len = strnlen(cmd, len); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("openFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we dont expect a file - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we dont expect a file */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } if(res->meerrno != 0) { - // errno from server + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -253,7 +250,7 @@ int openFile(const char* pathname, int flags) { return -1; } if(strncmp(res->ME, MEFP, sizeof(res->ME)) == 0) { - // some files were purged + /* some files were purged */ if(openedFiles->print){ fprintf(openedFiles->out, "\nIl server ha espulso i seguenti file:\n"); fflush(openedFiles->out); @@ -267,7 +264,7 @@ int openFile(const char* pathname, int flags) { fflush(openedFiles->out); } if(storeFilesInDirectory(openedFiles->wDir, res->numfiles, res->rf) == -1) { - perror("storeFilesindirectory"); + perror("openFile: storeFilesindirectory"); freeResponse(res); free(res); free(cmd); @@ -282,7 +279,7 @@ int openFile(const char* pathname, int flags) { } if(addOpenFile(pathname, flags) == -1) { - perror("addOpenFile"); + perror("openFile: addOpenFile"); return -1; } @@ -291,7 +288,7 @@ int openFile(const char* pathname, int flags) { free(openedFiles->createdAndLocked); openedFiles->createdAndLocked = calloc(strlen(pathname)+1, sizeof(char)); if(!openedFiles->createdAndLocked) { - perror("calloc"); + perror("openFile: calloc"); freeResponse(res); free(res); free(cmd); @@ -325,49 +322,51 @@ int readFile(const char* pathname, void** buf, size_t* size) { return -1; } - if(isOpen(pathname, 0) != 1) { // if it's not open => error + if(isOpen(pathname, 0) != 1) { /* if it's not open => error */ errno = EPERM; return -1; } - // invio al server la stringa readFile|$(pathname)" + /* send to server the string readFile|$(pathname)" */ long len = strlen("readFile")+1+strlen(pathname)+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("readFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "readFile|%s", pathname); len = strnlen(cmd, len); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("readFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 1) < 0) { // 1 because if we get a MEOK we expect a file - // errno is set by reciveData + + /* reciveData(, 1) because if we get a MEOK we expect a file */ + if(reciveData(res, 1) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } - if(res->meerrno != 0) { // errno from server + if(res->meerrno != 0) { /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -375,7 +374,7 @@ int readFile(const char* pathname, void** buf, size_t* size) { return -1; } - // no errors from server + /* no errors from server */ if(res->numfiles != 1) { freeResponse(res); free(res); @@ -389,7 +388,7 @@ int readFile(const char* pathname, void** buf, size_t* size) { freeResponse(res); free(res); free(cmd); - perror("malloc"); + perror("readFile: malloc"); return -1; } memcpy(*buf, res->rf[0].file, *size); @@ -404,7 +403,7 @@ int readFile(const char* pathname, void** buf, size_t* size) { fflush(openedFiles->out); } if(storeFilesInDirectory(openedFiles->rDir, 1, res->rf) == -1) { - perror("storeFilesInDirectory"); + perror("readFile: storeFilesInDirectory"); freeResponse(res); free(res); free(cmd); @@ -443,45 +442,47 @@ int readNFiles(int N, const char* dirname) { return -1; } - // invio al server la stringa "readNFiles|$(N)" + /* send to server the string "readNFiles|$(N)" */ int lenght_n = snprintf(NULL, 0, "%d", N); long len = strlen("readNFiles")+1+lenght_n+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("readNFiles: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "readNFiles|%d", N); len = strnlen(cmd, len); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("readNFiles: calloc"); free(cmd); return -1; } - if(reciveData(res, 1) < 0) { // 1 because if we get a MEOK we expect N files - // errno is set by reciveData + + /* reciveData(, 1) because if we get a MEOK we expect N files */ + if(reciveData(res, 1) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } - if(res->meerrno != 0) { // errno from server + if(res->meerrno != 0) { /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -496,9 +497,9 @@ int readNFiles(int N, const char* dirname) { fflush(openedFiles->out); } - // save files to directory + /* save files to directory */ if(storeFilesInDirectory(dirname, res->numfiles, res->rf) == -1) { - perror("storeFilesindirectory"); + perror("readNFiles: storeFilesindirectory"); freeResponse(res); free(res); free(cmd); @@ -536,32 +537,32 @@ int writeFile(const char* pathname, const char* dirname) { return -1; } - // leggo il file da scrivere sul server + /* read the file that needs to be sent to the server */ int fdi = -1; size_t lung = 0; size_t incr = 0; size_t size = 0; if ((fdi = open(pathname, O_RDONLY)) == -1) { - perror("open"); + perror("writeFile: open"); return -1; } - // get file length + /* get file length */ struct stat sb; if (fstat(fdi, &sb) == -1) { - perror("stat"); + perror("writeFile: fstat"); return -1; } lung = sb.st_size; void *content = malloc(lung); if(!content) { - perror("malloc"); + perror("writeFile: malloc"); return -1; } - // read file + /* read file */ while ((incr = read(fdi, content, lung)) > 0) { size += incr; lung -= incr; @@ -578,55 +579,57 @@ int writeFile(const char* pathname, const char* dirname) { } if (close(fdi) == -1) { - perror("closing file"); + perror("writeFile: close"); free(content); return -1; } - // invio al server la stringa "writeFile|$(pathname)|$(size)" + /* send to server the string "writeFile|$(pathname)|$(size)" */ int leng_size = snprintf(NULL, 0, "%zu", size); long len = strlen("writeFile")+1+strlen(pathname)+1+leng_size+1; char *cmd = calloc(len, sizeof(char)); if(!cmd) { - perror("calloc"); + perror("writeFile: calloc"); free(content); return -1; } snprintf(cmd, len, "writeFile|%s|%zu", pathname, size); len = strnlen(cmd, len); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(content); free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(content); free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("writeFile: calloc"); free(content); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we don't expect files - // errno is set by reciveData + /* reciveData(, 0) because if we get a MEOK we don't expect files */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); free(content); return -1; } - if(res->meerrno != 0) { // errno from server + if(res->meerrno != 0) { + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -635,7 +638,7 @@ int writeFile(const char* pathname, const char* dirname) { return -1; } if(strncmp(res->ME, MEFP, sizeof(res->ME)) == 0) { - // some files were purged + /* some files were purged */ if(openedFiles->print){ fprintf(openedFiles->out, "Il server ha espulso i seguenti file:\n"); fflush(openedFiles->out); @@ -645,7 +648,7 @@ int writeFile(const char* pathname, const char* dirname) { } if(dirname) { if(storeFilesInDirectory(dirname, res->numfiles, res->rf) == -1) { - perror("storeFilesindirectory"); + perror("writeFile: storeFilesindirectory"); freeResponse(res); free(res); free(content); @@ -664,9 +667,9 @@ int writeFile(const char* pathname, const char* dirname) { } } - // send file to server + /* send file to server */ if (writen(fd_skt, content, size) == -1) { - // errno set by writen + /* errno set by writen */ freeResponse(res); free(res); free(cmd); @@ -674,16 +677,17 @@ int writeFile(const char* pathname, const char* dirname) { return -1; } - // recive response - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we don't expect files - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we don't expect files */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); free(content); return -1; } - if(res->meerrno != 0) { // errno from server + if(res->meerrno != 0) { /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -729,44 +733,47 @@ int appendToFile(const char* pathname, void* buf, size_t size, const char* dirna fflush(openedFiles->out); } - // invio al server la stringa "appendToFile|$(pathname)|$(size)" - long len = strlen("appendToFile")+1+strlen(pathname)+1+sizeof(size)+1; + /* send to server the string "appendToFile|$(pathname)|$(size)" */ + int leng_size = snprintf(NULL, 0, "%zu", size); + long len = strlen("appendToFile")+1+strlen(pathname)+1+leng_size+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("appendToFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "appendToFile|%s|%zu", pathname, size); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("appendToFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we don't expect files - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we don't expect files */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } - if(res->meerrno != 0) { // errno from server + if(res->meerrno != 0) { /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -775,7 +782,7 @@ int appendToFile(const char* pathname, void* buf, size_t size, const char* dirna } if(strncmp(res->ME, MEFP, sizeof(res->ME)) == 0) { - // some files were purged + /* some files were purged */ if(openedFiles->print){ fprintf(openedFiles->out, "Il server ha espulso i seguenti file:\n"); fflush(openedFiles->out); @@ -785,7 +792,7 @@ int appendToFile(const char* pathname, void* buf, size_t size, const char* dirna } if(dirname) { if(storeFilesInDirectory(dirname, res->numfiles, res->rf) == -1) { - perror("storeFilesindirectory"); + perror("appendToFile: storeFilesindirectory"); freeResponse(res); free(res); free(cmd); @@ -803,9 +810,9 @@ int appendToFile(const char* pathname, void* buf, size_t size, const char* dirna } } - // send file to server + /* send file to server */ if (writen(fd_skt, buf, size) == -1) { - // errno set by writen + /* errno set by writen */ freeResponse(res); free(res); free(cmd); @@ -837,65 +844,65 @@ int lockFile(const char* pathname) { return -1; } - if(isOpen(pathname, O_LOCK)){ // file is already locked + if(isOpen(pathname, O_LOCK)){ /* file is already locked */ return 0; } int existing = 0; - if(isOpen(pathname, 0)){ // file is already open + if(isOpen(pathname, 0)){ /* file is already open */ existing = 1; goto _unlockFile; } - if (openFile(pathname, O_LOCK) == 0) // open the file with the lock + if (openFile(pathname, O_LOCK) == 0) /* open the file with the lock */ return 0; - if (errno == ENOENT) // file created but not locked + if (errno == ENOENT) /* file created but not locked */ goto _unlockFile; - return -1; // errno != ENOENT + return -1; /* errno != ENOENT */ _unlockFile: { - // invio al server la stringa "lockFile|$(pathname)" + /* send to server the string "lockFile|$(pathname)" */ long len = strlen("lockFile")+1+strlen(pathname)+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("lockFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "lockFile|%s", pathname); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("lockFile: calloc"); free(cmd); return -1; } - // 0 because if we get a MEOK we dont expect a file + /* reciveData(, 0) because if we get a MEOK we dont expect a file */ if(reciveData(res, 0) < 0) { - // errno is set by reciveData + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } if(res->meerrno != 0) { - // errno from server + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -905,7 +912,7 @@ _unlockFile: { if(!existing) { if(addOpenFile(pathname, O_LOCK) == -1) { - perror("addOpenFile"); + perror("lockFile: addOpenFile"); freeResponse(res); free(res); free(cmd); @@ -937,49 +944,51 @@ int unlockFile(const char* pathname) { errno = ENOTCONN; return -1; } - if(isOpen(pathname, 0) != 1) { // not open or not locked + if(isOpen(pathname, 0) != 1) { /* not open or not locked */ errno = EPERM; return -1; } - // invio al server la stringa "unlockFile|$(pathname)" + /* send to server the string "unlockFile|$(pathname)" */ long len = strlen("unlockFile")+1+strlen(pathname)+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("unlockFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "unlockFile|%s", pathname); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("unlockFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we dont expect a file - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we dont expect a file */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } if(res->meerrno != 0) { - // errno from server + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -1011,49 +1020,51 @@ int closeFile(const char *pathname) { return -1; } - if(isOpen(pathname, 0) != 1) { // not open + if(isOpen(pathname, 0) != 1) { /* not open */ errno = EPERM; return -1; } - // invio al server la stringa "closeFile|$(pathname)" + /* invio al server la stringa "closeFile|$(pathname)" */ long len = strlen("closeFile")+1+strlen(pathname)+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("closeFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "closeFile|%s", pathname); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("closeFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we dont expect a file - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we dont expect a file */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } if(res->meerrno != 0) { - // errno from server + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -1062,7 +1073,7 @@ int closeFile(const char *pathname) { } if (removeOpenFile(pathname) == -1) { - perror("removeOpenFile"); + perror("closeFile: removeOpenFile"); } else { openedFiles->numOfFiles--; } @@ -1092,49 +1103,51 @@ int removeFile(const char* pathname) { return -1; } - if (isOpen(pathname, 0) != 1) { // not open + if (isOpen(pathname, 0) != 1) { /* not open */ errno = EPERM; return -1; } - // invio al server la stringa "removeFile|$(pathname)" + /* send to server the string "removeFile|$(pathname)" */ long len = strlen("removeFile")+1+strlen(pathname)+1; char *cmd = malloc(len); if(!cmd) { - perror("malloc"); + perror("removeFile: malloc"); return -1; } memset(cmd, 0, len); snprintf(cmd, len, "removeFile|%s", pathname); - // send cmd + /* send cmd */ if (writen(fd_skt, &len, sizeof(long)) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } if (writen(fd_skt, cmd, len) == -1) { - // writen sets errno + /* writen sets errno */ free(cmd); return -1; } - // recive response + /* recive response */ response_t *res = calloc(1, sizeof(response_t)); if(!res){ - perror("calloc"); + perror("removeFile: calloc"); free(cmd); return -1; } - if(reciveData(res, 0) < 0) { // 0 because if we get a MEOK we dont expect a file - // errno is set by reciveData + + /* reciveData(, 0) because if we get a MEOK we dont expect a file */ + if(reciveData(res, 0) < 0) { + /* errno is set by reciveData */ freeResponse(res); free(res); free(cmd); return -1; } if(res->meerrno != 0) { - // errno from server + /* errno from server */ freeResponse(res); errno = res->meerrno; free(res); @@ -1143,7 +1156,7 @@ int removeFile(const char* pathname) { } if (removeOpenFile(pathname) == -1) { - perror("removeOpenFile"); + perror("removeFile: removeOpenFile"); } else { openedFiles->numOfFiles--; } @@ -1154,7 +1167,6 @@ int removeFile(const char* pathname) { } // ----------------------------------------------------------------------------- - int setDirectory(char* Dir, int rw) { if (!Dir) { errno = EINVAL; @@ -1190,10 +1202,10 @@ int setDirectory(char* Dir, int rw) { } void printInfo(int p, FILE *stream) { - // 1 prints, 0 does not print + /* 1 prints, 0 does not print */ if(!openedFiles) { if(createOpenedFiles()<0) { - perror("createOpenedfiles"); + perror("printInfo: createOpenedfiles"); return; } } @@ -1203,6 +1215,7 @@ void printInfo(int p, FILE *stream) { } // ----------------------------------------------------------------------------- +// helper functions int reciveData(response_t *res, int expected) { if(!res) { @@ -1213,21 +1226,21 @@ int reciveData(response_t *res, int expected) { int readnres; readnres = readn(fd_skt, &res->ME, sizeof(res->ME)); if(readnres <= 0) { - // readn sets errno + /* readn sets errno */ return -1; } - if(expected == 0) // no file expected + if(expected == 0) /* no file expected */ goto _nofile; - // file is expected + /* file is expected */ if(strncmp(res->ME, MEOK, sizeof(res->ME))==0){ - // ok response + /* ok response */ res->meerrno = 0; - // get number of files sent + /* get number of files sent */ readnres = readn(fd_skt, &res->numfiles, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; if(res->rf) @@ -1240,40 +1253,40 @@ int reciveData(response_t *res, int expected) { res->rf = calloc(res->numfiles, sizeof(recivedFile_t)); if(!res->rf){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } - // get files + /* get files */ for(int i=0;inumfiles;++i) { - // read path + /* read path */ readnres = readn(fd_skt, &res->rf[i].pathlen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; res->rf[i].path = calloc(res->rf[i].pathlen, sizeof(char)); if(!res->rf[i].path){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].path, res->rf[i].pathlen); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; - // we replace '/' char with '-' + /* we replace '/' char with '-' */ for(int j=0;jrf[i].pathlen; ++j){ if(res->rf[i].path[j] == '/') res->rf[i].path[j] = '-'; } - // read file + /* read file */ readnres = readn(fd_skt, &res->rf[i].filelen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; if(res->rf[i].filelen == 0) { res->rf[i].file = calloc(1, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } continue; @@ -1281,61 +1294,61 @@ int reciveData(response_t *res, int expected) { res->rf[i].file = calloc(res->rf[i].filelen, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].file, res->rf[i].filelen); - if(readnres<=0) {// readn sets errno + if(readnres<=0) {/* readn sets errno */ return -1; } } return 0; } if(strncmp(res->ME, MEFP, sizeof(res->ME))==0){ - // file purged + /* file purged */ res->meerrno = 0; - // get number of files sent + /* get number of files sent */ readnres = readn(fd_skt, &res->numfiles, sizeof(int)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; if(res->rf) free(res->rf); res->rf = calloc(res->numfiles, sizeof(recivedFile_t)); if(!res->rf){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } - // get files + /* get files */ for(int i=0;inumfiles;++i) { - // read path + /* read path */ readnres = readn(fd_skt, &res->rf[i].pathlen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; res->rf[i].path = calloc(res->rf[i].pathlen, sizeof(char)); if(!res->rf[i].path){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].path, res->rf[i].pathlen); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; - // we replace '/' char with '-' + /* we replace '/' char with '-' */ for(int j=0;jrf[i].pathlen; ++j){ if(res->rf[i].path[j] == '/') res->rf[i].path[j] = '-'; } - // read file + /* read file */ readnres = readn(fd_skt, &res->rf[i].filelen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; if(res->rf[i].filelen == 0) { res->rf[i].file = calloc(1, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } continue; @@ -1343,40 +1356,40 @@ int reciveData(response_t *res, int expected) { res->rf[i].file = calloc(res->rf[i].filelen, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].file, res->rf[i].filelen); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; } return 0; } if(strncmp(res->ME, MESD, sizeof(res->ME))==0){ - // server shutting down + /* server shutting down */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MENT, sizeof(res->ME))==0){ - // requested file action not taken + /* requested file action not taken */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MESY, sizeof(res->ME))==0){ - // syntax error + /* syntax error */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MESE, sizeof(res->ME))==0){ - // server error + /* server error */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } @@ -1391,16 +1404,16 @@ _nofile: res->rf = NULL; if(strncmp(res->ME, MEOK, sizeof(res->ME))==0){ - // simple ok response + /* simple ok response */ res->meerrno = 0; return 0; } if(strncmp(res->ME, MEFP, sizeof(res->ME))==0){ - // file purged + /* file purged */ res->meerrno = 0; - // get number of files sent + /* get number of files sent */ readnres = readn(fd_skt, &res->numfiles, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; @@ -1408,80 +1421,80 @@ _nofile: free(res->rf); res->rf = calloc(res->numfiles, sizeof(recivedFile_t)); if(!res->rf){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } - // get files + /* get files */ for(int i=0;inumfiles;++i) { - // read path + /* read path */ readnres = readn(fd_skt, &res->rf[i].pathlen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; res->rf[i].path = calloc(res->rf[i].pathlen, sizeof(char)); if(!res->rf[i].path){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].path, res->rf[i].pathlen); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; - // we replace '/' char with '-' + /* we replace '/' char with '-' */ for(int j=0;jrf[i].pathlen; ++j){ if(res->rf[i].path[j] == '/') res->rf[i].path[j] = '-'; } - // read file + /* read file */ readnres = readn(fd_skt, &res->rf[i].filelen, sizeof(int64_t)); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; - // file has lenght 0 -> allocate memory but dont read + /* file has lenght 0 -> allocate memory but dont read */ if(res->rf[i].filelen == 0) { res->rf[i].file = calloc(1, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } continue; } res->rf[i].file = calloc(res->rf[i].filelen, sizeof(char)); if(!res->rf[i].file){ - perror("calloc"); + perror("reciveData: calloc"); return -1; } readnres = readn(fd_skt, res->rf[i].file, res->rf[i].filelen); - if(readnres<=0) // readn sets errno + if(readnres<=0) /* readn sets errno */ return -1; } return 0; } if(strncmp(res->ME, MESD, sizeof(res->ME))==0){ - // server shutting down + /* server shutting down */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MENT, sizeof(res->ME))==0){ - // requested file action not taken + /* requested file action not taken */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MESY, sizeof(res->ME))==0){ - // syntax error + /* syntax error */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } if(strncmp(res->ME, MESE, sizeof(res->ME))==0){ - // server error + /* server error */ readnres = readn(fd_skt, &res->meerrno, sizeof(errno)); - if(readnres <= 0)// readn sets errno + if(readnres <= 0)/* readn sets errno */ return -1; return 0; } @@ -1496,27 +1509,27 @@ int storeFilesInDirectory(const char *dirname, int n, recivedFile_t *rf) { return -1; } - // create directory + /* create directory */ if(mkdir(dirname, 0777) == -1) { - if(errno != EEXIST) { // unknown error + if(errno != EEXIST) { /* unknown error */ return -1; } } - size_t basepathlen = strlen(dirname)+1+1; // +1 for '/' and +1 for '\0' + size_t basepathlen = strlen(dirname)+1+1; /* +1 for '/' and +1 for '\0' */ char *basepath = calloc(basepathlen, sizeof(char)); if(!basepath) { - perror("calloc"); + perror("storeFilesInDirectory: calloc"); return -1; } strcpy(basepath, dirname); strncat(basepath, "/", basepathlen); - // for each file, create and write + /* for each file, create and write */ for(int i=0;ilocked = flags&O_LOCK; new->filename = calloc(len, sizeof(char)); if(!new->filename) { - perror("calloc"); + perror("addOpenFile: calloc"); free(new); return -1; } @@ -1638,7 +1651,7 @@ int removeOpenFile(const char *pathname) { files_t *tmp = openedFiles->f; - // the element to remove is the first + /* the element to remove is the first */ if(strcmp(tmp->filename, pathname) == 0) { openedFiles->f = tmp->next; free(tmp->filename); @@ -1659,7 +1672,7 @@ int removeOpenFile(const char *pathname) { } } - // file not found + /* file not found */ errno = ENOENT; return -1; } @@ -1677,7 +1690,7 @@ int closeEveryFile() { if(closeFile(prc->filename) != 0) { if(removeOpenFile(prc->filename) != 0) { - perror("removeOpenfile"); + perror("closeEveryFile: removeOpenfile"); } openedFiles->numOfFiles--; } @@ -1704,10 +1717,10 @@ int closeEveryFile() { return 0; } -int createOpenedFiles(void) { +int createOpenedFiles() { openedFiles = calloc(1, sizeof(*openedFiles)); if(!openedFiles) { - perror("calloc"); + perror("createOpenedFiles: calloc"); return -1; } openedFiles->f = NULL; diff --git a/lib/api/api.h b/lib/api/api.h index c53b453..092efd2 100644 --- a/lib/api/api.h +++ b/lib/api/api.h @@ -9,37 +9,137 @@ struct timespec; #define O_CREATE 1 #define O_LOCK 2 -// struttura dati per la lista dei file aperti -typedef struct openFile_s { - char *filename; // nome del file - struct openFile_s *next; // puntatore al prossimo elemento nella lista -} openFile_t; +/** + * @brief Opens a connection over the unix socket + * + * @param socketname path to the socket + * @param msec milliseconds between tries + * @param abstime maximum time spent tring to connect + * @return 0 if connection has been established, -1 if an error has occurred + */ +int openConnection(const char *sockname, int msec, const struct timespec abstime); -int openConnection(const char* sockname, int msec, const struct timespec abstime); +/** + * @brief Closes the connection to the server + * + * @param socketname path to the socket + * @return 0 if successful, -1 if an error has occurred + */ +int closeConnection(const char *sockname); -int closeConnection(const char* sockname); +/** + * @brief Open or create a file on the server + * + * @param pathname name of the file to open + * @param flags can be 0, O_CREATE, O_LOCK or O_CREATE | O_LOCK + * @return 0 if successful, -1 if an error has occurred + */ +int openFile(const char *pathname, int flags); -int openFile(const char* pathname, int flags); +/** + * @brief Reads a file on the server and saves the content to the buffer + * + * @param pathname name of the file to read + * @param buf buffer that will hold the content of the file read + * @param size size of the buffer + * @return 0 if successful, -1 if an error has occurred + * + * @note buf is not deallocated before being reassigned + */ +int readFile(const char *pathname, void** buf, size_t *size); -int readFile(const char* pathname, void** buf, size_t* size); +/** + * @brief Reads N files on the server + * + * @pre program must have rights over the directory + * + * @param N number of files to read, if N<1 all files available will be read + * @param dirname path to directory to write the files into + * @return 0 if successful, -1 if an error has occurred + */ +int readNFiles(int N, const char *dirname); -int readNFiles(int N, const char* dirname); +/** + * @brief Sends a file to the server + * + * @pre program must have rights over the directory + * + * @param pathname name of the file to write + * @param dirname directory in witch files sent from the server may be written + * @return 0 if successful, -1 if an error has occurred + */ +int writeFile(const char *pathname, const char *dirname); -int writeFile(const char* pathname, const char* dirname); +/** + * @brief Appends the buffer to the file specified + * + * @pre program must have rights over the directory + * + * @param pathname name of the file to append to + * @param buf data to append + * @param size size of data to append + * @param dirname directory in witch files sent from the server may be written + * @return 0 if successful, -1 if an error has occurred + */ +int appendToFile(const char *pathname, void *buf, size_t size, const char *dirname); -int appendToFile(const char* pathname, void* buf, size_t size, const char* dirname); +/** + * @brief Acquire the lock over the file + * + * @param pathname name of the file to lock + * @return 0 if successful, -1 if an error has occurred + */ +int lockFile(const char *pathname); -int lockFile(const char* pathname); - -int unlockFile(const char* pathname); +/** + * @brief Relese the lock over the file + * + * @pre file must be opened and locked + * + * @param pathname name of the file to unlock + * @return 0 if successful, -1 if an error has occurred + */ +int unlockFile(const char *pathname); +/** + * @brief Closes the file + * + * @pre file must be opened + * + * @param pathname name of the file to close + * @return 0 if successful, -1 if an error has occurred + */ int closeFile(const char *pathname); -int removeFile(const char* pathname); +/** + * @brief Deletes the file from the server + * + * @pre file must be opened and locked + * + * @param pathname name of the file to close + * @return 0 if successful, -1 if an error has occurred + */ +int removeFile(const char *pathname); -int setDirectory(char* Dir, int rw); +// ----------------------------------------------------------------------------- +/** + * @brief Sets the default directory to saves files into if a capacity miss + * occurs + * + * @param Dir name of the directory + * @param rw 0 for read directory, 1 for writing directory + * @return 0 if successful, -1 if an error has occurred + */ +int setDirectory(char *Dir, int rw); +/** + * @brief Sets verbose mode and where to print + * + * @param p true if printing, 0 if not printing + * @param stream where to print + * @return 0 if successful, -1 if an error has occurred + */ void printInfo(int p, FILE *stream); #endif /* _API_CLIENT */ diff --git a/src/client.c b/src/client.c index 9080931..4db601d 100644 --- a/src/client.c +++ b/src/client.c @@ -1,59 +1,59 @@ #define _POSIX_C_SOURCE 200809L +#include +#include #include #include #include #include #include #include -#include -// fts uses this type but is not defined anywhere +/* fts uses this type but is not defined anywhere for xubuntu */ typedef unsigned short u_short; -#include #include #include #include -#include -#include +#include "api.h" +#include "strsep_gnu.h" #define UNIX_PATH_MAX 256 #define MAXARGLENGTH 256 -// path of socket +/* path of socket */ static char globalSocket[UNIX_PATH_MAX] = ""; -// structure of the command list +/* structure of the command list */ typedef struct cmd_s { - char name; // name of the command - char *arg; // argument of the command - struct cmd_s *next; // pointer to next element + char name; /* name of the command */ + char *arg; /* argument of the command */ + struct cmd_s *next; /* pointer to next element */ } cmd_t; // ----------------------------------------------------------------------------- // helper functions -// frees command list's memory +/* frees command list's memory */ void destroyCommandList(cmd_t *l); -// adds a command to the list +/* adds a command to the list */ int addCommand(cmd_t **l, char cmd, char *arg); -// reorder the list +/* reorder the list */ int reorderCommandList(cmd_t **l); -// execute all commands +/* execute all commands */ int execute(cmd_t *l, int print); -// close connection before the exit +/* close connection before the exit */ void cleanup() { if (strncmp(globalSocket, "", 2) != 0) { closeConnection(globalSocket); strncpy(globalSocket, "", 2); } } -// to compare files (fts) +/* to compare files (fts) */ int compare(const FTSENT ** first, const FTSENT ** second) { return (strcmp((*first)->fts_name, (*second)->fts_name)); } -// -h +/* -h */ static void usage(const char *argv0) { printf("Uso: %s\n", argv0); printf("-h: stampa il presente messaggio d'aiuto.\n"); @@ -70,21 +70,21 @@ static void usage(const char *argv0) { printf("-c file1[,file2]: rimuovi dal server una lista di file (se presenti), separati da virgole.\n"); printf("-p: stampa sullo standard output le informazioni riguardo ogni operazione effettuata.\n"); } -// -f +/* -f */ int cmd_f(char *socket); -// -w +/* -w */ int cmd_w(char *dirname, char *Dir, int print); -// -W +/* -W */ int cmd_W(char *filelist, char *Dir, int print); -// -r +/* -r */ int cmd_r(char *filelist, char *dir, int print); -// -R +/* -R */ int cmd_R(char *numStr, char *dir, int print); -// -l +/* -l */ int cmd_l(char *filelist, int print); -// -u +/* -u */ int cmd_u(char *filelist, int print); -// -c +/* -c */ int cmd_c(char *filelist, int print); @@ -93,14 +93,14 @@ int cmd_c(char *filelist, int print); int main(int argc, char* argv[]) { atexit(cleanup); - if(argc <= 1) { // no arguments => -h + if(argc <= 1) { /* no arguments => -h */ usage(argv[0]); return 0; } struct sigaction siga; - // ignore SIGPIPE + /* ignore SIGPIPE */ memset(&siga, 0, sizeof(siga)); siga.sa_handler = SIG_IGN; if (sigaction(SIGPIPE, &siga, NULL) == -1) { @@ -108,7 +108,7 @@ int main(int argc, char* argv[]) { return 1; } - // list of commands + /* list of commands */ cmd_t *cmds = NULL; int opt = 0; @@ -117,13 +117,13 @@ int main(int argc, char* argv[]) { int print = 0; char f = 0; - // add args to command list + /* add args to command list */ while ((opt = getopt(argc, argv, ":hpf:t:w:W:D:r:R:d:l:u:c:")) != -1) { switch (opt) { - case 'h': // help message + case 'h': /* help message */ usage(argv[0]); goto _cleanup; - case 'f': // name of socket + case 'f': /* name of socket */ if(!f) { if (optarg && strnlen(optarg, MAXARGLENGTH) > 0 && optarg[0] == '-') { fprintf(stderr, "Il comando -f necessita di un argomento.\n"); @@ -135,12 +135,12 @@ int main(int argc, char* argv[]) { ++f; } break; - case 'p': // print to stdout + case 'p': /* print to stdout */ if(!print) printInfo(1, stdout); print|=1; break; - case 'w': // send file from folder (n is read later) + case 'w': /* send file from folder (n is read later) */ if (optarg && strnlen(optarg, MAXARGLENGTH) > 0 && optarg[0] == '-') { fprintf(stderr, "Il comando -w necessita di un argomento.\n"); goto _cleanup; @@ -149,14 +149,14 @@ int main(int argc, char* argv[]) { strncpy(args, optarg, strnlen(optarg, MAXARGLENGTH-1)+1); addCommand(&cmds, opt, args); break; - case 'W': // files to send separated by ',' - case 'D': // dir to write file into - case 'r': // files to read from server separated by ',' - case 'd': // dir to write read files into - case 't': // time in ms between requests - case 'l': // file to request lock on separated by ',' - case 'u': // file to relese lock on separated by ',' - case 'c': // file to delete separated by ',' + case 'W': /* files to send separated by ',' */ + case 'D': /* dir to write file into */ + case 'r': /* files to read from server separated by ',' */ + case 'd': /* dir to write read files into */ + case 't': /* time in ms between requests */ + case 'l': /* file to request lock on separated by ',' */ + case 'u': /* file to relese lock on separated by ',' */ + case 'c': /* file to delete separated by ',' */ if (optarg && strnlen(optarg, MAXARGLENGTH) > 0 && optarg[0] == '-') { fprintf(stderr, "Il comando -%c necessita di un argomento.\n", optopt); goto _cleanup; @@ -165,7 +165,7 @@ int main(int argc, char* argv[]) { strncpy(args, optarg, strnlen(optarg, MAXARGLENGTH-1)+1); addCommand(&cmds, opt, args); break; - case 'R': // read n random files + case 'R': /* read n random files */ if (optarg && strnlen(optarg, MAXARGLENGTH) > 0 && optarg[0] == '-') { optind -= 1; addCommand(&cmds, opt, NULL); @@ -175,7 +175,7 @@ int main(int argc, char* argv[]) { strncpy(args, optarg, strnlen(optarg, MAXARGLENGTH-1)+1); addCommand(&cmds, opt, args); break; - case ':': // command with no argument (:: is a GNU extension) + case ':': /* command with no argument (:: is a GNU extension) */ switch(optopt) { case 'R': addCommand(&cmds, opt, NULL); @@ -185,8 +185,8 @@ int main(int argc, char* argv[]) { goto _cleanup; } break; - case '?': // unknown - default: // unknown + case '?': /* unknown */ + default: /* unknown */ fprintf(stderr, "Comando non riconosciuto: -%c.\n", optopt); usage(argv[0]); goto _cleanup; @@ -224,7 +224,7 @@ void destroyCommandList(cmd_t *l) { } cmd_t *tmp; - // visit every node and free memory + /* visit every node and free memory */ while (l) { tmp = l; @@ -259,7 +259,7 @@ int addCommand(cmd_t **l, char cmd, char *arg) { } new->next = NULL; - // if empty list -> add to the top + /* if empty list -> add to the top */ if (*l == NULL) { *l = new; return 0; @@ -274,8 +274,10 @@ int addCommand(cmd_t **l, char cmd, char *arg) { return 0; } -// inverts the order of -D and -d angainst -w, -W or -r, -R -// and adds -D/-d /dev/null after +/** + * inverts the order of -D and -d angainst -w, -W or -r, -R and + * adds -D/-d /dev/null after + */ int reorderCommandList(cmd_t **l) { if(!l) { errno = EINVAL; @@ -295,7 +297,7 @@ int reorderCommandList(cmd_t **l) { fprintf(stderr, "Il comando -d necessita -r o -R prima\n"); return -1; } - { // invert tmp and prev + { /* invert tmp and prev */ cmd_t t; t.arg = tmp->arg; t.name = tmp->name; @@ -310,7 +312,7 @@ int reorderCommandList(cmd_t **l) { if(!tmp->next) break; - // add redirect to /dev/null for next command if it's r or R + /* add redirect to /dev/null for next command if it's r or R */ if(tmp->next->name == 'r' || tmp->next->name == 'R') { cmd_t *new = calloc(1, sizeof(*new)); if(!new){ @@ -338,7 +340,7 @@ int reorderCommandList(cmd_t **l) { fprintf(stderr, "Il comando -D necessita -w o -W prima\n"); return -1; } - { // invert tmp and prev + { /* invert tmp and prev */ cmd_t t; t.arg = tmp->arg; t.name = tmp->name; @@ -353,7 +355,7 @@ int reorderCommandList(cmd_t **l) { if(!tmp->next) break; - // add redirect to dev/null for next command if it's w or W + /* add redirect to dev/null for next command if it's w or W */ if(tmp->next->name == 'w' || tmp->next->name == 'W') { cmd_t *new = calloc(1, sizeof(*new)); if(!new){ @@ -397,19 +399,19 @@ int execute(cmd_t *l, int print) { interval.tv_nsec = 0; interval.tv_sec = 0; - // loop that serches for -t + /* loop that serches for -t */ while(tmp) { switch(tmp->name) { - case 't': { // time in ms between requests + case 't': { /* time in ms between requests */ long num; num = strtol(tmp->arg, NULL, 10); if(num==0 && errno==EINVAL) { fprintf(stderr, "t - Tempo non riconosciuto dopo l'opzione -t\n"); return -1; } - // milliseconds to nanoseconds + /* milliseconds to nanoseconds */ interval.tv_nsec = (num%1000) * 1000000; - // seconds + /* seconds */ interval.tv_sec = (num/1000); if (print) @@ -427,7 +429,7 @@ int execute(cmd_t *l, int print) { fflush(stdout); - // loop that serches for -f + /* loop that serches for -f */ tmp = l; while(tmp) { switch(tmp->name) { @@ -448,10 +450,10 @@ int execute(cmd_t *l, int print) { } if(!ok) { closeConnection(tmp->arg); - return 0; // no socket to connect, nothing to do + return 0; /* no socket to connect, nothing to do */ } - // we only read the first -f, no error reported if more than one is - // specified + /* we only read the first -f, no error reported if more than one is + * specified */ tmp = NULL; break; } @@ -463,11 +465,11 @@ int execute(cmd_t *l, int print) { } fflush(stdout); - // loop that checks for consistencies: - // 1) -D with no -w or -W after - // 2) -d with no -r or -R after - // reduntant since we also reorder before but this function could be used - // alone so we have to check + /* loop that checks for consistencies: + * 1) -D with no -w or -W after + * 2) -d with no -r or -R after + * reduntant since we also reorder before but this function could be used + * alone so we have to check */ tmp = l; int unmachedD = 0; int unmachedd = 0; @@ -510,10 +512,10 @@ int execute(cmd_t *l, int print) { } fflush(stdout); - char *Dir = NULL; // -D folder - char *dir = NULL; // -d folder + char *Dir = NULL; /* -D folder */ + char *dir = NULL; /* -d folder */ - // loop that executes -w, -W, -D; -r, -R, -d; -l, -u, -c + /* loop that executes -w, -W, -D; -r, -R, -d; -l, -u, -c */ tmp = l; while(tmp) { switch (tmp->name) { @@ -567,7 +569,7 @@ int execute(cmd_t *l, int print) { default: break; } - // maybe better: while(nanosleep(&interval, &interval)); + /* maybe better: while(nanosleep(&interval, &interval)); */ nanosleep(&interval, NULL); tmp = tmp->next; } @@ -590,7 +592,7 @@ int execute(cmd_t *l, int print) { // ----------------------------------------------------------------------------- // commands -// -f +/* -f */ int cmd_f(char *socket) { if(!socket) { errno = EINVAL; @@ -607,7 +609,7 @@ int cmd_f(char *socket) { return 0; } -// -w +/* -w */ int cmd_w(char *dirname, char *Dir, int print) { if(!dirname) { errno = EINVAL; @@ -615,7 +617,7 @@ int cmd_w(char *dirname, char *Dir, int print) { } int num; - // copy dirname because we modify it after + /* copy dirname because we modify it after */ char *tofree = calloc(strnlen(dirname, MAXARGLENGTH)+1, sizeof(char)); if(!tofree) { perror("cmd_w: calloc"); @@ -625,7 +627,7 @@ int cmd_w(char *dirname, char *Dir, int print) { char *firstArg; char *secondArg = tofree; - firstArg = strsep_gnu(&secondArg, ","); // secondArg has the number of files + firstArg = strsep_gnu(&secondArg, ","); /* secondArg has the number of files */ if (!secondArg) { num = -1; @@ -649,8 +651,8 @@ int cmd_w(char *dirname, char *Dir, int print) { if (print) printf("w - Scrivo i seguenti file sul server:\n"); - // we use fts to traverse all files in the directory recursively - // and write them to a list so that we can open them later + /* we use fts to traverse all files in the directory recursively + * and write them to a list so that we can open them later */ FTS *fhandle = NULL; FTSENT *child = NULL; FTSENT *parent = NULL; @@ -661,12 +663,12 @@ int cmd_w(char *dirname, char *Dir, int print) { int numFiles = 0; if(fhandle != NULL) { - // we check for num == 0 so that -1 yields all files in folder + /* we check for num == 0 so that -1 yields all files in folder */ while (num!=0 && (parent = fts_read(fhandle)) != NULL) { child = fts_children(fhandle, 0); - while (num!=0 && (child != NULL)) { // for all children in folder - if(child->fts_info == FTS_F) { // if child is a file + while (num!=0 && (child != NULL)) { /* for all children in folder */ + if(child->fts_info == FTS_F) { /* if child is a file */ ++numFiles; listFiles = realloc(listFiles, numFiles * sizeof(char *)); listFiles[numFiles-1] = calloc(child->fts_namelen + child->fts_pathlen + 2, sizeof(char)); @@ -683,7 +685,7 @@ int cmd_w(char *dirname, char *Dir, int print) { if(print) { printf("%s [", listFiles[i]); } - // we send the file with cmd_W but set print to 0 + /* we send the file with cmd_W but set print to 0 */ int r = cmd_W(listFiles[i], Dir, 0); if(print && !r) { printf("Esito: ok"); @@ -703,14 +705,14 @@ int cmd_w(char *dirname, char *Dir, int print) { return 0; } -// -W +/* -W */ int cmd_W(char *filelist, char *Dir, int print) { if(!filelist) { errno = EINVAL; return -1; } - // we copy filelist because we modify it later + /* we copy filelist because we modify it later */ char *tofree = malloc(strnlen(filelist, MAXARGLENGTH)+1); if(!tofree) { perror("cmd_W: malloc"); @@ -726,7 +728,7 @@ int cmd_W(char *filelist, char *Dir, int print) { printf("W - Scrivo i seguenti file sul server:\n"); } - int r = 0; // return value + int r = 0; /* return value */ while ((token = strsep_gnu(&string, ",")) != NULL) { int ok = 1; int opened = 0; @@ -735,21 +737,21 @@ int cmd_W(char *filelist, char *Dir, int print) { fflush(stdout); } - // create the file locked + /* create the file locked */ if (openFile(token, O_CREATE | O_LOCK) == -1) { ok = 0; - } else { // success + } else { /* success */ opened = 1; } - // write to the file + /* write to the file */ if (opened && (writeFile(token, Dir) == -1)) { ok = 0; } - if (opened && !ok) { // previous error -> delete the empty file + if (opened && !ok) { /* previous error -> delete the empty file */ removeFile(token); - } else if (opened && (closeFile(token) == -1)) { // close the file + } else if (opened && (closeFile(token) == -1)) { /* close the file */ ok = 0; } @@ -773,14 +775,14 @@ int cmd_W(char *filelist, char *Dir, int print) { return r; } -// -r +/* -r */ int cmd_r(char *filelist, char *dir, int print) { if (!filelist) { errno = EINVAL; return -1; } - // we copy filelist because we modify it later + /* we copy filelist because we modify it later */ char *tofree = malloc(strnlen(filelist, MAXARGLENGTH)+1); if(!tofree) { perror("cmd_r: malloc"); @@ -805,7 +807,7 @@ int cmd_r(char *filelist, char *dir, int print) { printf("%s ", token); } - // open the file + /* open the file */ if (openFile(token, 0) == -1) { ok = 0; } else { @@ -816,7 +818,7 @@ int cmd_r(char *filelist, char *dir, int print) { size_t size = -1; printInfo(0, stdout); - // read the content of the file + /* read the content of the file */ if (ok && readFile(token, &buf, &size) == -1) { fprintf(stderr, "Errore durante la readFile\n"); ok = 0; @@ -832,7 +834,7 @@ int cmd_r(char *filelist, char *dir, int print) { free(buf); } - // close the file + /* close the file */ if (opened && closeFile(token) == -1) { fprintf(stderr, "Errore durante la closeFile\n"); ok = 0; @@ -861,7 +863,7 @@ int cmd_r(char *filelist, char *dir, int print) { return 0; } -// -R +/* -R */ int cmd_R(char *numStr, char *dir, int print) { if (print) { printf("R - Leggo i seguenti file dal server:\n"); @@ -869,7 +871,7 @@ int cmd_R(char *numStr, char *dir, int print) { } int n = -1; - if(!numStr) // skips the step of converting n from string to int + if(!numStr) /* skips the step of converting n from string to int */ goto skipGetNumber; if(strlen(numStr) < 2) @@ -904,14 +906,14 @@ skipGetNumber: return 0; } -// -l +/* -l */ int cmd_l(char *filelist, int print) { if (!filelist) { errno = EINVAL; return -1; } - // we copy filelist because we modify it later + /* we copy filelist because we modify it later */ char *tofree = calloc(strnlen(filelist, MAXARGLENGTH)+1, sizeof(char)); if(!tofree) { perror("cmd_l: malloc"); @@ -948,14 +950,14 @@ int cmd_l(char *filelist, int print) { return 0; } -// -u +/* -u */ int cmd_u(char *filelist, int print) { if (!filelist) { errno = EINVAL; return -1; } - // we copy filelist because we modify it later + /* we copy filelist because we modify it later */ char *tofree = calloc(strnlen(filelist, MAXARGLENGTH)+1, sizeof(char)); if(!tofree) { perror("cmd_u: calloc"); @@ -992,14 +994,14 @@ int cmd_u(char *filelist, int print) { return 0; } -// -c +/* -c */ int cmd_c(char *filelist, int print) { if (!filelist) { errno = EINVAL; return -1; } - // we copy filelist because we modify it later + /* we copy filelist because we modify it later */ char *tofree = calloc(strnlen(filelist, MAXARGLENGTH)+1, sizeof(char)); if(!tofree) { perror("cmd_c: calloc"); diff --git a/src/server.c b/src/server.c index 8d89f2a..6520275 100644 --- a/src/server.c +++ b/src/server.c @@ -9,21 +9,21 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "threadpool.h" +#include "conn.h" +#include "util.h" +#include "serverWorker.h" +#include "ini.h" +#include "serverUtil.h" +#include "fileQueue.h" +#include "taglialegna.h" typedef struct { - sigset_t *set; // set of signals to handle (masked) - int signal_pipe; // unnamed pipe's descriptor + sigset_t *set; /* set of signals to handle (masked) */ + int signal_pipe; /* unnamed pipe's descriptor */ } sigHandler_t; -// signal handler thread function +/* signal handler thread function */ static void *sigHandler(void *arg); static void usage(const char *argv0) { @@ -45,7 +45,7 @@ static void checkargs(int argc, char* argv[]) { } int main(int argc, char *argv[]) { - // read config file + /* read config file */ checkargs(argc, argv); ini_t *config = ini_load(argv[1]); int threadsInPool; CONFGETINT(threadsInPool, config, "threadpool", "quantity", NULL, 10); @@ -63,7 +63,7 @@ int main(int argc, char *argv[]) { sigset_t mask; sigfillset(&mask); - sigdelset(&mask, SIGPIPE); // only sigpipe is excluded + sigdelset(&mask, SIGPIPE); /* only sigpipe is excluded */ if (pthread_sigmask(SIG_SETMASK, &mask, NULL) != 0) { fprintf(stderr, "Error: setting mask.\n"); @@ -79,19 +79,19 @@ int main(int argc, char *argv[]) { (void) unlink(socketName); - // create structure for logging + /* create structure for logging */ taglia = taglia_init(logFile, 0); - free(logFile); // free the name of the file + free(logFile); /* free the name of the file */ if(taglia==NULL) { perror("main: taglia_init"); goto _cleanup_beforesigthread; } - // buffer for loggin + /* buffer for loggin */ char buf[2048]; int n; - // pipes for comunication between main thread, sigHandler thread - // and worker threads + /* pipes for comunication between main thread, sigHandler thread + * and worker threads */ int signal_pipe[2]; int request_pipe[2]; if (pipe(signal_pipe) == -1) { @@ -104,7 +104,7 @@ int main(int argc, char *argv[]) { } - // thread for handling interruptions + /* thread for handling interruptions */ pthread_t sighandler_thread; sigHandler_t handlerArgs = { &mask, signal_pipe[1] }; if (pthread_create(&sighandler_thread, NULL, sigHandler, &handlerArgs) != 0) { @@ -112,7 +112,7 @@ int main(int argc, char *argv[]) { goto _cleanup; } - // write to logfile + /* write to logfile */ n = snprintf(buf, sizeof(buf), "Creato signal thread con id: %ld\n", (long) sighandler_thread); if( n<0 ) { perror("main: snprintf"); @@ -122,14 +122,14 @@ int main(int argc, char *argv[]) { goto _cleanup; - // lock for operations on files + /* lock for operations on files */ pthread_mutex_t lock; if (pthread_mutex_init(&lock, NULL) != 0) { perror("main: pthread_mutex_init"); goto _cleanup; } - // create socket + /* create socket */ int listenfd; if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("main: socket"); @@ -150,7 +150,7 @@ int main(int argc, char *argv[]) { goto _cleanup; } - // write to logfile + /* write to logfile */ n = snprintf(buf, sizeof(buf), "Creato socket: %s\n", socketName); if( n<0 ) { perror("main: snprintf"); @@ -160,13 +160,13 @@ int main(int argc, char *argv[]) { goto _cleanup; - // create queue + /* create queue */ queue = createQueue(maxFiles, maxSize); - // create queue for clients waiting on a lock + /* create queue for clients waiting on a lock */ waiting_t *waiting = NULL; - // create threadpool + /* create threadpool */ threadpool_t *pool = NULL; pool = createThreadPool(threadsInPool, pendingSize); @@ -175,7 +175,7 @@ int main(int argc, char *argv[]) { goto _cleanup; } - // write to logfile + /* write to logfile */ n = snprintf(buf, sizeof(buf), "Creato threadpool di dimensione %d e pending size %d\n", threadsInPool, pendingSize); if(n<0) { perror("main: snprintf"); @@ -185,22 +185,22 @@ int main(int argc, char *argv[]) { goto _cleanup; - // selector + /* selector */ fd_set set, tmpset; FD_ZERO(&set); FD_ZERO(&tmpset); - // add fd for socket, signal pipe and request pipe. + /* add fd for socket, signal pipe and request pipe. */ FD_SET(listenfd, &set); FD_SET(signal_pipe[0], &set); FD_SET(request_pipe[0], &set); - // get max file descriptor + /* get max file descriptor */ int fdmax = (listenfd > signal_pipe[0]) ? listenfd : signal_pipe[0]; fdmax = (fdmax > request_pipe[0]) ? fdmax : request_pipe[0]; - // write to logfile + /* write to logfile */ n = snprintf(buf, sizeof(buf), "File Server ready.\n\tMaxFiles: %d\n\tMaxSize: %d\n", maxFiles, maxSize); if( n<0 ) { perror("main: snprintf"); @@ -218,13 +218,13 @@ int main(int argc, char *argv[]) { volatile int numberOfConnections = 0; while(!quit) { - // copy the set in the tmp variable for the select + /* copy the set in the tmp variable for the select */ tmpset = set; if (select(fdmax+1, &tmpset, NULL, NULL, NULL) == -1) { perror("main: select"); goto _cleanup; } - // search for the ready fd + /* search for the ready fd */ for(long i=0; i <= fdmax; ++i) { if (FD_ISSET(i, &tmpset)) { long* connfd = malloc(sizeof(long)); @@ -232,9 +232,9 @@ int main(int argc, char *argv[]) { perror("main: malloc"); goto _cleanup; } - if (i == listenfd) { // new request for connection - if(stopNewConnections) { // no new connections allowed - // write to logfile + if (i == listenfd) { /* new request for connection */ + if(stopNewConnections) { /* no new connections allowed */ + /* write to logfile */ if( taglia_log(taglia, "Nuova connessione rifiutata, server in terminazione\n") < 0) { free(connfd); goto _cleanup; @@ -246,14 +246,14 @@ int main(int argc, char *argv[]) { continue; } - // accept new connection + /* accept new connection */ if ((*connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL)) == -1) { perror("main: accept"); free(connfd); goto _cleanup; } - // write to logfile + /* write to logfile */ n = snprintf(buf, sizeof(buf), "Nuovo client: %ld\n", *connfd); if( n<0 ) { perror("main: snprintf"); @@ -265,7 +265,7 @@ int main(int argc, char *argv[]) { goto _cleanup; } - // create args to pass to the worker + /* create args to pass to the worker */ threadT* args = calloc(1, sizeof(threadT)); if(!args) { perror("main: calloc"); @@ -281,40 +281,40 @@ int main(int argc, char *argv[]) { args->lock = &lock; args->waiting = &waiting; - // add to threadpool + /* add to threadpool */ int r = addToThreadPool(pool, threadF, args); - if (r == 0) { // no errors + if (r == 0) { /* no errors */ numberOfConnections++; free(connfd); continue; } - if (r < 0) // internal error + if (r < 0) /* internal error */ fprintf(stderr, "Error: adding to the thread pool.\n"); - else // pending queue full + else /* pending queue full */ fprintf(stderr, "Error: server too busy.\n"); close(*connfd); free(connfd); continue; } - if (i == request_pipe[0]) { // worker finished task - long pdr; // get pipe descriptor + if (i == request_pipe[0]) { /* worker finished task */ + long pdr; /* get pipe descriptor */ if (readn(request_pipe[0], &pdr, sizeof(long)) == -1) { perror("main: readn"); free(connfd); break; } switch (pdr) { - case -1: // client disconnected + case -1: /* client disconnected */ --numberOfConnections; if (stopNewConnections && numberOfConnections <= 0) { - // quitting and terminating signalThread + /* quitting and terminating signalThread */ quit = 1; pthread_cancel(sighandler_thread); break; } free(connfd); continue; - default: // client served but not disconnected + default: /* client served but not disconnected */ FD_SET(pdr, &set); if (pdr > fdmax) { fdmax = pdr; @@ -324,7 +324,7 @@ int main(int argc, char *argv[]) { free(connfd); continue; } - if (i == signal_pipe[0]) { // check if we need to terminate + if (i == signal_pipe[0]) { /* check if we need to terminate */ int code; if (readn(signal_pipe[0], &code, sizeof(int)) == -1) { perror("main: readn"); @@ -332,24 +332,24 @@ int main(int argc, char *argv[]) { break; } switch (code) { - case 0: { // stop to new connections + case 0: { /* stop to new connections */ stopNewConnections = 1; - // write to logfile + /* write to logfile */ if(taglia_log(taglia, "Stop new connections\n") < 0){ free(connfd); goto _cleanup; } if(numberOfConnections == 0) { quit = 1; - // stop signalThread + /* stop signalThread */ pthread_cancel(sighandler_thread); } break; } - case 1: { // immediate stop + case 1: { /* immediate stop */ quit = 1; - // write to logfile + /* write to logfile */ if( taglia_log(taglia, "Immediate quit\n") < 0) { free(connfd); goto _cleanup; @@ -364,12 +364,12 @@ int main(int argc, char *argv[]) { free(connfd); break; } - else { // request from an already connected client + else { /* request from an already connected client */ FD_CLR(i, &set); fdmax = (i>fdmax)?i:fdmax; - // create args for worker thread + /* create args for worker thread */ threadT* args = calloc(1, sizeof(threadT)); if(!args) { perror("main: calloc"); @@ -385,15 +385,15 @@ int main(int argc, char *argv[]) { args->lock = &lock; args->waiting = &waiting; - // add to the threadpool + /* add to the threadpool */ int r = addToThreadPool(pool, threadF, args); if (r == 0) { free(connfd); continue; } - if (r < 0) // internal error + if (r < 0) /* internal error */ fprintf(stderr, "Error: adding to the thread pool.\n"); - else // pending queue full + else /* pending queue full */ fprintf(stderr, "Error: server too busy.\n"); close(*connfd); free(connfd); @@ -404,24 +404,24 @@ int main(int argc, char *argv[]) { } fprintf(stdout, "\n"); - destroyThreadPool(pool, 0); // notify the threads that need to stop - clearWaiting(&waiting); // destroy waiting list - taglia_stats(taglia, stdout); // print stats + destroyThreadPool(pool, 0); /* notify the threads that need to stop */ + clearWaiting(&waiting); /* destroy waiting list */ + taglia_stats(taglia, stdout); /* print stats */ - // print all files in storage during shutdown + /* print all files in storage during shutdown */ if (printQueue(stdout, queue) == -1) { perror("main: printQueue"); return 1; } destroyQueue(queue); - // wait for sigHandler thread + /* wait for sigHandler thread */ pthread_join(sighandler_thread, NULL); - // free log file structure + /* free log file structure */ taglia_del(taglia); - // unlink socket + /* unlink socket */ unlink(socketName); free(socketName); @@ -444,7 +444,7 @@ _cleanup_beforesigthread: return -1; } -// signal handler thread function +/* signal handler thread function */ static void *sigHandler(void *arg) { sigset_t *set = ((sigHandler_t*)arg)->set; int fd_pipe = ((sigHandler_t*)arg)->signal_pipe; @@ -468,7 +468,7 @@ static void *sigHandler(void *arg) { switch (sig) { case SIGHUP: code = 0; - // notify main thread to stop new connections + /* notify main thread to stop new connections */ if (writen(fd_pipe, &code, sizeof(int)) == -1) { perror("sigHandler: writen"); } @@ -476,7 +476,7 @@ static void *sigHandler(void *arg) { case SIGINT: case SIGQUIT: code = 1; - // notify main thread to stop immediatly + /* notify main thread to stop immediatly */ if (writen(fd_pipe, &code, sizeof(int)) == -1) { perror("sigHandler: writen"); } diff --git a/src/serverWorker.c b/src/serverWorker.c index 4e420b6..dca5467 100644 --- a/src/serverWorker.c +++ b/src/serverWorker.c @@ -1,25 +1,25 @@ +#include #include #include #include #include #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "conn.h" +#include "message.h" +#include "fileQueue.h" +#include "apiFile.h" +#include "taglialegna.h" +#include "serverWorker.h" +#include "threadpool.h" +#include "strsep_gnu.h" int parser(int len, char *command, queueT *queue, long fd_c, taglia_t* taglia, pthread_mutex_t *lock, waiting_t **waiting); -// worker function +/* worker function */ void threadF(void *arg) { if(!arg){ errno = EINVAL; @@ -37,7 +37,7 @@ void threadF(void *arg) { pthread_mutex_t *lock = argl->lock; waiting_t **waiting = argl->waiting; - // search for the id of the thread + /* search for the id of the thread */ int myid = -1; pthread_t tid = pthread_self(); @@ -55,8 +55,8 @@ void threadF(void *arg) { while(*quit == 0) { tmpset=set; int r; - // check if we need to quit - struct timeval timeout={0, 100000}; // 100 milliseconds + /* check if we need to quit */ + struct timeval timeout={0, 100000}; /* 100 milliseconds */ if ((r=select(connfd+1, &tmpset, NULL, NULL, &timeout)) < 0) { perror("threadF: select"); break; @@ -66,13 +66,13 @@ void threadF(void *arg) { goto _cleanup; continue; } - break; // r!=0 and quit==0 + break; /* r!=0 and quit==0 */ } - // comunicate with the client + /* comunicate with the client */ msg_t str; long n; - // read the size of the message + /* read the size of the message */ if ((n=readn(connfd, &str.len, sizeof(long))) == -1) { perror("threadF: readn, dimension"); goto _cleanup; @@ -88,7 +88,7 @@ void threadF(void *arg) { perror("threadF: calloc"); goto _cleanup; } - // read the message + /* read the message */ if ((n=readn(connfd, str.str, str.len * sizeof(char))) == -1) { perror("threadF: readn, message"); free(str.str); @@ -97,17 +97,17 @@ void threadF(void *arg) { str.str[str.len] = '\0'; closeConnection: - // the clients wants to disconnect or already diconnected + /* the clients wants to disconnect or already diconnected */ if(n==0 || strncmp(str.str, "quit", 5) == 0) { close(connfd); long close = -1; - // tell main that the client disconnected + /* tell main that the client disconnected */ if (writen(request_pipe, &close, sizeof(long)) == -1) { perror("threadF: writen"); goto _cleanup; } - // log closing connection + /* log closing connection */ int n = 0; char buf[1024]; n = snprintf(buf, sizeof(buf), "Chiusa connessione con il client %ld.\n", connfd); @@ -120,18 +120,18 @@ closeConnection: goto _cleanup; } - // execute what the client requested + /* execute what the client requested */ if (parser(str.len, str.str, q, connfd, taglia, lock, waiting) == -1) { goto _cleanup; } - // str.str is not valid anymore because parser frees + /* str.str is not valid anymore because parser frees */ - // tell main that the request has been handled + /* tell main that the request has been handled */ if (writen(request_pipe, &connfd, sizeof(long)) == -1) { perror("threadF: writen"); } - // write to logfile + /* write to logfile */ int m = 0; char buf[1024]; m = snprintf(buf, sizeof(buf), "Thread %d ha servito una richiesta del client %ld.\n", myid, connfd); @@ -157,7 +157,7 @@ int parser(int len, char *command, queueT *queue, long fd_c, taglia_t* taglia, p return -1; } - // copy command because we modify it later + /* copy command because we modify it later */ char *string = calloc(1, len+1); if(string == NULL) { perror("parser: calloc"); @@ -254,7 +254,7 @@ int parser(int len, char *command, queueT *queue, long fd_c, taglia_t* taglia, p removeFile(token2, queue, fd_c, taglia, lock, waiting); goto _parser_end; } - // if here no match + /* if here no match */ _parser_cleanup: free(command); diff --git a/src/serverWorker.h b/src/serverWorker.h index c56b6c4..e8c3164 100644 --- a/src/serverWorker.h +++ b/src/serverWorker.h @@ -9,19 +9,25 @@ #include #include -// struttura dati che contiene gli argomenti da passare ai worker threads +/* structure of the args to pass to the worker thread */ typedef struct struct_thread { volatile int *quit; int request_pipe; long connfd; - queueT *q; // puntatore alla queue dei file - taglia_t *taglia; // puntatore alla struct del file di log - threadpool_t *pool; // puntatore alla threadpool + queueT *q; /* pointer to file structure */ + taglia_t *taglia; /* pointer to logfile handler */ + threadpool_t *pool; /* pointer to threadpool */ pthread_mutex_t *lock; - waiting_t **waiting; // puntatore ai client in attesa di ottenere la lock su un file + waiting_t **waiting; /* pointer to clients waiting for a lock */ } threadT; -// funzione eseguita dal generico Worker del pool di thread + + +/* @brief Function executed by a worker thread to handle a single request from a + * client + * + * @param arg: type that holds all needed resources + */ void threadF(void *arg); #endif /* SERVERWORKER */