source: Main/trunk/Server/server.c@ 24

Last change on this file since 24 was 24, checked in by Nishi, on Sep 14, 2024 at 11:09:58 PM

redirects properly now

  • Property svn:keywords set to Id
File size: 16.2 KB
Line 
1/* $Id: server.c 24 2024-09-14 14:09:58Z nishi $ */
2
3#define SOURCE
4
5#include "tw_server.h"
6
7#include "tw_ssl.h"
8#include "tw_config.h"
9#include "tw_http.h"
10#include "tw_module.h"
11#include "tw_version.h"
12
13#include <unistd.h>
14#include <string.h>
15#include <stdbool.h>
16#include <stdarg.h>
17#include <sys/stat.h>
18
19#include <cm_string.h>
20#include <cm_log.h>
21#include <cm_dir.h>
22
23#ifdef __MINGW32__
24#include <winsock2.h>
25#include <process.h>
26#else
27#include <sys/select.h>
28#include <sys/socket.h>
29#include <arpa/inet.h>
30#include <netinet/in.h>
31#include <netinet/tcp.h>
32#endif
33
34extern struct tw_config config;
35extern char tw_server[];
36
37fd_set fdset;
38int sockcount = 0;
39
40SOCKADDR addresses[MAX_PORTS];
41int sockets[MAX_PORTS];
42
43/* https://qiita.com/gyu-don/items/5a640c6d2252a860c8cd */
44int tw_wildcard_match(const char* wildcard, const char* target) {
45 const char *pw = wildcard, *pt = target;
46
47 while(1) {
48 if(*pt == 0) {
49 while(*pw == '*') pw++;
50 return *pw == 0;
51 } else if(*pw == 0) {
52 return 0;
53 } else if(*pw == '*') {
54 return *(pw + 1) == 0 || tw_wildcard_match(pw, pt + 1) || tw_wildcard_match(pw + 1, pt);
55 } else if(*pw == '?' || (*pw == *pt)) {
56 pw++;
57 pt++;
58 continue;
59 } else {
60 return 0;
61 }
62 }
63}
64
65void close_socket(int sock) {
66#ifdef __MINGW32__
67 closesocket(sock);
68#else
69 close(sock);
70#endif
71}
72
73int tw_server_init(void) {
74 int i;
75#ifdef __MINGW32__
76 WSADATA wsa;
77 WSAStartup(MAKEWORD(2, 0), &wsa);
78#endif
79 for(i = 0; config.ports[i] != -1; i++)
80 ;
81 sockcount = i;
82 for(i = 0; config.ports[i] != -1; i++) {
83#ifdef NO_IPV6
84 int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
85#else
86 int sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
87#endif
88#ifdef __MINGW32__
89 if(sock == INVALID_SOCKET)
90#else
91 if(sock < 0)
92#endif
93 {
94 cm_log("Server", "Socket creation failure");
95 return 1;
96 }
97 int yes = 1;
98 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(yes)) < 0) {
99 close_socket(sock);
100 cm_log("Server", "setsockopt failure (reuseaddr)");
101 return 1;
102 }
103 if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(yes)) < 0) {
104 close_socket(sock);
105 cm_log("Server", "setsockopt failure (nodelay)");
106 return 1;
107 }
108#ifndef NO_IPV6
109 int no = 0;
110 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&no, sizeof(no)) < 0) {
111 close_socket(sock);
112 cm_log("Server", "setsockopt failure (IPv6)");
113 return 1;
114 }
115#endif
116 memset(&addresses[i], 0, sizeof(addresses[i]));
117#ifdef NO_IPV6
118 addresses[i].sin_family = AF_INET;
119 addresses[i].sin_addr.s_addr = INADDR_ANY;
120 addresses[i].sin_port = htons(config.ports[i]);
121#else
122 addresses[i].sin6_family = AF_INET6;
123 addresses[i].sin6_addr = in6addr_any;
124 addresses[i].sin6_port = htons(config.ports[i]);
125#endif
126 if(bind(sock, (struct sockaddr*)&addresses[i], sizeof(addresses[i])) < 0) {
127 close_socket(sock);
128 cm_log("Server", "Bind failure");
129 return 1;
130 }
131 if(listen(sock, 128) < 0) {
132 close_socket(sock);
133 cm_log("Server", "Listen failure");
134 return 1;
135 }
136 sockets[i] = sock;
137 }
138 return 0;
139}
140
141size_t tw_read(SSL* ssl, int s, void* data, size_t len) {
142 if(ssl == NULL) {
143 return recv(s, data, len, 0);
144 } else {
145 return SSL_read(ssl, data, len);
146 }
147}
148
149size_t tw_write(SSL* ssl, int s, void* data, size_t len) {
150 if(ssl == NULL) {
151 return send(s, data, len, 0);
152 } else {
153 return SSL_write(ssl, data, len);
154 }
155}
156
157#define ERROR_HTML \
158 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" \
159 "<html>\n" \
160 " <head>\n" \
161 " <title>%s</title>\n" \
162 " </head>\n" \
163 " <body>\n" \
164 " <h1>%s</h1>\n" \
165 " <hr>\n" \
166 " ", \
167 address, \
168 "\n" \
169 " </body>\n" \
170 "</html>\n"
171
172void _tw_process_page(SSL* ssl, int sock, const char* status, const char* type, FILE* f, const unsigned char* doc, size_t size, char** headers) {
173 char construct[512];
174 sprintf(construct, "%llu", (unsigned long long)size);
175 tw_write(ssl, sock, "HTTP/1.1 ", 9);
176 tw_write(ssl, sock, (char*)status, strlen(status));
177 tw_write(ssl, sock, "\r\n", 2);
178 if(type != NULL) {
179 tw_write(ssl, sock, "Content-Type: ", 7 + 5 + 2);
180 tw_write(ssl, sock, (char*)type, strlen(type));
181 tw_write(ssl, sock, "\r\n", 2);
182 }
183 tw_write(ssl, sock, "Server: ", 6 + 2);
184 tw_write(ssl, sock, tw_server, strlen(tw_server));
185 tw_write(ssl, sock, "\r\n", 2);
186 if(size != 0) {
187 tw_write(ssl, sock, "Content-Length: ", 7 + 7 + 2);
188 tw_write(ssl, sock, construct, strlen(construct));
189 tw_write(ssl, sock, "\r\n", 2);
190 }
191 int i;
192 if(headers != NULL) {
193 for(i = 0; headers[i] != NULL; i += 2) {
194 tw_write(ssl, sock, headers[i], strlen(headers[i]));
195 tw_write(ssl, sock, ": ", 2);
196 tw_write(ssl, sock, headers[i + 1], strlen(headers[i + 1]));
197 tw_write(ssl, sock, "\r\n", 2);
198 }
199 }
200 tw_write(ssl, sock, "\r\n", 2);
201 if(doc == NULL && f == NULL) return;
202 size_t incr = 0;
203 while(1) {
204 if(f != NULL) {
205 char buffer[128];
206 fread(buffer, size < 128 ? size : 128, 1, f);
207 tw_write(ssl, sock, buffer, size < 128 ? size : 128);
208 } else {
209 tw_write(ssl, sock, (unsigned char*)doc + incr, size < 128 ? size : 128);
210 }
211 incr += 128;
212 if(size <= 128) break;
213 size -= 128;
214 }
215}
216
217void tw_process_page(SSL* ssl, int sock, const char* status, const char* type, FILE* f, const unsigned char* doc, size_t size) { _tw_process_page(ssl, sock, status, type, f, doc, size, NULL); }
218
219const char* tw_http_status(int code) {
220 if(code == 200) {
221 return "200 OK";
222 } else if(code == 308) {
223 return "308 Permanent Redirect";
224 } else if(code == 400) {
225 return "400 Bad Request";
226 } else if(code == 401) {
227 return "401 Unauthorized";
228 } else if(code == 403) {
229 return "403 Forbidden";
230 } else if(code == 404) {
231 return "404 Not Found";
232 } else {
233 return "400 Bad Request";
234 }
235}
236
237char* tw_http_default_error(int code, char* name, int port) {
238 char address[1024];
239 sprintf(address, "<address>%s Server at %s Port %d</address>", tw_server, name, port);
240
241 char* st = cm_strdup(tw_http_status(code));
242 char* st2;
243 int i;
244 for(i = 0; st[i] != 0; i++) {
245 if(st[i] == ' ') {
246 st2 = cm_strdup(st + i + 1);
247 break;
248 }
249 }
250 char* buffer = malloc(4096);
251 char* str = cm_strcat3(ERROR_HTML);
252 sprintf(buffer, str, st, st2);
253 free(str);
254 free(st);
255 return buffer;
256}
257
258void tw_http_error(SSL* ssl, int sock, int error, char* name, int port) {
259 char* str = tw_http_default_error(error, name, port);
260 tw_process_page(ssl, sock, tw_http_status(error), "text/html", NULL, str, strlen(str));
261 free(str);
262}
263
264void addstring(char** str, const char* add, ...) {
265 int i;
266 char cbuf[2];
267 cbuf[1] = 0;
268 va_list va;
269 va_start(va, add);
270 for(i = 0; add[i] != 0; i++) {
271 cbuf[0] = add[i];
272 if(add[i] == '%') {
273 i++;
274 if(add[i] == 's') {
275 char* tmp = *str;
276 *str = cm_strcat(tmp, va_arg(va, const char*));
277 free(tmp);
278 } else if(add[i] == 'h') {
279 char* h = cm_html_escape(va_arg(va, const char*));
280 char* tmp = *str;
281 *str = cm_strcat(tmp, h);
282 free(tmp);
283 free(h);
284 } else if(add[i] == 'l') {
285 char* h = cm_url_escape(va_arg(va, const char*));
286 char* tmp = *str;
287 *str = cm_strcat(tmp, h);
288 free(tmp);
289 free(h);
290 } else if(add[i] == 'd') {
291 int n = va_arg(va, int);
292 char* h = malloc(512);
293 sprintf(h, "%d", n);
294 char* tmp = *str;
295 *str = cm_strcat(tmp, h);
296 free(tmp);
297 free(h);
298 } else if(add[i] == '%') {
299 char* tmp = *str;
300 *str = cm_strcat(tmp, "%");
301 free(tmp);
302 }
303 } else {
304 char* tmp = *str;
305 *str = cm_strcat(tmp, cbuf);
306 free(tmp);
307 }
308 }
309}
310
311char* tw_get_mime(const char* ext, struct tw_config_entry* vhost_entry) {
312 char* mime = "application/octet-stream";
313 if(ext == NULL) return mime;
314 bool set = false;
315 int i;
316 for(i = 0; i < vhost_entry->mime_count; i++) {
317 if(strcmp(vhost_entry->mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(vhost_entry->mimes[i].ext, ext))) {
318 mime = vhost_entry->mimes[i].mime;
319 set = true;
320 }
321 }
322 if(!set) {
323 for(i = 0; i < config.root.mime_count; i++) {
324 if(strcmp(config.root.mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(config.root.mimes[i].ext, ext))) {
325 mime = config.root.mimes[i].mime;
326 }
327 }
328 }
329 return mime;
330}
331
332char* tw_get_icon(const char* mime, struct tw_config_entry* vhost_entry) {
333 char* icon = "";
334 if(mime == NULL) return "";
335 bool set = false;
336 int i;
337 for(i = 0; i < vhost_entry->icon_count; i++) {
338 if(strcmp(vhost_entry->icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(vhost_entry->icons[i].mime, mime))) {
339 icon = vhost_entry->icons[i].icon;
340 set = true;
341 }
342 }
343 if(!set) {
344 for(i = 0; i < config.root.icon_count; i++) {
345 if(strcmp(config.root.icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(config.root.icons[i].mime, mime))) {
346 icon = config.root.icons[i].icon;
347 }
348 }
349 }
350 return icon;
351}
352
353#ifdef __MINGW32__
354struct pass_entry {
355 int sock;
356 int port;
357 bool ssl;
358 SOCKADDR addr;
359};
360
361unsigned int WINAPI tw_server_pass(void* ptr) {
362 int sock = ((struct pass_entry*)ptr)->sock;
363 bool ssl = ((struct pass_entry*)ptr)->ssl;
364 int port = ((struct pass_entry*)ptr)->port;
365 SOCKADDR addr = ((struct pass_entry*)ptr)->addr;
366 free(ptr);
367#else
368void tw_server_pass(int sock, bool ssl, int port, SOCKADDR addr) {
369#endif
370 char* name = config.hostname;
371
372 SSL_CTX* ctx = NULL;
373 SSL* s = NULL;
374 bool sslworks = false;
375 if(ssl) {
376 ctx = tw_create_ssl_ctx(port);
377 s = SSL_new(ctx);
378 SSL_set_fd(s, sock);
379 if(SSL_accept(s) <= 0) goto cleanup;
380 sslworks = true;
381 }
382 struct tw_http_request req;
383 struct tw_http_response res;
384 struct tw_tool tools;
385 res._processed = false;
386 tw_init_tools(&tools);
387 int ret = tw_http_parse(s, sock, &req);
388 if(ret == 0) {
389 char* vhost = cm_strdup(config.hostname);
390 int i;
391 for(i = 0; req.headers[i] != NULL; i += 2) {
392 if(cm_strcaseequ(req.headers[i], "Host")) {
393 free(vhost);
394 vhost = req.headers[i + 1];
395 break;
396 }
397 }
398 cm_log("Server", "Host is %s", vhost);
399 int port = s == NULL ? 80 : 443;
400 char* host = cm_strdup(vhost);
401 for(i = 0; vhost[i] != 0; i++) {
402 if(vhost[i] == ':') {
403 host[i] = 0;
404 port = atoi(host + i + 1);
405 break;
406 }
407 }
408 cm_log("Server", "Hostname is `%s', port is `%d'", host, port);
409 struct tw_config_entry* vhost_entry = tw_vhost_match(host, port);
410 for(i = 0; i < config.module_count; i++) {
411 tw_mod_request_t mod_req = (tw_mod_request_t)tw_module_symbol(config.modules[i], "mod_request");
412 if(mod_req != NULL) {
413 int ret = mod_req(&tools, &req, &res);
414 int co = ret & 0xff;
415 if(co == _TW_MODULE_PASS) continue;
416 if(co == _TW_MODULE_STOP) {
417 res._processed = true;
418 break;
419 }
420 if(co == _TW_MODULE_ERROR) {
421 tw_http_error(s, sock, (ret & 0xffff00) >> 8, name, port);
422 break;
423 }
424 }
425 }
426 if(!res._processed) {
427 cm_log("Server", "Document root is %s", vhost_entry->root == NULL ? "not set" : vhost_entry->root);
428 char* path = cm_strcat(vhost_entry->root == NULL ? "" : vhost_entry->root, req.path);
429 cm_log("Server", "Filesystem path is %s", path);
430 struct stat st;
431 if(stat(path, &st) == 0) {
432 if(!tw_permission_allowed(path, addr, req, vhost_entry)) {
433 tw_http_error(s, sock, 403, name, port);
434 } else if(S_ISDIR(st.st_mode)) {
435 if(req.path[strlen(req.path) - 1] != '/') {
436 char* headers[3] = {"Location", cm_strcat(req.path, "/"), NULL};
437 _tw_process_page(s, sock, tw_http_status(308), NULL, NULL, NULL, 0, headers);
438 free(headers[1]);
439 } else {
440 char** indexes = vhost_entry->index_count == 0 ? config.root.indexes : vhost_entry->indexes;
441 int index_count = vhost_entry->index_count == 0 ? config.root.index_count : vhost_entry->index_count;
442 bool found = false;
443 for(i = 0; i < index_count; i++) {
444 char* p = cm_strcat3(path, "/", indexes[i]);
445 FILE* f = fopen(p, "rb");
446 if(f != NULL) {
447 char* ext = NULL;
448 int j;
449 for(j = strlen(p) - 1; j >= 0; j--) {
450 if(p[j] == '.') {
451 ext = cm_strdup(p + j);
452 break;
453 } else if(p[j] == '/') {
454 break;
455 }
456 }
457 struct stat st;
458 stat(p, &st);
459 char* mime = tw_get_mime(ext, vhost_entry);
460 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size);
461 fclose(f);
462 free(p);
463 found = true;
464 break;
465 }
466 free(p);
467 }
468 if(!found) {
469 char* str = malloc(1);
470 str[0] = 0;
471 char** items = cm_scandir(path);
472 addstring(&str, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
473 addstring(&str, "<html>\n");
474 addstring(&str, " <head>\n");
475 addstring(&str, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
476 addstring(&str, " <title>Index of %h</title>\n", req.path);
477 addstring(&str, " </head>\n");
478 addstring(&str, " <body>\n");
479 addstring(&str, " <h1>Index of %h</h1>\n", req.path);
480 addstring(&str, " <hr>\n");
481 addstring(&str, " <table border=\"0\">\n");
482 addstring(&str, " <tr>\n");
483 addstring(&str, " <th></th>\n");
484 addstring(&str, " <th>Filename</th>\n");
485 addstring(&str, " </tr>\n");
486 if(items != NULL) {
487 for(i = 0; items[i] != NULL; i++) {
488 char* ext = NULL;
489 int j;
490 for(j = strlen(items[i]) - 1; j >= 0; j--) {
491 if(items[i][j] == '.') {
492 ext = cm_strdup(items[i] + j);
493 break;
494 } else if(items[i][j] == '/') {
495 break;
496 }
497 }
498 char* mime = tw_get_mime(ext, vhost_entry);
499 if(strcmp(items[i], "../") == 0) {
500 mime = "misc/parent";
501 } else if(items[i][strlen(items[i]) - 1] == '/') {
502 mime = "misc/dir";
503 }
504 char* icon = tw_get_icon(mime, vhost_entry);
505 if(ext != NULL) free(ext);
506 char* itm = cm_strdup(items[i]);
507 if(strlen(itm) >= 32) {
508 if(itm[strlen(itm) - 1] == '/') {
509 itm[31] = 0;
510 itm[30] = '/';
511 itm[29] = '.';
512 itm[28] = '.';
513 itm[27] = '.';
514 } else {
515 itm[31] = 0;
516 itm[30] = '.';
517 itm[29] = '.';
518 itm[28] = '.';
519 }
520 }
521 addstring(&str, "<tr>\n");
522 addstring(&str, " <td><img src=\"%s\" alt=\"icon\"></td>\n", icon);
523 addstring(&str, " <td><a href=\"%l\"><code>%h</code></a></td>\n", items[i], itm);
524 addstring(&str, "</tr>\n");
525 free(itm);
526 }
527 }
528 addstring(&str, " </table>\n");
529 addstring(&str, " <hr>\n");
530 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
531 addstring(&str, " </body>\n");
532 addstring(&str, "</html>\n");
533 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str));
534 free(str);
535 }
536 }
537 } else {
538 char* ext = NULL;
539 for(i = strlen(req.path) - 1; i >= 0; i--) {
540 if(req.path[i] == '.') {
541 ext = cm_strdup(req.path + i);
542 break;
543 } else if(req.path[i] == '/') {
544 break;
545 }
546 }
547 char* mime = tw_get_mime(ext, vhost_entry);
548 if(ext != NULL) free(ext);
549 FILE* f = fopen(path, "rb");
550 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size);
551 fclose(f);
552 }
553 } else {
554 tw_http_error(s, sock, 404, name, port);
555 }
556 free(path);
557 }
558 free(vhost);
559 free(host);
560 } else if(ret == -1) {
561 } else {
562 tw_http_error(s, sock, 400, name, port);
563 }
564cleanup:
565 if(sslworks) {
566 SSL_shutdown(s);
567 }
568 SSL_free(s);
569 close_socket(sock);
570#ifdef __MINGW32__
571 _endthreadex(0);
572#endif
573}
574
575void tw_server_loop(void) {
576 struct timeval tv;
577 while(1) {
578 FD_ZERO(&fdset);
579 int i;
580 for(i = 0; i < sockcount; i++) {
581 FD_SET(sockets[i], &fdset);
582 }
583 tv.tv_sec = 1;
584 tv.tv_usec = 0;
585 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
586 if(ret == -1) {
587 break;
588 } else if(ret > 0) {
589 /* connection */
590 int i;
591 for(i = 0; i < sockcount; i++) {
592 if(FD_ISSET(sockets[i], &fdset)) {
593 SOCKADDR claddr;
594 int clen = sizeof(claddr);
595 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
596 cm_log("Server", "New connection accepted");
597#ifdef __MINGW32__
598 HANDLE thread;
599 struct pass_entry* e = malloc(sizeof(*e));
600 e->sock = sock;
601 e->ssl = config.ports[i] & (1ULL << 32);
602 e->port = config.ports[i];
603 e->addr = claddr;
604 thread = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
605#else
606 pid_t pid = fork();
607 if(pid == 0) {
608 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
609 _exit(0);
610 } else {
611 close_socket(sock);
612 }
613#endif
614 }
615 }
616 }
617 }
618}
Note: See TracBrowser for help on using the repository browser.