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

Last change on this file since 394 was 394, checked in by Nishi, on Oct 28, 2024 at 8:55:11 AM

handle error

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