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

Last change on this file since 315 was 315, checked in by Nishi, on Oct 14, 2024 at 7:01:02 PM

wip

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