Subversion Repositories Tewi

Rev

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