-
Notifications
You must be signed in to change notification settings - Fork 603
/
Copy pathserver.c
380 lines (298 loc) · 9.93 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
/**
* webserver.c -- A webserver written in C
*
* Test with curl (if you don't have it, install it):
*
* curl -D - http://localhost:3490/
* curl -D - http://localhost:3490/d20
* curl -D - http://localhost:3490/date
*
* You can also test the above URLs in your browser! They should work!
*
* Posting Data:
*
* curl -D - -X POST -H 'Content-Type: text/plain' -d 'Hello, sample data!' http://localhost:3490/save
*
* (Posting data is harder to test from a browser.)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/file.h>
#include <fcntl.h>
#include "net.h"
#include "file.h"
#include "mime.h"
#include "cache.h"
#define PORT "3490" // the port users will be connecting to
#define SERVER_FILES "./serverfiles"
#define SERVER_ROOT "./serverroot"
// int get_current_time() {
// // gets current time as a string
// time_t rawtime;
// struct tm * timeinfo;
// time (&rawtime);
// timeinfo = localtime (&rawtime);
// return timeinfo;
// }
/**
* Send an HTTP response
*
* header: "HTTP/1.1 404 NOT FOUND" or "HTTP/1.1 200 OK", etc.
* content_type: "text/plain", etc.
* body: the data to send.
*
* Return the value from the send() function.
*/
int send_response(int fd, char *header, char *content_type, void *body, int content_length)
{
const int max_response_size = 262144;
char response[max_response_size];
// Build HTTP response and store it in response
// gets current time as a string
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
char * current_date = asctime(timeinfo);
int header_length = sprintf(response, "%s\n"
"Date: %s"
"Connection: close\n"
"Content-Length: %d\n"
"Content-Type: %s\n"
"\n", header, current_date, content_length, content_type);
// char *file_blob = malloc(content_length);
printf("copying memory %d - %d\n", header_length, content_length);
if (header_length + content_length > max_response_size) {
content_length = content_length - (header_length + content_length - max_response_size);
}
memcpy(response + header_length , body, content_length);
// response[header_length + content_length+1] = '\0';
printf("response\n------------\n%s\n-----------\n", response);
// Send it all!
int rv = send(fd, response, header_length + content_length, 0);
if (rv < 0) {
perror("send");
}
return rv;
}
/**
* Send a /d20 endpoint response
*/
void get_d20(int fd)
{
// Generate a random number between 1 and 20 inclusive
///////////////////
// IMPLEMENT ME! //
///////////////////
// time_t rawtime;
srand(time(NULL));
int d20_val = rand();
char output[100]; // one hundred just to be safe
sprintf(output, "%d", d20_val);
int output_len = strlen(output);//(int)((ceil(log10(d20_val))+1)*sizeof(char));
printf("d20 roll: %d\n", d20_val);
// Use send_response() to send it back as text/plain data
///////////////////
// IMPLEMENT ME! //
///////////////////
send_response(fd, "http/1.1 200 /d20", "text/plain", output, output_len);
}
/**
* Send a 404 response
*/
void resp_404(int fd)
{
char filepath[4096];
struct file_data *filedata;
char *mime_type;
// Fetch the 404.html file
snprintf(filepath, sizeof filepath, "%s/404.html", SERVER_FILES);
filedata = file_load(filepath);
if (filedata == NULL) {
// TODO: make this non-fatal
fprintf(stderr, "cannot find system 404 file\n");
exit(3);
}
mime_type = mime_type_get(filepath);
// printf("\"%s\"", filedata->data);
send_response(fd, "HTTP/1.1 404 NOT FOUND", mime_type, filedata->data, filedata->size);
file_free(filedata);
}
/**
* Read and return a file from disk or cache
*/
void get_file(int fd, struct cache *cache, char *request_path)
{
///////////////////
// IMPLEMENT ME! //
///////////////////
struct file_data *filedata;
char *mime_type;
char filepath[4096];
char header[64];
mime_type = mime_type_get(filepath);
sprintf(header, "HTTP/1.1 200 %s", request_path);
struct cache_entry * cached_entry = cache_get(cache, request_path);
// snprintf(request_path, sizeof request_path, "%s/index.html", SERVER_ROOT);
if (cached_entry != NULL) // file was cached
{
printf("serving cached file: %s \n", request_path);
send_response(fd, header, mime_type, cached_entry->content, cached_entry->content_length);
}
else // load from disk
{
// concat request_path with local dir
snprintf(filepath, sizeof filepath, "%s%s", SERVER_ROOT, request_path);
printf("getting file: %s\n", filepath);
filedata = file_load(filepath);
if (filedata == NULL) {
fprintf(stderr, "cannot find %s\n", filepath);
printf("path does not exist \n");
resp_404(fd);
// exit(3);
return;
}
// cache file
cache_put(cache, request_path, mime_type, filedata->data, filedata->size);
// mime_type = mime_type_get(filepath);
printf("header: %s\n", header);
send_response(fd, header, mime_type, filedata->data, filedata->size);
file_free(filedata);
}
}
/**
* Search for the end of the HTTP header
*
* "Newlines" in HTTP can be \r\n (carriage return followed by newline) or \n
* (newline) or \r (carriage return).
*/
char *find_start_of_body(char *header)
{
///////////////////
// IMPLEMENT ME! // (Stretch)
///////////////////
return "";
}
/**
* Handle HTTP request and send response
*/
void handle_http_request(int fd, struct cache *cache)
{
const int request_buffer_size = 262144; // 256 kb
char request[request_buffer_size];
// Read request
int bytes_recvd = recv(fd, request, request_buffer_size - 1, 0);
if (bytes_recvd < 0) {
perror("recv");
return;
}
///////////////////
// IMPLEMENT ME! //
///////////////////
// char *request_parts = strtok(request, " ");
// printf("request verb: %s request endpoint: %s", request_parts[0],request_parts[1]);
char request_type[10], path[50];
sscanf(request, "%s %s", request_type, path);
printf("request: %s %s\n", request_type, path);
// parse header
// Read the first two components of the first line of the request
// printf("request: %s\n", request);
// If GET, handle the get endpoints
// char *is_get = strstr(request, "GET");
// char *route = strchr(request, '/');
// printf("request endpoint: \"%s\" \"%s\"\n", is_get, route);
char filepath[4096];
struct file_data *filedata;
char *mime_type;
if (strcmp(request_type, "GET") == 0 && strcmp(path, "/index.html") == 0)
{
// I could make this into another function
printf("is get index.html\n");
struct cache_entry * cached_entry = cache_get(cache, path);
get_file(fd, cache, "index.html");
/*
if (cached_entry == NULL)
{
snprintf(filepath, sizeof filepath, "%s/index.html", SERVER_ROOT);
filedata = file_load(filepath);
if (filedata == NULL) {
fprintf(stderr, "cannot find index.html\n");
exit(3);
}
mime_type = mime_type_get(filepath);
cache_put(cache, path, mime_type, filedata->data, filedata->size);
send_response(fd, "HTTP/1.1 200 /index.html", mime_type, filedata->data, filedata->size);
file_free(filedata);
}
else
{
printf("serving cached file: %s \n", path);
send_response(fd, "HTTP/1.1 200 /index.html", mime_type, cached_entry->content, cached_entry->content_length);
}
*/
}
else if (strcmp(request_type, "GET") == 0 && strcmp(path, "/d20") == 0)
{
get_d20(fd);
}
else
{
// snprintf(filepath, sizeof filepath, "%s%s", SERVER_ROOT, path);
// printf("%s", filepath);
// check if file exists?
get_file(fd, cache, path);
}
// Check if it's /d20 and handle that special case
// Otherwise serve the requested file by calling get_file()
// (Stretch) If POST, handle the post request
}
/**
* Main
*/
int main(void)
{
int newfd; // listen on sock_fd, new connection on newfd
struct sockaddr_storage their_addr; // connector's address information
char s[INET6_ADDRSTRLEN];
struct cache *cache = cache_create(10, 0);
// Get a listening socket
int listenfd = get_listener_socket(PORT);
if (listenfd < 0) {
fprintf(stderr, "webserver: fatal error getting listening socket\n");
exit(1);
}
printf("webserver: waiting for connections on port %s...\n", PORT);
// This is the main loop that accepts incoming connections and
// responds to the request. The main parent process
// then goes back to waiting for new connections.
while(1) {
socklen_t sin_size = sizeof their_addr;
// Parent process will block on the accept() call until someone
// makes a new connection:
newfd = accept(listenfd, (struct sockaddr *)&their_addr, &sin_size);
if (newfd == -1) {
perror("accept");
continue;
}
// Print out a message that we got the connection
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
// newfd is a new socket descriptor for the new connection.
// listenfd is still listening for new connections.
handle_http_request(newfd, cache);
close(newfd);
}
// Unreachable code
return 0;
}