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

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

psp support

  • Property svn:keywords set to Id
File size: 26.2 KB
Line 
1/* $Id: server.c 183 2024-09-27 16:15:15Z 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#elif defined(_PSP)
434int tw_server_pass(void* ptr) {
435#endif
436#if defined(__HAIKU__) || defined(__MINGW32__) || defined(_PSP)
437 int sock = ((struct pass_entry*)ptr)->sock;
438 bool ssl = ((struct pass_entry*)ptr)->ssl;
439 int port = ((struct pass_entry*)ptr)->port;
440 SOCKADDR addr = ((struct pass_entry*)ptr)->addr;
441 free(ptr);
442#else
443 void tw_server_pass(int sock, bool ssl, int port, SOCKADDR addr) {
444#endif
445 char* name = config.hostname;
446
447#ifndef NO_SSL
448 SSL_CTX* ctx = NULL;
449 SSL* s = NULL;
450 bool sslworks = false;
451 if(ssl) {
452 ctx = tw_create_ssl_ctx(port);
453 s = SSL_new(ctx);
454 SSL_set_fd(s, sock);
455 if(SSL_accept(s) <= 0) goto cleanup;
456 sslworks = true;
457 }
458#else
459 void* s = NULL;
460#endif
461
462 char address[513];
463 address[0] = 0;
464#ifndef NO_GETADDRINFO
465 struct sockaddr* sa = (struct sockaddr*)&addr;
466 getnameinfo(sa, sizeof(addr), address, 512, NULL, 0, NI_NUMERICHOST);
467#endif
468
469 struct tw_http_request req;
470 struct tw_http_response res;
471 struct tw_tool tools;
472 res._processed = false;
473 tw_init_tools(&tools);
474 int ret = tw_http_parse(s, sock, &req);
475 if(ret == 0) {
476 char date[513];
477 time_t t = time(NULL);
478 struct tm* tm = localtime(&t);
479 strftime(date, 512, "%a, %d %b %Y %H:%M:%S %Z", tm);
480
481 char* useragent = cm_strdup("");
482
483 int i;
484 for(i = 0; req.headers[i] != NULL; i += 2) {
485 if(cm_strcaseequ(req.headers[i], "User-Agent")) {
486 free(useragent);
487 useragent = cm_strdup(req.headers[i + 1]);
488 }
489 }
490
491 char* tmp = cm_strcat3(address, " - [", date);
492 char* tmp2 = cm_strcat3(tmp, "] \"", req.method);
493 char* tmp3 = cm_strcat3(tmp2, " ", req.path);
494 char* tmp4 = cm_strcat3(tmp3, " ", req.version);
495 char* tmp5 = cm_strcat3(tmp4, "\" \"", useragent);
496 char* log = cm_strcat(tmp5, "\"");
497 free(tmp);
498 free(tmp2);
499 free(tmp3);
500 free(tmp4);
501 free(tmp5);
502 free(useragent);
503 cm_force_log(log);
504 free(log);
505
506 char* vhost = cm_strdup(config.hostname);
507 time_t cmtime = 0;
508 if(req.headers != NULL) {
509 for(i = 0; req.headers[i] != NULL; i += 2) {
510 if(cm_strcaseequ(req.headers[i], "Host")) {
511 free(vhost);
512 vhost = cm_strdup(req.headers[i + 1]);
513 } else if(cm_strcaseequ(req.headers[i], "If-Modified-Since")) {
514 struct tm tm;
515 strptime(req.headers[i + 1], "%a, %d %b %Y %H:%M:%S GMT", &tm);
516#if defined(__MINGW32__) || defined(_PSP)
517 time_t t = 0;
518 struct tm* btm = localtime(&t);
519 cmtime = mktime(&tm);
520 cmtime -= (btm->tm_hour * 60 + btm->tm_min) * 60;
521#else
522 cmtime = timegm(&tm);
523#endif
524 }
525 }
526 }
527 bool rej = false;
528 cm_log("Server", "Host is %s", vhost);
529 int port = s == NULL ? 80 : 443;
530 char* host = cm_strdup(vhost);
531 for(i = 0; vhost[i] != 0; i++) {
532 if(vhost[i] == ':') {
533 host[i] = 0;
534 port = atoi(host + i + 1);
535 break;
536 }
537 }
538 name = host;
539 cm_log("Server", "Hostname is `%s', port is `%d'", host, port);
540 struct tw_config_entry* vhost_entry = tw_vhost_match(host, port);
541#ifdef HAS_CHROOT
542 char* chrootpath = vhost_entry->chroot_path != NULL ? vhost_entry->chroot_path : config.root.chroot_path;
543 if(chrootpath != NULL) {
544 if(chdir(chrootpath) == 0) {
545 if(chroot(".") == 0) {
546 cm_log("Server", "Chroot successful");
547 }
548 } else {
549 cm_log("Server", "chdir() failed, cannot chroot");
550 tw_http_error(s, sock, 500, name, port, vhost_entry);
551 rej = true;
552 }
553 }
554#endif
555 for(i = 0; i < config.module_count; i++) {
556 tw_mod_request_t mod_req = (tw_mod_request_t)tw_module_symbol(config.modules[i], "mod_request");
557 if(mod_req != NULL) {
558 int ret = mod_req(&tools, &req, &res);
559 int co = ret & 0xff;
560 if(co == _TW_MODULE_PASS) {
561 continue;
562 } else if(co == _TW_MODULE_STOP) {
563 /* Handle response here ... */
564 res._processed = true;
565 break;
566 } else if(co == _TW_MODULE_STOP2) {
567 res._processed = true;
568 break;
569 } else if(co == _TW_MODULE_ERROR) {
570 tw_http_error(s, sock, (ret & 0xffff00) >> 8, name, port, vhost_entry);
571 break;
572 }
573 }
574 }
575 if(!res._processed) {
576 cm_log("Server", "Document root is %s", vhost_entry->root == NULL ? "not set" : vhost_entry->root);
577 char* path = cm_strcat(vhost_entry->root == NULL ? "" : vhost_entry->root, req.path);
578 cm_log("Server", "Filesystem path is %s", path);
579#ifdef __MINGW32__
580 char* rpath = cm_strdup(path);
581 for(i = strlen(rpath) - 1; i >= 0; i--) {
582 if(rpath[i] == '/') {
583 int j;
584 for(j = i + 1; rpath[j] != 0; j++) {
585 if(rpath[j] == ':' || rpath[j] == '.') {
586 rpath[j] = 0;
587 break;
588 }
589 }
590 break;
591 }
592 }
593 for(i = 0; i < sizeof(reserved_names) / sizeof(reserved_names[0]); i++) {
594 char* n = cm_strcat("/", reserved_names[i]);
595 if(cm_nocase_endswith(rpath, n)) {
596 tw_http_error(s, sock, 403, name, port, vhost_entry);
597 free(n);
598 rej = true;
599 cm_log("Server", "XP Patch ; rejecting access to device");
600 break;
601 }
602 free(n);
603 }
604 free(rpath);
605#endif
606 struct stat st;
607 if(!rej && stat(path, &st) == 0) {
608 if(!tw_permission_allowed(path, addr, req, vhost_entry)) {
609 tw_http_error(s, sock, 403, name, port, vhost_entry);
610 } else if(S_ISDIR(st.st_mode)) {
611 if(req.path[strlen(req.path) - 1] != '/') {
612 cm_log("Server", "Accessing directory without the slash at the end");
613 char* headers[3] = {"Location", cm_strcat(req.path, "/"), NULL};
614 _tw_process_page(s, sock, tw_http_status(301), NULL, NULL, NULL, 0, headers, 0, 0);
615 free(headers[1]);
616 } else {
617 char** indexes = vhost_entry->index_count == 0 ? config.root.indexes : vhost_entry->indexes;
618 int index_count = vhost_entry->index_count == 0 ? config.root.index_count : vhost_entry->index_count;
619 bool found = false;
620 for(i = 0; i < index_count; i++) {
621 char* p = cm_strcat3(path, "/", indexes[i]);
622 FILE* f = fopen(p, "rb");
623 if(f != NULL) {
624 char* ext = NULL;
625 int j;
626 for(j = strlen(p) - 1; j >= 0; j--) {
627 if(p[j] == '.') {
628 ext = cm_strdup(p + j);
629 break;
630 } else if(p[j] == '/') {
631 break;
632 }
633 }
634 struct stat st;
635 stat(p, &st);
636 char* mime = tw_get_mime(ext, vhost_entry);
637 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size, 0, 0);
638 fclose(f);
639 if(ext != NULL) free(ext);
640 free(p);
641 found = true;
642 break;
643 }
644 free(p);
645 }
646 if(!found) {
647 char* str = malloc(1);
648 str[0] = 0;
649 char** items = cm_scandir(path);
650 addstring(&str, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n");
651 addstring(&str, "<html>\n");
652 addstring(&str, " <head>\n");
653 addstring(&str, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
654 addstring(&str, " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
655 addstring(&str, " <title>Index of %h</title>\n", req.path);
656 addstring(&str, " </head>\n");
657 addstring(&str, " <body>\n");
658 addstring(&str, " <h1>Index of %h</h1>\n", req.path);
659 addstring(&str, " <hr>\n");
660 addstring(&str, " <table border=\"0\">\n");
661 addstring(&str, " <tr>\n");
662 addstring(&str, " <th></th>\n");
663 addstring(&str, " <th>Filename</th>\n");
664 addstring(&str, " <th>MIME</th>\n");
665 addstring(&str, " <th>Size</th>\n");
666 addstring(&str, " </tr>\n");
667 int readme = -1;
668 char** readmes = vhost_entry->readme_count == 0 ? config.root.readmes : vhost_entry->readmes;
669 int readme_count = vhost_entry->readme_count == 0 ? config.root.readme_count : vhost_entry->readme_count;
670 if(items != NULL) {
671 int phase = 0;
672 doit:
673 for(i = 0; items[i] != NULL; i++) {
674 int j;
675 char* fpth = cm_strcat3(path, "/", items[i]);
676 struct stat s;
677 char size[512];
678 size[0] = 0;
679 stat(fpth, &s);
680 if(phase == 0 && !S_ISDIR(s.st_mode)) {
681 free(fpth);
682 continue;
683 } else if(phase == 1 && S_ISDIR(s.st_mode)) {
684 free(fpth);
685 continue;
686 }
687 if(readme == -1) {
688 for(j = 0; j < readme_count; j++) {
689 if(strcmp(items[i], readmes[j]) == 0) {
690 readme = j;
691 break;
692 }
693 }
694 if(readme != -1) {
695 free(fpth);
696 continue;
697 }
698 }
699 if(s.st_size < 1024ULL) {
700 sprintf(size, "%d", (int)s.st_size);
701 } else if(s.st_size < 1024ULL * 1024) {
702 sprintf(size, "%.1fK", (double)s.st_size / 1024);
703 } else if(s.st_size < 1024ULL * 1024 * 1024) {
704 sprintf(size, "%.1fM", (double)s.st_size / 1024 / 1024);
705 } else if(s.st_size < 1024ULL * 1024 * 1024 * 1024) {
706 sprintf(size, "%.1fG", (double)s.st_size / 1024 / 1024 / 1024);
707 } else if(s.st_size < 1024ULL * 1024 * 1024 * 1024 * 1024) {
708 sprintf(size, "%.1fT", (double)s.st_size / 1024 / 1024 / 1024 / 1024);
709 }
710
711 free(fpth);
712
713 char* ext = NULL;
714 for(j = strlen(items[i]) - 1; j >= 0; j--) {
715 if(items[i][j] == '.') {
716 ext = cm_strdup(items[i] + j);
717 break;
718 } else if(items[i][j] == '/') {
719 break;
720 }
721 }
722 char* showmime = "";
723 char* mime = tw_get_mime(ext, vhost_entry);
724 if(strcmp(items[i], "../") == 0) {
725 mime = "misc/parent";
726 size[0] = 0;
727 } else if(items[i][strlen(items[i]) - 1] == '/') {
728 mime = "misc/dir";
729 size[0] = 0;
730 } else {
731 showmime = mime;
732 }
733 char* icon = tw_get_icon(mime, vhost_entry);
734 if(ext != NULL) free(ext);
735 char* itm = cm_strdup(items[i]);
736 if(strlen(itm) >= 32) {
737 if(itm[strlen(itm) - 1] == '/') {
738 itm[31] = 0;
739 itm[30] = '/';
740 itm[29] = '.';
741 itm[28] = '.';
742 itm[27] = '.';
743 } else {
744 itm[31] = 0;
745 itm[30] = '.';
746 itm[29] = '.';
747 itm[28] = '.';
748 }
749 }
750 addstring(&str, "<tr>\n");
751 addstring(&str, " <td><img src=\"%s\" alt=\"icon\"></td>\n", icon);
752 addstring(&str, " <td><a href=\"%l\"><code>%h</code></a></td>\n", items[i], itm);
753 addstring(&str, " <td><code> %h </code></td>\n", showmime);
754 addstring(&str, " <td><code> %s </code></td>\n", size);
755 addstring(&str, "</tr>\n");
756 free(itm);
757 }
758 phase++;
759 if(phase != 2) goto doit;
760 for(i = 0; items[i] != NULL; i++) free(items[i]);
761 free(items);
762 }
763 addstring(&str, " </table>\n");
764 if(readme != -1) {
765 addstring(&str, "<hr>\n");
766 char* fpth = cm_strcat3(path, "/", readmes[readme]);
767 struct stat s;
768 stat(fpth, &s);
769 FILE* fr = fopen(fpth, "r");
770 if(fr != NULL) {
771 char* rmbuf = malloc(s.st_size + 1);
772 rmbuf[s.st_size] = 0;
773 fread(rmbuf, s.st_size, 1, fr);
774 addstring(&str, "<pre><code>%h</code></pre>\n", rmbuf);
775 fclose(fr);
776 free(rmbuf);
777 }
778 free(fpth);
779 }
780 addstring(&str, " <hr>\n");
781 int hp = vhost_entry->hideport == -1 ? config.root.hideport : vhost_entry->hideport;
782 if(hp == 0) {
783 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
784 } else {
785 addstring(&str, " <address>%s Server at %s</address>\n", tw_server, name, port);
786 }
787 addstring(&str, " </body>\n");
788 addstring(&str, "</html>\n");
789 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str), 0, 0);
790 free(str);
791 }
792 }
793 } else {
794 char* ext = NULL;
795 for(i = strlen(req.path) - 1; i >= 0; i--) {
796 if(req.path[i] == '.') {
797 ext = cm_strdup(req.path + i);
798 break;
799 } else if(req.path[i] == '/') {
800 break;
801 }
802 }
803 char* mime = tw_get_mime(ext, vhost_entry);
804 if(ext != NULL) free(ext);
805 FILE* f = fopen(path, "rb");
806 if(f == NULL) {
807 tw_http_error(s, sock, 403, name, port, vhost_entry);
808 } else {
809 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size, st.st_mtime, cmtime);
810 fclose(f);
811 }
812 }
813 } else {
814 if(!rej) {
815 tw_http_error(s, sock, 404, name, port, vhost_entry);
816 }
817 }
818 free(path);
819 }
820 free(vhost);
821 free(host);
822 } else if(ret == -1) {
823 } else {
824 tw_http_error(s, sock, 400, name, port, &config.root);
825 }
826 tw_free_request(&req);
827cleanup:
828#ifndef NO_SSL
829 if(sslworks) {
830 SSL_shutdown(s);
831 }
832 SSL_free(s);
833#endif
834 close_socket(sock);
835#ifdef __MINGW32__
836 _endthreadex(0);
837#elif defined(__HAIKU__)
838 exit_thread(0);
839#endif
840 ;
841}
842
843#ifdef SERVICE
844extern SERVICE_STATUS status;
845extern SERVICE_STATUS_HANDLE status_handle;
846#endif
847
848#if defined(__MINGW32__) || defined(__HAIKU__)
849struct thread_entry {
850#ifdef __HAIKU__
851 thread_id thread;
852#else
853 HANDLE handle;
854#endif
855 bool used;
856};
857#endif
858
859extern int running;
860
861void tw_server_loop(void) {
862 int i;
863#if defined(__MINGW32__) || defined(__HAIKU__)
864 struct thread_entry threads[2048];
865 for(i = 0; i < sizeof(threads) / sizeof(threads[0]); i++) {
866 threads[i].used = false;
867 }
868#endif
869#ifdef USE_POLL
870 struct pollfd pollfds[sockcount];
871 for(i = 0; i < sockcount; i++) {
872 pollfds[i].fd = sockets[i];
873 pollfds[i].events = POLLIN | POLLPRI;
874 }
875#else
876 fd_set fdset;
877 struct timeval tv;
878#endif
879 while(running) {
880#ifdef USE_POLL
881 int ret = poll(pollfds, sockcount, 1000);
882#else
883 FD_ZERO(&fdset);
884 for(i = 0; i < sockcount; i++) {
885 FD_SET(sockets[i], &fdset);
886 }
887 tv.tv_sec = 1;
888 tv.tv_usec = 0;
889#ifdef __HAIKU__
890 int ret = select(32, &fdset, NULL, NULL, &tv);
891#else
892 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
893#endif
894#endif
895 if(ret == -1) {
896#ifndef __MINGW32__
897 cm_log("Server", "Select failure: %s", strerror(errno));
898#endif
899 break;
900 } else if(ret == 0) {
901#ifdef SERVICE
902 if(status.dwCurrentState == SERVICE_STOP_PENDING) {
903 break;
904 }
905#endif
906 } else if(ret > 0) {
907 /* connection */
908 int i;
909 for(i = 0; i < sockcount; i++) {
910 bool cond;
911#ifdef USE_POLL
912 cond = pollfds[i].revents & POLLIN;
913#else
914 cond = FD_ISSET(sockets[i], &fdset);
915#endif
916 if(cond) {
917 SOCKADDR claddr;
918 socklen_t clen = sizeof(claddr);
919 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
920 cm_log("Server", "New connection accepted");
921#if defined(__MINGW32__) || defined(__HAIKU__) || defined(_PSP)
922 struct pass_entry* e = malloc(sizeof(*e));
923 e->sock = sock;
924 e->ssl = config.ports[i] & (1ULL << 32);
925 e->port = config.ports[i];
926 e->addr = claddr;
927#endif
928#ifdef __MINGW32__
929 int j;
930 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
931 if(threads[j].used) {
932 DWORD ex;
933 GetExitCodeThread(threads[j].handle, &ex);
934 if(ex != STILL_ACTIVE) {
935 CloseHandle(threads[j].handle);
936 threads[j].used = false;
937 }
938 }
939 }
940 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
941 if(!threads[j].used) {
942 threads[j].handle = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
943 threads[j].used = true;
944 break;
945 }
946 }
947#elif defined(_PSP)
948 tw_server_pass(e);
949#elif defined(__HAIKU__)
950 int j;
951 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
952 if(threads[j].used) {
953 thread_info info;
954 bool kill = false;
955 if(get_thread_info(threads[j].thread, &info) == B_OK) {
956 } else {
957 kill = true;
958 }
959 if(kill) {
960 threads[j].used = false;
961 }
962 }
963 }
964 for(j = 0; j < sizeof(threads) / sizeof(threads[0]); j++) {
965 if(!threads[j].used) {
966 threads[j].thread = spawn_thread(tw_server_pass, "Tewi HTTPd", 60, e);
967 threads[j].used = true;
968 resume_thread(threads[j].thread);
969 break;
970 }
971 }
972#else
973 pid_t pid = fork();
974 if(pid == 0) {
975 int j;
976 for(j = 0; j < sockcount; j++) close_socket(sockets[j]);
977 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
978 _exit(0);
979 } else {
980 close_socket(sock);
981 }
982#endif
983 }
984 }
985 }
986 }
987}
Note: See TracBrowser for help on using the repository browser.