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

Last change on this file since 163 was 163, checked in by Nishi, on Sep 26, 2024 at 9:33:22 AM

add an option to disable getaddrinfo

  • Property svn:keywords set to Id
File size: 25.8 KB
Line 
1/* $Id: server.c 163 2024-09-26 00:33:22Z nishi $ */
2
3#define SOURCE
4
5#include "../config.h"
6
7#include "tw_server.h"
8
9#ifndef NO_SSL
10#include "tw_ssl.h"
11#endif
12
13#include "tw_config.h"
14#include "tw_http.h"
15#include "tw_module.h"
16#include "tw_version.h"
17
18#include <unistd.h>
19#include <string.h>
20#include <stdbool.h>
21#include <stdarg.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <errno.h>
25#include <sys/stat.h>
26#include <time.h>
27
28#include <cm_string.h>
29#include <cm_log.h>
30#include <cm_dir.h>
31
32#ifdef __MINGW32__
33#ifndef NO_GETADDRINFO
34#include <ws2tcpip.h>
35#include <wspiapi.h>
36#endif
37#include <winsock2.h>
38#include <process.h>
39#include <windows.h>
40
41#include "strptime.h"
42#else
43#ifdef USE_POLL
44#include <poll.h>
45#else
46#include <sys/select.h>
47#endif
48#include <sys/socket.h>
49#include <arpa/inet.h>
50#include <netinet/in.h>
51#include <netinet/tcp.h>
52#ifndef NO_GETADDRINFO
53#include <netdb.h>
54#endif
55#endif
56
57#ifdef __HAIKU__
58#include <OS.h>
59#endif
60
61extern struct tw_config config;
62extern char tw_server[];
63
64int sockcount = 0;
65
66SOCKADDR addresses[MAX_PORTS];
67int sockets[MAX_PORTS];
68
69#ifdef __MINGW32__
70const char* reserved_names[] = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};
71#endif
72
73/* https://qiita.com/gyu-don/items/5a640c6d2252a860c8cd */
74int tw_wildcard_match(const char* wildcard, const char* target) {
75 const char *pw = wildcard, *pt = target;
76
77 while(1) {
78 if(*pt == 0) {
79 while(*pw == '*') pw++;
80 return *pw == 0;
81 } else if(*pw == 0) {
82 return 0;
83 } else if(*pw == '*') {
84 return *(pw + 1) == 0 || tw_wildcard_match(pw, pt + 1) || tw_wildcard_match(pw + 1, pt);
85 } else if(*pw == '?' || (*pw == *pt)) {
86 pw++;
87 pt++;
88 continue;
89 } else {
90 return 0;
91 }
92 }
93}
94
95void close_socket(int sock) {
96#if defined(__MINGW32__)
97 closesocket(sock);
98#else
99 close(sock);
100#endif
101}
102
103int tw_server_init(void) {
104 int i;
105#ifdef __MINGW32__
106 WSADATA wsa;
107 WSAStartup(MAKEWORD(2, 0), &wsa);
108#endif
109 for(i = 0; config.ports[i] != -1; i++)
110 ;
111 sockcount = i;
112 for(i = 0; config.ports[i] != -1; i++) {
113#ifdef NO_IPV6
114 int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
115#else
116 int sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
117#endif
118#ifdef __MINGW32__
119 if(sock == INVALID_SOCKET)
120#else
121 if(sock < 0)
122#endif
123 {
124 cm_log("Server", "Socket creation failure");
125 return 1;
126 }
127 int yes = 1;
128 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(yes)) < 0) {
129 close_socket(sock);
130 cm_log("Server", "setsockopt failure (reuseaddr)");
131 return 1;
132 }
133 if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(yes)) < 0) {
134 close_socket(sock);
135 cm_log("Server", "setsockopt failure (nodelay)");
136 return 1;
137 }
138#ifndef NO_IPV6
139 int no = 0;
140 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&no, sizeof(no)) < 0) {
141 close_socket(sock);
142 cm_log("Server", "setsockopt failure (IPv6)");
143 return 1;
144 }
145#endif
146 memset(&addresses[i], 0, sizeof(addresses[i]));
147#ifdef NO_IPV6
148 addresses[i].sin_family = AF_INET;
149 addresses[i].sin_addr.s_addr = INADDR_ANY;
150 addresses[i].sin_port = htons(config.ports[i]);
151#else
152 addresses[i].sin6_family = AF_INET6;
153 addresses[i].sin6_addr = in6addr_any;
154 addresses[i].sin6_port = htons(config.ports[i]);
155#endif
156 if(bind(sock, (struct sockaddr*)&addresses[i], sizeof(addresses[i])) < 0) {
157 close_socket(sock);
158 cm_log("Server", "Bind failure");
159 return 1;
160 }
161 if(listen(sock, 128) < 0) {
162 close_socket(sock);
163 cm_log("Server", "Listen failure");
164 return 1;
165 }
166 sockets[i] = sock;
167 }
168 return 0;
169}
170
171size_t tw_read(SSL* ssl, int s, void* data, size_t len) {
172#ifndef NO_SSL
173 if(ssl == NULL) {
174 return recv(s, data, len, 0);
175 } else {
176 return SSL_read(ssl, data, len);
177 }
178#else
179 return recv(s, data, len, 0);
180#endif
181}
182
183size_t tw_write(SSL* ssl, int s, void* data, size_t len) {
184#ifndef NO_SSL
185 if(ssl == NULL) {
186 return send(s, data, len, 0);
187 } else {
188 return SSL_write(ssl, data, len);
189 }
190#else
191 return send(s, data, len, 0);
192#endif
193}
194
195#define ERROR_HTML \
196 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" \
197 "<html>\n" \
198 " <head>\n" \
199 " <title>%s</title>\n" \
200 " </head>\n" \
201 " <body>\n" \
202 " <h1>%s</h1>\n" \
203 " <hr>\n" \
204 " ", \
205 address, \
206 "\n" \
207 " </body>\n" \
208 "</html>\n"
209
210void _tw_process_page(SSL* ssl, int sock, const char* status, const char* type, FILE* f, const unsigned char* doc, size_t size, char** headers, time_t mtime, time_t cmtime) {
211 char construct[512];
212 if(mtime != 0 && cmtime != 0 && mtime <= cmtime) {
213 status = "304 Not Modified";
214 type = NULL;
215 size = 0;
216 headers = NULL;
217 f = NULL;
218 doc = NULL;
219 }
220 sprintf(construct, "%llu", (unsigned long long)size);
221 tw_write(ssl, sock, "HTTP/1.1 ", 9);
222 tw_write(ssl, sock, (char*)status, strlen(status));
223 tw_write(ssl, sock, "\r\n", 2);
224 if(type != NULL) {
225 tw_write(ssl, sock, "Content-Type: ", 7 + 5 + 2);
226 tw_write(ssl, sock, (char*)type, strlen(type));
227 tw_write(ssl, sock, "\r\n", 2);
228 }
229 tw_write(ssl, sock, "Server: ", 6 + 2);
230 tw_write(ssl, sock, tw_server, strlen(tw_server));
231 tw_write(ssl, sock, "\r\n", 2);
232 if(size != 0) {
233 tw_write(ssl, sock, "Content-Length: ", 7 + 7 + 2);
234 tw_write(ssl, sock, construct, strlen(construct));
235 tw_write(ssl, sock, "\r\n", 2);
236 if(mtime != 0) {
237 struct tm* tm = gmtime(&mtime);
238 char date[513];
239 strftime(date, 512, "%a, %d %b %Y %H:%M:%S GMT", tm);
240 tw_write(ssl, sock, "Last-Modified: ", 5 + 8 + 2);
241 tw_write(ssl, sock, date, strlen(date));
242 tw_write(ssl, sock, "\r\n", 2);
243 }
244 }
245 int i;
246 if(headers != NULL) {
247 for(i = 0; headers[i] != NULL; i += 2) {
248 tw_write(ssl, sock, headers[i], strlen(headers[i]));
249 tw_write(ssl, sock, ": ", 2);
250 tw_write(ssl, sock, headers[i + 1], strlen(headers[i + 1]));
251 tw_write(ssl, sock, "\r\n", 2);
252 }
253 }
254 tw_write(ssl, sock, "\r\n", 2);
255 if(doc == NULL && f == NULL) return;
256 size_t incr = 0;
257 while(1) {
258 if(f != NULL) {
259 char buffer[128];
260 fread(buffer, size < 128 ? size : 128, 1, f);
261 tw_write(ssl, sock, buffer, size < 128 ? size : 128);
262 } else {
263 tw_write(ssl, sock, (unsigned char*)doc + incr, size < 128 ? size : 128);
264 }
265 incr += 128;
266 if(size <= 128) break;
267 size -= 128;
268 }
269}
270
271void tw_process_page(SSL* ssl, int sock, const char* status, const char* type, FILE* f, const unsigned char* doc, size_t size, time_t mtime, time_t cmtime) { _tw_process_page(ssl, sock, status, type, f, doc, size, NULL, mtime, cmtime); }
272
273const char* tw_http_status(int code) {
274 if(code == 200) {
275 return "200 OK";
276 } else if(code == 308) {
277 return "308 Permanent Redirect";
278 } else if(code == 400) {
279 return "400 Bad Request";
280 } else if(code == 401) {
281 return "401 Unauthorized";
282 } else if(code == 403) {
283 return "403 Forbidden";
284 } else if(code == 404) {
285 return "404 Not Found";
286 } else if(code == 500) {
287 return "500 Internal Server Error";
288 } else {
289 return "400 Bad Request";
290 }
291}
292
293char* tw_http_default_error(int code, char* name, int port, struct tw_config_entry* vhost) {
294 char address[1024];
295
296 if((vhost->hideport == -1 ? config.root.hideport : vhost->hideport) == 1) {
297 sprintf(address, "<address>%s Server at %s</address>", tw_server, name, port);
298 } else {
299 sprintf(address, "<address>%s Server at %s Port %d</address>", tw_server, name, port);
300 }
301
302 char* st = cm_strdup(tw_http_status(code));
303 char* st2;
304 int i;
305 for(i = 0; st[i] != 0; i++) {
306 if(st[i] == ' ') {
307 st2 = cm_strdup(st + i + 1);
308 break;
309 }
310 }
311 char* buffer = malloc(4096);
312 char* str = cm_strcat3(ERROR_HTML);
313 sprintf(buffer, str, st, st2);
314 free(str);
315 free(st);
316 return buffer;
317}
318
319void tw_http_error(SSL* ssl, int sock, int error, char* name, int port, struct tw_config_entry* vhost) {
320 char* str = tw_http_default_error(error, name, port, vhost);
321 tw_process_page(ssl, sock, tw_http_status(error), "text/html", NULL, str, strlen(str), 0, 0);
322 free(str);
323}
324
325void addstring(char** str, const char* add, ...) {
326 int i;
327 char cbuf[2];
328 cbuf[1] = 0;
329 va_list va;
330 va_start(va, add);
331 for(i = 0; add[i] != 0; i++) {
332 cbuf[0] = add[i];
333 if(add[i] == '%') {
334 i++;
335 if(add[i] == 's') {
336 char* tmp = *str;
337 *str = cm_strcat(tmp, va_arg(va, const char*));
338 free(tmp);
339 } else if(add[i] == 'h') {
340 char* h = cm_html_escape(va_arg(va, const char*));
341 char* tmp = *str;
342 *str = cm_strcat(tmp, h);
343 free(tmp);
344 free(h);
345 } else if(add[i] == 'l') {
346 char* h = cm_url_escape(va_arg(va, const char*));
347 char* tmp = *str;
348 *str = cm_strcat(tmp, h);
349 free(tmp);
350 free(h);
351 } else if(add[i] == 'd') {
352 int n = va_arg(va, int);
353 char* h = malloc(512);
354 sprintf(h, "%d", n);
355 char* tmp = *str;
356 *str = cm_strcat(tmp, h);
357 free(tmp);
358 free(h);
359 } else if(add[i] == '%') {
360 char* tmp = *str;
361 *str = cm_strcat(tmp, "%");
362 free(tmp);
363 }
364 } else {
365 char* tmp = *str;
366 *str = cm_strcat(tmp, cbuf);
367 free(tmp);
368 }
369 }
370 va_end(va);
371}
372
373char* tw_get_mime(const char* ext, struct tw_config_entry* vhost_entry) {
374 char* mime = "application/octet-stream";
375 if(ext == NULL) return mime;
376 bool set = false;
377 int i;
378 for(i = 0; i < vhost_entry->mime_count; i++) {
379 if(strcmp(vhost_entry->mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(vhost_entry->mimes[i].ext, ext))) {
380 mime = vhost_entry->mimes[i].mime;
381 set = true;
382 }
383 }
384 if(!set) {
385 for(i = 0; i < config.root.mime_count; i++) {
386 if(strcmp(config.root.mimes[i].ext, "all") == 0 || (ext != NULL && tw_wildcard_match(config.root.mimes[i].ext, ext))) {
387 mime = config.root.mimes[i].mime;
388 }
389 }
390 }
391 return mime;
392}
393
394char* tw_get_icon(const char* mime, struct tw_config_entry* vhost_entry) {
395 char* icon = "";
396 if(mime == NULL) return "";
397 bool set = false;
398 int i;
399 for(i = 0; i < vhost_entry->icon_count; i++) {
400 if(strcmp(vhost_entry->icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(vhost_entry->icons[i].mime, mime))) {
401 icon = vhost_entry->icons[i].icon;
402 set = true;
403 }
404 }
405 if(!set) {
406 for(i = 0; i < config.root.icon_count; i++) {
407 if(strcmp(config.root.icons[i].mime, "all") == 0 || (mime != NULL && tw_wildcard_match(config.root.icons[i].mime, mime))) {
408 icon = config.root.icons[i].icon;
409 }
410 }
411 }
412 return icon;
413}
414
415struct pass_entry {
416 int sock;
417 int port;
418 bool ssl;
419 SOCKADDR addr;
420};
421
422#ifdef __MINGW32__
423unsigned int WINAPI tw_server_pass(void* ptr) {
424#elif defined(__HAIKU__)
425int32_t tw_server_pass(void* ptr) {
426#endif
427#if defined(__HAIKU__) || defined(__MINGW32__)
428 int sock = ((struct pass_entry*)ptr)->sock;
429 bool ssl = ((struct pass_entry*)ptr)->ssl;
430 int port = ((struct pass_entry*)ptr)->port;
431 SOCKADDR addr = ((struct pass_entry*)ptr)->addr;
432 free(ptr);
433#else
434 void tw_server_pass(int sock, bool ssl, int port, SOCKADDR addr) {
435#endif
436 char* name = config.hostname;
437
438#ifndef NO_SSL
439 SSL_CTX* ctx = NULL;
440 SSL* s = NULL;
441 bool sslworks = false;
442 if(ssl) {
443 ctx = tw_create_ssl_ctx(port);
444 s = SSL_new(ctx);
445 SSL_set_fd(s, sock);
446 if(SSL_accept(s) <= 0) goto cleanup;
447 sslworks = true;
448 }
449#else
450 void* s = NULL;
451#endif
452
453 char address[513];
454 address[0] = 0;
455#ifndef NO_GETADDRINFO
456 struct sockaddr* sa = (struct sockaddr*)&addr;
457 getnameinfo(sa, sizeof(addr), address, 512, NULL, 0, NI_NUMERICHOST);
458#endif
459
460 struct tw_http_request req;
461 struct tw_http_response res;
462 struct tw_tool tools;
463 res._processed = false;
464 tw_init_tools(&tools);
465 int ret = tw_http_parse(s, sock, &req);
466 if(ret == 0) {
467 char date[513];
468 time_t t = time(NULL);
469 struct tm* tm = localtime(&t);
470 strftime(date, 512, "%a, %d %b %Y %H:%M:%S %Z", tm);
471
472 char* useragent = cm_strdup("");
473
474 int i;
475 for(i = 0; req.headers[i] != NULL; i += 2) {
476 if(cm_strcaseequ(req.headers[i], "User-Agent")) {
477 free(useragent);
478 useragent = cm_strdup(req.headers[i + 1]);
479 }
480 }
481
482 char* tmp = cm_strcat3(address, " - [", date);
483 char* tmp2 = cm_strcat3(tmp, "] \"", req.method);
484 char* tmp3 = cm_strcat3(tmp2, " ", req.path);
485 char* tmp4 = cm_strcat3(tmp3, " ", req.version);
486 char* tmp5 = cm_strcat3(tmp4, "\" \"", useragent);
487 char* log = cm_strcat(tmp5, "\"");
488 free(tmp);
489 free(tmp2);
490 free(tmp3);
491 free(tmp4);
492 free(tmp5);
493 free(useragent);
494 cm_force_log(log);
495 free(log);
496
497 char* vhost = cm_strdup(config.hostname);
498 time_t cmtime = 0;
499 if(req.headers != NULL) {
500 for(i = 0; req.headers[i] != NULL; i += 2) {
501 if(cm_strcaseequ(req.headers[i], "Host")) {
502 free(vhost);
503 vhost = cm_strdup(req.headers[i + 1]);
504 } else if(cm_strcaseequ(req.headers[i], "If-Modified-Since")) {
505 struct tm tm;
506 strptime(req.headers[i + 1], "%a, %d %b %Y %H:%M:%S GMT", &tm);
507#ifdef __MINGW32__
508 time_t t = 0;
509 struct tm* btm = localtime(&t);
510 cmtime = mktime(&tm);
511 cmtime -= (btm->tm_hour * 60 + btm->tm_min) * 60;
512#else
513 cmtime = timegm(&tm);
514#endif
515 }
516 }
517 }
518 bool rej = false;
519 cm_log("Server", "Host is %s", vhost);
520 int port = s == NULL ? 80 : 443;
521 char* host = cm_strdup(vhost);
522 for(i = 0; vhost[i] != 0; i++) {
523 if(vhost[i] == ':') {
524 host[i] = 0;
525 port = atoi(host + i + 1);
526 break;
527 }
528 }
529 name = host;
530 cm_log("Server", "Hostname is `%s', port is `%d'", host, port);
531 struct tw_config_entry* vhost_entry = tw_vhost_match(host, port);
532#ifdef HAS_CHROOT
533 char* chrootpath = vhost_entry->chroot_path != NULL ? vhost_entry->chroot_path : config.root.chroot_path;
534 if(chrootpath != NULL) {
535 if(chdir(chrootpath) == 0) {
536 if(chroot(".") == 0) {
537 cm_log("Server", "Chroot successful");
538 }
539 } else {
540 cm_log("Server", "chdir() failed, cannot chroot");
541 tw_http_error(s, sock, 500, name, port, vhost_entry);
542 rej = true;
543 }
544 }
545#endif
546 for(i = 0; i < config.module_count; i++) {
547 tw_mod_request_t mod_req = (tw_mod_request_t)tw_module_symbol(config.modules[i], "mod_request");
548 if(mod_req != NULL) {
549 int ret = mod_req(&tools, &req, &res);
550 int co = ret & 0xff;
551 if(co == _TW_MODULE_PASS) {
552 continue;
553 } else if(co == _TW_MODULE_STOP) {
554 /* Handle response here ... */
555 res._processed = true;
556 break;
557 } else if(co == _TW_MODULE_STOP2) {
558 res._processed = true;
559 break;
560 } else if(co == _TW_MODULE_ERROR) {
561 tw_http_error(s, sock, (ret & 0xffff00) >> 8, name, port, vhost_entry);
562 break;
563 }
564 }
565 }
566 if(!res._processed) {
567 cm_log("Server", "Document root is %s", vhost_entry->root == NULL ? "not set" : vhost_entry->root);
568 char* path = cm_strcat(vhost_entry->root == NULL ? "" : vhost_entry->root, req.path);
569 cm_log("Server", "Filesystem path is %s", path);
570#ifdef __MINGW32__
571 char* rpath = cm_strdup(path);
572 for(i = strlen(rpath) - 1; i >= 0; i--) {
573 if(rpath[i] == '/') {
574 int j;
575 for(j = i + 1; rpath[j] != 0; j++) {
576 if(rpath[j] == ':' || rpath[j] == '.') {
577 rpath[j] = 0;
578 break;
579 }
580 }
581 break;
582 }
583 }
584 for(i = 0; i < sizeof(reserved_names) / sizeof(reserved_names[0]); i++) {
585 char* n = cm_strcat("/", reserved_names[i]);
586 if(cm_nocase_endswith(rpath, n)) {
587 tw_http_error(s, sock, 403, name, port, vhost_entry);
588 free(n);
589 rej = true;
590 cm_log("Server", "XP Patch ; rejecting access to device");
591 break;
592 }
593 free(n);
594 }
595 free(rpath);
596#endif
597 struct stat st;
598 if(!rej && stat(path, &st) == 0) {
599 if(!tw_permission_allowed(path, addr, req, vhost_entry)) {
600 tw_http_error(s, sock, 403, name, port, vhost_entry);
601 } else if(S_ISDIR(st.st_mode)) {
602 if(req.path[strlen(req.path) - 1] != '/') {
603 cm_log("Server", "Accessing directory without the slash at the end");
604 char* headers[3] = {"Location", cm_strcat(req.path, "/"), NULL};
605 _tw_process_page(s, sock, tw_http_status(308), NULL, NULL, NULL, 0, headers, 0, 0);
606 free(headers[1]);
607 } else {
608 char** indexes = vhost_entry->index_count == 0 ? config.root.indexes : vhost_entry->indexes;
609 int index_count = vhost_entry->index_count == 0 ? config.root.index_count : vhost_entry->index_count;
610 bool found = false;
611 for(i = 0; i < index_count; i++) {
612 char* p = cm_strcat3(path, "/", indexes[i]);
613 FILE* f = fopen(p, "rb");
614 if(f != NULL) {
615 char* ext = NULL;
616 int j;
617 for(j = strlen(p) - 1; j >= 0; j--) {
618 if(p[j] == '.') {
619 ext = cm_strdup(p + j);
620 break;
621 } else if(p[j] == '/') {
622 break;
623 }
624 }
625 struct stat st;
626 stat(p, &st);
627 char* mime = tw_get_mime(ext, vhost_entry);
628 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size, 0, 0);
629 fclose(f);
630 if(ext != NULL) free(ext);
631 free(p);
632 found = true;
633 break;
634 }
635 free(p);
636 }
637 if(!found) {
638 char* str = malloc(1);
639 str[0] = 0;
640 char** items = cm_scandir(path);
641 addstring(&str, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n");
642 addstring(&str, "<html>\n");
643 addstring(&str, " <head>\n");
644 addstring(&str, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
645 addstring(&str, " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
646 addstring(&str, " <title>Index of %h</title>\n", req.path);
647 addstring(&str, " </head>\n");
648 addstring(&str, " <body>\n");
649 addstring(&str, " <h1>Index of %h</h1>\n", req.path);
650 addstring(&str, " <hr>\n");
651 addstring(&str, " <table border=\"0\">\n");
652 addstring(&str, " <tr>\n");
653 addstring(&str, " <th></th>\n");
654 addstring(&str, " <th>Filename</th>\n");
655 addstring(&str, " <th>MIME</th>\n");
656 addstring(&str, " <th>Size</th>\n");
657 addstring(&str, " </tr>\n");
658 int readme = -1;
659 char** readmes = vhost_entry->readme_count == 0 ? config.root.readmes : vhost_entry->readmes;
660 int readme_count = vhost_entry->readme_count == 0 ? config.root.readme_count : vhost_entry->readme_count;
661 if(items != NULL) {
662 int phase = 0;
663 doit:
664 for(i = 0; items[i] != NULL; i++) {
665 int j;
666 char* fpth = cm_strcat3(path, "/", items[i]);
667 struct stat s;
668 char size[512];
669 size[0] = 0;
670 stat(fpth, &s);
671 if(phase == 0 && !S_ISDIR(s.st_mode)) {
672 free(fpth);
673 continue;
674 } else if(phase == 1 && S_ISDIR(s.st_mode)) {
675 free(fpth);
676 continue;
677 }
678 if(readme == -1) {
679 for(j = 0; j < readme_count; j++) {
680 if(strcmp(items[i], readmes[j]) == 0) {
681 readme = j;
682 break;
683 }
684 }
685 if(readme != -1) {
686 free(fpth);
687 continue;
688 }
689 }
690 if(s.st_size < 1024ULL) {
691 sprintf(size, "%d", (int)s.st_size);
692 } else if(s.st_size < 1024ULL * 1024) {
693 sprintf(size, "%.1fK", (double)s.st_size / 1024);
694 } else if(s.st_size < 1024ULL * 1024 * 1024) {
695 sprintf(size, "%.1fM", (double)s.st_size / 1024 / 1024);
696 } else if(s.st_size < 1024ULL * 1024 * 1024 * 1024) {
697 sprintf(size, "%.1fG", (double)s.st_size / 1024 / 1024 / 1024);
698 } else if(s.st_size < 1024ULL * 1024 * 1024 * 1024 * 1024) {
699 sprintf(size, "%.1fT", (double)s.st_size / 1024 / 1024 / 1024 / 1024);
700 }
701
702 free(fpth);
703
704 char* ext = NULL;
705 for(j = strlen(items[i]) - 1; j >= 0; j--) {
706 if(items[i][j] == '.') {
707 ext = cm_strdup(items[i] + j);
708 break;
709 } else if(items[i][j] == '/') {
710 break;
711 }
712 }
713 char* showmime = "";
714 char* mime = tw_get_mime(ext, vhost_entry);
715 if(strcmp(items[i], "../") == 0) {
716 mime = "misc/parent";
717 size[0] = 0;
718 } else if(items[i][strlen(items[i]) - 1] == '/') {
719 mime = "misc/dir";
720 size[0] = 0;
721 } else {
722 showmime = mime;
723 }
724 char* icon = tw_get_icon(mime, vhost_entry);
725 if(ext != NULL) free(ext);
726 char* itm = cm_strdup(items[i]);
727 if(strlen(itm) >= 32) {
728 if(itm[strlen(itm) - 1] == '/') {
729 itm[31] = 0;
730 itm[30] = '/';
731 itm[29] = '.';
732 itm[28] = '.';
733 itm[27] = '.';
734 } else {
735 itm[31] = 0;
736 itm[30] = '.';
737 itm[29] = '.';
738 itm[28] = '.';
739 }
740 }
741 addstring(&str, "<tr>\n");
742 addstring(&str, " <td><img src=\"%s\" alt=\"icon\"></td>\n", icon);
743 addstring(&str, " <td><a href=\"%l\"><code>%h</code></a></td>\n", items[i], itm);
744 addstring(&str, " <td><code> %h </code></td>\n", showmime);
745 addstring(&str, " <td><code> %s </code></td>\n", size);
746 addstring(&str, "</tr>\n");
747 free(itm);
748 }
749 phase++;
750 if(phase != 2) goto doit;
751 for(i = 0; items[i] != NULL; i++) free(items[i]);
752 free(items);
753 }
754 addstring(&str, " </table>\n");
755 if(readme != -1) {
756 addstring(&str, "<hr>\n");
757 char* fpth = cm_strcat3(path, "/", readmes[readme]);
758 struct stat s;
759 stat(fpth, &s);
760 FILE* fr = fopen(fpth, "r");
761 if(fr != NULL) {
762 char* rmbuf = malloc(s.st_size + 1);
763 rmbuf[s.st_size] = 0;
764 fread(rmbuf, s.st_size, 1, fr);
765 addstring(&str, "<pre><code>%h</code></pre>\n", rmbuf);
766 fclose(fr);
767 free(rmbuf);
768 }
769 free(fpth);
770 }
771 addstring(&str, " <hr>\n");
772 int hp = vhost_entry->hideport == -1 ? config.root.hideport : vhost_entry->hideport;
773 if(hp == 0) {
774 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
775 } else {
776 addstring(&str, " <address>%s Server at %s</address>\n", tw_server, name, port);
777 }
778 addstring(&str, " </body>\n");
779 addstring(&str, "</html>\n");
780 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str), 0, 0);
781 free(str);
782 }
783 }
784 } else {
785 char* ext = NULL;
786 for(i = strlen(req.path) - 1; i >= 0; i--) {
787 if(req.path[i] == '.') {
788 ext = cm_strdup(req.path + i);
789 break;
790 } else if(req.path[i] == '/') {
791 break;
792 }
793 }
794 char* mime = tw_get_mime(ext, vhost_entry);
795 if(ext != NULL) free(ext);
796 FILE* f = fopen(path, "rb");
797 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size, st.st_mtime, cmtime);
798 fclose(f);
799 }
800 } else {
801 if(!rej) {
802 tw_http_error(s, sock, 404, name, port, vhost_entry);
803 }
804 }
805 free(path);
806 }
807 free(vhost);
808 free(host);
809 } else if(ret == -1) {
810 } else {
811 tw_http_error(s, sock, 400, name, port, &config.root);
812 }
813 tw_free_request(&req);
814cleanup:
815#ifndef NO_SSL
816 if(sslworks) {
817 SSL_shutdown(s);
818 }
819 SSL_free(s);
820#endif
821 close_socket(sock);
822#ifdef __MINGW32__
823 _endthreadex(0);
824#elif defined(__HAIKU__)
825 exit_thread(0);
826#endif
827 ;
828}
829
830#ifdef SERVICE
831extern SERVICE_STATUS status;
832extern SERVICE_STATUS_HANDLE status_handle;
833#endif
834
835#if defined(__MINGW32__) || defined(__HAIKU__)
836struct thread_entry {
837#ifdef __HAIKU__
838 thread_id thread;
839#else
840 HANDLE handle;
841#endif
842 bool used;
843};
844#endif
845
846void tw_server_loop(void) {
847 int i;
848#if defined(__MINGW32__) || defined(__HAIKU__)
849 struct thread_entry threads[2048];
850 for(i = 0; i < sizeof(threads) / sizeof(threads[0]); i++) {
851 threads[i].used = false;
852 }
853#endif
854#ifdef USE_POLL
855 struct pollfd pollfds[sockcount];
856 for(i = 0; i < sockcount; i++) {
857 pollfds[i].fd = sockets[i];
858 pollfds[i].events = POLLIN | POLLPRI;
859 }
860#else
861 fd_set fdset;
862 struct timeval tv;
863#endif
864 while(1) {
865#ifdef USE_POLL
866 int ret = poll(pollfds, sockcount, 1000);
867#else
868 FD_ZERO(&fdset);
869 for(i = 0; i < sockcount; i++) {
870 FD_SET(sockets[i], &fdset);
871 }
872 tv.tv_sec = 1;
873 tv.tv_usec = 0;
874#ifdef __HAIKU__
875 int ret = select(32, &fdset, NULL, NULL, &tv);
876#else
877 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
878#endif
879#endif
880 if(ret == -1) {
881#ifndef __MINGW32__
882 cm_log("Server", "Select failure: %s", strerror(errno));
883#endif
884 break;
885 } else if(ret == 0) {
886#ifdef SERVICE
887 if(status.dwCurrentState == SERVICE_STOP_PENDING) {
888 break;
889 }
890#endif
891 } else if(ret > 0) {
892 /* connection */
893 int i;
894 for(i = 0; i < sockcount; i++) {
895 bool cond;
896#ifdef USE_POLL
897 cond = pollfds[i].revents & POLLIN;
898#else
899 cond = FD_ISSET(sockets[i], &fdset);
900#endif
901 if(cond) {
902 SOCKADDR claddr;
903 int clen = sizeof(claddr);
904 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
905 cm_log("Server", "New connection accepted");
906#if defined(__MINGW32__) || defined(__HAIKU__)
907 struct pass_entry* e = malloc(sizeof(*e));
908 e->sock = sock;
909 e->ssl = config.ports[i] & (1ULL << 32);
910 e->port = config.ports[i];
911 e->addr = claddr;
912#endif
913#ifdef __MINGW32__
914 int j;
915 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
916 if(threads[j].used) {
917 DWORD ex;
918 GetExitCodeThread(threads[j].handle, &ex);
919 if(ex != STILL_ACTIVE) {
920 CloseHandle(threads[j].handle);
921 threads[j].used = false;
922 }
923 }
924 }
925 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
926 if(!threads[j].used) {
927 threads[j].handle = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
928 threads[j].used = true;
929 break;
930 }
931 }
932#elif defined(__HAIKU__)
933 int j;
934 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
935 if(threads[j].used) {
936 thread_info info;
937 bool kill = false;
938 if(get_thread_info(threads[j].thread, &info) == B_OK) {
939 } else {
940 kill = true;
941 }
942 if(kill) {
943 threads[j].used = false;
944 }
945 }
946 }
947 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
948 if(!threads[j].used) {
949 threads[j].thread = spawn_thread(tw_server_pass, "Tewi HTTPd", 60, e);
950 threads[j].used = true;
951 resume_thread(threads[j].thread);
952 break;
953 }
954 }
955#else
956 pid_t pid = fork();
957 if(pid == 0) {
958 int j;
959 for(j = 0; j < sockcount; j++) close_socket(sockets[j]);
960 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
961 _exit(0);
962 } else {
963 close_socket(sock);
964 }
965#endif
966 }
967 }
968 }
969 }
970}
Note: See TracBrowser for help on using the repository browser.