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

Last change on this file since 277 was 276, checked in by Nishi, on Oct 8, 2024 at 8:02:04 PM

fix macro

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