aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/buffer.h105
-rw-r--r--src/dynamic-array.h59
-rw-r--r--src/http-server.c820
-rw-r--r--src/program-arguments.h89
-rw-r--r--src/string-view.h17
-rw-r--r--src/utils.h46
6 files changed, 1136 insertions, 0 deletions
diff --git a/src/buffer.h b/src/buffer.h
new file mode 100644
index 0000000..7fc2939
--- /dev/null
+++ b/src/buffer.h
@@ -0,0 +1,105 @@
1#ifndef INCLUDED_BUFFER_H
2#define INCLUDED_BUFFER_H
3
4#define BUFFER_SIZE 4096
5#define BUFFER_END(BUFFER) ((BUFFER).data + BUFFER_SIZE)
6#define BUFFER_SPACE_WRITE(BUFFER) (BUFFER_SIZE - ((BUFFER).head_write - (BUFFER).data))
7
8struct buffer {
9 char *head_read;
10 char *head_write;
11 char data[BUFFER_SIZE];
12};
13
14void
15buffer__align (struct buffer *buf)
16{
17 if (buf->head_read == buf->data)
18 return;
19
20 size_t size = buf->head_write - buf->head_read;
21 memmove (buf->data, buf->head_read, size);
22 buf->head_read = buf->data;
23 buf->head_write = buf->data + size;
24}
25
26int
27buffer__peek (struct buffer *buf, int *fd)
28{
29 if (buf->head_read < buf->head_write)
30 return *buf->head_read;
31
32 buf->head_read = buf->data;
33 buf->head_write = buf->data;
34
35 ssize_t bytes_read = read (*fd, buf->head_write, BUFFER_SPACE_WRITE (*buf));
36 if (bytes_read <= 0) {
37 *fd = -1;
38 return EOF;
39 }
40 buf->head_write += bytes_read;
41
42 return *buf->head_read;
43}
44
45int
46buffer__consume_one (struct buffer *buf, int *fd)
47{
48 int c = buffer__peek (buf, fd);
49 if (c == EOF) return EOF;
50 buf->head_read += 1;
51 return c;
52}
53
54char *
55buffer__consume_until (struct buffer *buf, int *fd, char c)
56{
57 char *ret = buf->head_read;
58 for (;;) {
59 int r = buffer__consume_one (buf, fd);
60 if (r == EOF) return NULL;
61 if (r == c ) return ret;
62 }
63}
64
65char *
66buffer__consume_until_one_of (struct buffer *buf, int *fd, char *cs)
67{
68 char *ret = buf->head_read;
69 for (;;) {
70 int r = buffer__consume_one (buf, fd);
71 if (r == EOF) return NULL;
72 if (strchr (cs, r)) return ret;
73 }
74}
75
76char *
77buffer__consume_while_one_of (struct buffer *buf, int *fd, char *cs)
78{
79 char *ret = buf->head_read;
80 for (;;) {
81 int r = buffer__peek (buf, fd);
82 if (r == EOF) return NULL;
83 if (!strchr (cs, r)) return ret;
84 buffer__consume_one (buf, fd);
85 }
86}
87
88bool
89buffer__skip_n (struct buffer *buf, int *fd, ssize_t n)
90{
91 buffer__align (buf);
92 while (n > 0) {
93 ssize_t bytes_read = read (*fd, buf->head_write,
94 n > BUFFER_SPACE_WRITE (*buf)
95 ? BUFFER_SPACE_WRITE (*buf) : n);
96 if (bytes_read <= 0) {
97 *fd = -1;
98 return false;
99 }
100 n -= bytes_read;
101 }
102 return true;
103}
104
105#endif // INCLUDED_BUFFER_H
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..726fcce
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,59 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
49 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
50
51#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
52
53#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
54
55#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
56 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
57 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
58
59#endif
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,
62enum 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,
69const 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,
75enum 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,
82const 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,
88enum 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,
95const 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,
101enum 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,
108int 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,
114const 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,
120int 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
125int sock;
126struct sockaddr_in addr;
127struct buffer buf;
128char path[MAX_PATH_LENGTH + 1];
129ssize_t path_len;
130ssize_t root_len;
131char path_resolved[MAX_PATH_LENGTH + 1];
132enum http_connection_type connection_type;
133DIR *dir = NULL;
134volatile bool should_stop = false;
135struct program_arguments pa;
136
137void
138signal_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
168cleanup:
169 errno = serrno;
170}
171
172void
173connection_lost (void)
174{
175 INFO ("Connection lost: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr));
176 _exit (EXIT_FAILURE);
177}
178
179void
180respond_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
257void
258redirect (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
298magic_t magic;
299
300const char *
301get_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
314int
315pretty_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
328off_t
329get_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
357void
358write_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
466void
467handle_connection (void)
468{
469again:
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);
680done:
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
687int
688main (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}
diff --git a/src/program-arguments.h b/src/program-arguments.h
new file mode 100644
index 0000000..dc87f4b
--- /dev/null
+++ b/src/program-arguments.h
@@ -0,0 +1,89 @@
1#ifndef INCLUDED_PROGRAM_ARGUMENTS_H
2#define INCLUDED_PROGRAM_ARGUMENTS_H
3
4void
5print_help (const char *program_name)
6{
7 fprintf (stderr, "Usage: %s [OPTION...]\n", program_name);
8 fprintf (stderr, "\n");
9 fprintf (stderr, "Options:\n");
10#define PROGRAM_ARGUMENT_BOOL( sym, s, l, h, ...) fprintf (stderr, " -%c, --%s %*s\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h);
11#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s <unsigned> %*s (default: %u)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d);
12#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s <string> %*s (default: %s)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d);
13 PROGRAM_ARGUMENTS
14#undef PROGRAM_ARGUMENT_BOOL
15#undef PROGRAM_ARGUMENT_UINT
16#undef PROGRAM_ARGUMENT_STRING
17}
18
19#define PROGRAM_ARGUMENT_BOOL( sym, ...) bool sym;
20#define PROGRAM_ARGUMENT_UINT( sym, ...) unsigned int sym;
21#define PROGRAM_ARGUMENT_STRING(sym, ...) const char *sym;
22struct program_arguments {
23 const char *program_name;
24 PROGRAM_ARGUMENTS
25};
26#undef PROGRAM_ARGUMENT_BOOL
27#undef PROGRAM_ARGUMENT_UINT
28#undef PROGRAM_ARGUMENT_STRING
29
30struct program_arguments
31parse_program_arguments (int argc, char *argv[])
32{
33 UNUSED (argc);
34#define PROGRAM_ARGUMENT_BOOL(...)
35#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) .sym = d,
36#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) .sym = d,
37 struct program_arguments pa = {
38 .program_name = *argv++,
39 PROGRAM_ARGUMENTS
40 };
41#undef PROGRAM_ARGUMENT_BOOL
42#undef PROGRAM_ARGUMENT_UINT
43#undef PROGRAM_ARGUMENT_STRING
44
45#define PROGRAM_ARGUMENT_BOOL(sym, s, l, ...) MATCH (s, l) { \
46 pa.sym = true; \
47 continue; \
48 }
49#define PROGRAM_ARGUMENT_UINT(sym, s, l, ...) MATCH (s, l) { \
50 arg += 1; \
51 if (*arg == NULL) { \
52 fprintf (stderr, "error"); \
53 exit (EXIT_FAILURE); \
54 } \
55 if (sscanf (*arg, "%u", &pa.sym) == 0) { \
56 fprintf (stderr, "error: wrong format for %s\n", arg[-1]); \
57 exit (EXIT_FAILURE); \
58 } \
59 continue; \
60 }
61#define PROGRAM_ARGUMENT_STRING(sym, s, l, ...) MATCH (s, l) { \
62 arg += 1; \
63 pa.sym = *arg; \
64 continue; \
65 }
66 for (char **arg = argv; *arg; ++arg) {
67 if ((*arg)[0] == '-') {
68 if ((*arg)[1] == '-') {
69#define MATCH(s, l) if (!strcmp (*arg + 2, l))
70 PROGRAM_ARGUMENTS;
71 fprintf (stderr, "error: unknown option %s\n", *arg);
72 exit (EXIT_FAILURE);
73#undef MATCH
74 }
75#define MATCH(s, l) if ((*arg)[1] == s && (*arg)[2] == '\0')
76 PROGRAM_ARGUMENTS;
77 fprintf (stderr, "error: unknown option %s\n", *arg);
78 exit (EXIT_FAILURE);
79#undef MATCH
80 }
81 }
82#undef PROGRAM_ARGUMENT_BOOL
83#undef PROGRAM_ARGUMENT_UINT
84#undef PROGRAM_ARGUMENT_STRING
85
86 return pa;
87}
88
89#endif // INCLUDED_PROGRAM_ARGUMENTS_H
diff --git a/src/string-view.h b/src/string-view.h
new file mode 100644
index 0000000..0b6034a
--- /dev/null
+++ b/src/string-view.h
@@ -0,0 +1,17 @@
1#ifndef INCLUDED_STRING_VIEW_H
2#define INCLUDED_STRING_VIEW_H
3
4#include <string.h>
5
6struct string_view {
7 const char *beg;
8 const char *end;
9};
10
11#define STRING_VIEW_FROM_CSTR(CSTR) ((struct string_view) { .beg = (CSTR), .end = (CSTR) + strlen (CSTR) })
12#define STRING_VIEW_LEN(SV) ((SV).end - (SV).beg)
13#define STRING_VIEW_EQUALS(A, B) \
14 (STRING_VIEW_LEN (A) == STRING_VIEW_LEN (B) && \
15 !memcmp ((A).beg, (B).beg, STRING_VIEW_LEN (A)))
16
17#endif // INCLUDED_STRING_VIEW_H
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..b94b821
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,46 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <stdarg.h>
5#include <stdlib.h>
6#include <stdio.h>
7#include <syslog.h>
8#include <assert.h>
9
10#define STRINGIFY(ARG) #ARG
11#define TO_STRING(ARG) STRINGIFY (ARG)
12#define LOG(PRIORITY, FMT, ...) \
13 syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \
14 FMT __VA_OPT__ (,) __VA_ARGS__)
15#define DEBUG( FMT, ...) \
16 LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__)
17#define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__)
18#define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__)
19#define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__)
20#define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__)
21#define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__)
22#define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__)
23#define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__)
24
25#define UNUSED(X) ((void) (X))
26#define UNREACHABLE() ASSERT (!"reached the unreachable...")
27#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__)
28// #define TODO(...)
29#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
30
31#define MALLOC malloc
32#define REALLOC realloc
33#define FREE free
34#define ASSERT assert
35
36#define PRINT_EXP(FMT, EXP) printf (#EXP" = "FMT"\n", EXP)
37
38#define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu"
39#define SOCKADDR_IN_SPLIT(ADDR) \
40 ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \
41 ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \
42 ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \
43 ntohl ((ADDR).sin_addr.s_addr) >> 0*8, \
44 ntohs ((ADDR).sin_port)
45
46#endif