-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
442 lines (367 loc) · 12 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#include <assert.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <zlib.h>
//Only allow 5 concurrent threads
#define MAXTHREAD (5)
#define windowBits 15
#define GZIP_ENCODING 16
const char* GET = "GET";
const int MAX_CWD = 100;
typedef enum {
HTML,
CSS,
JPG,
PDF,
PPTX,
ERROR
} filetype_t;
int starts_with(char *s, const char *with) {
return strncmp(s, with, strlen(with)) == 0;
}
int contains(const char *s1, const char *s2) {
return strstr(s1, s2) != NULL;
}
char *concat(const char *s1, const char *s2) {
char *r = malloc(strlen(s1) + strlen(s2) + 1);
strcpy(r, s1);
strcat(r, s2);
return r;
}
char *strappend(const char *s1, const char *s2) {
char *r = malloc(strlen(s1) + strlen(s2) + 1);
strcpy(r, s1);
strcat(r, s2);
assert(strlen(r) == strlen(s1) + strlen(s2));
return r;
}
char* substr(const char* input, int offset, int len, char* dest) {
int input_len = strlen (input);
if (offset + len > input_len) {
return NULL;
}
strncpy(dest, input + offset, len);
return dest;
}
//Error printing helper function
void error(char *message) {
perror(message);
exit(1);
}
//First function to read socket message - returns a char buffer
char *readFromSocket(int sockfd) {
const int bSize = 256;
char *buffer = malloc(bSize);
char *result = malloc(1);
result[0] = '\0';
int n;
while (1) {
int n = read(sockfd,buffer,bSize-1);
if (n < 0) {
error("Socket Error: Can't read");
}
buffer[n] = '\0';
char *last_result = result;
result = strappend(last_result, buffer);
free(last_result);
if (n < bSize - 1) {
break;
}
}
free(buffer);
buffer = 0;
return result;
}
//Write a char buffer to Socket
void writeToSocket(int sockfd, const char *message) {
write(sockfd, message, strlen(message));
write(sockfd, "\r\n", 2);
}
void writeNumberToSocket(int sockfd, int number) {
char* message = malloc(3);
sprintf(message, "%x\r\n", (int)number);
write(sockfd, message, strlen(message));
}
void writeContentToSocket(int sockfd, const char *content, filetype_t fileType) {
char lengthStr[100];
sprintf(lengthStr, "%d", (int)strlen(content));
char *contentLengthBuffer = concat("Content-Length: ", lengthStr);
writeToSocket(sockfd, "Server: Linux Mint KDE");
if(fileType == HTML)
writeToSocket(sockfd, "Content-Type: text/html");
else if(fileType == PDF)
writeToSocket(sockfd, "Content-Type: application/pdf");
else if(fileType == JPG)
writeToSocket(sockfd, "Content-Type: image/jpg");
writeToSocket(sockfd, contentLengthBuffer);
writeToSocket(sockfd, "");
writeToSocket(sockfd, content);
free(contentLengthBuffer);
contentLengthBuffer = 0;
}
void writeFileToSocket(int client, FILE* file, filetype_t fileType) {
char buffer[1024];
long file_size;
FILE *requested_file = file;
size_t read_bytes, total_read_bytes;
char html_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n";
char text_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
char css_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Type: text/css; charset=UTF-8\r\n\r\n";
char jpg_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Type: image/jpeg; charset=UTF-8\r\n\r\n";
char pdf_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Type: application/pdf; charset=UTF-8\r\n\r\n";
fseek(requested_file, 0, SEEK_END);
file_size = ftell(requested_file);
fseek(requested_file, 0, SEEK_SET);
if (fileType == HTML)
send(client, html_response, sizeof(html_response)-1, 0);
if ( fileType == JPG)
send(client, jpg_response, sizeof(jpg_response)-1, 0);
if ( fileType == CSS)
send(client, css_response, sizeof(css_response)-1, 0);
if ( fileType == PDF)
send(client, pdf_response, sizeof(pdf_response)-1, 0);
total_read_bytes = 0;
while (!feof(requested_file)) {
read_bytes = fread(buffer, 1, 1024, requested_file);
total_read_bytes += read_bytes;
send(client, buffer, read_bytes, 0);
}
fclose(requested_file);
}
void writeFileToSocketChunked(int client, FILE* file, filetype_t fileType) {
char buffer[1024];
long file_size;
FILE *requested_file = file;
size_t read_bytes, total_read_bytes;
char html_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n";
char text_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
char css_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: text/css; charset=UTF-8\r\n\r\n";
char jpg_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: image/jpeg; charset=UTF-8\r\n\r\n";
char pdf_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: application/pdf; charset=UTF-8\r\n\r\n";
char pptx_response[] = "HTTP/1.1 200 OK:\r\n" "Transfer-Encoding: chunked\r\n" "Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation; charset=UTF-8\r\n\r\n";
fseek(requested_file, 0, SEEK_END);
file_size = ftell(requested_file);
fseek(requested_file, 0, SEEK_SET);
if (fileType == HTML)
send(client, html_response, sizeof(html_response)-1, 0);
if ( fileType == JPG)
send(client, jpg_response, sizeof(jpg_response)-1, 0);
if ( fileType == CSS)
send(client, css_response, sizeof(css_response)-1, 0);
if ( fileType == PDF)
send(client, pdf_response, sizeof(pdf_response)-1, 0);
if ( fileType == PPTX)
send(client, pptx_response, sizeof(pptx_response)-1, 0);
total_read_bytes = 0;
while (!feof(requested_file)) {
read_bytes = fread(buffer, 1, 1024, requested_file);
total_read_bytes += read_bytes;
writeNumberToSocket(client, read_bytes);
write(client, buffer, read_bytes);
write(client, "\r\n", 2);
}
write(client, "0\r\n\r\n", 5);
fclose(requested_file);
}
void writeFileToSocketWithCompression(int client, FILE* file, filetype_t fileType) {
char buffer[1024];
long file_size;
FILE *requested_file = file;
size_t read_bytes, total_read_bytes;
char html_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Encoding: gzip\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n";
char css_response[] = "HTTP/1.1 200 OK:\r\n" "Content-Encoding: gzip\r\n" "Content-Type: text/css; charset=UTF-8\r\n\r\n";
fseek(requested_file, 0, SEEK_END);
file_size = ftell(requested_file);
fseek(requested_file, 0, SEEK_SET);
if (fileType == HTML)
send(client, html_response, sizeof(html_response)-1, 0);
if ( fileType == CSS)
send(client, css_response, sizeof(css_response)-1, 0);
char* encryptedBuffer;
total_read_bytes = 0;
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
while (!feof(requested_file)) {
read_bytes = fread(buffer, 1, 1024, requested_file);
total_read_bytes += read_bytes;
defstream.next_in = (Bytef *)buffer; // input char array
defstream.avail_in = read_bytes; // size of input, string + terminator
defstream.avail_out = read_bytes; // size of output
encryptedBuffer = malloc(read_bytes);
defstream.next_out = (Bytef *)encryptedBuffer; // output char array
deflateInit2(&defstream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
windowBits | GZIP_ENCODING,
8,
Z_DEFAULT_STRATEGY);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
send(client, encryptedBuffer, (char*)defstream.next_out - encryptedBuffer, 0);
free(encryptedBuffer);
}
fclose(requested_file);
}
void sendHTTP404Error(int sockfd) {
writeToSocket(sockfd, "HTTP/1.1 404 Not Found");
static const char *content = "<html><body><h1>404 Error: Requested content not found</h1></body></html>\r\n";
writeContentToSocket(sockfd, content, HTML);
}
void sendHTTPGetReply(int sockfd, FILE* file, filetype_t fileType) {
writeToSocket(sockfd, "HTTP/1.1 200 OK");
writeFileToSocketChunked(sockfd, file, fileType);
}
void sendHTTPGetEncryptedReply(int sockfd, FILE* file, filetype_t fileType) {
writeToSocket(sockfd, "HTTP/1.1 200 OK");
writeFileToSocketWithCompression(sockfd, file, fileType);
}
int checkIfGet(char *buffer) {
return starts_with(buffer, GET);
}
int checkIfGzipDeflate(char *buffer){
return contains(buffer, "Accept-Encoding: gzip, deflate");
}
char *extractPath(char *buffer) {
int startPos = strlen(GET) + 1;
char *end_of_path = strchr(buffer + startPos, ' ');
int end_pos = end_of_path - buffer;
int pathlen = end_pos - startPos;
char *path = malloc(pathlen + 1);
substr(buffer, startPos, pathlen, path);
path[pathlen] = '\0';
return path;
}
filetype_t extractFileType(char *path) {
char* tempBuffer;
int typeStartPos;
for(int i=0; i<strlen(path)-1; i++) {
if(path[strlen(path)-i] == '.') {
tempBuffer = malloc(i);
memcpy(tempBuffer, &path[strlen(path)-i+1], i-1);
tempBuffer[i-1] = '\0';
break;
}
else if(i == strlen(path) - 2){
return ERROR;
}
}
if(!strcmp(tempBuffer, "html"))
return HTML;
else if (!strcmp(tempBuffer, "pdf"))
return PDF;
else if (!strcmp(tempBuffer, "jpg"))
return JPG;
else if (!strcmp(tempBuffer, "pptx"))
return PPTX;
else if (!strcmp(tempBuffer, "css"))
return CSS;
else
return ERROR;
free(tempBuffer);
}
void outputStaticFile(int sockfd, const char *curdir, const char *path, int gzipflag) {
char* fullpath = malloc(strlen(curdir) + strlen(path) + 1);
strcpy(fullpath, curdir);
strcat(fullpath, path);
printf("Opening static file: [%s]\n", fullpath);
filetype_t fileType = extractFileType(fullpath);
if (fileType == ERROR) {
perror("Filetype not supported");
sendHTTP404Error(sockfd);
}
FILE *f = fopen(fullpath, "r");
if (!f) {
perror("Problem with fopen");
sendHTTP404Error(sockfd);
} else {
if(gzipflag && fileType == HTML) {
printf("Encrypted HTML serving\n");
sendHTTPGetEncryptedReply(sockfd, f, fileType);
}
else
sendHTTPGetReply(sockfd, f, fileType);
}
}
void *handleSocket(void* sockfd_arg) {
int sockfd = *((int *)sockfd_arg);
int gzipflag;
printf("Now socket: %d\n", sockfd);
char *text = readFromSocket(sockfd);
printf("Text from socket: %s\n\n", text);
if (checkIfGet(text)) {
char curdir[MAX_CWD];
if (!getcwd(curdir, MAX_CWD)) {
error("Couldn't read curdir");
}
gzipflag = checkIfGzipDeflate(text);
char *path = extractPath(text);
outputStaticFile(sockfd, curdir, path, gzipflag);
free(path);
} else {
sendHTTP404Error(sockfd);
}
free(text);
close(sockfd);
free(sockfd_arg);
return NULL;
}
int createNewSocket() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
int setopt = 1;
if (-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&setopt, sizeof(setopt))) {
error("ERROR setting socket options");
}
struct sockaddr_in serv_addr;
uint16_t port = 8000;
while (1) {
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
port++;
} else {
break;
}
}
if (listen(sockfd, SOMAXCONN) < 0) error("Couldn't listen");
printf("Running on port: %d\n", port);
return sockfd;
}
int main() {
int sockfd = createNewSocket();
struct sockaddr_in client_addr;
int cli_len = sizeof(client_addr);
int threads_count = 0;
pthread_t threads[MAXTHREAD];
while (1) {
int newsockfd = accept(sockfd, (struct sockaddr *) &client_addr, (socklen_t *) &cli_len);
if (newsockfd < 0) error("Error on accept");
printf("New socket: %d\n", newsockfd);
int *arg = malloc(sizeof(int));
*arg = newsockfd;
if (pthread_create(&threads[threads_count], NULL, handleSocket, arg)) {
printf("Error when creating thread %d\n", threads_count );
return 0;
}
if (++threads_count >= MAXTHREAD) {
break;
}
}
printf("Max thread number reached, wait for all threads to finish and exit...\n");
for (int i = 0; i < MAXTHREAD; ++i) {
pthread_join(threads[i], NULL);
}
close(sockfd);
return 0;
}