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

Last change on this file since 23 was 23, checked in by Nishi, on Sep 14, 2024 at 10:31:16 PM

icon works

  • Property svn:keywords set to Id
File size: 14.2 KB
Line 
1/* $Id: server.c 23 2024-09-14 13:31:16Z 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) {
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 tw_write(ssl, sock, "Content-Type: ", 7 + 5 + 2);
179 tw_write(ssl, sock, (char*)type, strlen(type));
180 tw_write(ssl, sock, "\r\n", 2);
181 tw_write(ssl, sock, "Server: ", 6 + 2);
182 tw_write(ssl, sock, tw_server, strlen(tw_server));
183 tw_write(ssl, sock, "\r\n", 2);
184 tw_write(ssl, sock, "Content-Length: ", 7 + 7 + 2);
185 tw_write(ssl, sock, construct, strlen(construct));
186 tw_write(ssl, sock, "\r\n", 2);
187 tw_write(ssl, sock, "\r\n", 2);
188 size_t incr = 0;
189 while(1) {
190 if(f != NULL) {
191 char buffer[128];
192 fread(buffer, size < 128 ? size : 128, 1, f);
193 tw_write(ssl, sock, buffer, size < 128 ? size : 128);
194 } else {
195 tw_write(ssl, sock, (unsigned char*)doc + incr, size < 128 ? size : 128);
196 }
197 incr += 128;
198 if(size <= 128) break;
199 size -= 128;
200 }
201}
202
203const char* tw_http_status(int code) {
204 if(code == 200) {
205 return "200 OK";
206 } else if(code == 400) {
207 return "400 Bad Request";
208 } else if(code == 401) {
209 return "401 Unauthorized";
210 } else if(code == 403) {
211 return "403 Forbidden";
212 } else if(code == 404) {
213 return "404 Not Found";
214 } else {
215 return "400 Bad Request";
216 }
217}
218
219char* tw_http_default_error(int code, char* name, int port) {
220 char address[1024];
221 sprintf(address, "<address>%s Server at %s Port %d</address>", tw_server, name, port);
222
223 char* st = cm_strdup(tw_http_status(code));
224 char* st2;
225 int i;
226 for(i = 0; st[i] != 0; i++) {
227 if(st[i] == ' ') {
228 st2 = cm_strdup(st + i + 1);
229 break;
230 }
231 }
232 char* buffer = malloc(4096);
233 char* str = cm_strcat3(ERROR_HTML);
234 sprintf(buffer, str, st, st2);
235 free(str);
236 free(st);
237 return buffer;
238}
239
240void tw_http_error(SSL* ssl, int sock, int error, char* name, int port) {
241 char* str = tw_http_default_error(error, name, port);
242 tw_process_page(ssl, sock, tw_http_status(error), "text/html", NULL, str, strlen(str));
243 free(str);
244}
245
246void addstring(char** str, const char* add, ...) {
247 int i;
248 char cbuf[2];
249 cbuf[1] = 0;
250 va_list va;
251 va_start(va, add);
252 for(i = 0; add[i] != 0; i++) {
253 cbuf[0] = add[i];
254 if(add[i] == '%') {
255 i++;
256 if(add[i] == 's') {
257 char* tmp = *str;
258 *str = cm_strcat(tmp, va_arg(va, const char*));
259 free(tmp);
260 } else if(add[i] == 'h') {
261 char* h = cm_html_escape(va_arg(va, const char*));
262 char* tmp = *str;
263 *str = cm_strcat(tmp, h);
264 free(tmp);
265 free(h);
266 } else if(add[i] == 'l') {
267 char* h = cm_url_escape(va_arg(va, const char*));
268 char* tmp = *str;
269 *str = cm_strcat(tmp, h);
270 free(tmp);
271 free(h);
272 } else if(add[i] == 'd') {
273 int n = va_arg(va, int);
274 char* h = malloc(512);
275 sprintf(h, "%d", n);
276 char* tmp = *str;
277 *str = cm_strcat(tmp, h);
278 free(tmp);
279 free(h);
280 } else if(add[i] == '%') {
281 char* tmp = *str;
282 *str = cm_strcat(tmp, "%");
283 free(tmp);
284 }
285 } else {
286 char* tmp = *str;
287 *str = cm_strcat(tmp, cbuf);
288 free(tmp);
289 }
290 }
291}
292
293char* tw_get_mime(const char* ext, struct tw_config_entry* vhost_entry) {
294 char* mime = "application/octet-stream";
295 if(ext == NULL) return mime;
296 bool set = false;
297 int i;
298 for(i = 0; i < vhost_entry->mime_count; i++) {
299 if(strcmp(vhost_entry->mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(vhost_entry->mimes[i].ext, ext))) {
300 mime = vhost_entry->mimes[i].mime;
301 set = true;
302 }
303 }
304 if(!set) {
305 for(i = 0; i < config.root.mime_count; i++) {
306 if(strcmp(config.root.mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(config.root.mimes[i].ext, ext))) {
307 mime = config.root.mimes[i].mime;
308 }
309 }
310 }
311 return mime;
312}
313
314char* tw_get_icon(const char* mime, struct tw_config_entry* vhost_entry) {
315 char* icon = "";
316 if(mime == NULL) return "";
317 bool set = false;
318 int i;
319 for(i = 0; i < vhost_entry->icon_count; i++) {
320 if(strcmp(vhost_entry->icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(vhost_entry->icons[i].mime, mime))) {
321 icon = vhost_entry->icons[i].icon;
322 set = true;
323 }
324 }
325 if(!set) {
326 for(i = 0; i < config.root.icon_count; i++) {
327 if(strcmp(config.root.icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(config.root.icons[i].mime, mime))) {
328 icon = config.root.icons[i].icon;
329 }
330 }
331 }
332 return icon;
333}
334
335#ifdef __MINGW32__
336struct pass_entry {
337 int sock;
338 int port;
339 bool ssl;
340 SOCKADDR addr;
341};
342
343unsigned int WINAPI tw_server_pass(void* ptr) {
344 int sock = ((struct pass_entry*)ptr)->sock;
345 bool ssl = ((struct pass_entry*)ptr)->ssl;
346 int port = ((struct pass_entry*)ptr)->port;
347 SOCKADDR addr = ((struct pass_entry*)ptr)->addr;
348 free(ptr);
349#else
350void tw_server_pass(int sock, bool ssl, int port, SOCKADDR addr) {
351#endif
352 char* name = config.hostname;
353
354 SSL_CTX* ctx = NULL;
355 SSL* s = NULL;
356 bool sslworks = false;
357 if(ssl) {
358 ctx = tw_create_ssl_ctx(port);
359 s = SSL_new(ctx);
360 SSL_set_fd(s, sock);
361 if(SSL_accept(s) <= 0) goto cleanup;
362 sslworks = true;
363 }
364 struct tw_http_request req;
365 struct tw_http_response res;
366 struct tw_tool tools;
367 res._processed = false;
368 tw_init_tools(&tools);
369 int ret = tw_http_parse(s, sock, &req);
370 if(ret == 0) {
371 char* vhost = cm_strdup(config.hostname);
372 int i;
373 for(i = 0; req.headers[i] != NULL; i += 2) {
374 if(cm_strcaseequ(req.headers[i], "Host")) {
375 free(vhost);
376 vhost = req.headers[i + 1];
377 break;
378 }
379 }
380 cm_log("Server", "Host is %s", vhost);
381 int port = s == NULL ? 80 : 443;
382 char* host = cm_strdup(vhost);
383 for(i = 0; vhost[i] != 0; i++) {
384 if(vhost[i] == ':') {
385 host[i] = 0;
386 port = atoi(host + i + 1);
387 break;
388 }
389 }
390 cm_log("Server", "Hostname is `%s', port is `%d'", host, port);
391 struct tw_config_entry* vhost_entry = tw_vhost_match(host, port);
392 for(i = 0; i < config.module_count; i++) {
393 tw_mod_request_t mod_req = (tw_mod_request_t)tw_module_symbol(config.modules[i], "mod_request");
394 if(mod_req != NULL) {
395 int ret = mod_req(&tools, &req, &res);
396 int co = ret & 0xff;
397 if(co == _TW_MODULE_PASS) continue;
398 if(co == _TW_MODULE_STOP) {
399 res._processed = true;
400 break;
401 }
402 if(co == _TW_MODULE_ERROR) {
403 tw_http_error(s, sock, (ret & 0xffff00) >> 8, name, port);
404 break;
405 }
406 }
407 }
408 if(!res._processed) {
409 cm_log("Server", "Document root is %s", vhost_entry->root == NULL ? "not set" : vhost_entry->root);
410 char* path = cm_strcat(vhost_entry->root == NULL ? "" : vhost_entry->root, req.path);
411 cm_log("Server", "Filesystem path is %s", path);
412 struct stat st;
413 if(stat(path, &st) == 0) {
414 if(!tw_permission_allowed(path, addr, req, vhost_entry)) {
415 tw_http_error(s, sock, 403, name, port);
416 } else if(S_ISDIR(st.st_mode)) {
417 char* str = malloc(1);
418 str[0] = 0;
419 char** items = cm_scandir(path);
420 addstring(&str, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
421 addstring(&str, "<html>\n");
422 addstring(&str, " <head>\n");
423 addstring(&str, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
424 addstring(&str, " <title>Index of %h</title>\n", req.path);
425 addstring(&str, " </head>\n");
426 addstring(&str, " <body>\n");
427 addstring(&str, " <h1>Index of %h</h1>\n", req.path);
428 addstring(&str, " <hr>\n");
429 addstring(&str, " <table border=\"0\">\n");
430 addstring(&str, " <tr>\n");
431 addstring(&str, " <th></th>\n");
432 addstring(&str, " <th>Filename</th>\n");
433 addstring(&str, " </tr>\n");
434 if(items != NULL) {
435 for(i = 0; items[i] != NULL; i++) {
436 char* ext = NULL;
437 int j;
438 for(j = strlen(items[i]) - 1; j >= 0; j--) {
439 if(items[i][j] == '.') {
440 ext = cm_strdup(items[i] + j);
441 break;
442 }
443 }
444 char* mime = tw_get_mime(ext, vhost_entry);
445 if(strcmp(items[i], "../") == 0) {
446 mime = "misc/parent";
447 } else if(items[i][strlen(items[i]) - 1] == '/') {
448 mime = "misc/dir";
449 }
450 char* icon = tw_get_icon(mime, vhost_entry);
451 if(ext != NULL) free(ext);
452 char* itm = cm_strdup(items[i]);
453 if(strlen(itm) >= 32) {
454 if(itm[strlen(itm) - 1] == '/') {
455 itm[31] = 0;
456 itm[30] = '/';
457 itm[29] = '.';
458 itm[28] = '.';
459 itm[27] = '.';
460 } else {
461 itm[31] = 0;
462 itm[30] = '.';
463 itm[29] = '.';
464 itm[28] = '.';
465 }
466 }
467 addstring(&str, "<tr>\n");
468 addstring(&str, " <td><img src=\"%s\" alt=\"icon\"></td>\n", icon);
469 addstring(&str, " <td><a href=\"%l\"><code>%h</code></a></td>\n", items[i], itm);
470 addstring(&str, "</tr>\n");
471 free(itm);
472 }
473 }
474 addstring(&str, " </table>\n");
475 addstring(&str, " <hr>\n");
476 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
477 addstring(&str, " </body>\n");
478 addstring(&str, "</html>\n");
479 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str));
480 free(str);
481 } else {
482 char* ext = NULL;
483 for(i = strlen(req.path) - 1; i >= 0; i--) {
484 if(req.path[i] == '.') {
485 ext = cm_strdup(req.path + i);
486 break;
487 }
488 }
489 char* mime = tw_get_mime(ext, vhost_entry);
490 if(ext != NULL) free(ext);
491 FILE* f = fopen(path, "rb");
492 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size);
493 fclose(f);
494 }
495 } else {
496 tw_http_error(s, sock, 404, name, port);
497 }
498 free(path);
499 }
500 free(vhost);
501 free(host);
502 } else if(ret == -1) {
503 } else {
504 tw_http_error(s, sock, 400, name, port);
505 }
506cleanup:
507 if(sslworks) {
508 SSL_shutdown(s);
509 }
510 SSL_free(s);
511 close_socket(sock);
512#ifdef __MINGW32__
513 _endthreadex(0);
514#endif
515}
516
517void tw_server_loop(void) {
518 struct timeval tv;
519 while(1) {
520 FD_ZERO(&fdset);
521 int i;
522 for(i = 0; i < sockcount; i++) {
523 FD_SET(sockets[i], &fdset);
524 }
525 tv.tv_sec = 1;
526 tv.tv_usec = 0;
527 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
528 if(ret == -1) {
529 break;
530 } else if(ret > 0) {
531 /* connection */
532 int i;
533 for(i = 0; i < sockcount; i++) {
534 if(FD_ISSET(sockets[i], &fdset)) {
535 SOCKADDR claddr;
536 int clen = sizeof(claddr);
537 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
538 cm_log("Server", "New connection accepted");
539#ifdef __MINGW32__
540 HANDLE thread;
541 struct pass_entry* e = malloc(sizeof(*e));
542 e->sock = sock;
543 e->ssl = config.ports[i] & (1ULL << 32);
544 e->port = config.ports[i];
545 e->addr = claddr;
546 thread = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
547#else
548 pid_t pid = fork();
549 if(pid == 0) {
550 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
551 _exit(0);
552 } else {
553 close_socket(sock);
554 }
555#endif
556 }
557 }
558 }
559 }
560}
Note: See TracBrowser for help on using the repository browser.