Subversion Repositories Tewi

Rev

Rev 272 | Rev 275 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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