diff options
Diffstat (limited to 'src/http-server.c')
| -rw-r--r-- | src/http-server.c | 820 |
1 files changed, 820 insertions, 0 deletions
diff --git a/src/http-server.c b/src/http-server.c new file mode 100644 index 0000000..4d038a1 --- /dev/null +++ b/src/http-server.c | |||
| @@ -0,0 +1,820 @@ | |||
| 1 | #include <stdio.h> | ||
| 2 | #include <stdlib.h> | ||
| 3 | #include <stdbool.h> | ||
| 4 | #include <unistd.h> | ||
| 5 | #include <fcntl.h> | ||
| 6 | #include <dirent.h> | ||
| 7 | #include <time.h> | ||
| 8 | #include <string.h> | ||
| 9 | #include <signal.h> | ||
| 10 | #include <errno.h> | ||
| 11 | #include <sys/stat.h> | ||
| 12 | #include <sys/wait.h> | ||
| 13 | #include <sys/socket.h> | ||
| 14 | #include <netinet/in.h> | ||
| 15 | #include <arpa/inet.h> | ||
| 16 | #include <magic.h> | ||
| 17 | |||
| 18 | #include "utils.h" | ||
| 19 | #include "dynamic-array.h" | ||
| 20 | #include "buffer.h" | ||
| 21 | |||
| 22 | #define SERVER "Martin" | ||
| 23 | #define MAX_PATH_LENGTH 1023 | ||
| 24 | #define ALLOWED_METHODS "GET, HEAD, POST" | ||
| 25 | |||
| 26 | #define PROGRAM_ARGUMENTS \ | ||
| 27 | PROGRAM_ARGUMENT_BOOL (help, 'h', "help", "Show this help message" ) \ | ||
| 28 | PROGRAM_ARGUMENT_BOOL (daemonize, 'd', "daemonize", "Daemonize process on startup" ) \ | ||
| 29 | PROGRAM_ARGUMENT_UINT (log_upto, 'l', "log-upto", "Log up to this Syslog priority", LOG_NOTICE ) \ | ||
| 30 | PROGRAM_ARGUMENT_STRING (root, 'r', "root", "Root to server from", "/srv/http") \ | ||
| 31 | PROGRAM_ARGUMENT_STRING (addr, 'a', "addr", "IP address to listen on", "0.0.0.0" ) \ | ||
| 32 | PROGRAM_ARGUMENT_UINT (port, 'p', "port", "Port to listen on", 80) | ||
| 33 | #include "program-arguments.h" | ||
| 34 | |||
| 35 | #define HTTP_REQUEST_METHODS \ | ||
| 36 | HTTP_REQUEST_METHOD (GET ) \ | ||
| 37 | HTTP_REQUEST_METHOD (HEAD) \ | ||
| 38 | HTTP_REQUEST_METHOD (POST) | ||
| 39 | |||
| 40 | #define HTTP_REQUEST_HEADER_KEYS \ | ||
| 41 | HTTP_REQUEST_HEADER_KEY (CONTENT_LENGTH, "Content-Length") \ | ||
| 42 | HTTP_REQUEST_HEADER_KEY (CONNECTION, "Connection" ) | ||
| 43 | |||
| 44 | #define HTTP_CONNECTION_TYPES \ | ||
| 45 | HTTP_CONNECTION_TYPE (CLOSE, "close" ) \ | ||
| 46 | HTTP_CONNECTION_TYPE (KEEP_ALIVE, "keep-alive") | ||
| 47 | |||
| 48 | #define HTTP_RESPONSE_STATUS_CODES \ | ||
| 49 | HTTP_RESPONSE_STATUS_CODE (MOVED_PERMANENTLY, 301, "Moved permanently" ) \ | ||
| 50 | HTTP_RESPONSE_STATUS_CODE (SEE_OTHER, 303, "See Other" ) \ | ||
| 51 | HTTP_RESPONSE_STATUS_CODE (BAD_REQUEST, 400, "Bad Request" ) \ | ||
| 52 | HTTP_RESPONSE_STATUS_CODE (FORBIDDEN, 403, "Forbidden" ) \ | ||
| 53 | HTTP_RESPONSE_STATUS_CODE (NOT_FOUND, 404, "Not Found" ) \ | ||
| 54 | HTTP_RESPONSE_STATUS_CODE (METHOD_NOT_ALLOWED, 405, "Method Not Allowed" ) \ | ||
| 55 | HTTP_RESPONSE_STATUS_CODE (LENGTH_REQUIRED, 411, "Length Required" ) \ | ||
| 56 | HTTP_RESPONSE_STATUS_CODE (CONTENT_TOO_LARGE, 413, "Content Too Large" ) \ | ||
| 57 | HTTP_RESPONSE_STATUS_CODE (URI_TOO_LONG, 414, "URI Too Long" ) \ | ||
| 58 | HTTP_RESPONSE_STATUS_CODE (INTERNAL_SERVER_ERROR, 500, "Internal Server Error" ) \ | ||
| 59 | HTTP_RESPONSE_STATUS_CODE (NOT_IMPLEMENTED, 501, "Not Implemented") | ||
| 60 | |||
| 61 | #define HTTP_REQUEST_METHOD(SYM) HTTP_REQUEST_METHOD_##SYM, | ||
| 62 | enum http_request_method { | ||
| 63 | HTTP_REQUEST_METHODS | ||
| 64 | HTTP_REQUEST_METHOD_COUNT | ||
| 65 | } method; | ||
| 66 | #undef HTTP_REQUEST_METHOD | ||
| 67 | |||
| 68 | #define HTTP_REQUEST_METHOD(SYM) [HTTP_REQUEST_METHOD_##SYM] = #SYM, | ||
| 69 | const char *http_request_method_to_str[HTTP_REQUEST_METHOD_COUNT] = { | ||
| 70 | HTTP_REQUEST_METHODS | ||
| 71 | }; | ||
| 72 | #undef HTTP_REQUEST_METHOD | ||
| 73 | |||
| 74 | #define HTTP_REQUEST_HEADER_KEY(SYM, STR) HTTP_REQUEST_HEADER_KEY_##SYM, | ||
| 75 | enum http_request_header_key { | ||
| 76 | HTTP_REQUEST_HEADER_KEYS | ||
| 77 | HTTP_REQUEST_HEADER_KEY_COUNT | ||
| 78 | }; | ||
| 79 | #undef HTTP_REQUEST_HEADER_KEY | ||
| 80 | |||
| 81 | #define HTTP_REQUEST_HEADER_KEY(SYM, STR) [HTTP_REQUEST_HEADER_KEY_##SYM] = STR, | ||
| 82 | const char *http_request_header_key_to_str[HTTP_REQUEST_HEADER_KEY_COUNT] = { | ||
| 83 | HTTP_REQUEST_HEADER_KEYS | ||
| 84 | }; | ||
| 85 | #undef HTTP_REQUEST_HEADER_KEY | ||
| 86 | |||
| 87 | #define HTTP_CONNECTION_TYPE(SYM, STR) HTTP_CONNECTION_TYPE_##SYM, | ||
| 88 | enum http_connection_type { | ||
| 89 | HTTP_CONNECTION_TYPES | ||
| 90 | HTTP_CONNECTION_TYPE_COUNT | ||
| 91 | }; | ||
| 92 | #undef HTTP_CONNECTION_TYPE | ||
| 93 | |||
| 94 | #define HTTP_CONNECTION_TYPE(SYM, STR) [HTTP_CONNECTION_TYPE_##SYM] = STR, | ||
| 95 | const char *http_connection_type_to_str[HTTP_CONNECTION_TYPE_COUNT] = { | ||
| 96 | HTTP_CONNECTION_TYPES | ||
| 97 | }; | ||
| 98 | #undef HTTP_CONNECTION_TYPE | ||
| 99 | |||
| 100 | #define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) HTTP_RESPONSE_STATUS_CODE_##SYM, | ||
| 101 | enum http_response_status_code { | ||
| 102 | HTTP_RESPONSE_STATUS_CODES | ||
| 103 | HTTP_RESPONSE_STATUS_CODE_COUNT | ||
| 104 | }; | ||
| 105 | #undef HTTP_RESPONSE_STATUS_CODE | ||
| 106 | |||
| 107 | #define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = NUM, | ||
| 108 | int http_response_status_code_to_num[HTTP_RESPONSE_STATUS_CODE_COUNT] = { | ||
| 109 | HTTP_RESPONSE_STATUS_CODES | ||
| 110 | }; | ||
| 111 | #undef HTTP_RESPONSE_STATUS_CODE | ||
| 112 | |||
| 113 | #define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = STR, | ||
| 114 | const char *http_response_status_code_to_str[HTTP_RESPONSE_STATUS_CODE_COUNT] = { | ||
| 115 | HTTP_RESPONSE_STATUS_CODES | ||
| 116 | }; | ||
| 117 | #undef HTTP_RESPONSE_STATUS_CODE | ||
| 118 | |||
| 119 | #define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = sizeof (STR) - 1, | ||
| 120 | int http_response_status_code_to_str_len[HTTP_RESPONSE_STATUS_CODE_COUNT] = { | ||
| 121 | HTTP_RESPONSE_STATUS_CODES | ||
| 122 | }; | ||
| 123 | #undef HTTP_RESPONSE_STATUS_CODE | ||
| 124 | |||
| 125 | int sock; | ||
| 126 | struct sockaddr_in addr; | ||
| 127 | struct buffer buf; | ||
| 128 | char path[MAX_PATH_LENGTH + 1]; | ||
| 129 | ssize_t path_len; | ||
| 130 | ssize_t root_len; | ||
| 131 | char path_resolved[MAX_PATH_LENGTH + 1]; | ||
| 132 | enum http_connection_type connection_type; | ||
| 133 | DIR *dir = NULL; | ||
| 134 | volatile bool should_stop = false; | ||
| 135 | struct program_arguments pa; | ||
| 136 | |||
| 137 | void | ||
| 138 | signal_handler (int sig) | ||
| 139 | { | ||
| 140 | int serrno = errno; | ||
| 141 | |||
| 142 | switch (sig) { | ||
| 143 | case SIGINT: | ||
| 144 | DEBUG ("Received SIGINT"); | ||
| 145 | should_stop = true; | ||
| 146 | break; | ||
| 147 | |||
| 148 | case SIGTERM: | ||
| 149 | DEBUG ("Received SIGTERM"); | ||
| 150 | should_stop = true; | ||
| 151 | break; | ||
| 152 | |||
| 153 | case SIGCHLD: | ||
| 154 | DEBUG ("Received SIGCHLD"); | ||
| 155 | for (;;) { | ||
| 156 | int status; | ||
| 157 | int pid = waitpid (WAIT_ANY, &status, WNOHANG); | ||
| 158 | if (pid <= 0) { | ||
| 159 | if (pid == -1) | ||
| 160 | DEBUG ("Failed to wait for any child: %s", strerror (errno)); | ||
| 161 | goto cleanup; | ||
| 162 | } DEBUG ("%d exited with %d", pid, status); | ||
| 163 | } break; | ||
| 164 | |||
| 165 | default: DEBUG ("Received unhandled %s", strsignal (sig)); | ||
| 166 | } | ||
| 167 | |||
| 168 | cleanup: | ||
| 169 | errno = serrno; | ||
| 170 | } | ||
| 171 | |||
| 172 | void | ||
| 173 | connection_lost (void) | ||
| 174 | { | ||
| 175 | INFO ("Connection lost: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); | ||
| 176 | _exit (EXIT_FAILURE); | ||
| 177 | } | ||
| 178 | |||
| 179 | void | ||
| 180 | respond_with_error (enum http_response_status_code code, const char *msg) | ||
| 181 | { | ||
| 182 | ASSERT (http_response_status_code_to_num[code] >= 400); | ||
| 183 | ASSERT (http_response_status_code_to_num[code] <= 599); | ||
| 184 | |||
| 185 | if (code < 500) { | ||
| 186 | NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s %d", | ||
| 187 | SOCKADDR_IN_SPLIT (addr), | ||
| 188 | method != HTTP_REQUEST_METHOD_COUNT | ||
| 189 | ? http_request_method_to_str[method] : "(unknown)", | ||
| 190 | path + root_len, http_response_status_code_to_num[code]); | ||
| 191 | } else { | ||
| 192 | WARNING ("Access: "SOCKADDR_IN_FMT" %s %s %d", | ||
| 193 | SOCKADDR_IN_SPLIT (addr), | ||
| 194 | http_request_method_to_str[method], | ||
| 195 | path + root_len, http_response_status_code_to_num[code]); | ||
| 196 | } | ||
| 197 | |||
| 198 | if (sock == -1) connection_lost (); | ||
| 199 | |||
| 200 | buf.head_read = buf.data; | ||
| 201 | buf.head_write = buf.data; | ||
| 202 | int bytes_written; | ||
| 203 | |||
| 204 | buf.head_write += bytes_written = | ||
| 205 | sprintf (buf.head_write, "HTTP/1.1 %d %s\r\n" | ||
| 206 | "Server: " SERVER "\r\n" | ||
| 207 | "Content-Type: text/html\r\n" | ||
| 208 | "Connection: close\r\n", | ||
| 209 | http_response_status_code_to_num[code], | ||
| 210 | http_response_status_code_to_str[code]); | ||
| 211 | |||
| 212 | time_t now = time (NULL); | ||
| 213 | struct tm gmt; | ||
| 214 | gmtime_r (&now, &gmt); | ||
| 215 | buf.head_write += bytes_written = | ||
| 216 | strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), | ||
| 217 | "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); | ||
| 218 | |||
| 219 | if (msg) { | ||
| 220 | buf.head_write += bytes_written = | ||
| 221 | sprintf (buf.head_write, | ||
| 222 | "Content-Length: %d\r\n" | ||
| 223 | "\r\n" | ||
| 224 | "<html>" | ||
| 225 | "<body>" | ||
| 226 | "<h1 style=\"text-align: center;\">%d %s</h1>" | ||
| 227 | "<h2 style=\"text-align: center;\">%s</h2>" | ||
| 228 | "</body>" | ||
| 229 | "</html>", | ||
| 230 | (int) (101 + 3 + http_response_status_code_to_str_len[code] + strlen (msg)), | ||
| 231 | http_response_status_code_to_num[code], | ||
| 232 | http_response_status_code_to_str[code], | ||
| 233 | msg); | ||
| 234 | } else { | ||
| 235 | buf.head_write += bytes_written = | ||
| 236 | sprintf (buf.head_write, | ||
| 237 | "Content-Length: %d\r\n" | ||
| 238 | "\r\n" | ||
| 239 | "<html>" | ||
| 240 | "<body>" | ||
| 241 | "<h1 style=\"text-align: center;\">%d %s</h1>" | ||
| 242 | "</body>" | ||
| 243 | "</html>", | ||
| 244 | 64 + 3 + http_response_status_code_to_str_len[code], | ||
| 245 | http_response_status_code_to_num[code], | ||
| 246 | http_response_status_code_to_str[code]); | ||
| 247 | } | ||
| 248 | |||
| 249 | write (sock, buf.head_read, buf.head_write - buf.head_read); | ||
| 250 | DEBUG ("Responding with error:\n%.*s\n", | ||
| 251 | (int) (buf.head_write - buf.head_read), buf.head_read); | ||
| 252 | _exit (code); | ||
| 253 | } | ||
| 254 | #define RESPOND_WITH_ERROR(SYM, MSG) \ | ||
| 255 | respond_with_error (HTTP_RESPONSE_STATUS_CODE_##SYM, MSG) | ||
| 256 | |||
| 257 | void | ||
| 258 | redirect (enum http_response_status_code code, const char *uri) | ||
| 259 | { | ||
| 260 | ASSERT (http_response_status_code_to_num[code] >= 300); | ||
| 261 | ASSERT (http_response_status_code_to_num[code] <= 399); | ||
| 262 | |||
| 263 | NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s %d", | ||
| 264 | SOCKADDR_IN_SPLIT (addr), http_request_method_to_str[method], | ||
| 265 | path + root_len, http_response_status_code_to_num[code]); | ||
| 266 | |||
| 267 | if (sock == -1) connection_lost (); | ||
| 268 | |||
| 269 | buf.head_read = buf.data; | ||
| 270 | buf.head_write = buf.data; | ||
| 271 | int bytes_written; | ||
| 272 | |||
| 273 | buf.head_write += bytes_written = | ||
| 274 | sprintf (buf.head_write, "HTTP/1.1 %d %s\r\n" | ||
| 275 | "Server: " SERVER "\r\n" | ||
| 276 | "Location: %s\r\n" | ||
| 277 | "Content-Length: 0\r\n" | ||
| 278 | "Connection: %s\r\n", | ||
| 279 | http_response_status_code_to_num[code], | ||
| 280 | http_response_status_code_to_str[code], | ||
| 281 | uri, http_connection_type_to_str[connection_type]); | ||
| 282 | |||
| 283 | time_t now = time (NULL); | ||
| 284 | struct tm gmt; | ||
| 285 | gmtime_r (&now, &gmt); | ||
| 286 | buf.head_write += bytes_written = | ||
| 287 | strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), | ||
| 288 | "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); | ||
| 289 | |||
| 290 | write (sock, buf.head_read, buf.head_write - buf.head_read); | ||
| 291 | DEBUG ("Responding with redirect:\n%.*s\n", | ||
| 292 | (int) (buf.head_write - buf.head_read), buf.head_read); | ||
| 293 | _exit (code); | ||
| 294 | } | ||
| 295 | #define REDIRECT(SYM, URI) \ | ||
| 296 | redirect (HTTP_RESPONSE_STATUS_CODE_##SYM, URI) | ||
| 297 | |||
| 298 | magic_t magic; | ||
| 299 | |||
| 300 | const char * | ||
| 301 | get_mimetype (const char *filename, int fd) | ||
| 302 | { | ||
| 303 | const char *ext = strrchr (filename, '.'); | ||
| 304 | if (!ext) goto fallback; | ||
| 305 | ext += 1; | ||
| 306 | if (strcmp (ext, "html") == 0) return "text/html"; | ||
| 307 | if (strcmp (ext, "css" ) == 0) return "text/css"; | ||
| 308 | if (strcmp (ext, "js" ) == 0) return "text/javascript"; | ||
| 309 | |||
| 310 | fallback: | ||
| 311 | return magic_descriptor (magic, fd) ?: "application/octet-stream"; | ||
| 312 | } | ||
| 313 | |||
| 314 | int | ||
| 315 | pretty_size (char *s, off_t size) | ||
| 316 | { | ||
| 317 | const char units[] = "BKMGTP"; | ||
| 318 | int i = 0; | ||
| 319 | double floating_size = (double) size; | ||
| 320 | while (floating_size >= 1024 && i < (int) (sizeof (units) - 2)) { | ||
| 321 | floating_size /= 1024; | ||
| 322 | i++; | ||
| 323 | } | ||
| 324 | return s ? sprintf (s, "%.1lf%c", floating_size, units[i]) | ||
| 325 | : snprintf (NULL, 0, "%.1lf%c", floating_size, units[i]); | ||
| 326 | } | ||
| 327 | |||
| 328 | off_t | ||
| 329 | get_content_length (int fd, struct stat *st) | ||
| 330 | { | ||
| 331 | if (S_ISREG (st->st_mode)) | ||
| 332 | return st->st_size; | ||
| 333 | |||
| 334 | off_t content_length = 1093 + 2*(path_len - root_len); | ||
| 335 | dir = fdopendir (fd); | ||
| 336 | struct dirent *entry; | ||
| 337 | while ((entry = readdir (dir)) != NULL) { | ||
| 338 | if (entry->d_name[0] == '.') { | ||
| 339 | if (entry->d_name[1] == '\0') continue; | ||
| 340 | if (entry->d_name[1] == '.') { | ||
| 341 | if (entry->d_name[2] == '\0') continue; | ||
| 342 | } | ||
| 343 | } | ||
| 344 | |||
| 345 | content_length += 70 + 2*strlen (entry->d_name); | ||
| 346 | |||
| 347 | strcpy (path + path_len, entry->d_name); | ||
| 348 | struct stat entry_st; | ||
| 349 | stat (path, &entry_st); | ||
| 350 | if (S_ISREG (entry_st.st_mode)) | ||
| 351 | content_length += pretty_size (NULL, entry_st.st_size); | ||
| 352 | } | ||
| 353 | |||
| 354 | return content_length; | ||
| 355 | } | ||
| 356 | |||
| 357 | void | ||
| 358 | write_content (int fd, struct stat *st) | ||
| 359 | { | ||
| 360 | if (S_ISREG (st->st_mode)) { | ||
| 361 | ssize_t bytes_read = read (fd, buf.head_write, BUFFER_SPACE_WRITE (buf)); | ||
| 362 | if (bytes_read == -1) RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); | ||
| 363 | buf.head_write += bytes_read; | ||
| 364 | if (write (sock, buf.head_read, buf.head_write - buf.head_read) == -1) | ||
| 365 | connection_lost (); | ||
| 366 | st->st_size -= bytes_read; | ||
| 367 | while (st->st_size > 0) { | ||
| 368 | st->st_size -= bytes_read = | ||
| 369 | read (fd, buf.data, st->st_size > BUFFER_SIZE ? BUFFER_SIZE : st->st_size); | ||
| 370 | if (bytes_read <= 0) RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); | ||
| 371 | if (write (sock, buf.data, bytes_read) == -1) | ||
| 372 | connection_lost (); | ||
| 373 | } | ||
| 374 | if (connection_type == HTTP_CONNECTION_TYPE_KEEP_ALIVE) | ||
| 375 | close (fd); | ||
| 376 | return; | ||
| 377 | } | ||
| 378 | |||
| 379 | buf.head_write += | ||
| 380 | sprintf (buf.head_write, | ||
| 381 | "<?xml version=\"1.0\" encoding=\"utf-8\"?>" | ||
| 382 | "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" | ||
| 383 | "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">" | ||
| 384 | "<head>" | ||
| 385 | "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"></meta>" | ||
| 386 | "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></meta>" | ||
| 387 | "<title>Index of %.*s</title>" | ||
| 388 | "<link rel=\"stylesheet\" href=\"/custom.css\"></link>" | ||
| 389 | "</head>" | ||
| 390 | "<body>" | ||
| 391 | "<nav>" | ||
| 392 | "<ul>" | ||
| 393 | "<li><span>navigation:</span>" | ||
| 394 | "<ul>" | ||
| 395 | "<li>[<a accesskey=\"h\" href=\"/\">home</a>]</li>" | ||
| 396 | "<li>[<a accesskey=\"r\" href=\"/files/\">root</a>]</li>" | ||
| 397 | "<li>[<a accesskey=\"u\" href=\"../\">up</a>]</li>" | ||
| 398 | "</ul>" | ||
| 399 | "</li>" | ||
| 400 | "<li><span>networks:</span>" | ||
| 401 | "<ul>" | ||
| 402 | "<li>[<a href=\"https:/www.michalec.dev/files/\">www</a>]</li>" | ||
| 403 | "<li>[<a href=\"http:/ygg.michalec.dev/files/\">ygg</a>]</li>" | ||
| 404 | "<li>[<a href=\"http:/i2p.michalec.dev/files/\">i2p</a>]</li>" | ||
| 405 | "</ul>" | ||
| 406 | "</li>" | ||
| 407 | "</ul>" | ||
| 408 | "</nav>" | ||
| 409 | "<div id=\"content\" class=\"content\">" | ||
| 410 | "<h1 class=\"title\">%.*s</h1>" | ||
| 411 | "<hr></hr>" | ||
| 412 | "<table>" | ||
| 413 | "<tr>" | ||
| 414 | "<th style=\"text-align:left\">name</th>" | ||
| 415 | "<th style=\"text-align:left\">size</th>" | ||
| 416 | "<th style=\"text-align:left\">date</th>" | ||
| 417 | "</tr>", | ||
| 418 | (int) (path_len - root_len), path + root_len, | ||
| 419 | (int) (path_len - root_len), path + root_len); | ||
| 420 | |||
| 421 | ASSERT (dir); | ||
| 422 | rewinddir (dir); | ||
| 423 | struct dirent *entry; | ||
| 424 | while ((entry = readdir (dir)) != NULL) { | ||
| 425 | if (entry->d_name[0] == '.') { | ||
| 426 | if (entry->d_name[1] == '\0') continue; | ||
| 427 | if (entry->d_name[1] == '.') { | ||
| 428 | if (entry->d_name[2] == '\0') continue; | ||
| 429 | } | ||
| 430 | } | ||
| 431 | |||
| 432 | strcpy (path + path_len, entry->d_name); | ||
| 433 | struct stat entry_st; | ||
| 434 | off_t entry_size = 0; | ||
| 435 | stat (path, &entry_st); | ||
| 436 | if (S_ISREG (entry_st.st_mode)) | ||
| 437 | entry_size = entry_st.st_size; | ||
| 438 | buf.head_write += sprintf (buf.head_write, "<tr><td><a href=\"%s\">%s</a></td><td>", | ||
| 439 | entry->d_name, entry->d_name); | ||
| 440 | if (entry_size) buf.head_write += pretty_size (buf.head_write, entry_size); | ||
| 441 | buf.head_write += sprintf (buf.head_write, "</td><td>"); | ||
| 442 | struct tm gmt; | ||
| 443 | gmtime_r (&entry_st.st_mtime, &gmt); | ||
| 444 | buf.head_write += | ||
| 445 | strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), | ||
| 446 | "%d-%m-%Y %H:%M:%S", &gmt); | ||
| 447 | buf.head_write += sprintf (buf.head_write, "</td></tr>"); | ||
| 448 | } | ||
| 449 | |||
| 450 | buf.head_write += sprintf (buf.head_write, "</table></div></body></html>"); | ||
| 451 | |||
| 452 | while (buf.head_read < buf.head_write) { | ||
| 453 | ssize_t bytes_written = | ||
| 454 | write (sock, buf.head_read, buf.head_write - buf.head_read); | ||
| 455 | if (bytes_written == -1) | ||
| 456 | connection_lost (); | ||
| 457 | buf.head_read += bytes_written; | ||
| 458 | } | ||
| 459 | |||
| 460 | if (connection_type == HTTP_CONNECTION_TYPE_KEEP_ALIVE) { | ||
| 461 | closedir (dir); | ||
| 462 | dir = NULL; | ||
| 463 | } | ||
| 464 | } | ||
| 465 | |||
| 466 | void | ||
| 467 | handle_connection (void) | ||
| 468 | { | ||
| 469 | again: | ||
| 470 | path_len = root_len; | ||
| 471 | method = HTTP_REQUEST_METHOD_COUNT; | ||
| 472 | buf.head_read = buf.data; | ||
| 473 | buf.head_write = buf.data; | ||
| 474 | |||
| 475 | DEBUG ("Parsing header"); | ||
| 476 | // METHOD | ||
| 477 | char *sym = buffer__consume_until (&buf, &sock, ' '); | ||
| 478 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 479 | size_t sym_len = buf.head_read - sym - 1; | ||
| 480 | DEBUG ("Parsed method: %.*s", (int) sym_len, sym); | ||
| 481 | for (int i = 0; i < HTTP_REQUEST_METHOD_COUNT; ++i) { | ||
| 482 | if (strncmp (sym, http_request_method_to_str[i], sym_len)) | ||
| 483 | continue; | ||
| 484 | method = i; | ||
| 485 | break; | ||
| 486 | } | ||
| 487 | if (method == HTTP_REQUEST_METHOD_COUNT) | ||
| 488 | RESPOND_WITH_ERROR (NOT_IMPLEMENTED, NULL); | ||
| 489 | |||
| 490 | // URI | ||
| 491 | sym = buffer__consume_until (&buf, &sock, ' '); | ||
| 492 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 493 | sym_len = buf.head_read - sym - 1; | ||
| 494 | DEBUG ("Parsed URI: %.*s", (int) sym_len, sym); | ||
| 495 | if (sym_len > MAX_PATH_LENGTH) | ||
| 496 | RESPOND_WITH_ERROR (URI_TOO_LONG, NULL); | ||
| 497 | memcpy (path + path_len, sym, sym_len); | ||
| 498 | path_len += sym_len; | ||
| 499 | path[path_len] = '\0'; | ||
| 500 | |||
| 501 | // VERSION | ||
| 502 | sym = buffer__consume_until (&buf, &sock, '\r'); | ||
| 503 | if (!sym || buffer__consume_one (&buf, &sock) != '\n') | ||
| 504 | RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 505 | sym_len = buf.head_read - sym - 2; | ||
| 506 | DEBUG ("Parsed version: %.*s", (int) sym_len, sym); | ||
| 507 | |||
| 508 | // HEADERS | ||
| 509 | ssize_t content_length = -1; | ||
| 510 | connection_type = HTTP_CONNECTION_TYPE_CLOSE; | ||
| 511 | while (buffer__peek (&buf, &sock) != '\r') { | ||
| 512 | sym = buffer__consume_until (&buf, &sock, ':'); | ||
| 513 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 514 | sym_len = buf.head_read - sym - 1; | ||
| 515 | DEBUG ("Parsed header key: %.*s", (int) sym_len, sym); | ||
| 516 | enum http_request_header_key key = HTTP_REQUEST_HEADER_KEY_COUNT; | ||
| 517 | for (int i = 0; i < HTTP_REQUEST_HEADER_KEY_COUNT; ++i) { | ||
| 518 | if (strncmp (sym, http_request_header_key_to_str[i], sym_len)) | ||
| 519 | continue; | ||
| 520 | key = i; | ||
| 521 | break; | ||
| 522 | } | ||
| 523 | |||
| 524 | sym = buffer__consume_while_one_of (&buf, &sock, " \t"); | ||
| 525 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 526 | |||
| 527 | sym = buffer__consume_until_one_of (&buf, &sock, " \t\r"); | ||
| 528 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 529 | sym_len = buf.head_read - sym - 1; | ||
| 530 | DEBUG ("Parsed header value: %.*s", (int) sym_len, sym); | ||
| 531 | switch (key) { | ||
| 532 | case HTTP_REQUEST_HEADER_KEY_CONTENT_LENGTH: | ||
| 533 | sscanf (sym, "%ld", &content_length); | ||
| 534 | break; | ||
| 535 | case HTTP_REQUEST_HEADER_KEY_CONNECTION: | ||
| 536 | connection_type = HTTP_CONNECTION_TYPE_COUNT; | ||
| 537 | for (int i = 0; i < HTTP_CONNECTION_TYPE_COUNT; ++i) { | ||
| 538 | if (strncmp (sym, http_connection_type_to_str[i], sym_len)) | ||
| 539 | continue; | ||
| 540 | connection_type = i; | ||
| 541 | break; | ||
| 542 | } | ||
| 543 | if (connection_type == HTTP_CONNECTION_TYPE_COUNT) | ||
| 544 | RESPOND_WITH_ERROR (BAD_REQUEST, "Unknown Connection value"); | ||
| 545 | break; | ||
| 546 | } | ||
| 547 | |||
| 548 | sym = buffer__consume_until (&buf, &sock, '\n'); | ||
| 549 | if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 550 | } buffer__consume_one (&buf, &sock); | ||
| 551 | if (buffer__consume_one (&buf, &sock) != '\n') | ||
| 552 | RESPOND_WITH_ERROR (BAD_REQUEST, NULL); | ||
| 553 | DEBUG ("Finished parsing header"); | ||
| 554 | |||
| 555 | if (method == HTTP_REQUEST_METHOD_POST) { // POST (simply echo) | ||
| 556 | if (content_length == -1) | ||
| 557 | RESPOND_WITH_ERROR (LENGTH_REQUIRED, NULL); | ||
| 558 | |||
| 559 | const char *template = | ||
| 560 | "HTTP/1.1 200 OK\r\n" | ||
| 561 | "Server: " SERVER "\r\n" | ||
| 562 | "Connection: %s\r\n" | ||
| 563 | "Content-Type: text/plain\r\n" | ||
| 564 | "Content-Length: %lu\r\n" | ||
| 565 | "\r\n"; | ||
| 566 | off_t bytes_written = snprintf (NULL, 0, template, | ||
| 567 | http_connection_type_to_str[connection_type], content_length); | ||
| 568 | size_t buffout_size = bytes_written + content_length; | ||
| 569 | char *buffout = malloc (buffout_size); | ||
| 570 | if (!buffout) | ||
| 571 | RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, "Server out of memory"); | ||
| 572 | snprintf (buffout, bytes_written + 1, template, | ||
| 573 | http_connection_type_to_str[connection_type], content_length); | ||
| 574 | |||
| 575 | size_t buf_size = buf.head_write - buf.head_read; | ||
| 576 | memcpy (buffout + bytes_written, buf.head_read, buf_size); | ||
| 577 | content_length -= buf_size; | ||
| 578 | bytes_written += buf_size; | ||
| 579 | |||
| 580 | while (content_length > 0) { | ||
| 581 | ssize_t bytes_read = read (sock, buffout + bytes_written, content_length); | ||
| 582 | if (bytes_read <= 0) connection_lost (); | ||
| 583 | content_length -= bytes_read; | ||
| 584 | bytes_written += bytes_read; | ||
| 585 | } | ||
| 586 | |||
| 587 | write (sock, buffout, buffout_size); | ||
| 588 | free (buffout); | ||
| 589 | } else { // GET/HEAD | ||
| 590 | buf.head_read = buf.data; | ||
| 591 | buf.head_write = buf.data; | ||
| 592 | |||
| 593 | if (content_length > 0) { | ||
| 594 | if (!buffer__skip_n (&buf, &sock, content_length)) | ||
| 595 | connection_lost (); | ||
| 596 | } | ||
| 597 | |||
| 598 | // if (path_len == root_len + 1 && path[path_len - 1] == '/') { | ||
| 599 | // strcpy (path + path_len, "en/"); | ||
| 600 | // REDIRECT (MOVED_PERMANENTLY, path + root_len); | ||
| 601 | // goto done; | ||
| 602 | // } | ||
| 603 | |||
| 604 | if (!realpath (path, path_resolved)) { | ||
| 605 | switch (errno) { | ||
| 606 | case EACCES: RESPOND_WITH_ERROR (FORBIDDEN, NULL); | ||
| 607 | case ENOENT: RESPOND_WITH_ERROR (NOT_FOUND, NULL); | ||
| 608 | } | ||
| 609 | } | ||
| 610 | if (strncmp (path_resolved, pa.root, root_len)) | ||
| 611 | RESPOND_WITH_ERROR (FORBIDDEN, NULL); | ||
| 612 | |||
| 613 | int fd = open (path_resolved, O_RDONLY); | ||
| 614 | if (fd == -1) { | ||
| 615 | switch (errno) { | ||
| 616 | case EACCES: RESPOND_WITH_ERROR (FORBIDDEN, NULL); | ||
| 617 | case ENOENT: RESPOND_WITH_ERROR (NOT_FOUND, NULL); | ||
| 618 | } | ||
| 619 | } | ||
| 620 | struct stat st; | ||
| 621 | if (fstat (fd, &st) == -1) | ||
| 622 | RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); | ||
| 623 | if (S_ISDIR (st.st_mode)) { | ||
| 624 | if (path[path_len - 1] != '/') { | ||
| 625 | strcpy (path + path_len, "/"); | ||
| 626 | REDIRECT (MOVED_PERMANENTLY, path + root_len); | ||
| 627 | goto done; | ||
| 628 | } | ||
| 629 | |||
| 630 | strcpy (path + path_len, "index.html"); | ||
| 631 | int index_fd = open (path, O_RDONLY); | ||
| 632 | if (index_fd == -1 && errno == EACCES) | ||
| 633 | RESPOND_WITH_ERROR (FORBIDDEN, NULL); | ||
| 634 | if (index_fd != -1) { | ||
| 635 | close (fd); | ||
| 636 | fd = index_fd; | ||
| 637 | if (fstat (fd, &st) == -1) | ||
| 638 | RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); | ||
| 639 | } | ||
| 640 | } | ||
| 641 | |||
| 642 | off_t bytes_written; | ||
| 643 | buf.head_write += bytes_written = | ||
| 644 | sprintf (buf.head_write, | ||
| 645 | "HTTP/1.1 200 OK\r\n" | ||
| 646 | "Server: " SERVER "\r\n" | ||
| 647 | "Connection: %s\r\n", http_connection_type_to_str[connection_type]); | ||
| 648 | |||
| 649 | time_t now = time (NULL); | ||
| 650 | struct tm gmt; | ||
| 651 | gmtime_r (&now, &gmt); | ||
| 652 | buf.head_write += bytes_written = | ||
| 653 | strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), | ||
| 654 | "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); | ||
| 655 | |||
| 656 | gmtime_r (&st.st_mtime, &gmt); | ||
| 657 | buf.head_write += bytes_written = | ||
| 658 | strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), | ||
| 659 | "Last-Modified: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); | ||
| 660 | |||
| 661 | buf.head_write += bytes_written = | ||
| 662 | sprintf (buf.head_write, | ||
| 663 | "Content-Type: %s\r\n" | ||
| 664 | "Content-Length: %lu\r\n" | ||
| 665 | "\r\n", | ||
| 666 | S_ISDIR (st.st_mode) ? "text/html" : get_mimetype (path, fd), | ||
| 667 | get_content_length (fd, &st)); | ||
| 668 | |||
| 669 | if (method == HTTP_REQUEST_METHOD_HEAD) { | ||
| 670 | if (write (sock, buf.head_read, buf.head_write - buf.head_read) == -1) | ||
| 671 | connection_lost (); | ||
| 672 | close (fd); | ||
| 673 | } else if (method == HTTP_REQUEST_METHOD_GET) { | ||
| 674 | write_content (fd, &st); | ||
| 675 | } | ||
| 676 | } | ||
| 677 | |||
| 678 | NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s 200", SOCKADDR_IN_SPLIT (addr), | ||
| 679 | http_request_method_to_str[method], path + root_len); | ||
| 680 | done: | ||
| 681 | switch (connection_type) { | ||
| 682 | case HTTP_CONNECTION_TYPE_CLOSE: _exit (EXIT_SUCCESS); | ||
| 683 | case HTTP_CONNECTION_TYPE_KEEP_ALIVE: goto again; | ||
| 684 | } | ||
| 685 | } | ||
| 686 | |||
| 687 | int | ||
| 688 | main (int argc, char *argv[]) | ||
| 689 | { | ||
| 690 | pa = parse_program_arguments (argc, argv); | ||
| 691 | if (pa.help) { | ||
| 692 | print_help (pa.program_name); | ||
| 693 | exit (EXIT_SUCCESS); | ||
| 694 | } | ||
| 695 | |||
| 696 | setlogmask (LOG_UPTO (pa.log_upto)); | ||
| 697 | openlog (basename (pa.program_name), | ||
| 698 | LOG_PID | (pa.daemonize ? 0 : LOG_PERROR), LOG_DAEMON); | ||
| 699 | |||
| 700 | if (pa.daemonize) { | ||
| 701 | close (STDIN_FILENO); | ||
| 702 | close (STDOUT_FILENO); | ||
| 703 | close (STDERR_FILENO); | ||
| 704 | DEBUG ("Closed standard file descriptors"); | ||
| 705 | } | ||
| 706 | |||
| 707 | struct sigaction sa = { .sa_handler = signal_handler }; | ||
| 708 | sigaction (SIGINT, &sa, NULL); | ||
| 709 | sigaction (SIGTERM, &sa, NULL); | ||
| 710 | sa.sa_flags = SA_RESTART; | ||
| 711 | sigaction (SIGHUP, &sa, NULL); | ||
| 712 | sigaction (SIGCHLD, &sa, NULL); | ||
| 713 | DEBUG ("Registered signal handlers"); | ||
| 714 | |||
| 715 | if (pa.daemonize) { | ||
| 716 | pid_t pid = fork (); | ||
| 717 | if (pid == -1) { | ||
| 718 | EMERGENCY ("Unable to fork: %s", strerror (errno)); | ||
| 719 | exit (EXIT_FAILURE); | ||
| 720 | } | ||
| 721 | |||
| 722 | if (pid > 0) | ||
| 723 | exit (EXIT_SUCCESS); | ||
| 724 | DEBUG ("Forked"); | ||
| 725 | |||
| 726 | pid_t sid = setsid (); | ||
| 727 | if (sid == -1) { | ||
| 728 | EMERGENCY ("Unable to set SID: %s", strerror (errno)); | ||
| 729 | exit (EXIT_FAILURE); | ||
| 730 | } DEBUG ("Set sid to %d", sid); | ||
| 731 | } | ||
| 732 | |||
| 733 | umask (0); | ||
| 734 | |||
| 735 | if (chdir (pa.root) == -1) { | ||
| 736 | EMERGENCY ("Unable to chdir to `%s': %s", pa.root, strerror (errno)); | ||
| 737 | exit (EXIT_FAILURE); | ||
| 738 | } DEBUG ("Changed directory to `%s'", pa.root); | ||
| 739 | root_len = strlen (pa.root); | ||
| 740 | if (root_len > MAX_PATH_LENGTH) { | ||
| 741 | EMERGENCY ("Path to root is too long: %ld > %d", root_len, MAX_PATH_LENGTH); | ||
| 742 | exit (EXIT_FAILURE); | ||
| 743 | } memcpy (path, pa.root, root_len + 1); | ||
| 744 | |||
| 745 | magic = magic_open (MAGIC_MIME_TYPE); | ||
| 746 | if (!magic) { | ||
| 747 | EMERGENCY ("Failed to open magic: %s", magic_error (magic)); | ||
| 748 | exit (EXIT_FAILURE); | ||
| 749 | } | ||
| 750 | if (magic_load (magic, NULL) == -1) { | ||
| 751 | EMERGENCY ("Failed to load magic: %s", magic_error (magic)); | ||
| 752 | exit (EXIT_FAILURE); | ||
| 753 | } | ||
| 754 | |||
| 755 | int listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 756 | if (listener == -1) { | ||
| 757 | EMERGENCY ("Failed to create socket: %s", strerror (errno)); | ||
| 758 | exit (EXIT_FAILURE); | ||
| 759 | } DEBUG ("Created socket"); | ||
| 760 | |||
| 761 | int reuseaddr = 1; | ||
| 762 | setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, | ||
| 763 | &reuseaddr, sizeof (reuseaddr)); | ||
| 764 | |||
| 765 | addr.sin_family = AF_INET; | ||
| 766 | addr.sin_port = htons (pa.port); | ||
| 767 | if (!inet_aton (pa.addr, &addr.sin_addr)) { | ||
| 768 | EMERGENCY ("Failed to convert address %s", pa.addr); | ||
| 769 | exit (EXIT_FAILURE); | ||
| 770 | } | ||
| 771 | |||
| 772 | if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) { | ||
| 773 | EMERGENCY ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s", | ||
| 774 | SOCKADDR_IN_SPLIT (addr), strerror (errno)); | ||
| 775 | exit (EXIT_FAILURE); | ||
| 776 | } | ||
| 777 | |||
| 778 | if (listen (listener, 1)) { | ||
| 779 | EMERGENCY ("Failed to listen on "SOCKADDR_IN_FMT": %s", | ||
| 780 | SOCKADDR_IN_SPLIT (addr), strerror (errno)); | ||
| 781 | exit (EXIT_FAILURE); | ||
| 782 | } | ||
| 783 | NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); | ||
| 784 | |||
| 785 | NOTICE ("Server started"); | ||
| 786 | while (!should_stop) { | ||
| 787 | socklen_t length = sizeof (addr); | ||
| 788 | sock = accept (listener, (struct sockaddr *) &addr, &length); | ||
| 789 | if (sock == -1) { | ||
| 790 | if (errno != EINTR) | ||
| 791 | ERROR ("Failed to accept connection: %s", strerror (errno)); | ||
| 792 | continue; | ||
| 793 | } | ||
| 794 | DEBUG ("Accepted connection: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); | ||
| 795 | |||
| 796 | pid_t pid = fork (); | ||
| 797 | if (pid == -1) { | ||
| 798 | ERROR ("Failed to fork: %s", strerror (errno)); | ||
| 799 | if (close (sock) == -1) | ||
| 800 | WARNING ("close: %s", strerror (errno)); | ||
| 801 | continue; | ||
| 802 | } | ||
| 803 | |||
| 804 | if (pid != 0) { | ||
| 805 | if (close (sock) == -1) // NOTE(cmmm): neccessary, would leak | ||
| 806 | WARNING ("close: %s", strerror (errno)); | ||
| 807 | continue; | ||
| 808 | } | ||
| 809 | |||
| 810 | // if (close (listener) == -1) // NOTE(cmmm): unneccessary syscall for each connection | ||
| 811 | // ERROR ("close: %s", strerror (errno)); | ||
| 812 | |||
| 813 | handle_connection (); | ||
| 814 | } | ||
| 815 | |||
| 816 | NOTICE ("Server stopping"); | ||
| 817 | while (waitpid (-1, NULL, 0) > 0); | ||
| 818 | NOTICE ("Server stopped"); | ||
| 819 | return EXIT_SUCCESS; | ||
| 820 | } | ||
