forked from sysprog21/lab0-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiny.c
351 lines (322 loc) · 10 KB
/
tiny.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
#include "tiny.h"
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
mime_map meme_types[] = {
{".aac", "audio/aac"},
{".abw", "application/x-abiword"},
{".arc", "application/x-freearc"},
{".avi", "video/x-msvideo"},
{".azw", "application/vnd.amazon.ebook"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".bz", "application/x-bzip"},
{".bz2", "application/x-bzip2"},
{".csh", "application/x-csh"},
{".css", "text/css"},
{".csv", "text/csv"},
{".doc", "application/msword"},
{".docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".eot", "application/vnd.ms-fontobject"},
{".epub", "application/epub+zip"},
{".gz", "application/gzip"},
{".gif", "image/gif"},
{".htm", "text/html"},
{".html", "text/html"},
{".ico", "image/vnd.microsoft.icon"},
{".ics", "text/calendar"},
{".jar", "application/java-archive"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "text/javascript"},
{".json", "application/json"},
{".jsonld", "application/ld+json"},
{".mid", "audio/midi audio/x-midi"},
{".midi", "audio/midi audio/x-midi"},
{".mjs", "text/javascript"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mpeg", "video/mpeg"},
{".mpkg", "application/vnd.apple.installer+xml"},
{".odp", "application/vnd.oasis.opendocument.presentation"},
{".ods", "application/vnd.oasis.opendocument.spreadsheet"},
{".odt", "application/vnd.oasis.opendocument.text"},
{".oga", "audio/ogg"},
{".ogv", "video/ogg"},
{".ogx", "application/ogg"},
{".opus", "audio/opus"},
{".otf", "font/otf"},
{".png", "image/png"},
{".pdf", "application/pdf"},
{".php", "application/x-httpd-php"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx",
"application/"
"vnd.openxmlformats-officedocument.presentationml.presentation"},
{".rar", "application/vnd.rar"},
{".rtf", "application/rtf"},
{".sh", "application/x-sh"},
{".svg", "image/svg+xml"},
{".swf", "application/x-shockwave-flash"},
{".tar", "application/x-tar"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".ts", "video/mp2t"},
{".ttf", "font/ttf"},
{".txt", "text/plain"},
{".vsd", "application/vnd.visio"},
{".wav", "audio/wav"},
{".weba", "audio/webm"},
{".webm", "video/webm"},
{".webp", "image/webp"},
{".woff", "font/woff"},
{".woff2", "font/woff2"},
{".xhtml", "application/xhtml+xml"},
{".xls", "application/vnd.ms-excel"},
{".xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xml", "text/xml"},
{".xul", "application/vnd.mozilla.xul+xml"},
{".zip", "application/zip"},
{".3gp", "video/3gpp"},
{".3g2", "video/3gpp2"},
{".7z", "application/x-7z-compressed"},
{NULL, NULL},
};
char *default_mime_type = "text/plain";
void rio_readinitb(_rio_t *rp, int fd)
{
rp->rio_fd = fd;
rp->rio_cnt = 0;
rp->rio_bufptr = rp->rio_buf;
}
ssize_t writen(int fd, void *usrbuf, size_t n)
{
size_t nleft = n;
while (nleft > 0) {
ssize_t nwritten;
char *bufp = usrbuf;
if ((nwritten = write(fd, bufp, nleft)) <= 0) {
if (errno == EINTR) { /* interrupted by sig handler return */
nwritten = 0; /* and call write() again */
} else {
return -1; /* errorno set by write() */
}
}
nleft -= nwritten;
bufp += nwritten;
}
return n;
}
/*
* rio_read - This is a wrapper for the Unix read() function that
* transfers min(n, rio_cnt) bytes from an internal buffer to a user
* buffer, where n is the number of bytes requested by the user and
* rio_cnt is the number of unread bytes in the internal buffer. On
* entry, rio_read() refills the internal buffer via a call to
* read() if the internal buffer is empty.
*/
/* $begin rio_read */
static ssize_t rio_read(_rio_t *rp, char *usrbuf, size_t n)
{
int cnt;
while (rp->rio_cnt <= 0) { /* refill if buf is empty */
rp->rio_cnt = read(rp->rio_fd, rp->rio_buf, sizeof(rp->rio_buf));
if (rp->rio_cnt < 0) {
if (errno != EINTR) { /* interrupted by sig handler return */
return -1;
}
} else if (rp->rio_cnt == 0) { /* EOF */
return 0;
} else
rp->rio_bufptr = rp->rio_buf; /* reset buffer ptr */
}
/* Copy min(n, rp->rio_cnt) bytes from internal buf to user buf */
cnt = n;
if (rp->rio_cnt < n) {
cnt = rp->rio_cnt;
}
memcpy(usrbuf, rp->rio_bufptr, cnt);
rp->rio_bufptr += cnt;
rp->rio_cnt -= cnt;
return cnt;
}
/*
* rio_readlineb - robustly read a text line (buffered)
*/
ssize_t rio_readlineb(_rio_t *rp, void *usrbuf, size_t maxlen)
{
int n;
char c, *bufp = usrbuf;
for (n = 1; n < maxlen; n++) {
int rc;
if ((rc = rio_read(rp, &c, 1)) == 1) {
*bufp++ = c;
if (c == '\n') {
break;
}
} else if (rc == 0) {
if (n == 1) {
return 0; /* EOF, no data read */
} else {
break; /* EOF, some data was read */
}
} else {
return -1; /* error */
}
}
*bufp = 0;
return n;
}
static const char *get_mime_type(char *filename)
{
char *dot = strrchr(filename, '.');
if (dot) { // strrchar Locate last occurrence of character in string
mime_map *map = meme_types;
while (map->extension) {
if (strcmp(map->extension, dot) == 0) {
return map->mime_type;
}
map++;
}
}
return default_mime_type;
}
int open_listenfd(int port)
{
int _listenfd, optval = 1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((_listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return -1;
}
/* Eliminates "Address already in use" error from bind. */
if (setsockopt(_listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *) &optval,
sizeof(int)) < 0) {
return -1;
}
// 6 is TCP's protocol number
// enable this, much faster : 4000 req/s -> 17000 req/s
if (setsockopt(_listenfd, 6, TCP_CORK, (const void *) &optval,
sizeof(int)) < 0) {
return -1;
}
/* Listenfd will be an endpoint for all requests to port
on any IP address for this host */
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short) port);
if (bind(_listenfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0) {
return -1;
}
/* Make it a listening socket ready to accept connection requests */
if (listen(_listenfd, LISTENQ) < 0) {
return -1;
}
return _listenfd;
}
void url_decode(char *src, char *dest, int max)
{
char *p = src;
char code[3] = {0};
while (*p && --max) {
if (*p == '%') {
memcpy(code, ++p, 2);
*dest++ = (char) strtoul(code, NULL, 16);
p += 2;
} else {
*dest++ = *p++;
}
}
*dest = '\0';
}
void parse_request(int fd, http_request *req)
{
_rio_t rio;
char buf[MAXLINE], method[MAXLINE], uri[MAXLINE];
req->offset = 0;
req->end = 0; /* default */
rio_readinitb(&rio, fd);
rio_readlineb(&rio, buf, MAXLINE);
sscanf(buf, "%1023s %1023s", method, uri); /* version is not cared */
/* read all */
while (buf[0] != '\n' && buf[1] != '\n') { /* \n || \r\n */
rio_readlineb(&rio, buf, MAXLINE);
if (buf[0] == 'R' && buf[1] == 'a' && buf[2] == 'n') {
sscanf(buf, "Range: bytes=%lu-%zu", &req->offset, &req->end);
// Range: [start, end]
if (req->end != 0) {
req->end++;
}
}
}
char *filename = uri;
if (uri[0] == '/') {
filename = uri + 1;
int length = strlen(filename);
if (length == 0) {
filename = ".";
} else {
int i = 0;
for (; i < length; ++i) {
if (filename[i] == '?') {
filename[i] = '\0';
break;
}
}
}
}
url_decode(filename, req->filename, MAXLINE);
}
#ifdef LOG_ACCESS
void log_access(int status, struct sockaddr_in *c_addr, http_request *req)
{
printf("%s:%d %d - '%s' (%s)\n", inet_ntoa(c_addr->sin_addr),
ntohs(c_addr->sin_port), status, req->filename,
get_mime_type(req->filename));
}
#endif
void client_error(int fd, int status, char *msg, char *longmsg)
{
char buf[MAXLINE];
snprintf(buf, MAXLINE, "HTTP/1.1 %d %s\r\n", status, msg);
snprintf(buf + strlen(buf), MAXLINE, "Content-length: %zu\r\n\r\n",
strlen(longmsg));
snprintf(buf + strlen(buf), MAXLINE, "%s", longmsg);
writen(fd, buf, strlen(buf));
}
char *process(int fd, struct sockaddr_in *clientaddr)
{
#ifdef LOG_ACCESS
printf("accept request, fd is %d, pid is %d\n", fd, getpid());
#endif
http_request req;
parse_request(fd, &req);
int status = 200;
char *p = req.filename;
/* Change '/' to ' ' */
if (p) {
while ((*p) != '\0') {
++p;
if (*p == '/') {
*p = ' ';
}
}
}
client_error(fd, status, "", "");
#ifdef LOG_ACCESS
log_access(status, clientaddr, &req);
#endif
char *ret = malloc(strlen(req.filename) + 1);
strncpy(ret, req.filename, strlen(req.filename) + 1);
return ret;
}
/*void print_help()
{
printf("TINY WEBSERVER HELP\n");
printf("tiny #use default port, serve current dir\n");
printf("tiny /tmp #use default port, serve given dir\n");
printf("tiny 1234 #use given port, serve current dir\n");
printf("tiny /tmp 1234 #use given port, serve given dir\n");
printf("default port is %d.\n", DEFAULT_PORT);
}*/