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

Last change on this file since 161 was 161, checked in by Nishi, on Sep 25, 2024 at 10:35:04 PM

adding chroot

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