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

Last change on this file since 163 was 163, checked in by Nishi, on Sep 26, 2024 at 9:33:22 AM

add an option to disable getaddrinfo

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