-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_utils.c
More file actions
464 lines (391 loc) · 16.6 KB
/
server_utils.c
File metadata and controls
464 lines (391 loc) · 16.6 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include "server_utils.h"
#include "networking.h"
#include "request.h"
#include "dynamic.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <unistd.h>
/* -------------------------------------------------------------------------
* accept_clients
* ---------------------------------------------------------------------- */
int accept_clients(int serv_sockfd, int *client_sockfd) {
struct sockaddr_storage client_addr;
socklen_t addr_size = sizeof(client_addr);
*client_sockfd = accept(serv_sockfd,
(struct sockaddr *)&client_addr, &addr_size);
if (*client_sockfd == -1) {
perror("accept");
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------
* receive_from_clients
* ---------------------------------------------------------------------- */
int receive_from_clients(int client_sockfd, char **buffer,
ssize_t *current_size_buffer) {
char chunk[BUFFER_SIZE];
ssize_t recv_size;
recv_size = recv(client_sockfd, chunk, BUFFER_SIZE, 0);
if (recv_size == 0) {
printf("Client closed connection.\n");
return -2; /* Caller should close the socket and exit the loop. */
}
if (recv_size == -1) {
perror("recv");
return -1; /* Caller should close the socket and exit the loop. */
}
printf("Received %ld bytes:\n%.*s\n", recv_size, (int)recv_size, chunk);
/*
* Fixed: the original realloc size was missing +1 for the null
* terminator, making the subsequent (*buffer)[size] = '\0' write
* one byte past the end of the allocation.
*/
char *temp = realloc(*buffer, *current_size_buffer + recv_size + 1);
if (temp == NULL) {
perror("realloc");
return -1;
}
*buffer = temp;
memcpy(*buffer + *current_size_buffer, chunk, recv_size);
*current_size_buffer += recv_size;
(*buffer)[*current_size_buffer] = '\0';
printf("Buffer (%zd bytes):\n%s", *current_size_buffer, *buffer);
return 0;
}
/* -------------------------------------------------------------------------
* get_request_from_buffer
* ---------------------------------------------------------------------- */
int get_request_from_buffer(char **buffer, ssize_t *current_size_buffer,
request **current_request) {
const char *terminator = "\r\n\r\n";
size_t terminator_len = strlen(terminator);
char *request_end = strstr(*buffer, terminator);
if (request_end == NULL) {
printf("get_request_from_buffer: incomplete request\n");
return -1;
}
/* --- Parse request line ------------------------------------------- */
char *request_line_end = strstr(*buffer, "\r\n");
if (request_line_end == NULL) {
fprintf(stderr, "Malformed request: no request line.\n");
return -1;
}
size_t request_line_len = (size_t)(request_line_end - *buffer);
char *request_line = strndup(*buffer, request_line_len);
if (request_line == NULL) {
perror("strndup request_line");
return -1;
}
char *method = strtok(request_line, " ");
char *uri = strtok(NULL, " ");
char *http_version = strtok(NULL, " ");
if (method == NULL || uri == NULL || http_version == NULL) {
fprintf(stderr, "Malformed request line.\n");
free(request_line);
return -2;
}
(*current_request)->method = strdup(method);
(*current_request)->uri = strdup(uri);
(*current_request)->httpversion = strdup(http_version);
free(request_line);
if (!(*current_request)->method ||
!(*current_request)->uri ||
!(*current_request)->httpversion) {
perror("strdup request fields");
return -1;
}
printf("Request line: %s %s %s\n",
(*current_request)->method,
(*current_request)->uri,
(*current_request)->httpversion);
/* --- Parse headers ------------------------------------------------- */
char *headers_start = request_line_end + 2; /* Skip \r\n */
size_t headers_len = (size_t)(request_end - headers_start);
char *headers_block = strndup(headers_start, headers_len);
if (headers_block == NULL) {
perror("strndup headers_block");
return -1;
}
request_header *tail = NULL;
char *header_line = strtok(headers_block, "\r\n");
while (header_line != NULL) {
char *sep = strstr(header_line, ": ");
if (sep != NULL) {
size_t key_len = (size_t)(sep - header_line);
char *key = strndup(header_line, key_len);
char *value = strdup(sep + 2);
/*
* Fixed: the original had no NULL check on malloc here.
*/
request_header *new_header = malloc(sizeof(request_header));
if (new_header == NULL || key == NULL || value == NULL) {
perror("malloc header");
free(key);
free(value);
free(new_header);
free(headers_block);
return -1;
}
new_header->key = key;
new_header->value = value;
new_header->next = NULL;
if ((*current_request)->headers == NULL) {
(*current_request)->headers = new_header;
tail = new_header;
} else {
tail->next = new_header;
tail = new_header;
}
} else {
fprintf(stderr, "Malformed header line (skipped): %s\n",
header_line);
}
header_line = strtok(NULL, "\r\n");
}
free(headers_block);
/* --- Extract body for PUT requests --------------------------------- */
if (strcmp((*current_request)->method, "PUT") == 0) {
char *content_length_str = find_content_len(current_request);
if (content_length_str == NULL) {
fprintf(stderr, "PUT request missing Content-Length header.\n");
return -1;
}
long content_len = strtol(content_length_str, NULL, 10);
if (content_len <= 0) {
fprintf(stderr, "Invalid Content-Length value.\n");
return -1;
}
ssize_t full_request_len = (request_end - *buffer) +
(ssize_t)terminator_len +
content_len;
ssize_t remaining_len = *current_size_buffer - full_request_len;
if (remaining_len < 0) {
printf("Incomplete PUT body, still need %zd bytes.\n",
-remaining_len);
return -1;
}
/* Attach content as a synthetic "Content" header. */
request_header *content_header = malloc(sizeof(request_header));
if (content_header == NULL) {
perror("malloc content_header");
return -1;
}
content_header->key = strdup("Content");
content_header->value = strndup(request_end + terminator_len,
(size_t)content_len);
content_header->next = NULL;
if (content_header->key == NULL || content_header->value == NULL) {
perror("strdup content_header fields");
free(content_header->key);
free(content_header->value);
free(content_header);
return -1;
}
if (tail != NULL) {
tail->next = content_header;
} else {
(*current_request)->headers = content_header;
}
/* Consume the processed request from the buffer. */
memmove(*buffer, *buffer + full_request_len, (size_t)remaining_len);
char *temp = realloc(*buffer, (size_t)remaining_len + 1);
if (temp == NULL) {
perror("realloc after PUT");
return -1;
}
*buffer = temp;
*current_size_buffer = remaining_len;
(*buffer)[*current_size_buffer] = '\0';
} else {
/* Non-PUT: consume only up to end of headers. */
ssize_t request_len = (request_end - *buffer) + (ssize_t)terminator_len;
ssize_t remaining_len = *current_size_buffer - request_len;
if (remaining_len < 0) {
printf("Incomplete request.\n");
return -1;
}
memmove(*buffer, *buffer + request_len, (size_t)remaining_len);
char *temp = realloc(*buffer, (size_t)remaining_len + 1);
if (temp == NULL) {
perror("realloc after non-PUT");
return -1;
}
*buffer = temp;
*current_size_buffer = remaining_len;
(*buffer)[*current_size_buffer] = '\0';
}
return 0;
}
/* -------------------------------------------------------------------------
* determine_reply
* ---------------------------------------------------------------------- */
/*
* Returns a heap-allocated response string for dynamic GET (caller must free),
* or a string literal for all other cases (caller must NOT free).
* To simplify caller logic the function always heap-allocates; the caller
* is responsible for freeing the returned string.
*/
char *determine_reply(request **current_request, dynamic **dynamic_list,
int dynamic_put_status) {
if (!(*current_request)->method ||
!(*current_request)->uri ||
!(*current_request)->httpversion) {
return strdup("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n");
}
const char *method = (*current_request)->method;
const char *uri = (*current_request)->uri;
printf("Handling: %s %s %s\n", method, uri,
(*current_request)->httpversion);
if (strcmp(method, "GET") == 0) {
if (strcmp(uri, "/static/bar") == 0) {
return strdup("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
"Content-Length: 3\r\n\r\nBar");
}
if (strcmp(uri, "/static/foo") == 0) {
return strdup("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
"Content-Length: 3\r\n\r\nFoo");
}
if (strcmp(uri, "/static/baz") == 0) {
return strdup("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
"Content-Length: 3\r\n\r\nBaz");
}
if (strncmp(uri, "/dynamic/", 9) == 0) {
dynamic *item = dynamic_get(dynamic_list, uri);
if (item == NULL) {
return strdup("HTTP/1.1 404 Not Found\r\n"
"Content-Length: 0\r\n\r\n");
}
/*
* Fixed: the original used a fixed 256-byte stack buffer that
* could overflow on large content, and malloc(strlen) missing
* the +1 for the null terminator. Now fully heap-allocated with
* an exact size calculation.
*/
int content_len = (int)strlen(item->content);
int header_len = snprintf(NULL, 0,
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
"Content-Length: %d\r\n\r\n", content_len);
char *response = malloc((size_t)(header_len + content_len + 1));
if (response == NULL) {
perror("malloc response");
return strdup("HTTP/1.1 500 Internal Server Error\r\n"
"Content-Length: 0\r\n\r\n");
}
snprintf(response, (size_t)(header_len + content_len + 1),
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
"Content-Length: %d\r\n\r\n%s", content_len, item->content);
return response;
}
return strdup("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
} else if (strcmp(method, "DELETE") == 0) {
if (strncmp(uri, "/dynamic/", 9) != 0) {
return strdup("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
}
int del_status = dynamic_del(dynamic_list, uri);
if (del_status == DYNAMIC_DEL_OK) {
return strdup("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n");
}
return strdup("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
} else if (strcmp(method, "PUT") == 0) {
if (strncmp(uri, "/dynamic/", 9) != 0) {
return strdup("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
}
if (dynamic_put_status == DYNAMIC_PUT_SUCCESS) {
return strdup("HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n");
}
if (dynamic_put_status == DYNAMIC_PUT_UPDATED) {
return strdup("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n");
}
return strdup("HTTP/1.1 500 Internal Server Error\r\n"
"Content-Length: 0\r\n\r\n");
}
return strdup("HTTP/1.1 501 Not Implemented\r\nContent-Length: 0\r\n\r\n");
}
/* -------------------------------------------------------------------------
* reply_request
* ---------------------------------------------------------------------- */
void reply_request(int client_sockfd, request **current_request,
dynamic **dynamic_list, int dynamic_put_status) {
char *response = determine_reply(current_request, dynamic_list,
dynamic_put_status);
if (response == NULL) {
return;
}
if (send(client_sockfd, response, strlen(response), 0) == -1) {
perror("send");
close(client_sockfd);
}
free(response);
}
/* -------------------------------------------------------------------------
* handle_clients
* ---------------------------------------------------------------------- */
void handle_clients(int client_sockfd, char **buffer,
ssize_t *current_size_buffer, dynamic **dynamic_list) {
while (1) {
int recv_status = receive_from_clients(client_sockfd, buffer,
current_size_buffer);
if (recv_status != 0) {
/*
* Fixed: the original only closed on -2 (clean disconnect) and
* looped forever on a recv error (-1). Both conditions mean the
* connection is unusable; close and exit either way.
*/
close(client_sockfd);
break;
}
/*
* Fixed: the original left all fields uninitialised after malloc.
* memset ensures request_free() can safely free every pointer field.
*/
request *current_request = malloc(sizeof(request));
if (current_request == NULL) {
perror("malloc request");
close(client_sockfd);
break;
}
memset(current_request, 0, sizeof(request));
int parse_status = get_request_from_buffer(buffer, current_size_buffer,
¤t_request);
if (parse_status == -2) {
/* Malformed request line — send 400 and keep the connection. */
const char *bad_req = "HTTP/1.1 400 Bad Request\r\n"
"Content-Length: 0\r\n\r\n";
if (send(client_sockfd, bad_req, strlen(bad_req), 0) == -1) {
perror("send 400");
request_free(current_request);
close(client_sockfd);
break;
}
} else if (parse_status == 0) {
/*
* Fixed: dynamic_put_status was declared but never initialised;
* if the first request was GET/DELETE the stale value would be
* passed to determine_reply.
*/
int dynamic_put_status = 0;
if (strcmp(current_request->method, "PUT") == 0) {
request_header *h = current_request->headers;
while (h != NULL && strcmp(h->key, "Content") != 0) {
h = h->next;
}
if (h != NULL) {
dynamic_put_status = dynamic_put(dynamic_list,
current_request->uri,
h->value);
}
}
reply_request(client_sockfd, ¤t_request,
dynamic_list, dynamic_put_status);
}
/* parse_status == -1 means incomplete data; wait for more. */
/*
* Fixed: the original called free(current_request) directly, leaking
* every header node. request_free() walks and frees the entire chain.
*/
request_free(current_request);
}
}