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

Last change on this file since 314 was 314, checked in by Nishi, on Oct 14, 2024 at 4:37:04 PM

module works

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