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

Last change on this file since 178 was 173, checked in by Nishi, on Sep 27, 2024 at 6:18:46 AM

fix fopen stuff

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