]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal-remote/journal-gatewayd.c
build-sys: use #if Y instead of #ifdef Y everywhere
[thirdparty/systemd.git] / src / journal-remote / journal-gatewayd.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2012 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <microhttpd.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "sd-bus.h"
28 #include "sd-daemon.h"
29 #include "sd-journal.h"
30
31 #include "alloc-util.h"
32 #include "bus-util.h"
33 #include "fd-util.h"
34 #include "fileio.h"
35 #include "hostname-util.h"
36 #include "log.h"
37 #include "logs-show.h"
38 #include "microhttpd-util.h"
39 #include "parse-util.h"
40 #include "sigbus.h"
41 #include "util.h"
42
43 #define JOURNAL_WAIT_TIMEOUT (10*USEC_PER_SEC)
44
45 static char *arg_key_pem = NULL;
46 static char *arg_cert_pem = NULL;
47 static char *arg_trust_pem = NULL;
48 static char *arg_directory = NULL;
49
50 typedef struct RequestMeta {
51 sd_journal *journal;
52
53 OutputMode mode;
54
55 char *cursor;
56 int64_t n_skip;
57 uint64_t n_entries;
58 bool n_entries_set;
59
60 FILE *tmp;
61 uint64_t delta, size;
62
63 int argument_parse_error;
64
65 bool follow;
66 bool discrete;
67
68 uint64_t n_fields;
69 bool n_fields_set;
70 } RequestMeta;
71
72 static const char* const mime_types[_OUTPUT_MODE_MAX] = {
73 [OUTPUT_SHORT] = "text/plain",
74 [OUTPUT_JSON] = "application/json",
75 [OUTPUT_JSON_SSE] = "text/event-stream",
76 [OUTPUT_EXPORT] = "application/vnd.fdo.journal",
77 };
78
79 static RequestMeta *request_meta(void **connection_cls) {
80 RequestMeta *m;
81
82 assert(connection_cls);
83 if (*connection_cls)
84 return *connection_cls;
85
86 m = new0(RequestMeta, 1);
87 if (!m)
88 return NULL;
89
90 *connection_cls = m;
91 return m;
92 }
93
94 static void request_meta_free(
95 void *cls,
96 struct MHD_Connection *connection,
97 void **connection_cls,
98 enum MHD_RequestTerminationCode toe) {
99
100 RequestMeta *m = *connection_cls;
101
102 if (!m)
103 return;
104
105 sd_journal_close(m->journal);
106
107 safe_fclose(m->tmp);
108
109 free(m->cursor);
110 free(m);
111 }
112
113 static int open_journal(RequestMeta *m) {
114 assert(m);
115
116 if (m->journal)
117 return 0;
118
119 if (arg_directory)
120 return sd_journal_open_directory(&m->journal, arg_directory, 0);
121 else
122 return sd_journal_open(&m->journal, SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM);
123 }
124
125 static int request_meta_ensure_tmp(RequestMeta *m) {
126 assert(m);
127
128 if (m->tmp)
129 rewind(m->tmp);
130 else {
131 int fd;
132
133 fd = open_tmpfile_unlinkable("/tmp", O_RDWR|O_CLOEXEC);
134 if (fd < 0)
135 return fd;
136
137 m->tmp = fdopen(fd, "w+");
138 if (!m->tmp) {
139 safe_close(fd);
140 return -errno;
141 }
142 }
143
144 return 0;
145 }
146
147 static ssize_t request_reader_entries(
148 void *cls,
149 uint64_t pos,
150 char *buf,
151 size_t max) {
152
153 RequestMeta *m = cls;
154 int r;
155 size_t n, k;
156
157 assert(m);
158 assert(buf);
159 assert(max > 0);
160 assert(pos >= m->delta);
161
162 pos -= m->delta;
163
164 while (pos >= m->size) {
165 off_t sz;
166
167 /* End of this entry, so let's serialize the next
168 * one */
169
170 if (m->n_entries_set &&
171 m->n_entries <= 0)
172 return MHD_CONTENT_READER_END_OF_STREAM;
173
174 if (m->n_skip < 0)
175 r = sd_journal_previous_skip(m->journal, (uint64_t) -m->n_skip + 1);
176 else if (m->n_skip > 0)
177 r = sd_journal_next_skip(m->journal, (uint64_t) m->n_skip + 1);
178 else
179 r = sd_journal_next(m->journal);
180
181 if (r < 0) {
182 log_error_errno(r, "Failed to advance journal pointer: %m");
183 return MHD_CONTENT_READER_END_WITH_ERROR;
184 } else if (r == 0) {
185
186 if (m->follow) {
187 r = sd_journal_wait(m->journal, (uint64_t) JOURNAL_WAIT_TIMEOUT);
188 if (r < 0) {
189 log_error_errno(r, "Couldn't wait for journal event: %m");
190 return MHD_CONTENT_READER_END_WITH_ERROR;
191 }
192 if (r == SD_JOURNAL_NOP)
193 break;
194
195 continue;
196 }
197
198 return MHD_CONTENT_READER_END_OF_STREAM;
199 }
200
201 if (m->discrete) {
202 assert(m->cursor);
203
204 r = sd_journal_test_cursor(m->journal, m->cursor);
205 if (r < 0) {
206 log_error_errno(r, "Failed to test cursor: %m");
207 return MHD_CONTENT_READER_END_WITH_ERROR;
208 }
209
210 if (r == 0)
211 return MHD_CONTENT_READER_END_OF_STREAM;
212 }
213
214 pos -= m->size;
215 m->delta += m->size;
216
217 if (m->n_entries_set)
218 m->n_entries -= 1;
219
220 m->n_skip = 0;
221
222 r = request_meta_ensure_tmp(m);
223 if (r < 0) {
224 log_error_errno(r, "Failed to create temporary file: %m");
225 return MHD_CONTENT_READER_END_WITH_ERROR;
226 }
227
228 r = output_journal(m->tmp, m->journal, m->mode, 0, OUTPUT_FULL_WIDTH, NULL);
229 if (r < 0) {
230 log_error_errno(r, "Failed to serialize item: %m");
231 return MHD_CONTENT_READER_END_WITH_ERROR;
232 }
233
234 sz = ftello(m->tmp);
235 if (sz == (off_t) -1) {
236 log_error_errno(errno, "Failed to retrieve file position: %m");
237 return MHD_CONTENT_READER_END_WITH_ERROR;
238 }
239
240 m->size = (uint64_t) sz;
241 }
242
243 if (m->tmp == NULL && m->follow)
244 return 0;
245
246 if (fseeko(m->tmp, pos, SEEK_SET) < 0) {
247 log_error_errno(errno, "Failed to seek to position: %m");
248 return MHD_CONTENT_READER_END_WITH_ERROR;
249 }
250
251 n = m->size - pos;
252 if (n < 1)
253 return 0;
254 if (n > max)
255 n = max;
256
257 errno = 0;
258 k = fread(buf, 1, n, m->tmp);
259 if (k != n) {
260 log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF");
261 return MHD_CONTENT_READER_END_WITH_ERROR;
262 }
263
264 return (ssize_t) k;
265 }
266
267 static int request_parse_accept(
268 RequestMeta *m,
269 struct MHD_Connection *connection) {
270
271 const char *header;
272
273 assert(m);
274 assert(connection);
275
276 header = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Accept");
277 if (!header)
278 return 0;
279
280 if (streq(header, mime_types[OUTPUT_JSON]))
281 m->mode = OUTPUT_JSON;
282 else if (streq(header, mime_types[OUTPUT_JSON_SSE]))
283 m->mode = OUTPUT_JSON_SSE;
284 else if (streq(header, mime_types[OUTPUT_EXPORT]))
285 m->mode = OUTPUT_EXPORT;
286 else
287 m->mode = OUTPUT_SHORT;
288
289 return 0;
290 }
291
292 static int request_parse_range(
293 RequestMeta *m,
294 struct MHD_Connection *connection) {
295
296 const char *range, *colon, *colon2;
297 int r;
298
299 assert(m);
300 assert(connection);
301
302 range = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Range");
303 if (!range)
304 return 0;
305
306 if (!startswith(range, "entries="))
307 return 0;
308
309 range += 8;
310 range += strspn(range, WHITESPACE);
311
312 colon = strchr(range, ':');
313 if (!colon)
314 m->cursor = strdup(range);
315 else {
316 const char *p;
317
318 colon2 = strchr(colon + 1, ':');
319 if (colon2) {
320 _cleanup_free_ char *t;
321
322 t = strndup(colon + 1, colon2 - colon - 1);
323 if (!t)
324 return -ENOMEM;
325
326 r = safe_atoi64(t, &m->n_skip);
327 if (r < 0)
328 return r;
329 }
330
331 p = (colon2 ? colon2 : colon) + 1;
332 if (*p) {
333 r = safe_atou64(p, &m->n_entries);
334 if (r < 0)
335 return r;
336
337 if (m->n_entries <= 0)
338 return -EINVAL;
339
340 m->n_entries_set = true;
341 }
342
343 m->cursor = strndup(range, colon - range);
344 }
345
346 if (!m->cursor)
347 return -ENOMEM;
348
349 m->cursor[strcspn(m->cursor, WHITESPACE)] = 0;
350 if (isempty(m->cursor))
351 m->cursor = mfree(m->cursor);
352
353 return 0;
354 }
355
356 static int request_parse_arguments_iterator(
357 void *cls,
358 enum MHD_ValueKind kind,
359 const char *key,
360 const char *value) {
361
362 RequestMeta *m = cls;
363 _cleanup_free_ char *p = NULL;
364 int r;
365
366 assert(m);
367
368 if (isempty(key)) {
369 m->argument_parse_error = -EINVAL;
370 return MHD_NO;
371 }
372
373 if (streq(key, "follow")) {
374 if (isempty(value)) {
375 m->follow = true;
376 return MHD_YES;
377 }
378
379 r = parse_boolean(value);
380 if (r < 0) {
381 m->argument_parse_error = r;
382 return MHD_NO;
383 }
384
385 m->follow = r;
386 return MHD_YES;
387 }
388
389 if (streq(key, "discrete")) {
390 if (isempty(value)) {
391 m->discrete = true;
392 return MHD_YES;
393 }
394
395 r = parse_boolean(value);
396 if (r < 0) {
397 m->argument_parse_error = r;
398 return MHD_NO;
399 }
400
401 m->discrete = r;
402 return MHD_YES;
403 }
404
405 if (streq(key, "boot")) {
406 if (isempty(value))
407 r = true;
408 else {
409 r = parse_boolean(value);
410 if (r < 0) {
411 m->argument_parse_error = r;
412 return MHD_NO;
413 }
414 }
415
416 if (r) {
417 char match[9 + 32 + 1] = "_BOOT_ID=";
418 sd_id128_t bid;
419
420 r = sd_id128_get_boot(&bid);
421 if (r < 0) {
422 log_error_errno(r, "Failed to get boot ID: %m");
423 return MHD_NO;
424 }
425
426 sd_id128_to_string(bid, match + 9);
427 r = sd_journal_add_match(m->journal, match, sizeof(match)-1);
428 if (r < 0) {
429 m->argument_parse_error = r;
430 return MHD_NO;
431 }
432 }
433
434 return MHD_YES;
435 }
436
437 p = strjoin(key, "=", strempty(value));
438 if (!p) {
439 m->argument_parse_error = log_oom();
440 return MHD_NO;
441 }
442
443 r = sd_journal_add_match(m->journal, p, 0);
444 if (r < 0) {
445 m->argument_parse_error = r;
446 return MHD_NO;
447 }
448
449 return MHD_YES;
450 }
451
452 static int request_parse_arguments(
453 RequestMeta *m,
454 struct MHD_Connection *connection) {
455
456 assert(m);
457 assert(connection);
458
459 m->argument_parse_error = 0;
460 MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, request_parse_arguments_iterator, m);
461
462 return m->argument_parse_error;
463 }
464
465 static int request_handler_entries(
466 struct MHD_Connection *connection,
467 void *connection_cls) {
468
469 struct MHD_Response *response;
470 RequestMeta *m = connection_cls;
471 int r;
472
473 assert(connection);
474 assert(m);
475
476 r = open_journal(m);
477 if (r < 0)
478 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %m");
479
480 if (request_parse_accept(m, connection) < 0)
481 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.");
482
483 if (request_parse_range(m, connection) < 0)
484 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Range header.");
485
486 if (request_parse_arguments(m, connection) < 0)
487 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse URL arguments.");
488
489 if (m->discrete) {
490 if (!m->cursor)
491 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Discrete seeks require a cursor specification.");
492
493 m->n_entries = 1;
494 m->n_entries_set = true;
495 }
496
497 if (m->cursor)
498 r = sd_journal_seek_cursor(m->journal, m->cursor);
499 else if (m->n_skip >= 0)
500 r = sd_journal_seek_head(m->journal);
501 else if (m->n_skip < 0)
502 r = sd_journal_seek_tail(m->journal);
503 if (r < 0)
504 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to seek in journal.");
505
506 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_entries, m, NULL);
507 if (!response)
508 return respond_oom(connection);
509
510 MHD_add_response_header(response, "Content-Type", mime_types[m->mode]);
511
512 r = MHD_queue_response(connection, MHD_HTTP_OK, response);
513 MHD_destroy_response(response);
514
515 return r;
516 }
517
518 static int output_field(FILE *f, OutputMode m, const char *d, size_t l) {
519 const char *eq;
520 size_t j;
521
522 eq = memchr(d, '=', l);
523 if (!eq)
524 return -EINVAL;
525
526 j = l - (eq - d + 1);
527
528 if (m == OUTPUT_JSON) {
529 fprintf(f, "{ \"%.*s\" : ", (int) (eq - d), d);
530 json_escape(f, eq+1, j, OUTPUT_FULL_WIDTH);
531 fputs(" }\n", f);
532 } else {
533 fwrite(eq+1, 1, j, f);
534 fputc('\n', f);
535 }
536
537 return 0;
538 }
539
540 static ssize_t request_reader_fields(
541 void *cls,
542 uint64_t pos,
543 char *buf,
544 size_t max) {
545
546 RequestMeta *m = cls;
547 int r;
548 size_t n, k;
549
550 assert(m);
551 assert(buf);
552 assert(max > 0);
553 assert(pos >= m->delta);
554
555 pos -= m->delta;
556
557 while (pos >= m->size) {
558 off_t sz;
559 const void *d;
560 size_t l;
561
562 /* End of this field, so let's serialize the next
563 * one */
564
565 if (m->n_fields_set &&
566 m->n_fields <= 0)
567 return MHD_CONTENT_READER_END_OF_STREAM;
568
569 r = sd_journal_enumerate_unique(m->journal, &d, &l);
570 if (r < 0) {
571 log_error_errno(r, "Failed to advance field index: %m");
572 return MHD_CONTENT_READER_END_WITH_ERROR;
573 } else if (r == 0)
574 return MHD_CONTENT_READER_END_OF_STREAM;
575
576 pos -= m->size;
577 m->delta += m->size;
578
579 if (m->n_fields_set)
580 m->n_fields -= 1;
581
582 r = request_meta_ensure_tmp(m);
583 if (r < 0) {
584 log_error_errno(r, "Failed to create temporary file: %m");
585 return MHD_CONTENT_READER_END_WITH_ERROR;
586 }
587
588 r = output_field(m->tmp, m->mode, d, l);
589 if (r < 0) {
590 log_error_errno(r, "Failed to serialize item: %m");
591 return MHD_CONTENT_READER_END_WITH_ERROR;
592 }
593
594 sz = ftello(m->tmp);
595 if (sz == (off_t) -1) {
596 log_error_errno(errno, "Failed to retrieve file position: %m");
597 return MHD_CONTENT_READER_END_WITH_ERROR;
598 }
599
600 m->size = (uint64_t) sz;
601 }
602
603 if (fseeko(m->tmp, pos, SEEK_SET) < 0) {
604 log_error_errno(errno, "Failed to seek to position: %m");
605 return MHD_CONTENT_READER_END_WITH_ERROR;
606 }
607
608 n = m->size - pos;
609 if (n > max)
610 n = max;
611
612 errno = 0;
613 k = fread(buf, 1, n, m->tmp);
614 if (k != n) {
615 log_error("Failed to read from file: %s", errno ? strerror(errno) : "Premature EOF");
616 return MHD_CONTENT_READER_END_WITH_ERROR;
617 }
618
619 return (ssize_t) k;
620 }
621
622 static int request_handler_fields(
623 struct MHD_Connection *connection,
624 const char *field,
625 void *connection_cls) {
626
627 struct MHD_Response *response;
628 RequestMeta *m = connection_cls;
629 int r;
630
631 assert(connection);
632 assert(m);
633
634 r = open_journal(m);
635 if (r < 0)
636 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %m");
637
638 if (request_parse_accept(m, connection) < 0)
639 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to parse Accept header.");
640
641 r = sd_journal_query_unique(m->journal, field);
642 if (r < 0)
643 return mhd_respond(connection, MHD_HTTP_BAD_REQUEST, "Failed to query unique fields.");
644
645 response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 4*1024, request_reader_fields, m, NULL);
646 if (!response)
647 return respond_oom(connection);
648
649 MHD_add_response_header(response, "Content-Type", mime_types[m->mode == OUTPUT_JSON ? OUTPUT_JSON : OUTPUT_SHORT]);
650
651 r = MHD_queue_response(connection, MHD_HTTP_OK, response);
652 MHD_destroy_response(response);
653
654 return r;
655 }
656
657 static int request_handler_redirect(
658 struct MHD_Connection *connection,
659 const char *target) {
660
661 char *page;
662 struct MHD_Response *response;
663 int ret;
664
665 assert(connection);
666 assert(target);
667
668 if (asprintf(&page, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target) < 0)
669 return respond_oom(connection);
670
671 response = MHD_create_response_from_buffer(strlen(page), page, MHD_RESPMEM_MUST_FREE);
672 if (!response) {
673 free(page);
674 return respond_oom(connection);
675 }
676
677 MHD_add_response_header(response, "Content-Type", "text/html");
678 MHD_add_response_header(response, "Location", target);
679
680 ret = MHD_queue_response(connection, MHD_HTTP_MOVED_PERMANENTLY, response);
681 MHD_destroy_response(response);
682
683 return ret;
684 }
685
686 static int request_handler_file(
687 struct MHD_Connection *connection,
688 const char *path,
689 const char *mime_type) {
690
691 struct MHD_Response *response;
692 int ret;
693 _cleanup_close_ int fd = -1;
694 struct stat st;
695
696 assert(connection);
697 assert(path);
698 assert(mime_type);
699
700 fd = open(path, O_RDONLY|O_CLOEXEC);
701 if (fd < 0)
702 return mhd_respondf(connection, errno, MHD_HTTP_NOT_FOUND, "Failed to open file %s: %m", path);
703
704 if (fstat(fd, &st) < 0)
705 return mhd_respondf(connection, errno, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to stat file: %m");
706
707 response = MHD_create_response_from_fd_at_offset64(st.st_size, fd, 0);
708 if (!response)
709 return respond_oom(connection);
710
711 fd = -1;
712
713 MHD_add_response_header(response, "Content-Type", mime_type);
714
715 ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
716 MHD_destroy_response(response);
717
718 return ret;
719 }
720
721 static int get_virtualization(char **v) {
722 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
723 char *b = NULL;
724 int r;
725
726 r = sd_bus_default_system(&bus);
727 if (r < 0)
728 return r;
729
730 r = sd_bus_get_property_string(
731 bus,
732 "org.freedesktop.systemd1",
733 "/org/freedesktop/systemd1",
734 "org.freedesktop.systemd1.Manager",
735 "Virtualization",
736 NULL,
737 &b);
738 if (r < 0)
739 return r;
740
741 if (isempty(b)) {
742 free(b);
743 *v = NULL;
744 return 0;
745 }
746
747 *v = b;
748 return 1;
749 }
750
751 static int request_handler_machine(
752 struct MHD_Connection *connection,
753 void *connection_cls) {
754
755 struct MHD_Response *response;
756 RequestMeta *m = connection_cls;
757 int r;
758 _cleanup_free_ char* hostname = NULL, *os_name = NULL;
759 uint64_t cutoff_from = 0, cutoff_to = 0, usage = 0;
760 char *json;
761 sd_id128_t mid, bid;
762 _cleanup_free_ char *v = NULL;
763
764 assert(connection);
765 assert(m);
766
767 r = open_journal(m);
768 if (r < 0)
769 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to open journal: %m");
770
771 r = sd_id128_get_machine(&mid);
772 if (r < 0)
773 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine machine ID: %m");
774
775 r = sd_id128_get_boot(&bid);
776 if (r < 0)
777 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine boot ID: %m");
778
779 hostname = gethostname_malloc();
780 if (!hostname)
781 return respond_oom(connection);
782
783 r = sd_journal_get_usage(m->journal, &usage);
784 if (r < 0)
785 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %m");
786
787 r = sd_journal_get_cutoff_realtime_usec(m->journal, &cutoff_from, &cutoff_to);
788 if (r < 0)
789 return mhd_respondf(connection, r, MHD_HTTP_INTERNAL_SERVER_ERROR, "Failed to determine disk usage: %m");
790
791 if (parse_env_file("/etc/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL) == -ENOENT)
792 (void) parse_env_file("/usr/lib/os-release", NEWLINE, "PRETTY_NAME", &os_name, NULL);
793
794 get_virtualization(&v);
795
796 r = asprintf(&json,
797 "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR "\","
798 "\"boot_id\" : \"" SD_ID128_FORMAT_STR "\","
799 "\"hostname\" : \"%s\","
800 "\"os_pretty_name\" : \"%s\","
801 "\"virtualization\" : \"%s\","
802 "\"usage\" : \"%"PRIu64"\","
803 "\"cutoff_from_realtime\" : \"%"PRIu64"\","
804 "\"cutoff_to_realtime\" : \"%"PRIu64"\" }\n",
805 SD_ID128_FORMAT_VAL(mid),
806 SD_ID128_FORMAT_VAL(bid),
807 hostname_cleanup(hostname),
808 os_name ? os_name : "Linux",
809 v ? v : "bare",
810 usage,
811 cutoff_from,
812 cutoff_to);
813
814 if (r < 0)
815 return respond_oom(connection);
816
817 response = MHD_create_response_from_buffer(strlen(json), json, MHD_RESPMEM_MUST_FREE);
818 if (!response) {
819 free(json);
820 return respond_oom(connection);
821 }
822
823 MHD_add_response_header(response, "Content-Type", "application/json");
824 r = MHD_queue_response(connection, MHD_HTTP_OK, response);
825 MHD_destroy_response(response);
826
827 return r;
828 }
829
830 static int request_handler(
831 void *cls,
832 struct MHD_Connection *connection,
833 const char *url,
834 const char *method,
835 const char *version,
836 const char *upload_data,
837 size_t *upload_data_size,
838 void **connection_cls) {
839 int r, code;
840
841 assert(connection);
842 assert(connection_cls);
843 assert(url);
844 assert(method);
845
846 if (!streq(method, "GET"))
847 return mhd_respond(connection, MHD_HTTP_NOT_ACCEPTABLE, "Unsupported method.");
848
849
850 if (!*connection_cls) {
851 if (!request_meta(connection_cls))
852 return respond_oom(connection);
853 return MHD_YES;
854 }
855
856 if (arg_trust_pem) {
857 r = check_permissions(connection, &code, NULL);
858 if (r < 0)
859 return code;
860 }
861
862 if (streq(url, "/"))
863 return request_handler_redirect(connection, "/browse");
864
865 if (streq(url, "/entries"))
866 return request_handler_entries(connection, *connection_cls);
867
868 if (startswith(url, "/fields/"))
869 return request_handler_fields(connection, url + 8, *connection_cls);
870
871 if (streq(url, "/browse"))
872 return request_handler_file(connection, DOCUMENT_ROOT "/browse.html", "text/html");
873
874 if (streq(url, "/machine"))
875 return request_handler_machine(connection, *connection_cls);
876
877 return mhd_respond(connection, MHD_HTTP_NOT_FOUND, "Not found.");
878 }
879
880 static void help(void) {
881 printf("%s [OPTIONS...] ...\n\n"
882 "HTTP server for journal events.\n\n"
883 " -h --help Show this help\n"
884 " --version Show package version\n"
885 " --cert=CERT.PEM Server certificate in PEM format\n"
886 " --key=KEY.PEM Server key in PEM format\n"
887 " --trust=CERT.PEM Certificate authority certificate in PEM format\n"
888 " -D --directory=PATH Serve journal files in directory\n",
889 program_invocation_short_name);
890 }
891
892 static int parse_argv(int argc, char *argv[]) {
893 enum {
894 ARG_VERSION = 0x100,
895 ARG_KEY,
896 ARG_CERT,
897 ARG_TRUST,
898 };
899
900 int r, c;
901
902 static const struct option options[] = {
903 { "help", no_argument, NULL, 'h' },
904 { "version", no_argument, NULL, ARG_VERSION },
905 { "key", required_argument, NULL, ARG_KEY },
906 { "cert", required_argument, NULL, ARG_CERT },
907 { "trust", required_argument, NULL, ARG_TRUST },
908 { "directory", required_argument, NULL, 'D' },
909 {}
910 };
911
912 assert(argc >= 0);
913 assert(argv);
914
915 while ((c = getopt_long(argc, argv, "hD:", options, NULL)) >= 0)
916
917 switch(c) {
918
919 case 'h':
920 help();
921 return 0;
922
923 case ARG_VERSION:
924 return version();
925
926 case ARG_KEY:
927 if (arg_key_pem) {
928 log_error("Key file specified twice");
929 return -EINVAL;
930 }
931 r = read_full_file(optarg, &arg_key_pem, NULL);
932 if (r < 0)
933 return log_error_errno(r, "Failed to read key file: %m");
934 assert(arg_key_pem);
935 break;
936
937 case ARG_CERT:
938 if (arg_cert_pem) {
939 log_error("Certificate file specified twice");
940 return -EINVAL;
941 }
942 r = read_full_file(optarg, &arg_cert_pem, NULL);
943 if (r < 0)
944 return log_error_errno(r, "Failed to read certificate file: %m");
945 assert(arg_cert_pem);
946 break;
947
948 case ARG_TRUST:
949 #if HAVE_GNUTLS
950 if (arg_trust_pem) {
951 log_error("CA certificate file specified twice");
952 return -EINVAL;
953 }
954 r = read_full_file(optarg, &arg_trust_pem, NULL);
955 if (r < 0)
956 return log_error_errno(r, "Failed to read CA certificate file: %m");
957 assert(arg_trust_pem);
958 break;
959 #else
960 log_error("Option --trust is not available.");
961 return -EINVAL;
962 #endif
963 case 'D':
964 arg_directory = optarg;
965 break;
966
967 case '?':
968 return -EINVAL;
969
970 default:
971 assert_not_reached("Unhandled option");
972 }
973
974 if (optind < argc) {
975 log_error("This program does not take arguments.");
976 return -EINVAL;
977 }
978
979 if (!!arg_key_pem != !!arg_cert_pem) {
980 log_error("Certificate and key files must be specified together");
981 return -EINVAL;
982 }
983
984 if (arg_trust_pem && !arg_key_pem) {
985 log_error("CA certificate can only be used with certificate file");
986 return -EINVAL;
987 }
988
989 return 1;
990 }
991
992 int main(int argc, char *argv[]) {
993 struct MHD_Daemon *d = NULL;
994 int r, n;
995
996 log_set_target(LOG_TARGET_AUTO);
997 log_parse_environment();
998 log_open();
999
1000 r = parse_argv(argc, argv);
1001 if (r < 0)
1002 return EXIT_FAILURE;
1003 if (r == 0)
1004 return EXIT_SUCCESS;
1005
1006 sigbus_install();
1007
1008 r = setup_gnutls_logger(NULL);
1009 if (r < 0)
1010 return EXIT_FAILURE;
1011
1012 n = sd_listen_fds(1);
1013 if (n < 0) {
1014 log_error_errno(n, "Failed to determine passed sockets: %m");
1015 goto finish;
1016 } else if (n > 1) {
1017 log_error("Can't listen on more than one socket.");
1018 goto finish;
1019 } else {
1020 struct MHD_OptionItem opts[] = {
1021 { MHD_OPTION_NOTIFY_COMPLETED,
1022 (intptr_t) request_meta_free, NULL },
1023 { MHD_OPTION_EXTERNAL_LOGGER,
1024 (intptr_t) microhttpd_logger, NULL },
1025 { MHD_OPTION_END, 0, NULL },
1026 { MHD_OPTION_END, 0, NULL },
1027 { MHD_OPTION_END, 0, NULL },
1028 { MHD_OPTION_END, 0, NULL },
1029 { MHD_OPTION_END, 0, NULL }};
1030 int opts_pos = 2;
1031
1032 /* We force MHD_USE_ITC here, in order to make sure
1033 * libmicrohttpd doesn't use shutdown() on our listening
1034 * socket, which would break socket re-activation. See
1035 *
1036 * https://lists.gnu.org/archive/html/libmicrohttpd/2015-09/msg00014.html
1037 * https://github.com/systemd/systemd/pull/1286
1038 */
1039
1040 int flags =
1041 MHD_USE_DEBUG |
1042 MHD_USE_DUAL_STACK |
1043 MHD_USE_ITC |
1044 MHD_USE_POLL_INTERNAL_THREAD |
1045 MHD_USE_THREAD_PER_CONNECTION;
1046
1047 if (n > 0)
1048 opts[opts_pos++] = (struct MHD_OptionItem)
1049 {MHD_OPTION_LISTEN_SOCKET, SD_LISTEN_FDS_START};
1050 if (arg_key_pem) {
1051 assert(arg_cert_pem);
1052 opts[opts_pos++] = (struct MHD_OptionItem)
1053 {MHD_OPTION_HTTPS_MEM_KEY, 0, arg_key_pem};
1054 opts[opts_pos++] = (struct MHD_OptionItem)
1055 {MHD_OPTION_HTTPS_MEM_CERT, 0, arg_cert_pem};
1056 flags |= MHD_USE_TLS;
1057 }
1058 if (arg_trust_pem) {
1059 assert(flags & MHD_USE_TLS);
1060 opts[opts_pos++] = (struct MHD_OptionItem)
1061 {MHD_OPTION_HTTPS_MEM_TRUST, 0, arg_trust_pem};
1062 }
1063
1064 d = MHD_start_daemon(flags, 19531,
1065 NULL, NULL,
1066 request_handler, NULL,
1067 MHD_OPTION_ARRAY, opts,
1068 MHD_OPTION_END);
1069 }
1070
1071 if (!d) {
1072 log_error("Failed to start daemon!");
1073 goto finish;
1074 }
1075
1076 pause();
1077
1078 r = EXIT_SUCCESS;
1079
1080 finish:
1081 if (d)
1082 MHD_stop_daemon(d);
1083
1084 return r;
1085 }