1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2012 Lennart Poettering
8 #include <microhttpd.h>
14 #include "sd-daemon.h"
15 #include "sd-journal.h"
17 #include "alloc-util.h"
21 #include "hostname-util.h"
23 #include "logs-show.h"
24 #include "microhttpd-util.h"
26 #include "parse-util.h"
30 #define JOURNAL_WAIT_TIMEOUT (10*USEC_PER_SEC)
32 static char *arg_key_pem
= NULL
;
33 static char *arg_cert_pem
= NULL
;
34 static char *arg_trust_pem
= NULL
;
35 static char *arg_directory
= NULL
;
37 typedef struct RequestMeta
{
50 int argument_parse_error
;
59 static const char* const mime_types
[_OUTPUT_MODE_MAX
] = {
60 [OUTPUT_SHORT
] = "text/plain",
61 [OUTPUT_JSON
] = "application/json",
62 [OUTPUT_JSON_SSE
] = "text/event-stream",
63 [OUTPUT_EXPORT
] = "application/vnd.fdo.journal",
66 static RequestMeta
*request_meta(void **connection_cls
) {
69 assert(connection_cls
);
71 return *connection_cls
;
73 m
= new0(RequestMeta
, 1);
81 static void request_meta_free(
83 struct MHD_Connection
*connection
,
84 void **connection_cls
,
85 enum MHD_RequestTerminationCode toe
) {
87 RequestMeta
*m
= *connection_cls
;
92 sd_journal_close(m
->journal
);
100 static int open_journal(RequestMeta
*m
) {
107 return sd_journal_open_directory(&m
->journal
, arg_directory
, 0);
109 return sd_journal_open(&m
->journal
, SD_JOURNAL_LOCAL_ONLY
|SD_JOURNAL_SYSTEM
);
112 static int request_meta_ensure_tmp(RequestMeta
*m
) {
120 fd
= open_tmpfile_unlinkable("/tmp", O_RDWR
|O_CLOEXEC
);
124 m
->tmp
= fdopen(fd
, "w+");
134 static ssize_t
request_reader_entries(
140 RequestMeta
*m
= cls
;
147 assert(pos
>= m
->delta
);
151 while (pos
>= m
->size
) {
154 /* End of this entry, so let's serialize the next
157 if (m
->n_entries_set
&&
159 return MHD_CONTENT_READER_END_OF_STREAM
;
162 r
= sd_journal_previous_skip(m
->journal
, (uint64_t) -m
->n_skip
+ 1);
163 else if (m
->n_skip
> 0)
164 r
= sd_journal_next_skip(m
->journal
, (uint64_t) m
->n_skip
+ 1);
166 r
= sd_journal_next(m
->journal
);
169 log_error_errno(r
, "Failed to advance journal pointer: %m");
170 return MHD_CONTENT_READER_END_WITH_ERROR
;
174 r
= sd_journal_wait(m
->journal
, (uint64_t) JOURNAL_WAIT_TIMEOUT
);
176 log_error_errno(r
, "Couldn't wait for journal event: %m");
177 return MHD_CONTENT_READER_END_WITH_ERROR
;
179 if (r
== SD_JOURNAL_NOP
)
185 return MHD_CONTENT_READER_END_OF_STREAM
;
191 r
= sd_journal_test_cursor(m
->journal
, m
->cursor
);
193 log_error_errno(r
, "Failed to test cursor: %m");
194 return MHD_CONTENT_READER_END_WITH_ERROR
;
198 return MHD_CONTENT_READER_END_OF_STREAM
;
204 if (m
->n_entries_set
)
209 r
= request_meta_ensure_tmp(m
);
211 log_error_errno(r
, "Failed to create temporary file: %m");
212 return MHD_CONTENT_READER_END_WITH_ERROR
;
215 r
= show_journal_entry(m
->tmp
, m
->journal
, m
->mode
, 0, OUTPUT_FULL_WIDTH
,
218 log_error_errno(r
, "Failed to serialize item: %m");
219 return MHD_CONTENT_READER_END_WITH_ERROR
;
223 if (sz
== (off_t
) -1) {
224 log_error_errno(errno
, "Failed to retrieve file position: %m");
225 return MHD_CONTENT_READER_END_WITH_ERROR
;
228 m
->size
= (uint64_t) sz
;
231 if (m
->tmp
== NULL
&& m
->follow
)
234 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
235 log_error_errno(errno
, "Failed to seek to position: %m");
236 return MHD_CONTENT_READER_END_WITH_ERROR
;
246 k
= fread(buf
, 1, n
, m
->tmp
);
248 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
249 return MHD_CONTENT_READER_END_WITH_ERROR
;
255 static int request_parse_accept(
257 struct MHD_Connection
*connection
) {
264 header
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Accept");
268 if (streq(header
, mime_types
[OUTPUT_JSON
]))
269 m
->mode
= OUTPUT_JSON
;
270 else if (streq(header
, mime_types
[OUTPUT_JSON_SSE
]))
271 m
->mode
= OUTPUT_JSON_SSE
;
272 else if (streq(header
, mime_types
[OUTPUT_EXPORT
]))
273 m
->mode
= OUTPUT_EXPORT
;
275 m
->mode
= OUTPUT_SHORT
;
280 static int request_parse_range(
282 struct MHD_Connection
*connection
) {
284 const char *range
, *colon
, *colon2
;
290 range
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Range");
294 if (!startswith(range
, "entries="))
298 range
+= strspn(range
, WHITESPACE
);
300 colon
= strchr(range
, ':');
302 m
->cursor
= strdup(range
);
306 colon2
= strchr(colon
+ 1, ':');
308 _cleanup_free_
char *t
;
310 t
= strndup(colon
+ 1, colon2
- colon
- 1);
314 r
= safe_atoi64(t
, &m
->n_skip
);
319 p
= (colon2
? colon2
: colon
) + 1;
321 r
= safe_atou64(p
, &m
->n_entries
);
325 if (m
->n_entries
<= 0)
328 m
->n_entries_set
= true;
331 m
->cursor
= strndup(range
, colon
- range
);
337 m
->cursor
[strcspn(m
->cursor
, WHITESPACE
)] = 0;
338 if (isempty(m
->cursor
))
339 m
->cursor
= mfree(m
->cursor
);
344 static int request_parse_arguments_iterator(
346 enum MHD_ValueKind kind
,
350 RequestMeta
*m
= cls
;
351 _cleanup_free_
char *p
= NULL
;
357 m
->argument_parse_error
= -EINVAL
;
361 if (streq(key
, "follow")) {
362 if (isempty(value
)) {
367 r
= parse_boolean(value
);
369 m
->argument_parse_error
= r
;
377 if (streq(key
, "discrete")) {
378 if (isempty(value
)) {
383 r
= parse_boolean(value
);
385 m
->argument_parse_error
= r
;
393 if (streq(key
, "boot")) {
397 r
= parse_boolean(value
);
399 m
->argument_parse_error
= r
;
405 char match
[9 + 32 + 1] = "_BOOT_ID=";
408 r
= sd_id128_get_boot(&bid
);
410 log_error_errno(r
, "Failed to get boot ID: %m");
414 sd_id128_to_string(bid
, match
+ 9);
415 r
= sd_journal_add_match(m
->journal
, match
, sizeof(match
)-1);
417 m
->argument_parse_error
= r
;
425 p
= strjoin(key
, "=", strempty(value
));
427 m
->argument_parse_error
= log_oom();
431 r
= sd_journal_add_match(m
->journal
, p
, 0);
433 m
->argument_parse_error
= r
;
440 static int request_parse_arguments(
442 struct MHD_Connection
*connection
) {
447 m
->argument_parse_error
= 0;
448 MHD_get_connection_values(connection
, MHD_GET_ARGUMENT_KIND
, request_parse_arguments_iterator
, m
);
450 return m
->argument_parse_error
;
453 static int request_handler_entries(
454 struct MHD_Connection
*connection
,
455 void *connection_cls
) {
457 struct MHD_Response
*response
;
458 RequestMeta
*m
= connection_cls
;
466 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
468 if (request_parse_accept(m
, connection
) < 0)
469 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
471 if (request_parse_range(m
, connection
) < 0)
472 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Range header.");
474 if (request_parse_arguments(m
, connection
) < 0)
475 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse URL arguments.");
479 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Discrete seeks require a cursor specification.");
482 m
->n_entries_set
= true;
486 r
= sd_journal_seek_cursor(m
->journal
, m
->cursor
);
487 else if (m
->n_skip
>= 0)
488 r
= sd_journal_seek_head(m
->journal
);
489 else if (m
->n_skip
< 0)
490 r
= sd_journal_seek_tail(m
->journal
);
492 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to seek in journal.");
494 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_entries
, m
, NULL
);
496 return respond_oom(connection
);
498 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
]);
500 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
501 MHD_destroy_response(response
);
506 static int output_field(FILE *f
, OutputMode m
, const char *d
, size_t l
) {
510 eq
= memchr(d
, '=', l
);
514 j
= l
- (eq
- d
+ 1);
516 if (m
== OUTPUT_JSON
) {
517 fprintf(f
, "{ \"%.*s\" : ", (int) (eq
- d
), d
);
518 json_escape(f
, eq
+1, j
, OUTPUT_FULL_WIDTH
);
521 fwrite(eq
+1, 1, j
, f
);
528 static ssize_t
request_reader_fields(
534 RequestMeta
*m
= cls
;
541 assert(pos
>= m
->delta
);
545 while (pos
>= m
->size
) {
550 /* End of this field, so let's serialize the next
553 if (m
->n_fields_set
&&
555 return MHD_CONTENT_READER_END_OF_STREAM
;
557 r
= sd_journal_enumerate_unique(m
->journal
, &d
, &l
);
559 log_error_errno(r
, "Failed to advance field index: %m");
560 return MHD_CONTENT_READER_END_WITH_ERROR
;
562 return MHD_CONTENT_READER_END_OF_STREAM
;
570 r
= request_meta_ensure_tmp(m
);
572 log_error_errno(r
, "Failed to create temporary file: %m");
573 return MHD_CONTENT_READER_END_WITH_ERROR
;
576 r
= output_field(m
->tmp
, m
->mode
, d
, l
);
578 log_error_errno(r
, "Failed to serialize item: %m");
579 return MHD_CONTENT_READER_END_WITH_ERROR
;
583 if (sz
== (off_t
) -1) {
584 log_error_errno(errno
, "Failed to retrieve file position: %m");
585 return MHD_CONTENT_READER_END_WITH_ERROR
;
588 m
->size
= (uint64_t) sz
;
591 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
592 log_error_errno(errno
, "Failed to seek to position: %m");
593 return MHD_CONTENT_READER_END_WITH_ERROR
;
601 k
= fread(buf
, 1, n
, m
->tmp
);
603 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
604 return MHD_CONTENT_READER_END_WITH_ERROR
;
610 static int request_handler_fields(
611 struct MHD_Connection
*connection
,
613 void *connection_cls
) {
615 struct MHD_Response
*response
;
616 RequestMeta
*m
= connection_cls
;
624 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
626 if (request_parse_accept(m
, connection
) < 0)
627 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
629 r
= sd_journal_query_unique(m
->journal
, field
);
631 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to query unique fields.");
633 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_fields
, m
, NULL
);
635 return respond_oom(connection
);
637 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
== OUTPUT_JSON
? OUTPUT_JSON
: OUTPUT_SHORT
]);
639 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
640 MHD_destroy_response(response
);
645 static int request_handler_redirect(
646 struct MHD_Connection
*connection
,
647 const char *target
) {
650 struct MHD_Response
*response
;
656 if (asprintf(&page
, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target
) < 0)
657 return respond_oom(connection
);
659 response
= MHD_create_response_from_buffer(strlen(page
), page
, MHD_RESPMEM_MUST_FREE
);
662 return respond_oom(connection
);
665 MHD_add_response_header(response
, "Content-Type", "text/html");
666 MHD_add_response_header(response
, "Location", target
);
668 ret
= MHD_queue_response(connection
, MHD_HTTP_MOVED_PERMANENTLY
, response
);
669 MHD_destroy_response(response
);
674 static int request_handler_file(
675 struct MHD_Connection
*connection
,
677 const char *mime_type
) {
679 struct MHD_Response
*response
;
681 _cleanup_close_
int fd
= -1;
688 fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
690 return mhd_respondf(connection
, errno
, MHD_HTTP_NOT_FOUND
, "Failed to open file %s: %m", path
);
692 if (fstat(fd
, &st
) < 0)
693 return mhd_respondf(connection
, errno
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to stat file: %m");
695 response
= MHD_create_response_from_fd_at_offset64(st
.st_size
, fd
, 0);
697 return respond_oom(connection
);
701 MHD_add_response_header(response
, "Content-Type", mime_type
);
703 ret
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
704 MHD_destroy_response(response
);
709 static int get_virtualization(char **v
) {
710 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
714 r
= sd_bus_default_system(&bus
);
718 r
= sd_bus_get_property_string(
720 "org.freedesktop.systemd1",
721 "/org/freedesktop/systemd1",
722 "org.freedesktop.systemd1.Manager",
739 static int request_handler_machine(
740 struct MHD_Connection
*connection
,
741 void *connection_cls
) {
743 struct MHD_Response
*response
;
744 RequestMeta
*m
= connection_cls
;
746 _cleanup_free_
char* hostname
= NULL
, *os_name
= NULL
;
747 uint64_t cutoff_from
= 0, cutoff_to
= 0, usage
= 0;
750 _cleanup_free_
char *v
= NULL
;
757 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
759 r
= sd_id128_get_machine(&mid
);
761 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine machine ID: %m");
763 r
= sd_id128_get_boot(&bid
);
765 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine boot ID: %m");
767 hostname
= gethostname_malloc();
769 return respond_oom(connection
);
771 r
= sd_journal_get_usage(m
->journal
, &usage
);
773 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
775 r
= sd_journal_get_cutoff_realtime_usec(m
->journal
, &cutoff_from
, &cutoff_to
);
777 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
779 (void) parse_os_release(NULL
, "PRETTY_NAME", &os_name
, NULL
);
780 (void) get_virtualization(&v
);
783 "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR
"\","
784 "\"boot_id\" : \"" SD_ID128_FORMAT_STR
"\","
785 "\"hostname\" : \"%s\","
786 "\"os_pretty_name\" : \"%s\","
787 "\"virtualization\" : \"%s\","
788 "\"usage\" : \"%"PRIu64
"\","
789 "\"cutoff_from_realtime\" : \"%"PRIu64
"\","
790 "\"cutoff_to_realtime\" : \"%"PRIu64
"\" }\n",
791 SD_ID128_FORMAT_VAL(mid
),
792 SD_ID128_FORMAT_VAL(bid
),
793 hostname_cleanup(hostname
),
794 os_name
? os_name
: "Linux",
801 return respond_oom(connection
);
803 response
= MHD_create_response_from_buffer(strlen(json
), json
, MHD_RESPMEM_MUST_FREE
);
806 return respond_oom(connection
);
809 MHD_add_response_header(response
, "Content-Type", "application/json");
810 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
811 MHD_destroy_response(response
);
816 static int request_handler(
818 struct MHD_Connection
*connection
,
822 const char *upload_data
,
823 size_t *upload_data_size
,
824 void **connection_cls
) {
828 assert(connection_cls
);
832 if (!streq(method
, "GET"))
833 return mhd_respond(connection
, MHD_HTTP_NOT_ACCEPTABLE
, "Unsupported method.");
835 if (!*connection_cls
) {
836 if (!request_meta(connection_cls
))
837 return respond_oom(connection
);
842 r
= check_permissions(connection
, &code
, NULL
);
848 return request_handler_redirect(connection
, "/browse");
850 if (streq(url
, "/entries"))
851 return request_handler_entries(connection
, *connection_cls
);
853 if (startswith(url
, "/fields/"))
854 return request_handler_fields(connection
, url
+ 8, *connection_cls
);
856 if (streq(url
, "/browse"))
857 return request_handler_file(connection
, DOCUMENT_ROOT
"/browse.html", "text/html");
859 if (streq(url
, "/machine"))
860 return request_handler_machine(connection
, *connection_cls
);
862 return mhd_respond(connection
, MHD_HTTP_NOT_FOUND
, "Not found.");
865 static void help(void) {
866 printf("%s [OPTIONS...] ...\n\n"
867 "HTTP server for journal events.\n\n"
868 " -h --help Show this help\n"
869 " --version Show package version\n"
870 " --cert=CERT.PEM Server certificate in PEM format\n"
871 " --key=KEY.PEM Server key in PEM format\n"
872 " --trust=CERT.PEM Certificate authority certificate in PEM format\n"
873 " -D --directory=PATH Serve journal files in directory\n",
874 program_invocation_short_name
);
877 static int parse_argv(int argc
, char *argv
[]) {
887 static const struct option options
[] = {
888 { "help", no_argument
, NULL
, 'h' },
889 { "version", no_argument
, NULL
, ARG_VERSION
},
890 { "key", required_argument
, NULL
, ARG_KEY
},
891 { "cert", required_argument
, NULL
, ARG_CERT
},
892 { "trust", required_argument
, NULL
, ARG_TRUST
},
893 { "directory", required_argument
, NULL
, 'D' },
900 while ((c
= getopt_long(argc
, argv
, "hD:", options
, NULL
)) >= 0)
913 log_error("Key file specified twice");
916 r
= read_full_file(optarg
, &arg_key_pem
, NULL
);
918 return log_error_errno(r
, "Failed to read key file: %m");
924 log_error("Certificate file specified twice");
927 r
= read_full_file(optarg
, &arg_cert_pem
, NULL
);
929 return log_error_errno(r
, "Failed to read certificate file: %m");
930 assert(arg_cert_pem
);
936 log_error("CA certificate file specified twice");
939 r
= read_full_file(optarg
, &arg_trust_pem
, NULL
);
941 return log_error_errno(r
, "Failed to read CA certificate file: %m");
942 assert(arg_trust_pem
);
945 log_error("Option --trust is not available.");
949 arg_directory
= optarg
;
956 assert_not_reached("Unhandled option");
960 log_error("This program does not take arguments.");
964 if (!!arg_key_pem
!= !!arg_cert_pem
) {
965 log_error("Certificate and key files must be specified together");
969 if (arg_trust_pem
&& !arg_key_pem
) {
970 log_error("CA certificate can only be used with certificate file");
977 int main(int argc
, char *argv
[]) {
978 struct MHD_Daemon
*d
= NULL
;
981 log_set_target(LOG_TARGET_AUTO
);
982 log_parse_environment();
985 r
= parse_argv(argc
, argv
);
993 r
= setup_gnutls_logger(NULL
);
997 n
= sd_listen_fds(1);
999 log_error_errno(n
, "Failed to determine passed sockets: %m");
1002 log_error("Can't listen on more than one socket.");
1005 struct MHD_OptionItem opts
[] = {
1006 { MHD_OPTION_NOTIFY_COMPLETED
,
1007 (intptr_t) request_meta_free
, NULL
},
1008 { MHD_OPTION_EXTERNAL_LOGGER
,
1009 (intptr_t) microhttpd_logger
, NULL
},
1010 { MHD_OPTION_END
, 0, NULL
},
1011 { MHD_OPTION_END
, 0, NULL
},
1012 { MHD_OPTION_END
, 0, NULL
},
1013 { MHD_OPTION_END
, 0, NULL
},
1014 { MHD_OPTION_END
, 0, NULL
}};
1017 /* We force MHD_USE_ITC here, in order to make sure
1018 * libmicrohttpd doesn't use shutdown() on our listening
1019 * socket, which would break socket re-activation. See
1021 * https://lists.gnu.org/archive/html/libmicrohttpd/2015-09/msg00014.html
1022 * https://github.com/systemd/systemd/pull/1286
1027 MHD_USE_DUAL_STACK
|
1029 MHD_USE_POLL_INTERNAL_THREAD
|
1030 MHD_USE_THREAD_PER_CONNECTION
;
1033 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1034 {MHD_OPTION_LISTEN_SOCKET
, SD_LISTEN_FDS_START
};
1036 assert(arg_cert_pem
);
1037 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1038 {MHD_OPTION_HTTPS_MEM_KEY
, 0, arg_key_pem
};
1039 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1040 {MHD_OPTION_HTTPS_MEM_CERT
, 0, arg_cert_pem
};
1041 flags
|= MHD_USE_TLS
;
1043 if (arg_trust_pem
) {
1044 assert(flags
& MHD_USE_TLS
);
1045 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1046 {MHD_OPTION_HTTPS_MEM_TRUST
, 0, arg_trust_pem
};
1049 d
= MHD_start_daemon(flags
, 19531,
1051 request_handler
, NULL
,
1052 MHD_OPTION_ARRAY
, opts
,
1057 log_error("Failed to start daemon!");