Added basic server functionality from ex 2 lesson 11

This commit is contained in:
elvis
2022-03-09 19:24:49 +01:00
parent c0372c44e2
commit d0a4e4411e
9 changed files with 869 additions and 0 deletions

226
src/server.c Normal file
View File

@ -0,0 +1,226 @@
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
#include <signal.h>
#include <sys/select.h>
#include <threadpool.h>
#include <conn.h>
#include <util.h>
#include <serverWorker.h>
/**
* @struct sigHandlerArgs_t
* @brief struttura contenente le informazioni da passare
* al signal handler thread
*
*/
typedef struct {
sigset_t *set; // set dei segnali da gestire (mascherati)
int signal_pipe; // descrittore di scrittura di una pipe senza nome
} sigHandler_t;
// funzione eseguita dal signal handler thread
static void *sigHandler(void *arg) {
sigset_t *set = ((sigHandler_t*)arg)->set;
int fd_pipe = ((sigHandler_t*)arg)->signal_pipe;
while(1) {
int sig;
int r = sigwait(set, &sig);
if (r != 0) {
errno = r;
// TODO logging utility
perror("FATAL ERROR 'sigwait'");
return NULL;
}
switch(sig) {
case SIGINT:
case SIGTERM:
case SIGQUIT:
close(fd_pipe); // notifico il listener thread della ricezione del segnale
return NULL;
default: ;
}
}
return NULL;
}
static void usage(const char *argv0) {
// TODO change this
fprintf(stderr, "use: %s threads-in-the-pool\n", argv0);
}
static void checkargs(int argc, char* argv[]) {
// TODO change all this
if (argc != 2) {
usage(argv[0]);
_exit(EXIT_FAILURE);
}
if ((int) strtol(argv[1], NULL, 10) <= 0) {
fprintf(stderr, "ERROR: threads-in-the-pool must be greater than zero\n\n");
usage(argv[0]);
_exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
// TODO read config file
checkargs(argc, argv);
int threadsInPool = (int) strtol(argv[1], NULL, 10);
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
sigaddset(&mask, SIGTERM);
if (pthread_sigmask(SIG_BLOCK, &mask, NULL) != 0) {
// TODO logging utility
fprintf(stderr, "ERROR setting mask\n");
goto _cleanup;
}
// ignoro SIGPIPE per evitare di essere terminato da una scrittura su un socket
struct sigaction s;
memset(&s, 0, sizeof(s));
s.sa_handler = SIG_IGN;
if ( (sigaction(SIGPIPE,&s,NULL)) == -1 ) {
// TODO logging utility
perror("sigaction");
goto _cleanup;
}
/*
* La pipe viene utilizzata come canale di comunicazione tra il signal handler thread ed il
* thread lisener per notificare la terminazione.
* Una alternativa è quella di utilizzare la chiamata di sistema
* 'signalfd' ma non e' POSIX.
*/
int signal_pipe[2];
if (pipe(signal_pipe) == -1) {
// TODO logging utility
perror("pipe");
goto _cleanup;
}
pthread_t sighandler_thread;
sigHandler_t handlerArgs = { &mask, signal_pipe[1] };
if (pthread_create(&sighandler_thread, NULL, sigHandler, &handlerArgs) != 0) {
// TODO logging utility
fprintf(stderr, "ERROR creating signal handler thread\n");
goto _cleanup;
}
int listenfd;
if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
// TODO logging utility
perror("socket");
goto _cleanup;
}
struct sockaddr_un serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
strncpy(serv_addr.sun_path, SOCKNAME, strlen(SOCKNAME)+1);
if (bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -1) {
// TODO logging utility
perror("bind");
goto _cleanup;
}
if (listen(listenfd, MAXBACKLOG) == -1) {
// TODO logging utility
perror("listen");
goto _cleanup;
}
threadpool_t *pool = NULL;
pool = createThreadPool(threadsInPool, threadsInPool);
if (!pool) {
// TODO logging utility
fprintf(stderr, "ERROR creating thread pool\n");
goto _cleanup;
}
fd_set set, tmpset;
FD_ZERO(&set);
FD_ZERO(&tmpset);
FD_SET(listenfd, &set); // aggiungo il listener fd al master set
FD_SET(signal_pipe[0], &set); // aggiungo il descrittore di lettura della signal_pipe
// tengo traccia del file descriptor con id piu' grande
int fdmax = (listenfd > signal_pipe[0]) ? listenfd : signal_pipe[0];
volatile long termina=0;
while(!termina) {
// copio il set nella variabile temporanea per la select
tmpset = set;
if (select(fdmax+1, &tmpset, NULL, NULL, NULL) == -1) {
perror("select");
goto _cleanup;
}
// cerchiamo di capire da quale fd abbiamo ricevuto una richiesta
for(int i=0; i <= fdmax; ++i) {
if (FD_ISSET(i, &tmpset)) {
long connfd;
if (i == listenfd) { // e' una nuova richiesta di connessione
if ((connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL)) == -1) {
// TODO logging utility
perror("accept");
goto _cleanup;
}
long* args = malloc(2*sizeof(long));
if (!args) {
// TODO logging utility
perror("ERROR FATAL malloc");
goto _cleanup;
}
args[0] = connfd;
args[1] = (long)&termina;
int r = addToThreadPool(pool, threadF, (void*)args);
if (r == 0)
continue; // aggiunto con successo
if (r < 0)// errore interno
fprintf(stderr, "ERROR FATAL adding to the thread pool\n");
// TODO logging utility
else // coda dei pendenti piena
fprintf(stderr, "ERROR SERVER TOO BUSY\n");
// TODO logging utility
free(args);
close(connfd);
continue;
}
if (i == signal_pipe[0]) {
// ricevuto un segnale, esco ed inizio il protocollo di terminazione
termina = 1;
break;
}
}
}
}
destroyThreadPool(pool, 0); // notifico che i thread dovranno uscire
// aspetto la terminazione de signal handler thread
pthread_join(sighandler_thread, NULL);
unlink(SOCKNAME);
return 0;
_cleanup:
unlink(SOCKNAME);
return -1;
}

