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

Last change on this file since 119 was 118, checked in by Nishi, on Sep 21, 2024 at 6:03:27 PM

use poll for select by default

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