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"
27 #define JOURNAL_WAIT_TIMEOUT (10*USEC_PER_SEC)
29 static char *arg_key_pem
= NULL
;
30 static char *arg_cert_pem
= NULL
;
31 static char *arg_trust_pem
= NULL
;
32 static char *arg_directory
= NULL
;
34 typedef struct RequestMeta
{
47 int argument_parse_error
;
56 static const char* const mime_types
[_OUTPUT_MODE_MAX
] = {
57 [OUTPUT_SHORT
] = "text/plain",
58 [OUTPUT_JSON
] = "application/json",
59 [OUTPUT_JSON_SSE
] = "text/event-stream",
60 [OUTPUT_EXPORT
] = "application/vnd.fdo.journal",
63 static RequestMeta
*request_meta(void **connection_cls
) {
66 assert(connection_cls
);
68 return *connection_cls
;
70 m
= new0(RequestMeta
, 1);
78 static void request_meta_free(
80 struct MHD_Connection
*connection
,
81 void **connection_cls
,
82 enum MHD_RequestTerminationCode toe
) {
84 RequestMeta
*m
= *connection_cls
;
89 sd_journal_close(m
->journal
);
97 static int open_journal(RequestMeta
*m
) {
104 return sd_journal_open_directory(&m
->journal
, arg_directory
, 0);
106 return sd_journal_open(&m
->journal
, SD_JOURNAL_LOCAL_ONLY
|SD_JOURNAL_SYSTEM
);
109 static int request_meta_ensure_tmp(RequestMeta
*m
) {
117 fd
= open_tmpfile_unlinkable("/tmp", O_RDWR
|O_CLOEXEC
);
121 m
->tmp
= fdopen(fd
, "w+");
131 static ssize_t
request_reader_entries(
137 RequestMeta
*m
= cls
;
144 assert(pos
>= m
->delta
);
148 while (pos
>= m
->size
) {
151 /* End of this entry, so let's serialize the next
154 if (m
->n_entries_set
&&
156 return MHD_CONTENT_READER_END_OF_STREAM
;
159 r
= sd_journal_previous_skip(m
->journal
, (uint64_t) -m
->n_skip
+ 1);
160 else if (m
->n_skip
> 0)
161 r
= sd_journal_next_skip(m
->journal
, (uint64_t) m
->n_skip
+ 1);
163 r
= sd_journal_next(m
->journal
);
166 log_error_errno(r
, "Failed to advance journal pointer: %m");
167 return MHD_CONTENT_READER_END_WITH_ERROR
;
171 r
= sd_journal_wait(m
->journal
, (uint64_t) JOURNAL_WAIT_TIMEOUT
);
173 log_error_errno(r
, "Couldn't wait for journal event: %m");
174 return MHD_CONTENT_READER_END_WITH_ERROR
;
176 if (r
== SD_JOURNAL_NOP
)
182 return MHD_CONTENT_READER_END_OF_STREAM
;
188 r
= sd_journal_test_cursor(m
->journal
, m
->cursor
);
190 log_error_errno(r
, "Failed to test cursor: %m");
191 return MHD_CONTENT_READER_END_WITH_ERROR
;
195 return MHD_CONTENT_READER_END_OF_STREAM
;
201 if (m
->n_entries_set
)
206 r
= request_meta_ensure_tmp(m
);
208 log_error_errno(r
, "Failed to create temporary file: %m");
209 return MHD_CONTENT_READER_END_WITH_ERROR
;
212 r
= show_journal_entry(m
->tmp
, m
->journal
, m
->mode
, 0, OUTPUT_FULL_WIDTH
,
215 log_error_errno(r
, "Failed to serialize item: %m");
216 return MHD_CONTENT_READER_END_WITH_ERROR
;
220 if (sz
== (off_t
) -1) {
221 log_error_errno(errno
, "Failed to retrieve file position: %m");
222 return MHD_CONTENT_READER_END_WITH_ERROR
;
225 m
->size
= (uint64_t) sz
;
228 if (m
->tmp
== NULL
&& m
->follow
)
231 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
232 log_error_errno(errno
, "Failed to seek to position: %m");
233 return MHD_CONTENT_READER_END_WITH_ERROR
;
243 k
= fread(buf
, 1, n
, m
->tmp
);
245 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
246 return MHD_CONTENT_READER_END_WITH_ERROR
;
252 static int request_parse_accept(
254 struct MHD_Connection
*connection
) {
261 header
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Accept");
265 if (streq(header
, mime_types
[OUTPUT_JSON
]))
266 m
->mode
= OUTPUT_JSON
;
267 else if (streq(header
, mime_types
[OUTPUT_JSON_SSE
]))
268 m
->mode
= OUTPUT_JSON_SSE
;
269 else if (streq(header
, mime_types
[OUTPUT_EXPORT
]))
270 m
->mode
= OUTPUT_EXPORT
;
272 m
->mode
= OUTPUT_SHORT
;
277 static int request_parse_range(
279 struct MHD_Connection
*connection
) {
281 const char *range
, *colon
, *colon2
;
287 range
= MHD_lookup_connection_value(connection
, MHD_HEADER_KIND
, "Range");
291 if (!startswith(range
, "entries="))
295 range
+= strspn(range
, WHITESPACE
);
297 colon
= strchr(range
, ':');
299 m
->cursor
= strdup(range
);
303 colon2
= strchr(colon
+ 1, ':');
305 _cleanup_free_
char *t
;
307 t
= strndup(colon
+ 1, colon2
- colon
- 1);
311 r
= safe_atoi64(t
, &m
->n_skip
);
316 p
= (colon2
? colon2
: colon
) + 1;
318 r
= safe_atou64(p
, &m
->n_entries
);
322 if (m
->n_entries
<= 0)
325 m
->n_entries_set
= true;
328 m
->cursor
= strndup(range
, colon
- range
);
334 m
->cursor
[strcspn(m
->cursor
, WHITESPACE
)] = 0;
335 if (isempty(m
->cursor
))
336 m
->cursor
= mfree(m
->cursor
);
341 static int request_parse_arguments_iterator(
343 enum MHD_ValueKind kind
,
347 RequestMeta
*m
= cls
;
348 _cleanup_free_
char *p
= NULL
;
354 m
->argument_parse_error
= -EINVAL
;
358 if (streq(key
, "follow")) {
359 if (isempty(value
)) {
364 r
= parse_boolean(value
);
366 m
->argument_parse_error
= r
;
374 if (streq(key
, "discrete")) {
375 if (isempty(value
)) {
380 r
= parse_boolean(value
);
382 m
->argument_parse_error
= r
;
390 if (streq(key
, "boot")) {
394 r
= parse_boolean(value
);
396 m
->argument_parse_error
= r
;
402 char match
[9 + 32 + 1] = "_BOOT_ID=";
405 r
= sd_id128_get_boot(&bid
);
407 log_error_errno(r
, "Failed to get boot ID: %m");
411 sd_id128_to_string(bid
, match
+ 9);
412 r
= sd_journal_add_match(m
->journal
, match
, sizeof(match
)-1);
414 m
->argument_parse_error
= r
;
422 p
= strjoin(key
, "=", strempty(value
));
424 m
->argument_parse_error
= log_oom();
428 r
= sd_journal_add_match(m
->journal
, p
, 0);
430 m
->argument_parse_error
= r
;
437 static int request_parse_arguments(
439 struct MHD_Connection
*connection
) {
444 m
->argument_parse_error
= 0;
445 MHD_get_connection_values(connection
, MHD_GET_ARGUMENT_KIND
, request_parse_arguments_iterator
, m
);
447 return m
->argument_parse_error
;
450 static int request_handler_entries(
451 struct MHD_Connection
*connection
,
452 void *connection_cls
) {
454 struct MHD_Response
*response
;
455 RequestMeta
*m
= connection_cls
;
463 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
465 if (request_parse_accept(m
, connection
) < 0)
466 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
468 if (request_parse_range(m
, connection
) < 0)
469 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Range header.");
471 if (request_parse_arguments(m
, connection
) < 0)
472 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse URL arguments.");
476 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Discrete seeks require a cursor specification.");
479 m
->n_entries_set
= true;
483 r
= sd_journal_seek_cursor(m
->journal
, m
->cursor
);
484 else if (m
->n_skip
>= 0)
485 r
= sd_journal_seek_head(m
->journal
);
486 else if (m
->n_skip
< 0)
487 r
= sd_journal_seek_tail(m
->journal
);
489 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to seek in journal.");
491 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_entries
, m
, NULL
);
493 return respond_oom(connection
);
495 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
]);
497 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
498 MHD_destroy_response(response
);
503 static int output_field(FILE *f
, OutputMode m
, const char *d
, size_t l
) {
507 eq
= memchr(d
, '=', l
);
511 j
= l
- (eq
- d
+ 1);
513 if (m
== OUTPUT_JSON
) {
514 fprintf(f
, "{ \"%.*s\" : ", (int) (eq
- d
), d
);
515 json_escape(f
, eq
+1, j
, OUTPUT_FULL_WIDTH
);
518 fwrite(eq
+1, 1, j
, f
);
525 static ssize_t
request_reader_fields(
531 RequestMeta
*m
= cls
;
538 assert(pos
>= m
->delta
);
542 while (pos
>= m
->size
) {
547 /* End of this field, so let's serialize the next
550 if (m
->n_fields_set
&&
552 return MHD_CONTENT_READER_END_OF_STREAM
;
554 r
= sd_journal_enumerate_unique(m
->journal
, &d
, &l
);
556 log_error_errno(r
, "Failed to advance field index: %m");
557 return MHD_CONTENT_READER_END_WITH_ERROR
;
559 return MHD_CONTENT_READER_END_OF_STREAM
;
567 r
= request_meta_ensure_tmp(m
);
569 log_error_errno(r
, "Failed to create temporary file: %m");
570 return MHD_CONTENT_READER_END_WITH_ERROR
;
573 r
= output_field(m
->tmp
, m
->mode
, d
, l
);
575 log_error_errno(r
, "Failed to serialize item: %m");
576 return MHD_CONTENT_READER_END_WITH_ERROR
;
580 if (sz
== (off_t
) -1) {
581 log_error_errno(errno
, "Failed to retrieve file position: %m");
582 return MHD_CONTENT_READER_END_WITH_ERROR
;
585 m
->size
= (uint64_t) sz
;
588 if (fseeko(m
->tmp
, pos
, SEEK_SET
) < 0) {
589 log_error_errno(errno
, "Failed to seek to position: %m");
590 return MHD_CONTENT_READER_END_WITH_ERROR
;
598 k
= fread(buf
, 1, n
, m
->tmp
);
600 log_error("Failed to read from file: %s", errno
? strerror(errno
) : "Premature EOF");
601 return MHD_CONTENT_READER_END_WITH_ERROR
;
607 static int request_handler_fields(
608 struct MHD_Connection
*connection
,
610 void *connection_cls
) {
612 struct MHD_Response
*response
;
613 RequestMeta
*m
= connection_cls
;
621 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
623 if (request_parse_accept(m
, connection
) < 0)
624 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to parse Accept header.");
626 r
= sd_journal_query_unique(m
->journal
, field
);
628 return mhd_respond(connection
, MHD_HTTP_BAD_REQUEST
, "Failed to query unique fields.");
630 response
= MHD_create_response_from_callback(MHD_SIZE_UNKNOWN
, 4*1024, request_reader_fields
, m
, NULL
);
632 return respond_oom(connection
);
634 MHD_add_response_header(response
, "Content-Type", mime_types
[m
->mode
== OUTPUT_JSON
? OUTPUT_JSON
: OUTPUT_SHORT
]);
636 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
637 MHD_destroy_response(response
);
642 static int request_handler_redirect(
643 struct MHD_Connection
*connection
,
644 const char *target
) {
647 struct MHD_Response
*response
;
653 if (asprintf(&page
, "<html><body>Please continue to the <a href=\"%s\">journal browser</a>.</body></html>", target
) < 0)
654 return respond_oom(connection
);
656 response
= MHD_create_response_from_buffer(strlen(page
), page
, MHD_RESPMEM_MUST_FREE
);
659 return respond_oom(connection
);
662 MHD_add_response_header(response
, "Content-Type", "text/html");
663 MHD_add_response_header(response
, "Location", target
);
665 ret
= MHD_queue_response(connection
, MHD_HTTP_MOVED_PERMANENTLY
, response
);
666 MHD_destroy_response(response
);
671 static int request_handler_file(
672 struct MHD_Connection
*connection
,
674 const char *mime_type
) {
676 struct MHD_Response
*response
;
678 _cleanup_close_
int fd
= -1;
685 fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
687 return mhd_respondf(connection
, errno
, MHD_HTTP_NOT_FOUND
, "Failed to open file %s: %m", path
);
689 if (fstat(fd
, &st
) < 0)
690 return mhd_respondf(connection
, errno
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to stat file: %m");
692 response
= MHD_create_response_from_fd_at_offset64(st
.st_size
, fd
, 0);
694 return respond_oom(connection
);
698 MHD_add_response_header(response
, "Content-Type", mime_type
);
700 ret
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
701 MHD_destroy_response(response
);
706 static int get_virtualization(char **v
) {
707 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
711 r
= sd_bus_default_system(&bus
);
715 r
= sd_bus_get_property_string(
717 "org.freedesktop.systemd1",
718 "/org/freedesktop/systemd1",
719 "org.freedesktop.systemd1.Manager",
736 static int request_handler_machine(
737 struct MHD_Connection
*connection
,
738 void *connection_cls
) {
740 struct MHD_Response
*response
;
741 RequestMeta
*m
= connection_cls
;
743 _cleanup_free_
char* hostname
= NULL
, *os_name
= NULL
;
744 uint64_t cutoff_from
= 0, cutoff_to
= 0, usage
= 0;
747 _cleanup_free_
char *v
= NULL
;
754 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to open journal: %m");
756 r
= sd_id128_get_machine(&mid
);
758 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine machine ID: %m");
760 r
= sd_id128_get_boot(&bid
);
762 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine boot ID: %m");
764 hostname
= gethostname_malloc();
766 return respond_oom(connection
);
768 r
= sd_journal_get_usage(m
->journal
, &usage
);
770 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
772 r
= sd_journal_get_cutoff_realtime_usec(m
->journal
, &cutoff_from
, &cutoff_to
);
774 return mhd_respondf(connection
, r
, MHD_HTTP_INTERNAL_SERVER_ERROR
, "Failed to determine disk usage: %m");
776 (void) parse_os_release(NULL
, "PRETTY_NAME", &os_name
, NULL
);
777 (void) get_virtualization(&v
);
780 "{ \"machine_id\" : \"" SD_ID128_FORMAT_STR
"\","
781 "\"boot_id\" : \"" SD_ID128_FORMAT_STR
"\","
782 "\"hostname\" : \"%s\","
783 "\"os_pretty_name\" : \"%s\","
784 "\"virtualization\" : \"%s\","
785 "\"usage\" : \"%"PRIu64
"\","
786 "\"cutoff_from_realtime\" : \"%"PRIu64
"\","
787 "\"cutoff_to_realtime\" : \"%"PRIu64
"\" }\n",
788 SD_ID128_FORMAT_VAL(mid
),
789 SD_ID128_FORMAT_VAL(bid
),
790 hostname_cleanup(hostname
),
791 os_name
? os_name
: "Linux",
798 return respond_oom(connection
);
800 response
= MHD_create_response_from_buffer(strlen(json
), json
, MHD_RESPMEM_MUST_FREE
);
803 return respond_oom(connection
);
806 MHD_add_response_header(response
, "Content-Type", "application/json");
807 r
= MHD_queue_response(connection
, MHD_HTTP_OK
, response
);
808 MHD_destroy_response(response
);
813 static int request_handler(
815 struct MHD_Connection
*connection
,
819 const char *upload_data
,
820 size_t *upload_data_size
,
821 void **connection_cls
) {
825 assert(connection_cls
);
829 if (!streq(method
, "GET"))
830 return mhd_respond(connection
, MHD_HTTP_NOT_ACCEPTABLE
, "Unsupported method.");
832 if (!*connection_cls
) {
833 if (!request_meta(connection_cls
))
834 return respond_oom(connection
);
839 r
= check_permissions(connection
, &code
, NULL
);
845 return request_handler_redirect(connection
, "/browse");
847 if (streq(url
, "/entries"))
848 return request_handler_entries(connection
, *connection_cls
);
850 if (startswith(url
, "/fields/"))
851 return request_handler_fields(connection
, url
+ 8, *connection_cls
);
853 if (streq(url
, "/browse"))
854 return request_handler_file(connection
, DOCUMENT_ROOT
"/browse.html", "text/html");
856 if (streq(url
, "/machine"))
857 return request_handler_machine(connection
, *connection_cls
);
859 return mhd_respond(connection
, MHD_HTTP_NOT_FOUND
, "Not found.");
862 static void help(void) {
863 printf("%s [OPTIONS...] ...\n\n"
864 "HTTP server for journal events.\n\n"
865 " -h --help Show this help\n"
866 " --version Show package version\n"
867 " --cert=CERT.PEM Server certificate in PEM format\n"
868 " --key=KEY.PEM Server key in PEM format\n"
869 " --trust=CERT.PEM Certificate authority certificate in PEM format\n"
870 " -D --directory=PATH Serve journal files in directory\n",
871 program_invocation_short_name
);
874 static int parse_argv(int argc
, char *argv
[]) {
884 static const struct option options
[] = {
885 { "help", no_argument
, NULL
, 'h' },
886 { "version", no_argument
, NULL
, ARG_VERSION
},
887 { "key", required_argument
, NULL
, ARG_KEY
},
888 { "cert", required_argument
, NULL
, ARG_CERT
},
889 { "trust", required_argument
, NULL
, ARG_TRUST
},
890 { "directory", required_argument
, NULL
, 'D' },
897 while ((c
= getopt_long(argc
, argv
, "hD:", options
, NULL
)) >= 0)
910 log_error("Key file specified twice");
913 r
= read_full_file(optarg
, &arg_key_pem
, NULL
);
915 return log_error_errno(r
, "Failed to read key file: %m");
921 log_error("Certificate file specified twice");
924 r
= read_full_file(optarg
, &arg_cert_pem
, NULL
);
926 return log_error_errno(r
, "Failed to read certificate file: %m");
927 assert(arg_cert_pem
);
933 log_error("CA certificate file specified twice");
936 r
= read_full_file(optarg
, &arg_trust_pem
, NULL
);
938 return log_error_errno(r
, "Failed to read CA certificate file: %m");
939 assert(arg_trust_pem
);
942 log_error("Option --trust is not available.");
946 arg_directory
= optarg
;
953 assert_not_reached("Unhandled option");
957 log_error("This program does not take arguments.");
961 if (!!arg_key_pem
!= !!arg_cert_pem
) {
962 log_error("Certificate and key files must be specified together");
966 if (arg_trust_pem
&& !arg_key_pem
) {
967 log_error("CA certificate can only be used with certificate file");
974 int main(int argc
, char *argv
[]) {
975 struct MHD_Daemon
*d
= NULL
;
978 log_set_target(LOG_TARGET_AUTO
);
979 log_parse_environment();
982 r
= parse_argv(argc
, argv
);
990 r
= setup_gnutls_logger(NULL
);
994 n
= sd_listen_fds(1);
996 log_error_errno(n
, "Failed to determine passed sockets: %m");
999 log_error("Can't listen on more than one socket.");
1002 struct MHD_OptionItem opts
[] = {
1003 { MHD_OPTION_NOTIFY_COMPLETED
,
1004 (intptr_t) request_meta_free
, NULL
},
1005 { MHD_OPTION_EXTERNAL_LOGGER
,
1006 (intptr_t) microhttpd_logger
, NULL
},
1007 { MHD_OPTION_END
, 0, NULL
},
1008 { MHD_OPTION_END
, 0, NULL
},
1009 { MHD_OPTION_END
, 0, NULL
},
1010 { MHD_OPTION_END
, 0, NULL
},
1011 { MHD_OPTION_END
, 0, NULL
}};
1014 /* We force MHD_USE_ITC here, in order to make sure
1015 * libmicrohttpd doesn't use shutdown() on our listening
1016 * socket, which would break socket re-activation. See
1018 * https://lists.gnu.org/archive/html/libmicrohttpd/2015-09/msg00014.html
1019 * https://github.com/systemd/systemd/pull/1286
1024 MHD_USE_DUAL_STACK
|
1026 MHD_USE_POLL_INTERNAL_THREAD
|
1027 MHD_USE_THREAD_PER_CONNECTION
;
1030 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1031 {MHD_OPTION_LISTEN_SOCKET
, SD_LISTEN_FDS_START
};
1033 assert(arg_cert_pem
);
1034 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1035 {MHD_OPTION_HTTPS_MEM_KEY
, 0, arg_key_pem
};
1036 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1037 {MHD_OPTION_HTTPS_MEM_CERT
, 0, arg_cert_pem
};
1038 flags
|= MHD_USE_TLS
;
1040 if (arg_trust_pem
) {
1041 assert(flags
& MHD_USE_TLS
);
1042 opts
[opts_pos
++] = (struct MHD_OptionItem
)
1043 {MHD_OPTION_HTTPS_MEM_TRUST
, 0, arg_trust_pem
};
1046 d
= MHD_start_daemon(flags
, 19531,
1048 request_handler
, NULL
,
1049 MHD_OPTION_ARRAY
, opts
,
1054 log_error("Failed to start daemon!");