1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include <microhttpd.h>
11 #include "sd-daemon.h"
12 #include "sd-journal.h"
14 #include "alloc-util.h"
18 #include "hostname-util.h"
20 #include "logs-show.h"
21 #include "microhttpd-util.h"
23 #include "parse-util.h"
24 #include "pretty-print.h"
28 #define JOURNAL_WAIT_TIMEOUT (10*USEC_PER_SEC)
30 static char *arg_key_pem
= NULL
;
31 static char *arg_cert_pem
= NULL
;
32 static char *arg_trust_pem
= NULL
;
33 static char *arg_directory
= NULL
;
35 typedef struct RequestMeta
{
48 int argument_parse_error
;
57 static const char* const mime_types
[_OUTPUT_MODE_MAX
] = {
58 [OUTPUT_SHORT
] = "text/plain",
59 [OUTPUT_JSON
] = "application/json",
60 [OUTPUT_JSON_SSE
] = "text/event-stream",
61 [OUTPUT_JSON_SEQ
] = "application/json-seq",
62 [OUTPUT_EXPORT
] = "application/vnd.fdo.journal",
65 static RequestMeta
*request_meta(void **connection_cls
) {
68 assert(connection_cls
);
70 return *connection_cls
;
72 m
= new0(RequestMeta
, 1);
80 static void request_meta_free(
82 struct MHD_Connection
*connection
,
83 void **connection_cls
,
84 enum MHD_RequestTerminationCode toe
) {
86 RequestMeta
*m
= *connection_cls
;
91 sd_journal_close(m
->journal
);
99 static int open_journal(RequestMeta
*m
) {
106 return sd_journal_open_directory(&m
->journal
, arg_directory
, 0);
108 return sd_journal_open(&m
->journal
, SD_JOURNAL_LOCAL_ONLY
|SD_JOURNAL_SYSTEM
);
111 static int request_meta_ensure_tmp(RequestMeta
*m
) {
119 fd
= open_tmpfile_unlinkable("/tmp", O_RDWR
|O_CLOEXEC
);
123 m
->tmp
= fdopen(fd
, "w+");
133 static ssize_t
request_reader_entries(
139 RequestMeta
*m
= cls
;
146 assert(pos
>= m
->delta
);
150 while (pos
>= m
->size
) {
153 /* End of this entry, so let's serialize the next
156 if (m
->n_entries_set
&&
158 return MHD_CONTENT_READER_END_OF_STREAM
;
161 r
= sd_journal_previous_skip(m
->journal
, (uint64_t) -m
->n_skip
+ 1);
162 else if (m
->n_skip
> 0)
163 r
= sd_journal_next_skip(m
->journal
, (uint64_t) m
->n_skip
+ 1);
165 r
= sd_journal_next(m
->journal
);
168 log_error_errno(r
, "Failed to advance journal pointer: %m");
169 return MHD_CONTENT_READER_END_WITH_ERROR
;
173 r
= sd_journal_wait(m
->journal
, (uint64_t) JOURNAL_WAIT_TIMEOUT
);
175 log_error_errno(r
, "Couldn't wait for journal event: %m");
176 return MHD_CONTENT_READER_END_WITH_ERROR
;
178 if (r
== SD_JOURNAL_NOP
)
184 return MHD_CONTENT_READER_END_OF_STREAM
;
190 r
= sd_journal_test_cursor(m
->journal
, m
->cursor
);
192 log_error_errno(r
, "Failed to test cursor: %m");
193 return MHD_CONTENT_READER_END_WITH_ERROR
;
197 return MHD_CONTENT_READER_END_OF_STREAM
;
203 if (m
->n_entries_set
)
208 r
= request_meta_ensure_tmp(m
);
210 log_error_errno(r
, "Failed to create temporary file: %m");
211 return MHD_CONTENT_READER_END_WITH_ERROR
;
214 r
= show_journal_entry(m
->tmp
, m
->journal
, m
->mode
, 0, OUTPUT_FULL_WIDTH
,
217 log_error_errno(r
, "Failed to serialize item: %m");
218 return MHD_CONTENT_READER_END_WITH_ERROR
;
222 if (sz
== (off_t
) -1) {
223 log_error_errno(errno
, "Failed to retrieve file position: %m");
224 return MHD_CONTENT_READER_END_WITH_ERROR
;
227 m
->size
= (uint64_t) sz
;
230 if (m
->tmp
== NULL
&& m
->follow
)
233 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
234 log_error_errno(errno
, "Failed to seek to position: %m");
235 return MHD_CONTENT_READER_END_WITH_ERROR
;
245 k
= fread(buf
, 1, n
, m
->tmp
);
247 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
248 return MHD_CONTENT_READER_END_WITH_ERROR
;
254 static int request_parse_accept(
256 struct MHD_Connection
*connection
) {
263 header
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Accept");
267 if (streq(header
, mime_types
[OUTPUT_JSON
]))
268 m
->mode
= OUTPUT_JSON
;
269 else if (streq(header
, mime_types
[OUTPUT_JSON_SSE
]))
270 m
->mode
= OUTPUT_JSON_SSE
;
271 else if (streq(header
, mime_types
[OUTPUT_JSON_SEQ
]))
272 m
->mode
= OUTPUT_JSON_SEQ
;
273 else if (streq(header
, mime_types
[OUTPUT_EXPORT
]))
274 m
->mode
= OUTPUT_EXPORT
;
276 m
->mode
= OUTPUT_SHORT
;
281 static int request_parse_range(
283 struct MHD_Connection
*connection
) {
285 const char *range
, *colon
, *colon2
;
291 range
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Range");
295 if (!startswith(range
, "entries="))
299 range
+= strspn(range
, WHITESPACE
);
301 colon
= strchr(range
, ':');
303 m
->cursor
= strdup(range
);
307 colon2
= strchr(colon
+ 1, ':');
309 _cleanup_free_
char *t
;
311 t
= strndup(colon
+ 1, colon2
- colon
- 1);
315 r
= safe_atoi64(t
, &m
->n_skip
);
320 p
= (colon2
? colon2
: colon
) + 1;
322 r
= safe_atou64(p
, &m
->n_entries
);
326 if (m
->n_entries
<= 0)
329 m
->n_entries_set
= true;
332 m
->cursor
= strndup(range
, colon
- range
);
338 m
->cursor
[strcspn(m
->cursor
, WHITESPACE
)] = 0;
339 if (isempty(m
->cursor
))
340 m
->cursor
= mfree(m
->cursor
);
345 static int request_parse_arguments_iterator(
347 enum MHD_ValueKind kind
,
351 RequestMeta
*m
= cls
;
352 _cleanup_free_
char *p
= NULL
;
358 m
->argument_parse_error
= -EINVAL
;
362 if (streq(key
, "follow")) {
363 if (isempty(value
)) {
368 r
= parse_boolean(value
);
370 m
->argument_parse_error
= r
;
378 if (streq(key
, "discrete")) {
379 if (isempty(value
)) {
384 r
= parse_boolean(value
);
386 m
->argument_parse_error
= r
;
394 if (streq(key
, "boot")) {
398 r
= parse_boolean(value
);
400 m
->argument_parse_error
= r
;
406 char match
[9 + 32 + 1] = "_BOOT_ID=";
409 r
= sd_id128_get_boot(&bid
);
411 log_error_errno(r
, "Failed to get boot ID: %m");
415 sd_id128_to_string(bid
, match
+ 9);
416 r
= sd_journal_add_match(m
->journal
, match
, sizeof(match
)-1);
418 m
->argument_parse_error
= r
;
426 p
= strjoin(key
, "=", strempty(value
));
428 m
->argument_parse_error
= log_oom();
432 r
= sd_journal_add_match(m
->journal
, p
, 0);
434 m
->argument_parse_error
= r
;
441 static int request_parse_arguments(
443 struct MHD_Connection
*connection
) {
448 m
->argument_parse_error
= 0;
449 MHD_get_connection_values(connection
, MHD_GET_ARGUMENT_KIND
, request_parse_arguments_iterator
, m
);
451 return m
->argument_parse_error
;
454 static int request_handler_entries(
455 struct MHD_Connection
*connection
,
456 void *connection_cls
) {
458 struct MHD_Response
*response
;
459 RequestMeta
*m
= connection_cls
;
467 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
469 if (request_parse_accept(m
, connection
) < 0)
470 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
472 if (request_parse_range(m
, connection
) < 0)
473 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Range header.");
475 if (request_parse_arguments(m
, connection
) < 0)
476 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse URL arguments.");
480 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Discrete seeks require a cursor specification.");
483 m
->n_entries_set
= true;
487 r
= sd_journal_seek_cursor(m
->journal
, m
->cursor
);
488 else if (m
->n_skip
>= 0)
489 r
= sd_journal_seek_head(m
->journal
);
490 else if (m
->n_skip
< 0)
491 r
= sd_journal_seek_tail(m
->journal
);
493 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to seek in journal.");
495 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_entries
, m
, NULL
);
497 return respond_oom(connection
);
499 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
]);
501 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
502 MHD_destroy_response(response
);
507 static int output_field(FILE *f
, OutputMode m
, const char *d
, size_t l
) {
511 eq
= memchr(d
, '=', l
);
515 j
= l
- (eq
- d
+ 1);
517 if (m
== OUTPUT_JSON
) {
518 fprintf(f
, "{ \"%.*s\" : ", (int) (eq
- d
), d
);
519 json_escape(f
, eq
+1, j
, OUTPUT_FULL_WIDTH
);
522 fwrite(eq
+1, 1, j
, f
);
529 static ssize_t
request_reader_fields(
535 RequestMeta
*m
= cls
;
542 assert(pos
>= m
->delta
);
546 while (pos
>= m
->size
) {
551 /* End of this field, so let's serialize the next
554 if (m
->n_fields_set
&&
556 return MHD_CONTENT_READER_END_OF_STREAM
;
558 r
= sd_journal_enumerate_unique(m
->journal
, &d
, &l
);
560 log_error_errno(r
, "Failed to advance field index: %m");
561 return MHD_CONTENT_READER_END_WITH_ERROR
;
563 return MHD_CONTENT_READER_END_OF_STREAM
;
571 r
= request_meta_ensure_tmp(m
);
573 log_error_errno(r
, "Failed to create temporary file: %m");
574 return MHD_CONTENT_READER_END_WITH_ERROR
;
577 r
= output_field(m
->tmp
, m
->mode
, d
, l
);
579 log_error_errno(r
, "Failed to serialize item: %m");
580 return MHD_CONTENT_READER_END_WITH_ERROR
;
584 if (sz
== (off_t
) -1) {
585 log_error_errno(errno
, "Failed to retrieve file position: %m");
586 return MHD_CONTENT_READER_END_WITH_ERROR
;
589 m
->size
= (uint64_t) sz
;
592 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
593 log_error_errno(errno
, "Failed to seek to position: %m");
594 return MHD_CONTENT_READER_END_WITH_ERROR
;
602 k
= fread(buf
, 1, n
, m
->tmp
);
604 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
605 return MHD_CONTENT_READER_END_WITH_ERROR
;
611 static int request_handler_fields(
612 struct MHD_Connection
*connection
,
614 void *connection_cls
) {
616 struct MHD_Response
*response
;
617 RequestMeta
*m
= connection_cls
;
625 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
627 if (request_parse_accept(m
, connection
) < 0)
628 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
630 r
= sd_journal_query_unique(m
->journal
, field
);
632 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to query unique fields.");
634 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_fields
, m
, NULL
);
636 return respond_oom(connection
);
638 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
== OUTPUT_JSON
? OUTPUT_JSON
: OUTPUT_SHORT
]);
640 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
641 MHD_destroy_response(response
);
646 static int request_handler_redirect(
647 struct MHD_Connection
*connection
,
648 const char *target
) {
651 struct MHD_Response
*response
;
657 if (asprintf(&page
, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target
) < 0)
658 return respond_oom(connection
);
660 response
= MHD_create_response_from_buffer(strlen(page
), page
, MHD_RESPMEM_MUST_FREE
);
663 return respond_oom(connection
);
666 MHD_add_response_header(response
, "Content-Type", "text/html");
667 MHD_add_response_header(response
, "Location", target
);
669 ret
= MHD_queue_response(connection
, MHD_HTTP_MOVED_PERMANENTLY
, response
);
670 MHD_destroy_response(response
);
675 static int request_handler_file(
676 struct MHD_Connection
*connection
,
678 const char *mime_type
) {
680 struct MHD_Response
*response
;
682 _cleanup_close_
int fd
= -1;
689 fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
691 return mhd_respondf(connection
, errno
, MHD_HTTP_NOT_FOUND
, "Failed to open file %s: %m", path
);
693 if (fstat(fd
, &st
) < 0)
694 return mhd_respondf(connection
, errno
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to stat file: %m");
696 response
= MHD_create_response_from_fd_at_offset64(st
.st_size
, fd
, 0);
698 return respond_oom(connection
);
702 MHD_add_response_header(response
, "Content-Type", mime_type
);
704 ret
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
705 MHD_destroy_response(response
);
710 static int get_virtualization(char **v
) {
711 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
715 r
= sd_bus_default_system(&bus
);
719 r
= sd_bus_get_property_string(
721 "org.freedesktop.systemd1",
722 "/org/freedesktop/systemd1",
723 "org.freedesktop.systemd1.Manager",
740 static int request_handler_machine(
741 struct MHD_Connection
*connection
,
742 void *connection_cls
) {
744 struct MHD_Response
*response
;
745 RequestMeta
*m
= connection_cls
;
747 _cleanup_free_
char* hostname
= NULL
, *os_name
= NULL
;
748 uint64_t cutoff_from
= 0, cutoff_to
= 0, usage
= 0;
751 _cleanup_free_
char *v
= NULL
;
758 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
760 r
= sd_id128_get_machine(&mid
);
762 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine machine ID: %m");
764 r
= sd_id128_get_boot(&bid
);
766 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine boot ID: %m");
768 hostname
= gethostname_malloc();
770 return respond_oom(connection
);
772 r
= sd_journal_get_usage(m
->journal
, &usage
);
774 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
776 r
= sd_journal_get_cutoff_realtime_usec(m
->journal
, &cutoff_from
, &cutoff_to
);
778 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
780 (void) parse_os_release(NULL
, "PRETTY_NAME", &os_name
, NULL
);
781 (void) get_virtualization(&v
);
784 "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR
"\","
785 "\"boot_id\" : \"" SD_ID128_FORMAT_STR
"\","
786 "\"hostname\" : \"%s\","
787 "\"os_pretty_name\" : \"%s\","
788 "\"virtualization\" : \"%s\","
789 "\"usage\" : \"%"PRIu64
"\","
790 "\"cutoff_from_realtime\" : \"%"PRIu64
"\","
791 "\"cutoff_to_realtime\" : \"%"PRIu64
"\" }\n",
792 SD_ID128_FORMAT_VAL(mid
),
793 SD_ID128_FORMAT_VAL(bid
),
794 hostname_cleanup(hostname
),
795 os_name
? os_name
: "Linux",
802 return respond_oom(connection
);
804 response
= MHD_create_response_from_buffer(strlen(json
), json
, MHD_RESPMEM_MUST_FREE
);
807 return respond_oom(connection
);
810 MHD_add_response_header(response
, "Content-Type", "application/json");
811 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
812 MHD_destroy_response(response
);
817 static int request_handler(
819 struct MHD_Connection
*connection
,
823 const char *upload_data
,
824 size_t *upload_data_size
,
825 void **connection_cls
) {
829 assert(connection_cls
);
833 if (!streq(method
, "GET"))
834 return mhd_respond(connection
, MHD_HTTP_NOT_ACCEPTABLE
, "Unsupported method.");
836 if (!*connection_cls
) {
837 if (!request_meta(connection_cls
))
838 return respond_oom(connection
);
843 r
= check_permissions(connection
, &code
, NULL
);
849 return request_handler_redirect(connection
, "/browse");
851 if (streq(url
, "/entries"))
852 return request_handler_entries(connection
, *connection_cls
);
854 if (startswith(url
, "/fields/"))
855 return request_handler_fields(connection
, url
+ 8, *connection_cls
);
857 if (streq(url
, "/browse"))
858 return request_handler_file(connection
, DOCUMENT_ROOT
"/browse.html", "text/html");
860 if (streq(url
, "/machine"))
861 return request_handler_machine(connection
, *connection_cls
);
863 return mhd_respond(connection
, MHD_HTTP_NOT_FOUND
, "Not found.");
866 static int help(void) {
867 _cleanup_free_
char *link
= NULL
;
870 r
= terminal_urlify_man("systemd-journal-gatewayd.service", "8", &link
);
874 printf("%s [OPTIONS...] ...\n\n"
875 "HTTP server for journal events.\n\n"
876 " -h --help Show this help\n"
877 " --version Show package version\n"
878 " --cert=CERT.PEM Server certificate in PEM format\n"
879 " --key=KEY.PEM Server key in PEM format\n"
880 " --trust=CERT.PEM Certificate authority certificate in PEM format\n"
881 " -D --directory=PATH Serve journal files in directory\n"
882 "\nSee the %s for details.\n"
883 , program_invocation_short_name
890 static int parse_argv(int argc
, char *argv
[]) {
900 static const struct option options
[] = {
901 { "help", no_argument
, NULL
, 'h' },
902 { "version", no_argument
, NULL
, ARG_VERSION
},
903 { "key", required_argument
, NULL
, ARG_KEY
},
904 { "cert", required_argument
, NULL
, ARG_CERT
},
905 { "trust", required_argument
, NULL
, ARG_TRUST
},
906 { "directory", required_argument
, NULL
, 'D' },
913 while ((c
= getopt_long(argc
, argv
, "hD:", options
, NULL
)) >= 0)
925 log_error("Key file specified twice");
928 r
= read_full_file(optarg
, &arg_key_pem
, NULL
);
930 return log_error_errno(r
, "Failed to read key file: %m");
936 log_error("Certificate file specified twice");
939 r
= read_full_file(optarg
, &arg_cert_pem
, NULL
);
941 return log_error_errno(r
, "Failed to read certificate file: %m");
942 assert(arg_cert_pem
);
948 log_error("CA certificate file specified twice");
951 r
= read_full_file(optarg
, &arg_trust_pem
, NULL
);
953 return log_error_errno(r
, "Failed to read CA certificate file: %m");
954 assert(arg_trust_pem
);
957 log_error("Option --trust is not available.");
961 arg_directory
= optarg
;
968 assert_not_reached("Unhandled option");
972 log_error("This program does not take arguments.");
976 if (!!arg_key_pem
!= !!arg_cert_pem
) {
977 log_error("Certificate and key files must be specified together");
981 if (arg_trust_pem
&& !arg_key_pem
) {
982 log_error("CA certificate can only be used with certificate file");
989 int main(int argc
, char *argv
[]) {
990 struct MHD_Daemon
*d
= NULL
;
995 r
= parse_argv(argc
, argv
);
1003 r
= setup_gnutls_logger(NULL
);
1005 return EXIT_FAILURE
;
1007 n
= sd_listen_fds(1);
1009 log_error_errno(n
, "Failed to determine passed sockets: %m");
1012 log_error("Can't listen on more than one socket.");
1015 struct MHD_OptionItem opts
[] = {
1016 { MHD_OPTION_NOTIFY_COMPLETED
,
1017 (intptr_t) request_meta_free
, NULL
},
1018 { MHD_OPTION_EXTERNAL_LOGGER
,
1019 (intptr_t) microhttpd_logger
, NULL
},
1020 { MHD_OPTION_END
, 0, NULL
},
1021 { MHD_OPTION_END
, 0, NULL
},
1022 { MHD_OPTION_END
, 0, NULL
},
1023 { MHD_OPTION_END
, 0, NULL
},
1024 { MHD_OPTION_END
, 0, NULL
}};
1027 /* We force MHD_USE_ITC here, in order to make sure
1028 * libmicrohttpd doesn't use shutdown() on our listening
1029 * socket, which would break socket re-activation. See
1031 * https://lists.gnu.org/archive/html/libmicrohttpd/2015-09/msg00014.html
1032 * https://github.com/systemd/systemd/pull/1286
1037 MHD_USE_DUAL_STACK
|
1039 MHD_USE_POLL_INTERNAL_THREAD
|
1040 MHD_USE_THREAD_PER_CONNECTION
;
1043 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1044 {MHD_OPTION_LISTEN_SOCKET
, SD_LISTEN_FDS_START
};
1046 assert(arg_cert_pem
);
1047 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1048 {MHD_OPTION_HTTPS_MEM_KEY
, 0, arg_key_pem
};
1049 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1050 {MHD_OPTION_HTTPS_MEM_CERT
, 0, arg_cert_pem
};
1051 flags
|= MHD_USE_TLS
;
1053 if (arg_trust_pem
) {
1054 assert(flags
& MHD_USE_TLS
);
1055 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1056 {MHD_OPTION_HTTPS_MEM_TRUST
, 0, arg_trust_pem
};
1059 d
= MHD_start_daemon(flags
, 19531,
1061 request_handler
, NULL
,
1062 MHD_OPTION_ARRAY
, opts
,
1067 log_error("Failed to start daemon!");