-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
375 lines (323 loc) · 10.2 KB
/
server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <communication.h>
#include <fcntl.h>
#include <pthread.h>
#include <request.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
// tutto ciò per poter usare uno switch (solo int)
// i valori hash dei vari comandi
#define REGISTER -1825436278
#define STORE 235691186
#define RETRIVE 1392069094
#define DELETE -1417066568
#define LEAVE 226835570
#define NUM_THREADS 12
#define MAX_WAIT_TIME_IN_SECONDS (4)
int listenfd;
static volatile sig_atomic_t stopFlag = 0;
pthread_mutex_t worker_stop_mtx = PTHREAD_MUTEX_INITIALIZER;
volatile int worker_num = 1;
pthread_mutex_t worker_num_mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t worker_num_cond = PTHREAD_COND_INITIALIZER;
static int waitForWorkers(int numworker) {
int ret = 0;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += MAX_WAIT_TIME_IN_SECONDS;
pthread_mutex_lock(&worker_num_mtx);
while (worker_num >= numworker && ret == 0) {
ret = pthread_cond_timedwait(&worker_num_cond, &worker_num_mtx, &ts);
}
if (ret != 0) {
if (errno == ETIMEDOUT)
perror("Abnormal starvation of threads. Aborting server...");
else if (errno == EINVAL)
perror("Waiting for avaiable threads");
fflush(stderr);
}
pthread_mutex_unlock(&worker_num_mtx);
return 0;
}
static void* sig_thread(void* arg) {
sigset_t* set = arg;
int s, sig;
while (1) {
s = sigwait(set, &sig);
if (s != 0) {
perror("sigwait");
}
switch (sig) {
case SIGUSR1:
printf("Print statistics...\n");
handle_print_stats();
break;
default:
pthread_mutex_lock(&worker_stop_mtx);
stopFlag = 1;
pthread_mutex_unlock(&worker_stop_mtx);
// pthread_mutex_lock(&worker_num_mtx);
s = waitForWorkers(2);
// pthread_mutex_unlock(&worker_num_mtx);
SYSCALL(s, shutdown(listenfd, SHUT_RD), "Error shutdowning");
pthread_mutex_lock(&worker_num_mtx);
worker_num--;
pthread_mutex_unlock(&worker_num_mtx);
return (NULL);
}
}
}
int parseCmd(const char* cmd) {
assert(cmd != NULL);
int hash = 5381;
int c;
while ((c = *cmd++))
hash = ((hash << 5) + hash) + c;
// printf(":%d \n", hash);
return hash;
}
void* clientHandler(void* arg) {
int unused;
long fd = (long)arg;
// tokenizzazione
char* token;
char *tokFull, *tokHeader;
char* cmd;
int ret;
char* response = NULL;
char buf[BUFSIZE];
char header[BUFSIZE];
int leave = 0;
void* block = NULL;
char name[BUFSIZE];
char nameFile[BUFSIZE];
char* pathFile;
char* res = NULL;
size_t sizeForRetrive = 0;
do {
pthread_mutex_lock(&worker_stop_mtx);
if (stopFlag) {
pthread_mutex_unlock(&worker_stop_mtx);
break;
}
pthread_mutex_unlock(&worker_stop_mtx);
CHECKNULL(response, calloc(BUFSIZE, sizeof(char)),
"Error on calloc memory");
memset(buf, 0, BUFSIZE);
SYSCALL(ret, read(fd, buf, BUFSIZE), "first read ");
if (ret < 1) {
handle_disconnect(name);
break;
}
CHECKNULL(token, strtok_r(buf, "\n", &tokFull), "Error tokening header");
sprintf(header, "%s", token);
CHECKNULL(cmd, strtok_r(token, " ", &tokHeader), "Error tokening command");
switch (parseCmd(cmd)) {
case REGISTER:
CHECKNULL(token, strtok_r(NULL, " ", &tokHeader), "tokName");
sprintf(name, "%s", token);
ret = handle_register(name);
if (ret == 0) {
sprintf(response, "OK \n");
} else {
sprintf(response, "KO not registred\n");
}
break;
case STORE:
// può essere NULL
block = strtok_r(NULL, "", &tokFull);
CHECKNULL(token, strtok_r(NULL, " ", &tokHeader), "tokName");
sprintf(nameFile, "%s", token);
char* lenStr;
CHECKNULL(lenStr, strtok_r(NULL, " ", &tokHeader), "tokLen");
size_t len;
len = strtol(lenStr, NULL, 10);
if (errno == EINVAL || errno == ERANGE) {
strcpy(response, "KO error on data length\n");
break;
}
CHECKNULL(pathFile,
calloc(strlen("data/") + strlen(name) + strlen(nameFile) + 2,
sizeof(char)),
"Error on calloc pathFile");
sprintf(pathFile, "data/%s/%s", name, nameFile);
// potential len, i cannot use strlen on void*
size_t maxLenBlock = BUFSIZE - 1 - strlen(header); // 2=\n-1 in first
// read
// insted of read the rest of data and concatenate in a new block, i'll
// read the rest of potential data in handle_store, concatenating
// directly on the file. A little problem of separation of concerns
ret = handle_store(pathFile, block, len, maxLenBlock, fd);
if (ret == 0) {
strcpy(response, "OK \n");
} else {
strcpy(response, "KO \n");
}
free(pathFile);
break;
case RETRIVE:
CHECKNULL(token, strtok_r(NULL, " ", &tokHeader), "tokName");
sprintf(nameFile, "%s", token);
CHECKNULL(pathFile,
calloc(strlen("data/") + strlen(name) + strlen(nameFile) + 2,
sizeof(char)),
"Error on calloc pathFile");
sprintf(pathFile, "data/%s/%s", name, nameFile);
ret = handle_retrive(pathFile, &res);
if (ret > 0) {
sizeForRetrive = ret;
response = res;
} else {
sprintf(response, "KO \n");
}
free(pathFile);
break;
case DELETE:
CHECKNULL(token, strtok_r(NULL, " ", &tokHeader), "tokName");
sprintf(nameFile, "%s", token);
CHECKNULL(pathFile,
calloc(strlen("data/") + strlen(name) + strlen(nameFile) + 2,
sizeof(char)),
"Error on calloc pathFile");
sprintf(pathFile, "data/%s/%s", name, nameFile);
ret = handle_delete(pathFile);
if (ret == 0) {
sprintf(response, "OK \n");
} else {
sprintf(response, "KO \n");
}
free(pathFile);
break;
case LEAVE:
if (handle_disconnect(name) == 0) {
sprintf(response, "OK \n");
} else {
sprintf(response, "KO removing user for connected users\n");
}
leave = 1;
break;
default:
printf("Error! header [%s] is not correct\n", header);
}
if (sizeForRetrive == 0) {
SYSCALL(ret, writen(fd, response, strlen(response)), "write");
} else {
SYSCALL(ret, writen(fd, response, sizeForRetrive), "write");
sizeForRetrive = 0;
}
free(response);
} while (leave != 1);
pthread_mutex_lock(&worker_num_mtx);
worker_num--;
pthread_mutex_unlock(&worker_num_mtx);
pthread_cond_signal(&worker_num_cond);
SYSCALL(unused, close(fd), "Error on close");
return (NULL);
}
int setNoBlocking(int fd) {
int unused;
int flags;
SYSCALL(flags, fcntl(fd, F_GETFL), "fcntl");
flags |= O_NONBLOCK;
SYSCALL(unused, fcntl(fd, F_SETFL, flags), "fcntl");
return unused;
}
void cleanup() {
int unused;
if ((unused = unlink(SOCKNAME)) == -1) {
if (errno == ENOENT)
return;
perror("unlink");
}
freeTable();
}
// int argc, char* argv[]
int main() {
int unused;
pthread_t tid[NUM_THREADS];
pthread_attr_t attr;
ISZERO(unused, pthread_attr_init(&attr), "Error init pthread_attr");
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
initTable();
if ((unused = unlink(SOCKNAME)) == -1) {
if (!(errno == ENOENT)) {
perror("unlink");
return -1;
}
}
ISZERO(unused, atexit(cleanup), "Atexit");
SYSCALL(listenfd, socket(AF_UNIX, SOCK_STREAM, 0), "socket");
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);
int enable = 1;
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) ==
-1) {
perror("setsockopt()");
exit(errno);
}
SYSCALL(unused,
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)),
"bind");
SYSCALL(unused, listen(listenfd, MAXBACKLOG), "listen");
if (mkdir("data", 0777) && errno != EEXIST) {
printf("error while trying to create data directory\n");
exit(errno);
}
sigset_t set;
// block signal
SYSCALL(unused, sigemptyset(&set), "Error on sigemptyset");
SYSCALL(unused, sigaddset(&set, SIGINT), "Error on sigaddset");
SYSCALL(unused, sigaddset(&set, SIGQUIT), "Error on sigaddset");
SYSCALL(unused, sigaddset(&set, SIGUSR1), "Error on sigaddset");
SYSCALL(unused, sigaddset(&set, SIGTSTP), "Error on sigaddset");
ISZERO(unused, pthread_sigmask(SIG_BLOCK, &set, NULL), "pthread_sigmask");
ISZERO(unused, pthread_create(&tid[0], &attr, &sig_thread, (void*)&set),
"pthread_create");
long connfd;
pthread_mutex_lock(&worker_stop_mtx);
while (stopFlag == 0) {
pthread_mutex_unlock(&worker_stop_mtx);
if ((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1) {
if (!(errno == EAGAIN || errno == EWOULDBLOCK)) {
if (errno == EINVAL) {
printf("Listen socket isn't listening, closing server...\n");
break;
}
perror("accept");
}
} else {
unused = waitForWorkers(NUM_THREADS);
if (unused != 0) {
printf("cazz");
break;
}
// timer on block receiving from client
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
if (setsockopt(connfd, SOL_SOCKET, SO_RCVTIMEO, (struct timeval*)&tv,
sizeof(struct timeval))) {
perror("setsockopt: rcvtimeo");
exit(1);
}
pthread_mutex_lock(&worker_num_mtx);
pthread_create(&tid[worker_num], &attr, &clientHandler, (void*)connfd);
worker_num++;
pthread_mutex_unlock(&worker_num_mtx);
}
pthread_mutex_lock(&worker_stop_mtx);
}
pthread_attr_destroy(&attr);
waitForWorkers(1);
SYSCALL(unused, close(listenfd), "Error on close");
exit(EXIT_SUCCESS);
}