From f3c478bc0ce492e9ebc516f445312dfd9e6a2a7a Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 12:28:03 +0300 Subject: publish --- src/http-server.c | 820 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 820 insertions(+) create mode 100644 src/http-server.c (limited to 'src/http-server.c') 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 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "dynamic-array.h" +#include "buffer.h" + +#define SERVER "Martin" +#define MAX_PATH_LENGTH 1023 +#define ALLOWED_METHODS "GET, HEAD, POST" + +#define PROGRAM_ARGUMENTS \ + PROGRAM_ARGUMENT_BOOL (help, 'h', "help", "Show this help message" ) \ + PROGRAM_ARGUMENT_BOOL (daemonize, 'd', "daemonize", "Daemonize process on startup" ) \ + PROGRAM_ARGUMENT_UINT (log_upto, 'l', "log-upto", "Log up to this Syslog priority", LOG_NOTICE ) \ + PROGRAM_ARGUMENT_STRING (root, 'r', "root", "Root to server from", "/srv/http") \ + PROGRAM_ARGUMENT_STRING (addr, 'a', "addr", "IP address to listen on", "0.0.0.0" ) \ + PROGRAM_ARGUMENT_UINT (port, 'p', "port", "Port to listen on", 80) +#include "program-arguments.h" + +#define HTTP_REQUEST_METHODS \ + HTTP_REQUEST_METHOD (GET ) \ + HTTP_REQUEST_METHOD (HEAD) \ + HTTP_REQUEST_METHOD (POST) + +#define HTTP_REQUEST_HEADER_KEYS \ + HTTP_REQUEST_HEADER_KEY (CONTENT_LENGTH, "Content-Length") \ + HTTP_REQUEST_HEADER_KEY (CONNECTION, "Connection" ) + +#define HTTP_CONNECTION_TYPES \ + HTTP_CONNECTION_TYPE (CLOSE, "close" ) \ + HTTP_CONNECTION_TYPE (KEEP_ALIVE, "keep-alive") + +#define HTTP_RESPONSE_STATUS_CODES \ + HTTP_RESPONSE_STATUS_CODE (MOVED_PERMANENTLY, 301, "Moved permanently" ) \ + HTTP_RESPONSE_STATUS_CODE (SEE_OTHER, 303, "See Other" ) \ + HTTP_RESPONSE_STATUS_CODE (BAD_REQUEST, 400, "Bad Request" ) \ + HTTP_RESPONSE_STATUS_CODE (FORBIDDEN, 403, "Forbidden" ) \ + HTTP_RESPONSE_STATUS_CODE (NOT_FOUND, 404, "Not Found" ) \ + HTTP_RESPONSE_STATUS_CODE (METHOD_NOT_ALLOWED, 405, "Method Not Allowed" ) \ + HTTP_RESPONSE_STATUS_CODE (LENGTH_REQUIRED, 411, "Length Required" ) \ + HTTP_RESPONSE_STATUS_CODE (CONTENT_TOO_LARGE, 413, "Content Too Large" ) \ + HTTP_RESPONSE_STATUS_CODE (URI_TOO_LONG, 414, "URI Too Long" ) \ + HTTP_RESPONSE_STATUS_CODE (INTERNAL_SERVER_ERROR, 500, "Internal Server Error" ) \ + HTTP_RESPONSE_STATUS_CODE (NOT_IMPLEMENTED, 501, "Not Implemented") + +#define HTTP_REQUEST_METHOD(SYM) HTTP_REQUEST_METHOD_##SYM, +enum http_request_method { + HTTP_REQUEST_METHODS + HTTP_REQUEST_METHOD_COUNT +} method; +#undef HTTP_REQUEST_METHOD + +#define HTTP_REQUEST_METHOD(SYM) [HTTP_REQUEST_METHOD_##SYM] = #SYM, +const char *http_request_method_to_str[HTTP_REQUEST_METHOD_COUNT] = { + HTTP_REQUEST_METHODS +}; +#undef HTTP_REQUEST_METHOD + +#define HTTP_REQUEST_HEADER_KEY(SYM, STR) HTTP_REQUEST_HEADER_KEY_##SYM, +enum http_request_header_key { + HTTP_REQUEST_HEADER_KEYS + HTTP_REQUEST_HEADER_KEY_COUNT +}; +#undef HTTP_REQUEST_HEADER_KEY + +#define HTTP_REQUEST_HEADER_KEY(SYM, STR) [HTTP_REQUEST_HEADER_KEY_##SYM] = STR, +const char *http_request_header_key_to_str[HTTP_REQUEST_HEADER_KEY_COUNT] = { + HTTP_REQUEST_HEADER_KEYS +}; +#undef HTTP_REQUEST_HEADER_KEY + +#define HTTP_CONNECTION_TYPE(SYM, STR) HTTP_CONNECTION_TYPE_##SYM, +enum http_connection_type { + HTTP_CONNECTION_TYPES + HTTP_CONNECTION_TYPE_COUNT +}; +#undef HTTP_CONNECTION_TYPE + +#define HTTP_CONNECTION_TYPE(SYM, STR) [HTTP_CONNECTION_TYPE_##SYM] = STR, +const char *http_connection_type_to_str[HTTP_CONNECTION_TYPE_COUNT] = { + HTTP_CONNECTION_TYPES +}; +#undef HTTP_CONNECTION_TYPE + +#define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) HTTP_RESPONSE_STATUS_CODE_##SYM, +enum http_response_status_code { + HTTP_RESPONSE_STATUS_CODES + HTTP_RESPONSE_STATUS_CODE_COUNT +}; +#undef HTTP_RESPONSE_STATUS_CODE + +#define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = NUM, +int http_response_status_code_to_num[HTTP_RESPONSE_STATUS_CODE_COUNT] = { + HTTP_RESPONSE_STATUS_CODES +}; +#undef HTTP_RESPONSE_STATUS_CODE + +#define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = STR, +const char *http_response_status_code_to_str[HTTP_RESPONSE_STATUS_CODE_COUNT] = { + HTTP_RESPONSE_STATUS_CODES +}; +#undef HTTP_RESPONSE_STATUS_CODE + +#define HTTP_RESPONSE_STATUS_CODE(SYM, NUM, STR) [HTTP_RESPONSE_STATUS_CODE_##SYM] = sizeof (STR) - 1, +int http_response_status_code_to_str_len[HTTP_RESPONSE_STATUS_CODE_COUNT] = { + HTTP_RESPONSE_STATUS_CODES +}; +#undef HTTP_RESPONSE_STATUS_CODE + +int sock; +struct sockaddr_in addr; +struct buffer buf; +char path[MAX_PATH_LENGTH + 1]; +ssize_t path_len; +ssize_t root_len; +char path_resolved[MAX_PATH_LENGTH + 1]; +enum http_connection_type connection_type; +DIR *dir = NULL; +volatile bool should_stop = false; +struct program_arguments pa; + +void +signal_handler (int sig) +{ + int serrno = errno; + + switch (sig) { + case SIGINT: + DEBUG ("Received SIGINT"); + should_stop = true; + break; + + case SIGTERM: + DEBUG ("Received SIGTERM"); + should_stop = true; + break; + + case SIGCHLD: + DEBUG ("Received SIGCHLD"); + for (;;) { + int status; + int pid = waitpid (WAIT_ANY, &status, WNOHANG); + if (pid <= 0) { + if (pid == -1) + DEBUG ("Failed to wait for any child: %s", strerror (errno)); + goto cleanup; + } DEBUG ("%d exited with %d", pid, status); + } break; + + default: DEBUG ("Received unhandled %s", strsignal (sig)); + } + +cleanup: + errno = serrno; +} + +void +connection_lost (void) +{ + INFO ("Connection lost: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); + _exit (EXIT_FAILURE); +} + +void +respond_with_error (enum http_response_status_code code, const char *msg) +{ + ASSERT (http_response_status_code_to_num[code] >= 400); + ASSERT (http_response_status_code_to_num[code] <= 599); + + if (code < 500) { + NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s %d", + SOCKADDR_IN_SPLIT (addr), + method != HTTP_REQUEST_METHOD_COUNT + ? http_request_method_to_str[method] : "(unknown)", + path + root_len, http_response_status_code_to_num[code]); + } else { + WARNING ("Access: "SOCKADDR_IN_FMT" %s %s %d", + SOCKADDR_IN_SPLIT (addr), + http_request_method_to_str[method], + path + root_len, http_response_status_code_to_num[code]); + } + + if (sock == -1) connection_lost (); + + buf.head_read = buf.data; + buf.head_write = buf.data; + int bytes_written; + + buf.head_write += bytes_written = + sprintf (buf.head_write, "HTTP/1.1 %d %s\r\n" + "Server: " SERVER "\r\n" + "Content-Type: text/html\r\n" + "Connection: close\r\n", + http_response_status_code_to_num[code], + http_response_status_code_to_str[code]); + + time_t now = time (NULL); + struct tm gmt; + gmtime_r (&now, &gmt); + buf.head_write += bytes_written = + strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), + "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); + + if (msg) { + buf.head_write += bytes_written = + sprintf (buf.head_write, + "Content-Length: %d\r\n" + "\r\n" + "" + "" + "

