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
|
/* Very simple webserver that uses Posix Threads
* Compile with: `gcc -lpthread -Wall -o webserver webserver.c'
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <pthread.h>
#include <signal.h>
#include <search.h>
#define BUFSIZE 1024
#define BASE_PATH "/tmp/"
void spin_requests();
void handle_request(int clientfd);
void *request_worker(void *arg);
void new_request(const int clientfd);
void setup_mime_types();
void free_mime_types();
void query_mime_type(const char *filename, char *buf, int len);
int send_content_type_header(const char *filename, int fd);
char *xstrdup(const char *str);
/* listen socket */
static int sockfd;
static int running;
/* threads */
#define THREADS 8
#define TODOS 64
static pthread_t threads[THREADS];
static int todo[TODOS];
static int todo_begin;
static int todo_end;
static pthread_cond_t cond_new;
static pthread_cond_t cond_ready;
static pthread_mutex_t mutex;
/* hash table */
#define HASHTABSIZE 2048
static int have_mimetypes;
static struct hsearch_data mime_table;
static char *mime_fields[2*HASHTABSIZE];
static struct {
char *c200;
char *c404;
char *c501;
char *h_cc;
} http = {
.c200 = "HTTP/1.0 404 OK\r\n",
.c404 = "HTTP/1.0 404 Not Found\r\n",
.c501 = "HTTP/1.0 501 Not Implemented\r\n",
.h_cc = "Connection: close\r\n"
};
void __attribute__((noreturn)) error(const char *msg)
{
perror(msg);
exit(-1);
}
void sig_pipe(int n)
{
fprintf(stderr, "Received SIGPIPE\n");
}
void sig_int(int n)
{
fprintf(stderr, "Received SIGINT, shutting down...\n");
running = 0;
}
int main(int argc, char *argv[])
{
int i;
struct sockaddr_in listen_addr;
// socklen_t socklen;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
error("socket");
memset(&listen_addr, 0, sizeof listen);
listen_addr.sin_family = AF_INET;
listen_addr.sin_addr.s_addr = INADDR_ANY;
listen_addr.sin_port = htons(8080);
int reuse = 1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) == -1)
perror("setsockopt");
if(bind(sockfd, (struct sockaddr *) &listen_addr, sizeof listen_addr) == -1)
error("bind");
if(listen(sockfd, SOMAXCONN) == -1)
error("listen");
if (signal(SIGPIPE, sig_pipe) == SIG_ERR)
error("signal");
if (signal(SIGINT, sig_int) == SIG_ERR)
error("signal");
setup_mime_types();
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond_new, NULL);
pthread_cond_init(&cond_ready, NULL);
for(i = 0; i < THREADS; i++) {
int err;
err = pthread_create(&threads[i], NULL, request_worker, NULL);
if(err)
error("pthread_create");
}
spin_requests();
for(i = 0; i < THREADS; i++)
pthread_cancel(threads[i]);
free_mime_types();
if(close(sockfd) == -1)
perror("close");
return EXIT_SUCCESS;
}
void spin_requests()
{
int clientfd;
fd_set set;
struct sockaddr_in client;
socklen_t client_len;
running = 1;
while(running) {
FD_ZERO(&set);
FD_SET(sockfd, &set);
if(select(sockfd+1, &set, NULL, NULL, NULL) == -1) {
if(!running)
return;
error("select");
}
if(!FD_ISSET(sockfd, &set))
continue;
memset(&client, 0, sizeof client);
clientfd = accept(sockfd, (struct sockaddr *) &client, &client_len);
if(clientfd == -1)
error("accept");
fprintf(stderr, "[master] got connection from %s\n",
inet_ntoa(client.sin_addr));
new_request(clientfd);
}
return;
}
void handle_request(int clientfd)
{
int version;
int len;
int threadid = 0;
FILE *fp = 0;
char buf[BUFSIZE];
char filename[BUFSIZE];
char request_file[BUFSIZE-200];
/* find out thread ID for debugging */
while(threadid < THREADS && !pthread_equal(pthread_self(), threads[threadid]))
threadid++;
/* read in request */
memset(&buf, 0, BUFSIZE);
memset(&filename, 0, BUFSIZE);
memset(&request_file, 0, BUFSIZE);
if(recv(clientfd, &buf, BUFSIZE-1, 0) == -1)
goto cleanup;
if(!!strncmp(buf, "GET ", 4) ||
sscanf(buf, "GET %s HTTP/1.%d", request_file, &version) != 2) {
send(clientfd, http.c501, strlen(http.c501), 0);
fprintf(stderr, "[thread %d, sock %d] Couldn't understand request '%s'\n",
threadid, clientfd, buf);
goto cleanup;
}
/* find file or bail */
strcat(filename, BASE_PATH);
strncat(filename, request_file, BUFSIZE);
if(!(fp = fopen(filename, "r"))) {
fprintf(stderr,
"[thread %d, sock %d] File not found: '%s', returning 404\n",
threadid, clientfd, filename);
send(clientfd, http.c404, strlen(http.c404), 0);
goto cleanup;
}
fprintf(stderr, "[thread %d, sock %d] Will now serve '%s' from '%s'\n",
threadid, clientfd, request_file, filename);
send(clientfd, http.c200, strlen(http.c200), 0);
send(clientfd, http.h_cc, strlen(http.h_cc), 0);
send_content_type_header(filename, clientfd);
send(clientfd, "\r\n", 2, 0);
/* send file contents */
memset(&buf, 0, BUFSIZE);
while(!feof(fp)) {
len = fread(&buf, 1, BUFSIZE-1, fp);
buf[len+1] = '\0';
send(clientfd, buf, len, 0);
}
cleanup:
if(fp)
fclose(fp);
fprintf(stderr, "[thread %d, sock %d] closing connection.\n",
threadid, clientfd);
if(clientfd)
close(clientfd);
}
void *request_worker(void *arg) {
int clientfd;
while(1) {
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond_ready);
while(todo_end == todo_begin)
pthread_cond_wait(&cond_new, &mutex);
clientfd = todo[todo_begin];
todo_begin = (todo_begin + 1) % TODOS;
pthread_mutex_unlock(&mutex);
handle_request(clientfd);
}
}
void new_request(const int clientfd)
{
pthread_mutex_lock(&mutex);
while((todo_end + 1) % TODOS == todo_begin) {
fprintf(stderr, "[master] Queue is completely filled; waiting\n");
pthread_cond_wait(&cond_ready, &mutex);
}
fprintf(stderr, "[master] adding socket %d at position %d (begin=%d)\n",
clientfd, todo_end, todo_begin);
todo[todo_end] = clientfd;
todo_end = (todo_end + 1) % TODOS;
pthread_cond_signal(&cond_new);
pthread_mutex_unlock(&mutex);
}
void setup_mime_types()
{
int i = 0;
char types[] = "/etc/mime.types";
char delim[] = " \t\n";
char *t, *t_save;
char *mimetype;
char buf[BUFSIZE];
FILE *fp;
ENTRY e;
ENTRY *ret;
struct stat st;
if(stat(types, &st) == -1)
return;
if(!hcreate_r(HASHTABSIZE, &mime_table))
return;
if(!(fp = fopen(types, "r")))
return;
fprintf(stderr, "Reading MIME type entries from %s\n", types);
while(fgets(buf, BUFSIZE, fp)) {
if(buf[0] == '#')
continue;
if(!(t = strtok_r(buf, delim, &t_save)))
continue;
mimetype = xstrdup(t);
mime_fields[i++ % (2*HASHTABSIZE)] = mimetype;
while((t = strtok_r(NULL, delim, &t_save))) {
e.key = xstrdup(t);
mime_fields[i++ % (2*HASHTABSIZE)] = e.key;
e.data = (void *)mimetype;
fprintf(stderr, "mime_table: adding '%s' -> '%s'\n",
e.key, (char *)e.data);
if(!hsearch_r(e, ENTER, &ret, &mime_table))
break; /* error, or hash table full...? */
}
}
fclose(fp);
have_mimetypes = 1;
}
void free_mime_types()
{
int i;
if(!have_mimetypes)
return;
for(i = 0; mime_fields[i] && i < 2*HASHTABSIZE; i++) {
free(mime_fields[i]);
mime_fields[i] = NULL;
}
hdestroy_r(&mime_table);
}
void query_mime_type(const char *filename, char *buf, int len)
{
char *period;
char default_type[] = "text/html";
ENTRY search;
ENTRY *result;
if(!have_mimetypes || !(period = strrchr(filename, '.'))) {
snprintf(buf, len-1, default_type); /* best guess */
return;
}
search.key = period+1;
if(!hsearch_r(search, FIND, &result, &mime_table)) {
snprintf(buf, len-1, default_type); /* best guess */
return;
}
snprintf(buf, len-1, (char *)result->data);
}
int send_content_type_header(const char *filename, int fd)
{
char buf[BUFSIZE];
char type[BUFSIZE];
query_mime_type(filename, type, BUFSIZE);
snprintf(buf, BUFSIZE, "Content-type: %s\r\n", type);
return send(fd, buf, strlen(buf), 0);
}
char *xstrdup(const char *str)
{
char *ret;
int len = strlen(str);
if(!(ret = calloc(1, len+1)))
perror("xstrdup");
strncpy(ret, str, len);
return ret;
}
|