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

Last change on this file since 359 was 359, checked in by Nishi, on Oct 16, 2024 at 11:34:51 PM

add dos supportr

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