%d %s

" + "

%s

" + "" + "", + (int) (101 + 3 + http_response_status_code_to_str_len[code] + strlen (msg)), + http_response_status_code_to_num[code], + http_response_status_code_to_str[code], + msg); + } else { + buf.head_write += bytes_written = + sprintf (buf.head_write, + "Content-Length: %d\r\n" + "\r\n" + "" + "" + "

%d %s

" + "" + "", + 64 + 3 + http_response_status_code_to_str_len[code], + http_response_status_code_to_num[code], + http_response_status_code_to_str[code]); + } + + write (sock, buf.head_read, buf.head_write - buf.head_read); + DEBUG ("Responding with error:\n%.*s\n", + (int) (buf.head_write - buf.head_read), buf.head_read); + _exit (code); +} +#define RESPOND_WITH_ERROR(SYM, MSG) \ + respond_with_error (HTTP_RESPONSE_STATUS_CODE_##SYM, MSG) + +void +redirect (enum http_response_status_code code, const char *uri) +{ + ASSERT (http_response_status_code_to_num[code] >= 300); + ASSERT (http_response_status_code_to_num[code] <= 399); + + NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s %d", + SOCKADDR_IN_SPLIT (addr), http_request_method_to_str[method], + path + root_len, http_response_status_code_to_num[code]); + + if (sock == -1) connection_lost (); + + buf.head_read = buf.data; + buf.head_write = buf.data; + int bytes_written; + + buf.head_write += bytes_written = + sprintf (buf.head_write, "HTTP/1.1 %d %s\r\n" + "Server: " SERVER "\r\n" + "Location: %s\r\n" + "Content-Length: 0\r\n" + "Connection: %s\r\n", + http_response_status_code_to_num[code], + http_response_status_code_to_str[code], + uri, http_connection_type_to_str[connection_type]); + + time_t now = time (NULL); + struct tm gmt; + gmtime_r (&now, &gmt); + buf.head_write += bytes_written = + strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), + "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); + + write (sock, buf.head_read, buf.head_write - buf.head_read); + DEBUG ("Responding with redirect:\n%.*s\n", + (int) (buf.head_write - buf.head_read), buf.head_read); + _exit (code); +} +#define REDIRECT(SYM, URI) \ + redirect (HTTP_RESPONSE_STATUS_CODE_##SYM, URI) + +magic_t magic; + +const char * +get_mimetype (const char *filename, int fd) +{ + const char *ext = strrchr (filename, '.'); + if (!ext) goto fallback; + ext += 1; + if (strcmp (ext, "html") == 0) return "text/html"; + if (strcmp (ext, "css" ) == 0) return "text/css"; + if (strcmp (ext, "js" ) == 0) return "text/javascript"; + + fallback: + return magic_descriptor (magic, fd) ?: "application/octet-stream"; +} + +int +pretty_size (char *s, off_t size) +{ + const char units[] = "BKMGTP"; + int i = 0; + double floating_size = (double) size; + while (floating_size >= 1024 && i < (int) (sizeof (units) - 2)) { + floating_size /= 1024; + i++; + } + return s ? sprintf (s, "%.1lf%c", floating_size, units[i]) + : snprintf (NULL, 0, "%.1lf%c", floating_size, units[i]); +} + +off_t +get_content_length (int fd, struct stat *st) +{ + if (S_ISREG (st->st_mode)) + return st->st_size; + + off_t content_length = 1093 + 2*(path_len - root_len); + dir = fdopendir (fd); + struct dirent *entry; + while ((entry = readdir (dir)) != NULL) { + if (entry->d_name[0] == '.') { + if (entry->d_name[1] == '\0') continue; + if (entry->d_name[1] == '.') { + if (entry->d_name[2] == '\0') continue; + } + } + + content_length += 70 + 2*strlen (entry->d_name); + + strcpy (path + path_len, entry->d_name); + struct stat entry_st; + stat (path, &entry_st); + if (S_ISREG (entry_st.st_mode)) + content_length += pretty_size (NULL, entry_st.st_size); + } + + return content_length; +} + +void +write_content (int fd, struct stat *st) +{ + if (S_ISREG (st->st_mode)) { + ssize_t bytes_read = read (fd, buf.head_write, BUFFER_SPACE_WRITE (buf)); + if (bytes_read == -1) RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); + buf.head_write += bytes_read; + if (write (sock, buf.head_read, buf.head_write - buf.head_read) == -1) + connection_lost (); + st->st_size -= bytes_read; + while (st->st_size > 0) { + st->st_size -= bytes_read = + read (fd, buf.data, st->st_size > BUFFER_SIZE ? BUFFER_SIZE : st->st_size); + if (bytes_read <= 0) RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); + if (write (sock, buf.data, bytes_read) == -1) + connection_lost (); + } + if (connection_type == HTTP_CONNECTION_TYPE_KEEP_ALIVE) + close (fd); + return; + } + + buf.head_write += + sprintf (buf.head_write, + "" + "" + "" + "" + "" + "" + "Index of %.*s" + "" + "" + "" + "" + "
" + "

