style and fixed bug allocating too much memory in append file

This commit is contained in:
elvis
2022-05-07 17:28:41 +02:00
parent b602e8e7dd
commit d9de77e427
6 changed files with 628 additions and 507 deletions

File diff suppressed because it is too large Load Diff

View File

@ -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 */

View File

@ -1,59 +1,59 @@
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
// 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 <sys/stat.h>
#include <fts.h>
#include <time.h>
#include <unistd.h>
#include <api.h>
#include <strsep_gnu.h>
#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");

View File

@ -9,21 +9,21 @@
#include <ctype.h>
#include <sys/select.h>
#include <threadpool.h>
#include <conn.h>
#include <util.h>
#include <serverWorker.h>
#include <ini.h>
#include <serverUtil.h>
#include <fileQueue.h>
#include <taglialegna.h>
#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");
}

View File

@ -1,25 +1,25 @@
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <sys/select.h>
#include <pthread.h>
#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>
#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);

View File

@ -9,19 +9,25 @@
#include <taglialegna.h>
#include <threadpool.h>
// 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 */