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

Last change on this file since 28 was 28, checked in by Nishi, on Sep 15, 2024 at 1:25:08 AM

show size

  • Property svn:keywords set to Id
File size: 17.3 KB
Line 
1/* $Id: server.c 28 2024-09-14 16:25:08Z 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, " <th>MIME</th>\n");
486 addstring(&str, " <th>Size</th>\n");
487 addstring(&str, " </tr>\n");
488 if(items != NULL) {
489 for(i = 0; items[i] != NULL; i++) {
490 char* fpth = cm_strcat3(path, "/", items[i]);
491 struct stat s;
492 char size[512];
493 size[0] = 0;
494 stat(fpth, &s);
495 if(s.st_size < 1024ULL){
496 sprintf(size, "%d", s.st_size);
497 }else if(s.st_size < 1024ULL * 1024){
498 sprintf(size, "%.1f K", (double)s.st_size / 1024);
499 }else if(s.st_size < 1024ULL * 1024 * 1024){
500 sprintf(size, "%.1f M", (double)s.st_size / 1024 / 1024);
501 }else if(s.st_size < 1024ULL * 1024 * 1024 * 1024){
502 sprintf(size, "%.1f G", (double)s.st_size / 1024 / 1024 / 1024);
503 }else if(s.st_size < 1024ULL * 1024 * 1024 * 1024 * 1024){
504 sprintf(size, "%.1f T", (double)s.st_size / 1024 / 1024 / 1024 / 1024);
505 }
506
507 free(fpth);
508
509 char* ext = NULL;
510 int j;
511 for(j = strlen(items[i]) - 1; j >= 0; j--) {
512 if(items[i][j] == '.') {
513 ext = cm_strdup(items[i] + j);
514 break;
515 } else if(items[i][j] == '/') {
516 break;
517 }
518 }
519 char* showmime = "";
520 char* mime = tw_get_mime(ext, vhost_entry);
521 if(strcmp(items[i], "../") == 0) {
522 mime = "misc/parent";
523 } else if(items[i][strlen(items[i]) - 1] == '/') {
524 mime = "misc/dir";
525 }else{
526 showmime = mime;
527 }
528 char* icon = tw_get_icon(mime, vhost_entry);
529 if(ext != NULL) free(ext);
530 char* itm = cm_strdup(items[i]);
531 if(strlen(itm) >= 32) {
532 if(itm[strlen(itm) - 1] == '/') {
533 itm[31] = 0;
534 itm[30] = '/';
535 itm[29] = '.';
536 itm[28] = '.';
537 itm[27] = '.';
538 } else {
539 itm[31] = 0;
540 itm[30] = '.';
541 itm[29] = '.';
542 itm[28] = '.';
543 }
544 }
545 addstring(&str, "<tr>\n");
546 addstring(&str, " <td><img src=\"%s\" alt=\"icon\"></td>\n", icon);
547 addstring(&str, " <td><a href=\"%l\"><code>%h</code></a></td>\n", items[i], itm);
548 addstring(&str, " <td><code>%h</code></td>\n", showmime);
549 addstring(&str, " <td><code>%s</code></td>\n", size);
550 addstring(&str, "</tr>\n");
551 free(itm);
552 }
553 }
554 addstring(&str, " </table>\n");
555 addstring(&str, " <hr>\n");
556 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
557 addstring(&str, " </body>\n");
558 addstring(&str, "</html>\n");
559 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str));
560 free(str);
561 }
562 }
563 } else {
564 char* ext = NULL;
565 for(i = strlen(req.path) - 1; i >= 0; i--) {
566 if(req.path[i] == '.') {
567 ext = cm_strdup(req.path + i);
568 break;
569 } else if(req.path[i] == '/') {
570 break;
571 }
572 }
573 char* mime = tw_get_mime(ext, vhost_entry);
574 if(ext != NULL) free(ext);
575 FILE* f = fopen(path, "rb");
576 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size);
577 fclose(f);
578 }
579 } else {
580 tw_http_error(s, sock, 404, name, port);
581 }
582 free(path);
583 }
584 free(vhost);
585 free(host);
586 } else if(ret == -1) {
587 } else {
588 tw_http_error(s, sock, 400, name, port);
589 }
590cleanup:
591 if(sslworks) {
592 SSL_shutdown(s);
593 }
594 SSL_free(s);
595 close_socket(sock);
596#ifdef __MINGW32__
597 _endthreadex(0);
598#endif
599}
600
601void tw_server_loop(void) {
602 struct timeval tv;
603 while(1) {
604 FD_ZERO(&fdset);
605 int i;
606 for(i = 0; i < sockcount; i++) {
607 FD_SET(sockets[i], &fdset);
608 }
609 tv.tv_sec = 1;
610 tv.tv_usec = 0;
611 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
612 if(ret == -1) {
613 break;
614 } else if(ret > 0) {
615 /* connection */
616 int i;
617 for(i = 0; i < sockcount; i++) {
618 if(FD_ISSET(sockets[i], &fdset)) {
619 SOCKADDR claddr;
620 int clen = sizeof(claddr);
621 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
622 cm_log("Server", "New connection accepted");
623#ifdef __MINGW32__
624 HANDLE thread;
625 struct pass_entry* e = malloc(sizeof(*e));
626 e->sock = sock;
627 e->ssl = config.ports[i] & (1ULL << 32);
628 e->port = config.ports[i];
629 e->addr = claddr;
630 thread = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
631#else
632 pid_t pid = fork();
633 if(pid == 0) {
634 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
635 _exit(0);
636 } else {
637 close_socket(sock);
638 }
639#endif
640 }
641 }
642 }
643 }
644}
Note: See TracBrowser for help on using the repository browser.