Subversion Repositories Tewi

Rev

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