-
Notifications
You must be signed in to change notification settings - Fork 603
/
Copy pathserver.c
295 lines (248 loc) · 7.89 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
/**
* 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"
/**
* 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
///////////////////
// IMPLEMENT ME! //
///////////////////
//time
time_t rawtime;
struct tm *info;
time (&rawtime);
info = localtime(&rawtime);
//build header
int response_length = snprintf(response, max_response_size,
"%s\n"
"Date: %s" //asctime adds its own new line
"Content-Type: %s\n"
"Content-Length: %d\n"
"Connection: close\n"
"\n",
//"%s\n", //taking body off the response header and creating separate send
header, asctime(info), content_type, content_length //,body
);
// Send it all!
int rv = send(fd, response, response_length, 0);
if (rv < 0) {
perror("send");
}
//refactor this (creating another send) to accommodate png so send body (and its length) separately from the response so still only one request
rv = send(fd, body, 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! //
///////////////////
char str[4];
int random_number = rand() % 21; //num = (rand() % (upper – lower + 1)) + lower
sprintf(str, "%d\n", random_number);
// Use send_response() to send it back as text/plain data
///////////////////
// IMPLEMENT ME! //
///////////////////
send_response(fd, "HTTP/1.1 200 OK", "text/plain", str, strlen(str));
}
/**
* 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);
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! //
///////////////////
//read file
char filepath[4096];
struct file_data *filedata; //loads file into memory and returns pointer to data
char *mime_type;
//fetch file.
//append path user requests (which != filepath) to server root (3490/index.html)
snprintf(filepath, sizeof filepath, "%s%s", SERVER_ROOT, request_path);
printf("\"%s\"\n", filepath);
//time comparison for expiration of cache (implemented with cache put/get)
struct cache_entry *ce = cache_get(cache, filepath);
//expire then refresh file and delete item out of cache (eg if cur time less that time greater than 1min)
if (time(NULL) - ce->timestamp > 60) { //timestamp decl in struct cache_entry in cache.h so know when it was created
}
//load that file
filedata = file_load(filepath);
//if file not found
if (filedata == NULL)
{
resp_404(fd);
return;
}
//get mimetype
mime_type = mime_type_get(filepath);
printf("%s\n", mime_type);
//send file out
send_response(fd, "HTTP/1.1 200 OK", mime_type, filedata->data, filedata->size);
//then free data bc loaded these data into memory
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)
// ///////////////////
// (void)header;
// }
/**
* Handle HTTP request and send response
*/
void handle_http_request(int fd, struct cache *cache)
{
(void)cache; //rememember to remove all these voids. reeeeeeeeemember!
const int request_buffer_size = 65536; // 64K
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! //
///////////////////
// Read the three components of the first request line
char method[512];
char path[8192];
sscanf(request, "%s %s", method, path);
printf("method: \"%s\"\n", method);
printf("path: \"%s\"\n", path);
// If GET, handle the get endpoints
// Check if it's /d20 and handle that special case
// Otherwise serve the requested file by calling get_file()
if (strcmp(method, "GET") == 0) {
if (strcmp(path, "/d20") == 0) { //strcmp returns 0 if equal
get_d20(fd);
} else {
get_file(fd, NULL, path);
//resp_404(fd); //used 404 before completing get_file
}
}
// (Stretch) If POST, handle the post request
//if (strcmp(method, "POST") == 0)
}
/**
* 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
// forks a handler process to take care of it. 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;
}