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

Last change on this file since 182 was 182, checked in by Nishi, on Sep 27, 2024 at 9:55:12 PM

psp

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