1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
12 #include "conf-parser.h"
13 #include "daemon-util.h"
18 #include "format-util.h"
19 #include "glob-util.h"
20 #include "journal-upload.h"
22 #include "main-func.h"
24 #include "parse-argument.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "pretty-print.h"
28 #include "process-util.h"
29 #include "rlimit-util.h"
31 #include "signal-util.h"
32 #include "string-util.h"
34 #include "tmpfile-util.h"
38 #define PRIV_KEY_FILE CERTIFICATE_ROOT "/private/journal-upload.pem"
39 #define CERT_FILE CERTIFICATE_ROOT "/certs/journal-upload.pem"
40 #define TRUST_FILE CERTIFICATE_ROOT "/ca/trusted.pem"
41 #define DEFAULT_PORT 19532
43 static const char* arg_url
= NULL
;
44 static const char *arg_key
= NULL
;
45 static const char *arg_cert
= NULL
;
46 static const char *arg_trust
= NULL
;
47 static const char *arg_directory
= NULL
;
48 static char **arg_file
= NULL
;
49 static const char *arg_cursor
= NULL
;
50 static bool arg_after_cursor
= false;
51 static int arg_journal_type
= 0;
52 static const char *arg_machine
= NULL
;
53 static bool arg_merge
= false;
54 static int arg_follow
= -1;
55 static const char *arg_save_state
= NULL
;
56 static usec_t arg_network_timeout_usec
= USEC_INFINITY
;
58 static void close_fd_input(Uploader
*u
);
60 #define SERVER_ANSWER_KEEP 2048
62 #define STATE_FILE "/var/lib/systemd/journal-upload/state"
64 #define easy_setopt(curl, opt, value, level, cmd) \
66 code = curl_easy_setopt(curl, opt, value); \
69 "curl_easy_setopt " #opt " failed: %s", \
70 curl_easy_strerror(code)); \
75 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(CURL
*, curl_easy_cleanup
, NULL
);
76 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct curl_slist
*, curl_slist_free_all
, NULL
);
78 static size_t output_callback(char *buf
,
86 log_debug("The server answers (%zu bytes): %.*s",
87 size
*nmemb
, (int)(size
*nmemb
), buf
);
89 if (nmemb
&& !u
->answer
) {
90 u
->answer
= strndup(buf
, size
*nmemb
);
92 log_warning("Failed to store server answer (%zu bytes): out of memory", size
*nmemb
);
98 static int check_cursor_updating(Uploader
*u
) {
99 _cleanup_free_
char *temp_path
= NULL
;
100 _cleanup_fclose_
FILE *f
= NULL
;
106 r
= mkdir_parents(u
->state_file
, 0755);
108 return log_error_errno(r
, "Cannot create parent directory of state file %s: %m",
111 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
113 return log_error_errno(r
, "Cannot save state to %s: %m",
115 (void) unlink(temp_path
);
120 static int update_cursor_state(Uploader
*u
) {
121 _cleanup_free_
char *temp_path
= NULL
;
122 _cleanup_fclose_
FILE *f
= NULL
;
125 if (!u
->state_file
|| !u
->last_cursor
)
128 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
133 "# This is private data. Do not parse.\n"
137 r
= fflush_and_check(f
);
141 if (rename(temp_path
, u
->state_file
) < 0) {
150 (void) unlink(temp_path
);
152 (void) unlink(u
->state_file
);
154 return log_error_errno(r
, "Failed to save state %s: %m", u
->state_file
);
157 static int load_cursor_state(Uploader
*u
) {
163 r
= parse_env_file(NULL
, u
->state_file
, "LAST_CURSOR", &u
->last_cursor
);
165 log_debug("State file %s is not present.", u
->state_file
);
167 return log_error_errno(r
, "Failed to read state file %s: %m",
170 log_debug("Last cursor was %s", u
->last_cursor
);
175 int start_upload(Uploader
*u
,
176 size_t (*input_callback
)(void *ptr
,
184 assert(input_callback
);
187 _cleanup_(curl_slist_free_allp
) struct curl_slist
*h
= NULL
;
188 struct curl_slist
*l
;
190 h
= curl_slist_append(NULL
, "Content-Type: application/vnd.fdo.journal");
194 l
= curl_slist_append(h
, "Transfer-Encoding: chunked");
199 l
= curl_slist_append(h
, "Accept: text/plain");
204 u
->header
= TAKE_PTR(h
);
208 _cleanup_(curl_easy_cleanupp
) CURL
*curl
= NULL
;
210 curl
= curl_easy_init();
212 return log_error_errno(SYNTHETIC_ERRNO(ENOSR
),
213 "Call to curl_easy_init failed.");
215 /* If configured, set a timeout for the curl operation. */
216 if (arg_network_timeout_usec
!= USEC_INFINITY
)
217 easy_setopt(curl
, CURLOPT_TIMEOUT
,
218 (long) DIV_ROUND_UP(arg_network_timeout_usec
, USEC_PER_SEC
),
219 LOG_ERR
, return -EXFULL
);
221 /* tell it to POST to the URL */
222 easy_setopt(curl
, CURLOPT_POST
, 1L,
223 LOG_ERR
, return -EXFULL
);
225 easy_setopt(curl
, CURLOPT_ERRORBUFFER
, u
->error
,
226 LOG_ERR
, return -EXFULL
);
228 /* set where to write to */
229 easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, output_callback
,
230 LOG_ERR
, return -EXFULL
);
232 easy_setopt(curl
, CURLOPT_WRITEDATA
, data
,
233 LOG_ERR
, return -EXFULL
);
235 /* set where to read from */
236 easy_setopt(curl
, CURLOPT_READFUNCTION
, input_callback
,
237 LOG_ERR
, return -EXFULL
);
239 easy_setopt(curl
, CURLOPT_READDATA
, data
,
240 LOG_ERR
, return -EXFULL
);
242 /* use our special own mime type and chunked transfer */
243 easy_setopt(curl
, CURLOPT_HTTPHEADER
, u
->header
,
244 LOG_ERR
, return -EXFULL
);
247 /* enable verbose for easier tracing */
248 easy_setopt(curl
, CURLOPT_VERBOSE
, 1L, LOG_WARNING
, );
250 easy_setopt(curl
, CURLOPT_USERAGENT
,
251 "systemd-journal-upload " GIT_VERSION
,
254 if (!streq_ptr(arg_key
, "-") && (arg_key
|| startswith(u
->url
, "https://"))) {
255 easy_setopt(curl
, CURLOPT_SSLKEY
, arg_key
?: PRIV_KEY_FILE
,
256 LOG_ERR
, return -EXFULL
);
257 easy_setopt(curl
, CURLOPT_SSLCERT
, arg_cert
?: CERT_FILE
,
258 LOG_ERR
, return -EXFULL
);
261 if (STRPTR_IN_SET(arg_trust
, "-", "all"))
262 easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, 0,
263 LOG_ERR
, return -EUCLEAN
);
264 else if (arg_trust
|| startswith(u
->url
, "https://"))
265 easy_setopt(curl
, CURLOPT_CAINFO
, arg_trust
?: TRUST_FILE
,
266 LOG_ERR
, return -EXFULL
);
268 if (arg_key
|| arg_trust
)
269 easy_setopt(curl
, CURLOPT_SSLVERSION
, CURL_SSLVERSION_TLSv1
,
272 u
->easy
= TAKE_PTR(curl
);
274 /* truncate the potential old error message */
281 /* upload to this place */
282 code
= curl_easy_setopt(u
->easy
, CURLOPT_URL
, u
->url
);
284 return log_error_errno(SYNTHETIC_ERRNO(EXFULL
),
285 "curl_easy_setopt CURLOPT_URL failed: %s",
286 curl_easy_strerror(code
));
293 static size_t fd_input_callback(void *buf
, size_t size
, size_t nmemb
, void *userp
) {
298 assert(nmemb
< SSIZE_MAX
/ size
);
303 assert(!size_multiply_overflow(size
, nmemb
));
305 n
= read(u
->input
, buf
, size
* nmemb
);
306 log_debug("%s: allowed %zu, read %zd", __func__
, size
*nmemb
, n
);
310 u
->uploading
= false;
312 log_error_errno(errno
, "Aborting transfer after read error on input: %m.");
313 return CURL_READFUNC_ABORT
;
316 log_debug("Reached EOF");
321 static void close_fd_input(Uploader
*u
) {
324 u
->input
= safe_close(u
->input
);
328 static int dispatch_fd_input(sd_event_source
*event
,
337 if (revents
& EPOLLHUP
) {
338 log_debug("Received HUP");
343 if (!(revents
& EPOLLIN
)) {
344 log_warning("Unexpected poll event %"PRIu32
".", revents
);
349 log_warning("dispatch_fd_input called when uploading, ignoring.");
353 return start_upload(u
, fd_input_callback
, u
);
356 static int open_file_for_upload(Uploader
*u
, const char *filename
) {
359 if (streq(filename
, "-"))
362 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
364 return log_error_errno(errno
, "Failed to open %s: %m", filename
);
369 if (arg_follow
!= 0) {
370 r
= sd_event_add_io(u
->events
, &u
->input_event
,
371 fd
, EPOLLIN
, dispatch_fd_input
, u
);
373 if (r
!= -EPERM
|| arg_follow
> 0)
374 return log_error_errno(r
, "Failed to register input event: %m");
376 /* Normal files should just be consumed without polling. */
377 r
= start_upload(u
, fd_input_callback
, u
);
384 static int dispatch_sigterm(sd_event_source
*event
,
385 const struct signalfd_siginfo
*si
,
387 Uploader
*u
= userdata
;
391 log_received_signal(LOG_INFO
, si
);
394 close_journal_input(u
);
396 sd_event_exit(u
->events
, 0);
400 static int setup_signals(Uploader
*u
) {
405 assert_se(sigprocmask_many(SIG_SETMASK
, NULL
, SIGINT
, SIGTERM
, -1) >= 0);
407 r
= sd_event_add_signal(u
->events
, &u
->sigterm_event
, SIGTERM
, dispatch_sigterm
, u
);
411 r
= sd_event_add_signal(u
->events
, &u
->sigint_event
, SIGINT
, dispatch_sigterm
, u
);
418 static int setup_uploader(Uploader
*u
, const char *url
, const char *state_file
) {
420 const char *host
, *proto
= "";
429 host
= STARTSWITH_SET(url
, "http://", "https://");
435 if (strchr(host
, ':'))
436 u
->url
= strjoin(proto
, url
, "/upload");
443 while (x
> 0 && t
[x
- 1] == '/')
446 u
->url
= strjoin(proto
, t
, ":" STRINGIFY(DEFAULT_PORT
), "/upload");
451 u
->state_file
= state_file
;
453 r
= sd_event_default(&u
->events
);
455 return log_error_errno(r
, "sd_event_default failed: %m");
457 r
= setup_signals(u
);
459 return log_error_errno(r
, "Failed to set up signals: %m");
461 (void) sd_watchdog_enabled(false, &u
->watchdog_usec
);
463 return load_cursor_state(u
);
466 static void destroy_uploader(Uploader
*u
) {
469 curl_easy_cleanup(u
->easy
);
470 curl_slist_free_all(u
->header
);
473 free(u
->last_cursor
);
474 free(u
->current_cursor
);
478 u
->input_event
= sd_event_source_unref(u
->input_event
);
481 close_journal_input(u
);
483 sd_event_source_unref(u
->sigterm_event
);
484 sd_event_source_unref(u
->sigint_event
);
485 sd_event_unref(u
->events
);
488 static int perform_upload(Uploader
*u
) {
494 u
->watchdog_timestamp
= now(CLOCK_MONOTONIC
);
495 code
= curl_easy_perform(u
->easy
);
498 log_error("Upload to %s failed: %.*s",
499 u
->url
, (int) sizeof(u
->error
), u
->error
);
501 log_error("Upload to %s failed: %s",
502 u
->url
, curl_easy_strerror(code
));
506 code
= curl_easy_getinfo(u
->easy
, CURLINFO_RESPONSE_CODE
, &status
);
508 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
509 "Failed to retrieve response code: %s",
510 curl_easy_strerror(code
));
513 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
514 "Upload to %s failed with code %ld: %s",
515 u
->url
, status
, strna(u
->answer
));
516 else if (status
< 200)
517 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
518 "Upload to %s finished with unexpected code %ld: %s",
519 u
->url
, status
, strna(u
->answer
));
521 log_debug("Upload finished successfully with code %ld: %s",
522 status
, strna(u
->answer
));
524 free_and_replace(u
->last_cursor
, u
->current_cursor
);
526 return update_cursor_state(u
);
529 static int config_parse_path_or_ignore(
531 const char *filename
,
534 unsigned section_line
,
541 _cleanup_free_
char *n
= NULL
;
561 r
= path_simplify_and_warn(n
, PATH_CHECK_ABSOLUTE
| (fatal
? PATH_CHECK_FATAL
: 0), unit
, filename
, line
, lvalue
);
563 return fatal
? -ENOEXEC
: 0;
566 return free_and_replace(*s
, n
);
569 static int parse_config(void) {
570 const ConfigTableItem items
[] = {
571 { "Upload", "URL", config_parse_string
, 0, &arg_url
},
572 { "Upload", "ServerKeyFile", config_parse_path_or_ignore
, 0, &arg_key
},
573 { "Upload", "ServerCertificateFile", config_parse_path_or_ignore
, 0, &arg_cert
},
574 { "Upload", "TrustedCertificateFile", config_parse_path_or_ignore
, 0, &arg_trust
},
575 { "Upload", "NetworkTimeoutSec", config_parse_sec
, 0, &arg_network_timeout_usec
},
579 return config_parse_many_nulstr(
580 PKGSYSCONFDIR
"/journal-upload.conf",
581 CONF_PATHS_NULSTR("systemd/journal-upload.conf.d"),
583 config_item_table_lookup
, items
,
589 static int help(void) {
590 _cleanup_free_
char *link
= NULL
;
593 r
= terminal_urlify_man("systemd-journal-upload.service", "8", &link
);
597 printf("%s -u URL {FILE|-}...\n\n"
598 "Upload journal events to a remote server.\n\n"
599 " -h --help Show this help\n"
600 " --version Show package version\n"
601 " -u --url=URL Upload to this address (default port "
602 STRINGIFY(DEFAULT_PORT
) ")\n"
603 " --key=FILENAME Specify key in PEM format (default:\n"
604 " \"" PRIV_KEY_FILE
"\")\n"
605 " --cert=FILENAME Specify certificate in PEM format (default:\n"
606 " \"" CERT_FILE
"\")\n"
607 " --trust=FILENAME|all Specify CA certificate or disable checking (default:\n"
608 " \"" TRUST_FILE
"\")\n"
609 " --system Use the system journal\n"
610 " --user Use the user journal for the current user\n"
611 " -m --merge Use all available journals\n"
612 " -M --machine=CONTAINER Operate on local container\n"
613 " -D --directory=PATH Use journal files from directory\n"
614 " --file=PATH Use this journal file\n"
615 " --cursor=CURSOR Start at the specified cursor\n"
616 " --after-cursor=CURSOR Start after the specified cursor\n"
617 " --follow[=BOOL] Do [not] wait for input\n"
618 " --save-state[=FILE] Save uploaded cursors (default \n"
620 "\nSee the %s for details.\n",
621 program_invocation_short_name
,
627 static int parse_argv(int argc
, char *argv
[]) {
642 static const struct option options
[] = {
643 { "help", no_argument
, NULL
, 'h' },
644 { "version", no_argument
, NULL
, ARG_VERSION
},
645 { "url", required_argument
, NULL
, 'u' },
646 { "key", required_argument
, NULL
, ARG_KEY
},
647 { "cert", required_argument
, NULL
, ARG_CERT
},
648 { "trust", required_argument
, NULL
, ARG_TRUST
},
649 { "system", no_argument
, NULL
, ARG_SYSTEM
},
650 { "user", no_argument
, NULL
, ARG_USER
},
651 { "merge", no_argument
, NULL
, 'm' },
652 { "machine", required_argument
, NULL
, 'M' },
653 { "directory", required_argument
, NULL
, 'D' },
654 { "file", required_argument
, NULL
, ARG_FILE
},
655 { "cursor", required_argument
, NULL
, ARG_CURSOR
},
656 { "after-cursor", required_argument
, NULL
, ARG_AFTER_CURSOR
},
657 { "follow", optional_argument
, NULL
, ARG_FOLLOW
},
658 { "save-state", optional_argument
, NULL
, ARG_SAVE_STATE
},
669 while ((c
= getopt_long(argc
, argv
, "hu:mM:D:", options
, NULL
)) >= 0)
679 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
680 "cannot use more than one --url");
687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
688 "cannot use more than one --key");
695 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
696 "cannot use more than one --cert");
703 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
704 "cannot use more than one --trust");
710 arg_journal_type
|= SD_JOURNAL_SYSTEM
;
714 arg_journal_type
|= SD_JOURNAL_CURRENT_USER
;
723 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
724 "cannot use more than one --machine/-M");
726 arg_machine
= optarg
;
731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
732 "cannot use more than one --directory/-D");
734 arg_directory
= optarg
;
738 r
= glob_extend(&arg_file
, optarg
, GLOB_NOCHECK
);
740 return log_error_errno(r
, "Failed to add paths: %m");
745 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
746 "cannot use more than one --cursor/--after-cursor");
751 case ARG_AFTER_CURSOR
:
753 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
754 "cannot use more than one --cursor/--after-cursor");
757 arg_after_cursor
= true;
761 r
= parse_boolean_argument("--follow", optarg
, NULL
);
768 arg_save_state
= optarg
?: STATE_FILE
;
772 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
773 "Unknown option %s.",
777 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
778 "Missing argument to %s.",
782 assert_not_reached("Unhandled option code.");
786 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
787 "Required --url/-u option missing.");
789 if (!!arg_key
!= !!arg_cert
)
790 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
791 "Options --key and --cert must be used together.");
793 if (optind
< argc
&& (arg_directory
|| arg_file
|| arg_machine
|| arg_journal_type
))
794 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
795 "Input arguments make no sense with journal input.");
800 static int open_journal(sd_journal
**j
) {
804 r
= sd_journal_open_directory(j
, arg_directory
, arg_journal_type
);
806 r
= sd_journal_open_files(j
, (const char**) arg_file
, 0);
807 else if (arg_machine
) {
808 #pragma GCC diagnostic push
809 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
810 /* FIXME: replace with D-Bus call OpenMachineRootDirectory() so that things also work with raw disk images */
811 r
= sd_journal_open_container(j
, arg_machine
, 0);
812 #pragma GCC diagnostic pop
814 r
= sd_journal_open(j
, (arg_merge
? 0 : SD_JOURNAL_LOCAL_ONLY
) | arg_journal_type
);
816 log_error_errno(r
, "Failed to open %s: %m",
817 arg_directory
? arg_directory
: arg_file
? "files" : "journal");
821 static int run(int argc
, char **argv
) {
822 _cleanup_(destroy_uploader
) Uploader u
= {};
823 _cleanup_(notify_on_cleanup
) const char *notify_message
= NULL
;
827 log_show_color(true);
828 log_parse_environment();
830 /* The journal merging logic potentially needs a lot of fds. */
831 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
837 r
= parse_argv(argc
, argv
);
843 r
= setup_uploader(&u
, arg_url
, arg_save_state
);
847 sd_event_set_watchdog(u
.events
, true);
849 r
= check_cursor_updating(&u
);
853 log_debug("%s running as pid "PID_FMT
,
854 program_invocation_short_name
, getpid_cached());
856 use_journal
= optind
>= argc
;
859 r
= open_journal(&j
);
862 r
= open_journal_for_upload(&u
, j
,
863 arg_cursor
?: u
.last_cursor
,
864 arg_cursor
? arg_after_cursor
: true,
870 notify_message
= notify_start("READY=1\n"
871 "STATUS=Processing input...",
875 r
= sd_event_get_state(u
.events
);
878 if (r
== SD_EVENT_FINISHED
)
885 r
= check_journal_input(&u
);
886 } else if (u
.input
< 0 && !use_journal
) {
890 log_debug("Using %s as input.", argv
[optind
]);
891 r
= open_file_for_upload(&u
, argv
[optind
++]);
897 r
= perform_upload(&u
);
902 r
= sd_event_run(u
.events
, u
.timeout
);
904 return log_error_errno(r
, "Failed to run event loop: %m");
908 DEFINE_MAIN_FUNCTION(run
);