80
src/serverWorker.c Normal file
View File

@ -0,0 +1,80 @@
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <sys/select.h>
#include <conn.h>
#include <message.h>
// converte tutti i carattere minuscoli in maiuscoli
static void toup(char *str) {
char *p = str;
while(*p != '\0') {
*p = (islower(*p)?toupper(*p):*p);
++p;
}
}
// funzione eseguita dal Worker thread del pool
// gestisce una intera connessione di un client
//
void threadF(void *arg) {
assert(arg);
long* args = (long*)arg;
long connfd = args[0];
long* termina = (long*)(args[1]);
free(arg);
fd_set set, tmpset;
FD_ZERO(&set);
FD_SET(connfd, &set);
do {
tmpset=set;
int r;
// ogni tanto controllo se devo terminare
struct timeval timeout={0, 100000}; // 100 milliseconds
if ((r=select(connfd+1, &tmpset, NULL, NULL, &timeout)) < 0) {
perror("select");
break;
}
if (r==0) {
if (*termina) break;
continue;
}
msg_t str;
int n;
if ((n=readn(connfd, &str.len, sizeof(int))) == -1) {
perror("read1");
break;
}
if (n==0) break;
str.str = calloc((str.len), sizeof(char));
if (!str.str) {
perror("calloc");
fprintf(stderr, "Memoria esaurita....\n");
break;
}
if ((n=readn(connfd, str.str, str.len * sizeof(char))) == -1) {
perror("read2");
free(str.str);
break;
}
toup(str.str);
if ((n=writen(connfd, &str.len, sizeof(int))) == -1) {
perror("write1");
free(str.str);
break;
}
if ((n=writen(connfd, str.str, str.len*sizeof(char))) == -1) {
perror("write2");
free(str.str);
break;
}
free(str.str);
} while(*termina == 0);
close(connfd);
}

7
src/serverWorker.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef SERVERWORKER
#define SERVERWORKER
// funzione eseguita dal generico Worker del pool di thread
void threadF(void *arg);
#endif /* SERVERWORKER */