1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2012 Lennart Poettering
10 #include <microhttpd.h>
16 #include "sd-daemon.h"
17 #include "sd-journal.h"
19 #include "alloc-util.h"
23 #include "hostname-util.h"
25 #include "logs-show.h"
26 #include "microhttpd-util.h"
28 #include "parse-util.h"
32 #define JOURNAL_WAIT_TIMEOUT (10*USEC_PER_SEC)
34 static char *arg_key_pem
= NULL
;
35 static char *arg_cert_pem
= NULL
;
36 static char *arg_trust_pem
= NULL
;
37 static char *arg_directory
= NULL
;
39 typedef struct RequestMeta
{
52 int argument_parse_error
;
61 static const char* const mime_types
[_OUTPUT_MODE_MAX
] = {
62 [OUTPUT_SHORT
] = "text/plain",
63 [OUTPUT_JSON
] = "application/json",
64 [OUTPUT_JSON_SSE
] = "text/event-stream",
65 [OUTPUT_EXPORT
] = "application/vnd.fdo.journal",
68 static RequestMeta
*request_meta(void **connection_cls
) {
71 assert(connection_cls
);
73 return *connection_cls
;
75 m
= new0(RequestMeta
, 1);
83 static void request_meta_free(
85 struct MHD_Connection
*connection
,
86 void **connection_cls
,
87 enum MHD_RequestTerminationCode toe
) {
89 RequestMeta
*m
= *connection_cls
;
94 sd_journal_close(m
->journal
);
102 static int open_journal(RequestMeta
*m
) {
109 return sd_journal_open_directory(&m
->journal
, arg_directory
, 0);
111 return sd_journal_open(&m
->journal
, SD_JOURNAL_LOCAL_ONLY
|SD_JOURNAL_SYSTEM
);
114 static int request_meta_ensure_tmp(RequestMeta
*m
) {
122 fd
= open_tmpfile_unlinkable("/tmp", O_RDWR
|O_CLOEXEC
);
126 m
->tmp
= fdopen(fd
, "w+");
136 static ssize_t
request_reader_entries(
142 RequestMeta
*m
= cls
;
149 assert(pos
>= m
->delta
);
153 while (pos
>= m
->size
) {
156 /* End of this entry, so let's serialize the next
159 if (m
->n_entries_set
&&
161 return MHD_CONTENT_READER_END_OF_STREAM
;
164 r
= sd_journal_previous_skip(m
->journal
, (uint64_t) -m
->n_skip
+ 1);
165 else if (m
->n_skip
> 0)
166 r
= sd_journal_next_skip(m
->journal
, (uint64_t) m
->n_skip
+ 1);
168 r
= sd_journal_next(m
->journal
);
171 log_error_errno(r
, "Failed to advance journal pointer: %m");
172 return MHD_CONTENT_READER_END_WITH_ERROR
;
176 r
= sd_journal_wait(m
->journal
, (uint64_t) JOURNAL_WAIT_TIMEOUT
);
178 log_error_errno(r
, "Couldn't wait for journal event: %m");
179 return MHD_CONTENT_READER_END_WITH_ERROR
;
181 if (r
== SD_JOURNAL_NOP
)
187 return MHD_CONTENT_READER_END_OF_STREAM
;
193 r
= sd_journal_test_cursor(m
->journal
, m
->cursor
);
195 log_error_errno(r
, "Failed to test cursor: %m");
196 return MHD_CONTENT_READER_END_WITH_ERROR
;
200 return MHD_CONTENT_READER_END_OF_STREAM
;
206 if (m
->n_entries_set
)
211 r
= request_meta_ensure_tmp(m
);
213 log_error_errno(r
, "Failed to create temporary file: %m");
214 return MHD_CONTENT_READER_END_WITH_ERROR
;
217 r
= show_journal_entry(m
->tmp
, m
->journal
, m
->mode
, 0, OUTPUT_FULL_WIDTH
,
220 log_error_errno(r
, "Failed to serialize item: %m");
221 return MHD_CONTENT_READER_END_WITH_ERROR
;
225 if (sz
== (off_t
) -1) {
226 log_error_errno(errno
, "Failed to retrieve file position: %m");
227 return MHD_CONTENT_READER_END_WITH_ERROR
;
230 m
->size
= (uint64_t) sz
;
233 if (m
->tmp
== NULL
&& m
->follow
)
236 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
237 log_error_errno(errno
, "Failed to seek to position: %m");
238 return MHD_CONTENT_READER_END_WITH_ERROR
;
248 k
= fread(buf
, 1, n
, m
->tmp
);
250 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
251 return MHD_CONTENT_READER_END_WITH_ERROR
;
257 static int request_parse_accept(
259 struct MHD_Connection
*connection
) {
266 header
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Accept");
270 if (streq(header
, mime_types
[OUTPUT_JSON
]))
271 m
->mode
= OUTPUT_JSON
;
272 else if (streq(header
, mime_types
[OUTPUT_JSON_SSE
]))
273 m
->mode
= OUTPUT_JSON_SSE
;
274 else if (streq(header
, mime_types
[OUTPUT_EXPORT
]))
275 m
->mode
= OUTPUT_EXPORT
;
277 m
->mode
= OUTPUT_SHORT
;
282 static int request_parse_range(
284 struct MHD_Connection
*connection
) {
286 const char *range
, *colon
, *colon2
;
292 range
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Range");
296 if (!startswith(range
, "entries="))
300 range
+= strspn(range
, WHITESPACE
);
302 colon
= strchr(range
, ':');
304 m
->cursor
= strdup(range
);
308 colon2
= strchr(colon
+ 1, ':');
310 _cleanup_free_
char *t
;
312 t
= strndup(colon
+ 1, colon2
- colon
- 1);
316 r
= safe_atoi64(t
, &m
->n_skip
);
321 p
= (colon2
? colon2
: colon
) + 1;
323 r
= safe_atou64(p
, &m
->n_entries
);
327 if (m
->n_entries
<= 0)
330 m
->n_entries_set
= true;
333 m
->cursor
= strndup(range
, colon
- range
);
339 m
->cursor
[strcspn(m
->cursor
, WHITESPACE
)] = 0;
340 if (isempty(m
->cursor
))
341 m
->cursor
= mfree(m
->cursor
);
346 static int request_parse_arguments_iterator(
348 enum MHD_ValueKind kind
,
352 RequestMeta
*m
= cls
;
353 _cleanup_free_
char *p
= NULL
;
359 m
->argument_parse_error
= -EINVAL
;
363 if (streq(key
, "follow")) {
364 if (isempty(value
)) {
369 r
= parse_boolean(value
);
371 m
->argument_parse_error
= r
;
379 if (streq(key
, "discrete")) {
380 if (isempty(value
)) {
385 r
= parse_boolean(value
);
387 m
->argument_parse_error
= r
;
395 if (streq(key
, "boot")) {
399 r
= parse_boolean(value
);
401 m
->argument_parse_error
= r
;
407 char match
[9 + 32 + 1] = "_BOOT_ID=";
410 r
= sd_id128_get_boot(&bid
);
412 log_error_errno(r
, "Failed to get boot ID: %m");
416 sd_id128_to_string(bid
, match
+ 9);
417 r
= sd_journal_add_match(m
->journal
, match
, sizeof(match
)-1);
419 m
->argument_parse_error
= r
;
427 p
= strjoin(key
, "=", strempty(value
));
429 m
->argument_parse_error
= log_oom();
433 r
= sd_journal_add_match(m
->journal
, p
, 0);
435 m
->argument_parse_error
= r
;
442 static int request_parse_arguments(
444 struct MHD_Connection
*connection
) {
449 m
->argument_parse_error
= 0;
450 MHD_get_connection_values(connection
, MHD_GET_ARGUMENT_KIND
, request_parse_arguments_iterator
, m
);
452 return m
->argument_parse_error
;
455 static int request_handler_entries(
456 struct MHD_Connection
*connection
,
457 void *connection_cls
) {
459 struct MHD_Response
*response
;
460 RequestMeta
*m
= connection_cls
;
468 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
470 if (request_parse_accept(m
, connection
) < 0)
471 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
473 if (request_parse_range(m
, connection
) < 0)
474 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Range header.");
476 if (request_parse_arguments(m
, connection
) < 0)
477 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse URL arguments.");
481 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Discrete seeks require a cursor specification.");
484 m
->n_entries_set
= true;
488 r
= sd_journal_seek_cursor(m
->journal
, m
->cursor
);
489 else if (m
->n_skip
>= 0)
490 r
= sd_journal_seek_head(m
->journal
);
491 else if (m
->n_skip
< 0)
492 r
= sd_journal_seek_tail(m
->journal
);
494 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to seek in journal.");
496 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_entries
, m
, NULL
);
498 return respond_oom(connection
);
500 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
]);
502 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
503 MHD_destroy_response(response
);
508 static int output_field(FILE *f
, OutputMode m
, const char *d
, size_t l
) {
512 eq
= memchr(d
, '=', l
);
516 j
= l
- (eq
- d
+ 1);
518 if (m
== OUTPUT_JSON
) {
519 fprintf(f
, "{ \"%.*s\" : ", (int) (eq
- d
), d
);
520 json_escape(f
, eq
+1, j
, OUTPUT_FULL_WIDTH
);
523 fwrite(eq
+1, 1, j
, f
);
530 static ssize_t
request_reader_fields(
536 RequestMeta
*m
= cls
;
543 assert(pos
>= m
->delta
);
547 while (pos
>= m
->size
) {
552 /* End of this field, so let's serialize the next
555 if (m
->n_fields_set
&&
557 return MHD_CONTENT_READER_END_OF_STREAM
;
559 r
= sd_journal_enumerate_unique(m
->journal
, &d
, &l
);
561 log_error_errno(r
, "Failed to advance field index: %m");
562 return MHD_CONTENT_READER_END_WITH_ERROR
;
564 return MHD_CONTENT_READER_END_OF_STREAM
;
572 r
= request_meta_ensure_tmp(m
);
574 log_error_errno(r
, "Failed to create temporary file: %m");
575 return MHD_CONTENT_READER_END_WITH_ERROR
;
578 r
= output_field(m
->tmp
, m
->mode
, d
, l
);
580 log_error_errno(r
, "Failed to serialize item: %m");
581 return MHD_CONTENT_READER_END_WITH_ERROR
;
585 if (sz
== (off_t
) -1) {
586 log_error_errno(errno
, "Failed to retrieve file position: %m");
587 return MHD_CONTENT_READER_END_WITH_ERROR
;
590 m
->size
= (uint64_t) sz
;
593 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
594 log_error_errno(errno
, "Failed to seek to position: %m");
595 return MHD_CONTENT_READER_END_WITH_ERROR
;
603 k
= fread(buf
, 1, n
, m
->tmp
);
605 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
606 return MHD_CONTENT_READER_END_WITH_ERROR
;
612 static int request_handler_fields(
613 struct MHD_Connection
*connection
,
615 void *connection_cls
) {
617 struct MHD_Response
*response
;
618 RequestMeta
*m
= connection_cls
;
626 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
628 if (request_parse_accept(m
, connection
) < 0)
629 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
631 r
= sd_journal_query_unique(m
->journal
, field
);
633 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to query unique fields.");
635 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_fields
, m
, NULL
);
637 return respond_oom(connection
);
639 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
== OUTPUT_JSON
? OUTPUT_JSON
: OUTPUT_SHORT
]);
641 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
642 MHD_destroy_response(response
);
647 static int request_handler_redirect(
648 struct MHD_Connection
*connection
,
649 const char *target
) {
652 struct MHD_Response
*response
;
658 if (asprintf(&page
, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target
) < 0)
659 return respond_oom(connection
);
661 response
= MHD_create_response_from_buffer(strlen(page
), page
, MHD_RESPMEM_MUST_FREE
);
664 return respond_oom(connection
);
667 MHD_add_response_header(response
, "Content-Type", "text/html");
668 MHD_add_response_header(response
, "Location", target
);
670 ret
= MHD_queue_response(connection
, MHD_HTTP_MOVED_PERMANENTLY
, response
);
671 MHD_destroy_response(response
);
676 static int request_handler_file(
677 struct MHD_Connection
*connection
,
679 const char *mime_type
) {
681 struct MHD_Response
*response
;
683 _cleanup_close_
int fd
= -1;
690 fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
692 return mhd_respondf(connection
, errno
, MHD_HTTP_NOT_FOUND
, "Failed to open file %s: %m", path
);
694 if (fstat(fd
, &st
) < 0)
695 return mhd_respondf(connection
, errno
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to stat file: %m");
697 response
= MHD_create_response_from_fd_at_offset64(st
.st_size
, fd
, 0);
699 return respond_oom(connection
);
703 MHD_add_response_header(response
, "Content-Type", mime_type
);
705 ret
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
706 MHD_destroy_response(response
);
711 static int get_virtualization(char **v
) {
712 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
716 r
= sd_bus_default_system(&bus
);
720 r
= sd_bus_get_property_string(
722 "org.freedesktop.systemd1",
723 "/org/freedesktop/systemd1",
724 "org.freedesktop.systemd1.Manager",
741 static int request_handler_machine(
742 struct MHD_Connection
*connection
,
743 void *connection_cls
) {
745 struct MHD_Response
*response
;
746 RequestMeta
*m
= connection_cls
;
748 _cleanup_free_
char* hostname
= NULL
, *os_name
= NULL
;
749 uint64_t cutoff_from
= 0, cutoff_to
= 0, usage
= 0;
752 _cleanup_free_
char *v
= NULL
;
759 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
761 r
= sd_id128_get_machine(&mid
);
763 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine machine ID: %m");
765 r
= sd_id128_get_boot(&bid
);
767 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine boot ID: %m");
769 hostname
= gethostname_malloc();
771 return respond_oom(connection
);
773 r
= sd_journal_get_usage(m
->journal
, &usage
);
775 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
777 r
= sd_journal_get_cutoff_realtime_usec(m
->journal
, &cutoff_from
, &cutoff_to
);
779 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
781 (void) parse_os_release(NULL
, "PRETTY_NAME", &os_name
, NULL
);
782 (void) get_virtualization(&v
);
785 "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR
"\","
786 "\"boot_id\" : \"" SD_ID128_FORMAT_STR
"\","
787 "\"hostname\" : \"%s\","
788 "\"os_pretty_name\" : \"%s\","
789 "\"virtualization\" : \"%s\","
790 "\"usage\" : \"%"PRIu64
"\","
791 "\"cutoff_from_realtime\" : \"%"PRIu64
"\","
792 "\"cutoff_to_realtime\" : \"%"PRIu64
"\" }\n",
793 SD_ID128_FORMAT_VAL(mid
),
794 SD_ID128_FORMAT_VAL(bid
),
795 hostname_cleanup(hostname
),
796 os_name
? os_name
: "Linux",
803 return respond_oom(connection
);
805 response
= MHD_create_response_from_buffer(strlen(json
), json
, MHD_RESPMEM_MUST_FREE
);
808 return respond_oom(connection
);
811 MHD_add_response_header(response
, "Content-Type", "application/json");
812 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
813 MHD_destroy_response(response
);
818 static int request_handler(
820 struct MHD_Connection
*connection
,
824 const char *upload_data
,
825 size_t *upload_data_size
,
826 void **connection_cls
) {
830 assert(connection_cls
);
834 if (!streq(method
, "GET"))
835 return mhd_respond(connection
, MHD_HTTP_NOT_ACCEPTABLE
, "Unsupported method.");
837 if (!*connection_cls
) {
838 if (!request_meta(connection_cls
))
839 return respond_oom(connection
);
844 r
= check_permissions(connection
, &code
, NULL
);
850 return request_handler_redirect(connection
, "/browse");
852 if (streq(url
, "/entries"))
853 return request_handler_entries(connection
, *connection_cls
);
855 if (startswith(url
, "/fields/"))
856 return request_handler_fields(connection
, url
+ 8, *connection_cls
);
858 if (streq(url
, "/browse"))
859 return request_handler_file(connection
, DOCUMENT_ROOT
"/browse.html", "text/html");
861 if (streq(url
, "/machine"))
862 return request_handler_machine(connection
, *connection_cls
);
864 return mhd_respond(connection
, MHD_HTTP_NOT_FOUND
, "Not found.");
867 static void help(void) {
868 printf("%s [OPTIONS...] ...\n\n"
869 "HTTP server for journal events.\n\n"
870 " -h --help Show this help\n"
871 " --version Show package version\n"
872 " --cert=CERT.PEM Server certificate in PEM format\n"
873 " --key=KEY.PEM Server key in PEM format\n"
874 " --trust=CERT.PEM Certificate authority certificate in PEM format\n"
875 " -D --directory=PATH Serve journal files in directory\n",
876 program_invocation_short_name
);
879 static int parse_argv(int argc
, char *argv
[]) {
889 static const struct option options
[] = {
890 { "help", no_argument
, NULL
, 'h' },
891 { "version", no_argument
, NULL
, ARG_VERSION
},
892 { "key", required_argument
, NULL
, ARG_KEY
},
893 { "cert", required_argument
, NULL
, ARG_CERT
},
894 { "trust", required_argument
, NULL
, ARG_TRUST
},
895 { "directory", required_argument
, NULL
, 'D' },
902 while ((c
= getopt_long(argc
, argv
, "hD:", options
, NULL
)) >= 0)
915 log_error("Key file specified twice");
918 r
= read_full_file(optarg
, &arg_key_pem
, NULL
);
920 return log_error_errno(r
, "Failed to read key file: %m");
926 log_error("Certificate file specified twice");
929 r
= read_full_file(optarg
, &arg_cert_pem
, NULL
);
931 return log_error_errno(r
, "Failed to read certificate file: %m");
932 assert(arg_cert_pem
);
938 log_error("CA certificate file specified twice");
941 r
= read_full_file(optarg
, &arg_trust_pem
, NULL
);
943 return log_error_errno(r
, "Failed to read CA certificate file: %m");
944 assert(arg_trust_pem
);
947 log_error("Option --trust is not available.");
951 arg_directory
= optarg
;
958 assert_not_reached("Unhandled option");
962 log_error("This program does not take arguments.");
966 if (!!arg_key_pem
!= !!arg_cert_pem
) {
967 log_error("Certificate and key files must be specified together");
971 if (arg_trust_pem
&& !arg_key_pem
) {
972 log_error("CA certificate can only be used with certificate file");
979 int main(int argc
, char *argv
[]) {
980 struct MHD_Daemon
*d
= NULL
;
983 log_set_target(LOG_TARGET_AUTO
);
984 log_parse_environment();
987 r
= parse_argv(argc
, argv
);
995 r
= setup_gnutls_logger(NULL
);
999 n
= sd_listen_fds(1);
1001 log_error_errno(n
, "Failed to determine passed sockets: %m");
1004 log_error("Can't listen on more than one socket.");
1007 struct MHD_OptionItem opts
[] = {
1008 { MHD_OPTION_NOTIFY_COMPLETED
,
1009 (intptr_t) request_meta_free
, NULL
},
1010 { MHD_OPTION_EXTERNAL_LOGGER
,
1011 (intptr_t) microhttpd_logger
, NULL
},
1012 { MHD_OPTION_END
, 0, NULL
},
1013 { MHD_OPTION_END
, 0, NULL
},
1014 { MHD_OPTION_END
, 0, NULL
},
1015 { MHD_OPTION_END
, 0, NULL
},
1016 { MHD_OPTION_END
, 0, NULL
}};
1019 /* We force MHD_USE_ITC here, in order to make sure
1020 * libmicrohttpd doesn't use shutdown() on our listening
1021 * socket, which would break socket re-activation. See
1023 * https://lists.gnu.org/archive/html/libmicrohttpd/2015-09/msg00014.html
1024 * https://github.com/systemd/systemd/pull/1286
1029 MHD_USE_DUAL_STACK
|
1031 MHD_USE_POLL_INTERNAL_THREAD
|
1032 MHD_USE_THREAD_PER_CONNECTION
;
1035 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1036 {MHD_OPTION_LISTEN_SOCKET
, SD_LISTEN_FDS_START
};
1038 assert(arg_cert_pem
);
1039 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1040 {MHD_OPTION_HTTPS_MEM_KEY
, 0, arg_key_pem
};
1041 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1042 {MHD_OPTION_HTTPS_MEM_CERT
, 0, arg_cert_pem
};
1043 flags
|= MHD_USE_TLS
;
1045 if (arg_trust_pem
) {
1046 assert(flags
& MHD_USE_TLS
);
1047 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1048 {MHD_OPTION_HTTPS_MEM_TRUST
, 0, arg_trust_pem
};
1051 d
= MHD_start_daemon(flags
, 19531,
1053 request_handler
, NULL
,
1054 MHD_OPTION_ARRAY
, opts
,
1059 log_error("Failed to start daemon!");