%.*s

" + "
" + "" + "" + "" + "" + "" + "", + (int) (path_len - root_len), path + root_len, + (int) (path_len - root_len), path + root_len); + + ASSERT (dir); + rewinddir (dir); + struct dirent *entry; + while ((entry = readdir (dir)) != NULL) { + if (entry->d_name[0] == '.') { + if (entry->d_name[1] == '\0') continue; + if (entry->d_name[1] == '.') { + if (entry->d_name[2] == '\0') continue; + } + } + + strcpy (path + path_len, entry->d_name); + struct stat entry_st; + off_t entry_size = 0; + stat (path, &entry_st); + if (S_ISREG (entry_st.st_mode)) + entry_size = entry_st.st_size; + buf.head_write += sprintf (buf.head_write, ""); + } + + buf.head_write += sprintf (buf.head_write, "
namesizedate
%s", + entry->d_name, entry->d_name); + if (entry_size) buf.head_write += pretty_size (buf.head_write, entry_size); + buf.head_write += sprintf (buf.head_write, ""); + struct tm gmt; + gmtime_r (&entry_st.st_mtime, &gmt); + buf.head_write += + strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), + "%d-%m-%Y %H:%M:%S", &gmt); + buf.head_write += sprintf (buf.head_write, "
"); + + while (buf.head_read < buf.head_write) { + ssize_t bytes_written = + write (sock, buf.head_read, buf.head_write - buf.head_read); + if (bytes_written == -1) + connection_lost (); + buf.head_read += bytes_written; + } + + if (connection_type == HTTP_CONNECTION_TYPE_KEEP_ALIVE) { + closedir (dir); + dir = NULL; + } +} + +void +handle_connection (void) +{ +again: + path_len = root_len; + method = HTTP_REQUEST_METHOD_COUNT; + buf.head_read = buf.data; + buf.head_write = buf.data; + + DEBUG ("Parsing header"); + // METHOD + char *sym = buffer__consume_until (&buf, &sock, ' '); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + size_t sym_len = buf.head_read - sym - 1; + DEBUG ("Parsed method: %.*s", (int) sym_len, sym); + for (int i = 0; i < HTTP_REQUEST_METHOD_COUNT; ++i) { + if (strncmp (sym, http_request_method_to_str[i], sym_len)) + continue; + method = i; + break; + } + if (method == HTTP_REQUEST_METHOD_COUNT) + RESPOND_WITH_ERROR (NOT_IMPLEMENTED, NULL); + + // URI + sym = buffer__consume_until (&buf, &sock, ' '); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + sym_len = buf.head_read - sym - 1; + DEBUG ("Parsed URI: %.*s", (int) sym_len, sym); + if (sym_len > MAX_PATH_LENGTH) + RESPOND_WITH_ERROR (URI_TOO_LONG, NULL); + memcpy (path + path_len, sym, sym_len); + path_len += sym_len; + path[path_len] = '\0'; + + // VERSION + sym = buffer__consume_until (&buf, &sock, '\r'); + if (!sym || buffer__consume_one (&buf, &sock) != '\n') + RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + sym_len = buf.head_read - sym - 2; + DEBUG ("Parsed version: %.*s", (int) sym_len, sym); + + // HEADERS + ssize_t content_length = -1; + connection_type = HTTP_CONNECTION_TYPE_CLOSE; + while (buffer__peek (&buf, &sock) != '\r') { + sym = buffer__consume_until (&buf, &sock, ':'); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + sym_len = buf.head_read - sym - 1; + DEBUG ("Parsed header key: %.*s", (int) sym_len, sym); + enum http_request_header_key key = HTTP_REQUEST_HEADER_KEY_COUNT; + for (int i = 0; i < HTTP_REQUEST_HEADER_KEY_COUNT; ++i) { + if (strncmp (sym, http_request_header_key_to_str[i], sym_len)) + continue; + key = i; + break; + } + + sym = buffer__consume_while_one_of (&buf, &sock, " \t"); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + + sym = buffer__consume_until_one_of (&buf, &sock, " \t\r"); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + sym_len = buf.head_read - sym - 1; + DEBUG ("Parsed header value: %.*s", (int) sym_len, sym); + switch (key) { + case HTTP_REQUEST_HEADER_KEY_CONTENT_LENGTH: + sscanf (sym, "%ld", &content_length); + break; + case HTTP_REQUEST_HEADER_KEY_CONNECTION: + connection_type = HTTP_CONNECTION_TYPE_COUNT; + for (int i = 0; i < HTTP_CONNECTION_TYPE_COUNT; ++i) { + if (strncmp (sym, http_connection_type_to_str[i], sym_len)) + continue; + connection_type = i; + break; + } + if (connection_type == HTTP_CONNECTION_TYPE_COUNT) + RESPOND_WITH_ERROR (BAD_REQUEST, "Unknown Connection value"); + break; + } + + sym = buffer__consume_until (&buf, &sock, '\n'); + if (!sym) RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + } buffer__consume_one (&buf, &sock); + if (buffer__consume_one (&buf, &sock) != '\n') + RESPOND_WITH_ERROR (BAD_REQUEST, NULL); + DEBUG ("Finished parsing header"); + + if (method == HTTP_REQUEST_METHOD_POST) { // POST (simply echo) + if (content_length == -1) + RESPOND_WITH_ERROR (LENGTH_REQUIRED, NULL); + + const char *template = + "HTTP/1.1 200 OK\r\n" + "Server: " SERVER "\r\n" + "Connection: %s\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: %lu\r\n" + "\r\n"; + off_t bytes_written = snprintf (NULL, 0, template, + http_connection_type_to_str[connection_type], content_length); + size_t buffout_size = bytes_written + content_length; + char *buffout = malloc (buffout_size); + if (!buffout) + RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, "Server out of memory"); + snprintf (buffout, bytes_written + 1, template, + http_connection_type_to_str[connection_type], content_length); + + size_t buf_size = buf.head_write - buf.head_read; + memcpy (buffout + bytes_written, buf.head_read, buf_size); + content_length -= buf_size; + bytes_written += buf_size; + + while (content_length > 0) { + ssize_t bytes_read = read (sock, buffout + bytes_written, content_length); + if (bytes_read <= 0) connection_lost (); + content_length -= bytes_read; + bytes_written += bytes_read; + } + + write (sock, buffout, buffout_size); + free (buffout); + } else { // GET/HEAD + buf.head_read = buf.data; + buf.head_write = buf.data; + + if (content_length > 0) { + if (!buffer__skip_n (&buf, &sock, content_length)) + connection_lost (); + } + + // if (path_len == root_len + 1 && path[path_len - 1] == '/') { + // strcpy (path + path_len, "en/"); + // REDIRECT (MOVED_PERMANENTLY, path + root_len); + // goto done; + // } + + if (!realpath (path, path_resolved)) { + switch (errno) { + case EACCES: RESPOND_WITH_ERROR (FORBIDDEN, NULL); + case ENOENT: RESPOND_WITH_ERROR (NOT_FOUND, NULL); + } + } + if (strncmp (path_resolved, pa.root, root_len)) + RESPOND_WITH_ERROR (FORBIDDEN, NULL); + + int fd = open (path_resolved, O_RDONLY); + if (fd == -1) { + switch (errno) { + case EACCES: RESPOND_WITH_ERROR (FORBIDDEN, NULL); + case ENOENT: RESPOND_WITH_ERROR (NOT_FOUND, NULL); + } + } + struct stat st; + if (fstat (fd, &st) == -1) + RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); + if (S_ISDIR (st.st_mode)) { + if (path[path_len - 1] != '/') { + strcpy (path + path_len, "/"); + REDIRECT (MOVED_PERMANENTLY, path + root_len); + goto done; + } + + strcpy (path + path_len, "index.html"); + int index_fd = open (path, O_RDONLY); + if (index_fd == -1 && errno == EACCES) + RESPOND_WITH_ERROR (FORBIDDEN, NULL); + if (index_fd != -1) { + close (fd); + fd = index_fd; + if (fstat (fd, &st) == -1) + RESPOND_WITH_ERROR (INTERNAL_SERVER_ERROR, NULL); + } + } + + off_t bytes_written; + buf.head_write += bytes_written = + sprintf (buf.head_write, + "HTTP/1.1 200 OK\r\n" + "Server: " SERVER "\r\n" + "Connection: %s\r\n", http_connection_type_to_str[connection_type]); + + time_t now = time (NULL); + struct tm gmt; + gmtime_r (&now, &gmt); + buf.head_write += bytes_written = + strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), + "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); + + gmtime_r (&st.st_mtime, &gmt); + buf.head_write += bytes_written = + strftime (buf.head_write, BUFFER_SPACE_WRITE (buf), + "Last-Modified: %a, %d %b %Y %H:%M:%S GMT\r\n", &gmt); + + buf.head_write += bytes_written = + sprintf (buf.head_write, + "Content-Type: %s\r\n" + "Content-Length: %lu\r\n" + "\r\n", + S_ISDIR (st.st_mode) ? "text/html" : get_mimetype (path, fd), + get_content_length (fd, &st)); + + if (method == HTTP_REQUEST_METHOD_HEAD) { + if (write (sock, buf.head_read, buf.head_write - buf.head_read) == -1) + connection_lost (); + close (fd); + } else if (method == HTTP_REQUEST_METHOD_GET) { + write_content (fd, &st); + } + } + + NOTICE ("Access: "SOCKADDR_IN_FMT" %s %s 200", SOCKADDR_IN_SPLIT (addr), + http_request_method_to_str[method], path + root_len); +done: + switch (connection_type) { + case HTTP_CONNECTION_TYPE_CLOSE: _exit (EXIT_SUCCESS); + case HTTP_CONNECTION_TYPE_KEEP_ALIVE: goto again; + } +} + +int +main (int argc, char *argv[]) +{ + pa = parse_program_arguments (argc, argv); + if (pa.help) { + print_help (pa.program_name); + exit (EXIT_SUCCESS); + } + + setlogmask (LOG_UPTO (pa.log_upto)); + openlog (basename (pa.program_name), + LOG_PID | (pa.daemonize ? 0 : LOG_PERROR), LOG_DAEMON); + + if (pa.daemonize) { + close (STDIN_FILENO); + close (STDOUT_FILENO); + close (STDERR_FILENO); + DEBUG ("Closed standard file descriptors"); + } + + struct sigaction sa = { .sa_handler = signal_handler }; + sigaction (SIGINT, &sa, NULL); + sigaction (SIGTERM, &sa, NULL); + sa.sa_flags = SA_RESTART; + sigaction (SIGHUP, &sa, NULL); + sigaction (SIGCHLD, &sa, NULL); + DEBUG ("Registered signal handlers"); + + if (pa.daemonize) { + pid_t pid = fork (); + if (pid == -1) { + EMERGENCY ("Unable to fork: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + + if (pid > 0) + exit (EXIT_SUCCESS); + DEBUG ("Forked"); + + pid_t sid = setsid (); + if (sid == -1) { + EMERGENCY ("Unable to set SID: %s", strerror (errno)); + exit (EXIT_FAILURE); + } DEBUG ("Set sid to %d", sid); + } + + umask (0); + + if (chdir (pa.root) == -1) { + EMERGENCY ("Unable to chdir to `%s': %s", pa.root, strerror (errno)); + exit (EXIT_FAILURE); + } DEBUG ("Changed directory to `%s'", pa.root); + root_len = strlen (pa.root); + if (root_len > MAX_PATH_LENGTH) { + EMERGENCY ("Path to root is too long: %ld > %d", root_len, MAX_PATH_LENGTH); + exit (EXIT_FAILURE); + } memcpy (path, pa.root, root_len + 1); + + magic = magic_open (MAGIC_MIME_TYPE); + if (!magic) { + EMERGENCY ("Failed to open magic: %s", magic_error (magic)); + exit (EXIT_FAILURE); + } + if (magic_load (magic, NULL) == -1) { + EMERGENCY ("Failed to load magic: %s", magic_error (magic)); + exit (EXIT_FAILURE); + } + + int listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listener == -1) { + EMERGENCY ("Failed to create socket: %s", strerror (errno)); + exit (EXIT_FAILURE); + } DEBUG ("Created socket"); + + int reuseaddr = 1; + setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, + &reuseaddr, sizeof (reuseaddr)); + + addr.sin_family = AF_INET; + addr.sin_port = htons (pa.port); + if (!inet_aton (pa.addr, &addr.sin_addr)) { + EMERGENCY ("Failed to convert address %s", pa.addr); + exit (EXIT_FAILURE); + } + + if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) { + EMERGENCY ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s", + SOCKADDR_IN_SPLIT (addr), strerror (errno)); + exit (EXIT_FAILURE); + } + + if (listen (listener, 1)) { + EMERGENCY ("Failed to listen on "SOCKADDR_IN_FMT": %s", + SOCKADDR_IN_SPLIT (addr), strerror (errno)); + exit (EXIT_FAILURE); + } + NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); + + NOTICE ("Server started"); + while (!should_stop) { + socklen_t length = sizeof (addr); + sock = accept (listener, (struct sockaddr *) &addr, &length); + if (sock == -1) { + if (errno != EINTR) + ERROR ("Failed to accept connection: %s", strerror (errno)); + continue; + } + DEBUG ("Accepted connection: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr)); + + pid_t pid = fork (); + if (pid == -1) { + ERROR ("Failed to fork: %s", strerror (errno)); + if (close (sock) == -1) + WARNING ("close: %s", strerror (errno)); + continue; + } + + if (pid != 0) { + if (close (sock) == -1) // NOTE(cmmm): neccessary, would leak + WARNING ("close: %s", strerror (errno)); + continue; + } + + // if (close (listener) == -1) // NOTE(cmmm): unneccessary syscall for each connection + // ERROR ("close: %s", strerror (errno)); + + handle_connection (); + } + + NOTICE ("Server stopping"); + while (waitpid (-1, NULL, 0) > 0); + NOTICE ("Server stopped"); + return EXIT_SUCCESS; +} -- cgit v1.3.1