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

Last change on this file since 21 was 21, checked in by Nishi, on Sep 14, 2024 at 9:39:39 PM

can send file now

  • Property svn:keywords set to Id
File size: 12.0 KB
Line 
1/* $Id: server.c 21 2024-09-14 12:39:39Z nishi $ */
2
3#define SOURCE
4
5#include "tw_server.h"
6
7#include "tw_ssl.h"
8#include "tw_config.h"
9#include "tw_http.h"
10#include "tw_module.h"
11#include "tw_version.h"
12
13#include <unistd.h>
14#include <string.h>
15#include <stdbool.h>
16#include <stdarg.h>
17#include <sys/stat.h>
18
19#include <cm_string.h>
20#include <cm_log.h>
21#include <cm_dir.h>
22
23#ifdef __MINGW32__
24#include <winsock2.h>
25#include <process.h>
26#else
27#include <sys/select.h>
28#include <sys/socket.h>
29#include <arpa/inet.h>
30#include <netinet/in.h>
31#include <netinet/tcp.h>
32#endif
33
34extern struct tw_config config;
35extern char tw_server[];
36
37fd_set fdset;
38int sockcount = 0;
39
40SOCKADDR addresses[MAX_PORTS];
41int sockets[MAX_PORTS];
42
43void close_socket(int sock) {
44#ifdef __MINGW32__
45 closesocket(sock);
46#else
47 close(sock);
48#endif
49}
50
51int tw_server_init(void) {
52 int i;
53#ifdef __MINGW32__
54 WSADATA wsa;
55 WSAStartup(MAKEWORD(2, 0), &wsa);
56#endif
57 for(i = 0; config.ports[i] != -1; i++)
58 ;
59 sockcount = i;
60 for(i = 0; config.ports[i] != -1; i++) {
61#ifdef NO_IPV6
62 int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
63#else
64 int sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
65#endif
66#ifdef __MINGW32__
67 if(sock == INVALID_SOCKET)
68#else
69 if(sock < 0)
70#endif
71 {
72 cm_log("Server", "Socket creation failure");
73 return 1;
74 }
75 int yes = 1;
76 if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(yes)) < 0) {
77 close_socket(sock);
78 cm_log("Server", "setsockopt failure (reuseaddr)");
79 return 1;
80 }
81 if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(yes)) < 0) {
82 close_socket(sock);
83 cm_log("Server", "setsockopt failure (nodelay)");
84 return 1;
85 }
86#ifndef NO_IPV6
87 int no = 0;
88 if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&no, sizeof(no)) < 0) {
89 close_socket(sock);
90 cm_log("Server", "setsockopt failure (IPv6)");
91 return 1;
92 }
93#endif
94 memset(&addresses[i], 0, sizeof(addresses[i]));
95#ifdef NO_IPV6
96 addresses[i].sin_family = AF_INET;
97 addresses[i].sin_addr.s_addr = INADDR_ANY;
98 addresses[i].sin_port = htons(config.ports[i]);
99#else
100 addresses[i].sin6_family = AF_INET6;
101 addresses[i].sin6_addr = in6addr_any;
102 addresses[i].sin6_port = htons(config.ports[i]);
103#endif
104 if(bind(sock, (struct sockaddr*)&addresses[i], sizeof(addresses[i])) < 0) {
105 close_socket(sock);
106 cm_log("Server", "Bind failure");
107 return 1;
108 }
109 if(listen(sock, 128) < 0) {
110 close_socket(sock);
111 cm_log("Server", "Listen failure");
112 return 1;
113 }
114 sockets[i] = sock;
115 }
116 return 0;
117}
118
119size_t tw_read(SSL* ssl, int s, void* data, size_t len) {
120 if(ssl == NULL) {
121 return recv(s, data, len, 0);
122 } else {
123 return SSL_read(ssl, data, len);
124 }
125}
126
127size_t tw_write(SSL* ssl, int s, void* data, size_t len) {
128 if(ssl == NULL) {
129 return send(s, data, len, 0);
130 } else {
131 return SSL_write(ssl, data, len);
132 }
133}
134
135#define ERROR_HTML \
136 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" \
137 "<html>\n" \
138 " <head>\n" \
139 " <title>%s</title>\n" \
140 " </head>\n" \
141 " <body>\n" \
142 " <h1>%s</h1>\n" \
143 " <hr>\n" \
144 " ", \
145 address, \
146 "\n" \
147 " </body>\n" \
148 "</html>\n"
149
150void tw_process_page(SSL* ssl, int sock, const char* status, const char* type, FILE* f, const unsigned char* doc, size_t size) {
151 char construct[512];
152 sprintf(construct, "%llu", (unsigned long long)size);
153 tw_write(ssl, sock, "HTTP/1.1 ", 9);
154 tw_write(ssl, sock, (char*)status, strlen(status));
155 tw_write(ssl, sock, "\r\n", 2);
156 tw_write(ssl, sock, "Content-Type: ", 7 + 5 + 2);
157 tw_write(ssl, sock, (char*)type, strlen(type));
158 tw_write(ssl, sock, "\r\n", 2);
159 tw_write(ssl, sock, "Server: ", 6 + 2);
160 tw_write(ssl, sock, tw_server, strlen(tw_server));
161 tw_write(ssl, sock, "\r\n", 2);
162 tw_write(ssl, sock, "Content-Length: ", 7 + 7 + 2);
163 tw_write(ssl, sock, construct, strlen(construct));
164 tw_write(ssl, sock, "\r\n", 2);
165 tw_write(ssl, sock, "\r\n", 2);
166 size_t incr = 0;
167 while(1) {
168 if(f != NULL){
169 char buffer[128];
170 fread(buffer, size < 128 ? size : 128, 1, f);
171 tw_write(ssl, sock, buffer, size < 128 ? size : 128);
172 }else{
173 tw_write(ssl, sock, (unsigned char*)doc + incr, size < 128 ? size : 128);
174 }
175 incr += 128;
176 if(size <= 128) break;
177 size -= 128;
178 }
179}
180
181const char* tw_http_status(int code) {
182 if(code == 200) {
183 return "200 OK";
184 } else if(code == 400) {
185 return "400 Bad Request";
186 } else if(code == 401) {
187 return "401 Unauthorized";
188 } else if(code == 403) {
189 return "403 Forbidden";
190 } else if(code == 404) {
191 return "404 Not Found";
192 } else {
193 return "400 Bad Request";
194 }
195}
196
197char* tw_http_default_error(int code, char* name, int port) {
198 char address[1024];
199 sprintf(address, "<address>%s Server at %s Port %d</address>", tw_server, name, port);
200
201 char* st = cm_strdup(tw_http_status(code));
202 char* st2;
203 int i;
204 for(i = 0; st[i] != 0; i++) {
205 if(st[i] == ' ') {
206 st2 = cm_strdup(st + i + 1);
207 break;
208 }
209 }
210 char* buffer = malloc(4096);
211 char* str = cm_strcat3(ERROR_HTML);
212 sprintf(buffer, str, st, st2);
213 free(str);
214 free(st);
215 return buffer;
216}
217
218void tw_http_error(SSL* ssl, int sock, int error, char* name, int port) {
219 char* str = tw_http_default_error(error, name, port);
220 tw_process_page(ssl, sock, tw_http_status(error), "text/html", NULL, str, strlen(str));
221 free(str);
222}
223
224void addstring(char** str, const char* add, ...) {
225 int i;
226 char cbuf[2];
227 cbuf[1] = 0;
228 va_list va;
229 va_start(va, add);
230 for(i = 0; add[i] != 0; i++) {
231 cbuf[0] = add[i];
232 if(add[i] == '%') {
233 i++;
234 if(add[i] == 's') {
235 char* tmp = *str;
236 *str = cm_strcat(tmp, va_arg(va, const char*));
237 free(tmp);
238 } else if(add[i] == 'h') {
239 char* h = cm_html_escape(va_arg(va, const char*));
240 char* tmp = *str;
241 *str = cm_strcat(tmp, h);
242 free(tmp);
243 free(h);
244 } else if(add[i] == 'l') {
245 char* h = cm_url_escape(va_arg(va, const char*));
246 char* tmp = *str;
247 *str = cm_strcat(tmp, h);
248 free(tmp);
249 free(h);
250 } else if(add[i] == 'd') {
251 int n = va_arg(va, int);
252 char* h = malloc(512);
253 sprintf(h, "%d", n);
254 char* tmp = *str;
255 *str = cm_strcat(tmp, h);
256 free(tmp);
257 free(h);
258 } else if(add[i] == '%') {
259 char* tmp = *str;
260 *str = cm_strcat(tmp, "%");
261 free(tmp);
262 }
263 } else {
264 char* tmp = *str;
265 *str = cm_strcat(tmp, cbuf);
266 free(tmp);
267 }
268 }
269}
270
271#ifdef __MINGW32__
272struct pass_entry {
273 int sock;
274 int port;
275 bool ssl;
276 SOCKADDR addr;
277};
278
279unsigned int WINAPI tw_server_pass(void* ptr) {
280 int sock = ((struct pass_entry*)ptr)->sock;
281 bool ssl = ((struct pass_entry*)ptr)->ssl;
282 int port = ((struct pass_entry*)ptr)->port;
283 SOCKADDR addr = ((struct pass_entry*)ptr)->addr;
284 free(ptr);
285#else
286void tw_server_pass(int sock, bool ssl, int port, SOCKADDR addr) {
287#endif
288 char* name = config.hostname;
289
290 SSL_CTX* ctx = NULL;
291 SSL* s = NULL;
292 bool sslworks = false;
293 if(ssl) {
294 ctx = tw_create_ssl_ctx(port);
295 s = SSL_new(ctx);
296 SSL_set_fd(s, sock);
297 if(SSL_accept(s) <= 0) goto cleanup;
298 sslworks = true;
299 }
300 struct tw_http_request req;
301 struct tw_http_response res;
302 struct tw_tool tools;
303 res._processed = false;
304 tw_init_tools(&tools);
305 int ret = tw_http_parse(s, sock, &req);
306 if(ret == 0) {
307 char* vhost = cm_strdup(config.hostname);
308 int i;
309 for(i = 0; req.headers[i] != NULL; i += 2){
310 if(cm_strcaseequ(req.headers[i], "Host")){
311 free(vhost);
312 vhost = req.headers[i + 1];
313 break;
314 }
315 }
316 cm_log("Server", "Host is %s", vhost);
317 int port = s == NULL ? 80 : 443;
318 char* host = cm_strdup(vhost);
319 for(i = 0; vhost[i] != 0; i++){
320 if(vhost[i] == ':'){
321 host[i] = 0;
322 port = atoi(host + i + 1);
323 break;
324 }
325 }
326 cm_log("Server", "Hostname is `%s', port is `%d'", host, port);
327 struct tw_config_entry* vhost_entry = tw_vhost_match(host, port);
328 for(i = 0; i < config.module_count; i++) {
329 tw_mod_request_t mod_req = (tw_mod_request_t)tw_module_symbol(config.modules[i], "mod_request");
330 if(mod_req != NULL) {
331 int ret = mod_req(&tools, &req, &res);
332 int co = ret & 0xff;
333 if(co == _TW_MODULE_PASS) continue;
334 if(co == _TW_MODULE_STOP) {
335 res._processed = true;
336 break;
337 }
338 if(co == _TW_MODULE_ERROR) {
339 tw_http_error(s, sock, (ret & 0xffff00) >> 8, name, port);
340 break;
341 }
342 }
343 }
344 if(!res._processed) {
345 cm_log("Server", "Document root is %s", vhost_entry->root == NULL ? "not set" : vhost_entry->root);
346 char* path = cm_strcat(vhost_entry->root == NULL ? "" : vhost_entry->root, req.path);
347 cm_log("Server", "Filesystem path is %s", path);
348 struct stat st;
349 if(stat(path, &st) == 0){
350 if(!tw_permission_allowed(path, addr, req, vhost_entry)){
351 tw_http_error(s, sock, 403, name, port);
352 }else if(S_ISDIR(st.st_mode)){
353 char* str = malloc(1);
354 str[0] = 0;
355 char** items = cm_scandir(path);
356 addstring(&str, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
357 addstring(&str, "<html>\n");
358 addstring(&str, " <head>\n");
359 addstring(&str, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
360 addstring(&str, " <title>Index of %h</title>\n", req.path);
361 addstring(&str, " </head>\n");
362 addstring(&str, " <body>\n");
363 addstring(&str, " <h1>Index of %h</h1>\n", req.path);
364 addstring(&str, " <hr>\n");
365 addstring(&str, " <table border=\"0\">\n");
366 addstring(&str, " <tr>\n");
367 addstring(&str, " <th></th>\n");
368 addstring(&str, " <th>Filename</th>\n");
369 addstring(&str, " </tr>\n");
370 if(items != NULL){
371 for(i = 0; items[i] != NULL; i++){
372 addstring(&str, "<tr>\n");
373 addstring(&str, " <td></td>\n");
374 addstring(&str, " <td><a href=\"%l\">%h</a></td>\n", items[i], items[i]);
375 addstring(&str, "</tr>\n");
376 }
377 }
378 addstring(&str, " </table>\n");
379 addstring(&str, " <hr>\n");
380 addstring(&str, " <address>%s Server at %s Port %d</address>\n", tw_server, name, port);
381 addstring(&str, " </body>\n");
382 addstring(&str, "</html>\n");
383 tw_process_page(s, sock, tw_http_status(200), "text/html", NULL, str, strlen(str));
384 free(str);
385 }else{
386 char* mime = "application/octet-stream";
387 bool set = false;
388 char* ext = NULL;
389 for(i = strlen(req.path) - 1; i >= 0; i--){
390 if(req.path[i] == '.'){
391 ext = cm_strdup(req.path + i);
392 break;
393 }
394 }
395 for(i = 0; i < vhost_entry->mime_count; i++){
396 if(strcmp(vhost_entry->mimes[i].ext, "all") == 0 || (ext != NULL && strcmp(vhost_entry->mimes[i].ext, ext) == 0)){
397 mime = vhost_entry->mimes[i].mime;
398 set = true;
399 }
400 }
401 if(!set){
402 for(i = 0; i < config.root.mime_count; i++){
403 if(strcmp(config.root.mimes[i].ext, "all") == 0 || (ext != NULL && strcmp(config.root.mimes[i].ext, ext) == 0)){
404 mime = config.root.mimes[i].mime;
405 set = true;
406 }
407 }
408 }
409 if(ext != NULL) free(ext);
410 FILE* f = fopen(path, "rb");
411 tw_process_page(s, sock, tw_http_status(200), mime, f, NULL, st.st_size);
412 fclose(f);
413 }
414 }else{
415 tw_http_error(s, sock, 404, name, port);
416 }
417 free(path);
418 }
419 free(vhost);
420 free(host);
421 } else {
422 tw_http_error(s, sock, 400, name, port);
423 }
424cleanup:
425 if(sslworks) {
426 SSL_shutdown(s);
427 }
428 SSL_free(s);
429 close_socket(sock);
430#ifdef __MINGW32__
431 _endthreadex(0);
432#endif
433}
434
435void tw_server_loop(void) {
436 struct timeval tv;
437 while(1) {
438 FD_ZERO(&fdset);
439 int i;
440 for(i = 0; i < sockcount; i++) {
441 FD_SET(sockets[i], &fdset);
442 }
443 tv.tv_sec = 1;
444 tv.tv_usec = 0;
445 int ret = select(FD_SETSIZE, &fdset, NULL, NULL, &tv);
446 if(ret == -1) {
447 break;
448 } else if(ret > 0) {
449 /* connection */
450 int i;
451 for(i = 0; i < sockcount; i++) {
452 if(FD_ISSET(sockets[i], &fdset)) {
453 SOCKADDR claddr;
454 int clen = sizeof(claddr);
455 int sock = accept(sockets[i], (struct sockaddr*)&claddr, &clen);
456 cm_log("Server", "New connection accepted");
457#ifdef __MINGW32__
458 HANDLE thread;
459 struct pass_entry* e = malloc(sizeof(*e));
460 e->sock = sock;
461 e->ssl = config.ports[i] & (1ULL << 32);
462 e->port = config.ports[i];
463 e->addr = claddr;
464 thread = (HANDLE)_beginthreadex(NULL, 0, tw_server_pass, e, 0, NULL);
465#else
466 pid_t pid = fork();
467 if(pid == 0) {
468 tw_server_pass(sock, config.ports[i] & (1ULL << 32), config.ports[i], claddr);
469 _exit(0);
470 } else {
471 close_socket(sock);
472 }
473#endif
474 }
475 }
476 }
477 }
478}
Note: See TracBrowser for help on using the repository browser.