1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "sd-daemon.h"
12 #include "alloc-util.h"
13 #include "conf-parser.h"
14 #include "daemon-util.h"
19 #include "format-util.h"
20 #include "glob-util.h"
21 #include "journal-upload.h"
23 #include "main-func.h"
25 #include "parse-argument.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "pretty-print.h"
29 #include "process-util.h"
30 #include "rlimit-util.h"
32 #include "signal-util.h"
33 #include "string-util.h"
35 #include "tmpfile-util.h"
39 #define PRIV_KEY_FILE CERTIFICATE_ROOT "/private/journal-upload.pem"
40 #define CERT_FILE CERTIFICATE_ROOT "/certs/journal-upload.pem"
41 #define TRUST_FILE CERTIFICATE_ROOT "/ca/trusted.pem"
42 #define DEFAULT_PORT 19532
44 static const char* arg_url
= NULL
;
45 static const char *arg_key
= NULL
;
46 static const char *arg_cert
= NULL
;
47 static const char *arg_trust
= NULL
;
48 static const char *arg_directory
= NULL
;
49 static char **arg_file
= NULL
;
50 static const char *arg_cursor
= NULL
;
51 static bool arg_after_cursor
= false;
52 static int arg_journal_type
= 0;
53 static const char *arg_machine
= NULL
;
54 static bool arg_merge
= false;
55 static int arg_follow
= -1;
56 static const char *arg_save_state
= NULL
;
57 static usec_t arg_network_timeout_usec
= USEC_INFINITY
;
59 static void close_fd_input(Uploader
*u
);
61 #define SERVER_ANSWER_KEEP 2048
63 #define STATE_FILE "/var/lib/systemd/journal-upload/state"
65 #define easy_setopt(curl, opt, value, level, cmd) \
67 code = curl_easy_setopt(curl, opt, value); \
70 "curl_easy_setopt " #opt " failed: %s", \
71 curl_easy_strerror(code)); \
76 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(CURL
*, curl_easy_cleanup
, NULL
);
77 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct curl_slist
*, curl_slist_free_all
, NULL
);
79 static size_t output_callback(char *buf
,
87 log_debug("The server answers (%zu bytes): %.*s",
88 size
*nmemb
, (int)(size
*nmemb
), buf
);
90 if (nmemb
&& !u
->answer
) {
91 u
->answer
= strndup(buf
, size
*nmemb
);
93 log_warning("Failed to store server answer (%zu bytes): out of memory", size
*nmemb
);
99 static int check_cursor_updating(Uploader
*u
) {
100 _cleanup_free_
char *temp_path
= NULL
;
101 _cleanup_fclose_
FILE *f
= NULL
;
107 r
= mkdir_parents(u
->state_file
, 0755);
109 return log_error_errno(r
, "Cannot create parent directory of state file %s: %m",
112 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
114 return log_error_errno(r
, "Cannot save state to %s: %m",
116 (void) unlink(temp_path
);
121 static int update_cursor_state(Uploader
*u
) {
122 _cleanup_free_
char *temp_path
= NULL
;
123 _cleanup_fclose_
FILE *f
= NULL
;
126 if (!u
->state_file
|| !u
->last_cursor
)
129 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
134 "# This is private data. Do not parse.\n"
138 r
= fflush_and_check(f
);
142 if (rename(temp_path
, u
->state_file
) < 0) {
151 (void) unlink(temp_path
);
153 (void) unlink(u
->state_file
);
155 return log_error_errno(r
, "Failed to save state %s: %m", u
->state_file
);
158 static int load_cursor_state(Uploader
*u
) {
164 r
= parse_env_file(NULL
, u
->state_file
, "LAST_CURSOR", &u
->last_cursor
);
166 log_debug("State file %s is not present.", u
->state_file
);
168 return log_error_errno(r
, "Failed to read state file %s: %m",
171 log_debug("Last cursor was %s", u
->last_cursor
);
176 int start_upload(Uploader
*u
,
177 size_t (*input_callback
)(void *ptr
,
185 assert(input_callback
);
188 _cleanup_(curl_slist_free_allp
) struct curl_slist
*h
= NULL
;
189 struct curl_slist
*l
;
191 h
= curl_slist_append(NULL
, "Content-Type: application/vnd.fdo.journal");
195 l
= curl_slist_append(h
, "Transfer-Encoding: chunked");
200 l
= curl_slist_append(h
, "Accept: text/plain");
205 u
->header
= TAKE_PTR(h
);
209 _cleanup_(curl_easy_cleanupp
) CURL
*curl
= NULL
;
211 curl
= curl_easy_init();
213 return log_error_errno(SYNTHETIC_ERRNO(ENOSR
),
214 "Call to curl_easy_init failed.");
216 /* If configured, set a timeout for the curl operation. */
217 if (arg_network_timeout_usec
!= USEC_INFINITY
)
218 easy_setopt(curl
, CURLOPT_TIMEOUT
,
219 (long) DIV_ROUND_UP(arg_network_timeout_usec
, USEC_PER_SEC
),
220 LOG_ERR
, return -EXFULL
);
222 /* tell it to POST to the URL */
223 easy_setopt(curl
, CURLOPT_POST
, 1L,
224 LOG_ERR
, return -EXFULL
);
226 easy_setopt(curl
, CURLOPT_ERRORBUFFER
, u
->error
,
227 LOG_ERR
, return -EXFULL
);
229 /* set where to write to */
230 easy_setopt(curl
, CURLOPT_WRITEFUNCTION
, output_callback
,
231 LOG_ERR
, return -EXFULL
);
233 easy_setopt(curl
, CURLOPT_WRITEDATA
, data
,
234 LOG_ERR
, return -EXFULL
);
236 /* set where to read from */
237 easy_setopt(curl
, CURLOPT_READFUNCTION
, input_callback
,
238 LOG_ERR
, return -EXFULL
);
240 easy_setopt(curl
, CURLOPT_READDATA
, data
,
241 LOG_ERR
, return -EXFULL
);
243 /* use our special own mime type and chunked transfer */
244 easy_setopt(curl
, CURLOPT_HTTPHEADER
, u
->header
,
245 LOG_ERR
, return -EXFULL
);
248 /* enable verbose for easier tracing */
249 easy_setopt(curl
, CURLOPT_VERBOSE
, 1L, LOG_WARNING
, );
251 easy_setopt(curl
, CURLOPT_USERAGENT
,
252 "systemd-journal-upload " GIT_VERSION
,
255 if (!streq_ptr(arg_key
, "-") && (arg_key
|| startswith(u
->url
, "https://"))) {
256 easy_setopt(curl
, CURLOPT_SSLKEY
, arg_key
?: PRIV_KEY_FILE
,
257 LOG_ERR
, return -EXFULL
);
258 easy_setopt(curl
, CURLOPT_SSLCERT
, arg_cert
?: CERT_FILE
,
259 LOG_ERR
, return -EXFULL
);
262 if (STRPTR_IN_SET(arg_trust
, "-", "all"))
263 easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, 0,
264 LOG_ERR
, return -EUCLEAN
);
265 else if (arg_trust
|| startswith(u
->url
, "https://"))
266 easy_setopt(curl
, CURLOPT_CAINFO
, arg_trust
?: TRUST_FILE
,
267 LOG_ERR
, return -EXFULL
);
269 if (arg_key
|| arg_trust
)
270 easy_setopt(curl
, CURLOPT_SSLVERSION
, CURL_SSLVERSION_TLSv1
,
273 u
->easy
= TAKE_PTR(curl
);
275 /* truncate the potential old error message */
282 /* upload to this place */
283 code
= curl_easy_setopt(u
->easy
, CURLOPT_URL
, u
->url
);
285 return log_error_errno(SYNTHETIC_ERRNO(EXFULL
),
286 "curl_easy_setopt CURLOPT_URL failed: %s",
287 curl_easy_strerror(code
));
294 static size_t fd_input_callback(void *buf
, size_t size
, size_t nmemb
, void *userp
) {
299 assert(nmemb
< SSIZE_MAX
/ size
);
304 assert(!size_multiply_overflow(size
, nmemb
));
306 n
= read(u
->input
, buf
, size
* nmemb
);
307 log_debug("%s: allowed %zu, read %zd", __func__
, size
*nmemb
, n
);
311 u
->uploading
= false;
313 log_error_errno(errno
, "Aborting transfer after read error on input: %m.");
314 return CURL_READFUNC_ABORT
;
317 log_debug("Reached EOF");
322 static void close_fd_input(Uploader
*u
) {
325 u
->input
= safe_close(u
->input
);
329 static int dispatch_fd_input(sd_event_source
*event
,
338 if (revents
& EPOLLHUP
) {
339 log_debug("Received HUP");
344 if (!(revents
& EPOLLIN
)) {
345 log_warning("Unexpected poll event %"PRIu32
".", revents
);
350 log_warning("dispatch_fd_input called when uploading, ignoring.");
354 return start_upload(u
, fd_input_callback
, u
);
357 static int open_file_for_upload(Uploader
*u
, const char *filename
) {
360 if (streq(filename
, "-"))
363 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
365 return log_error_errno(errno
, "Failed to open %s: %m", filename
);
370 if (arg_follow
!= 0) {
371 r
= sd_event_add_io(u
->events
, &u
->input_event
,
372 fd
, EPOLLIN
, dispatch_fd_input
, u
);
374 if (r
!= -EPERM
|| arg_follow
> 0)
375 return log_error_errno(r
, "Failed to register input event: %m");
377 /* Normal files should just be consumed without polling. */
378 r
= start_upload(u
, fd_input_callback
, u
);
385 static int dispatch_sigterm(sd_event_source
*event
,
386 const struct signalfd_siginfo
*si
,
388 Uploader
*u
= userdata
;
392 log_received_signal(LOG_INFO
, si
);
395 close_journal_input(u
);
397 sd_event_exit(u
->events
, 0);
401 static int setup_signals(Uploader
*u
) {
406 assert_se(sigprocmask_many(SIG_SETMASK
, NULL
, SIGINT
, SIGTERM
, -1) >= 0);
408 r
= sd_event_add_signal(u
->events
, &u
->sigterm_event
, SIGTERM
, dispatch_sigterm
, u
);
412 r
= sd_event_add_signal(u
->events
, &u
->sigint_event
, SIGINT
, dispatch_sigterm
, u
);
419 static int setup_uploader(Uploader
*u
, const char *url
, const char *state_file
) {
421 const char *host
, *proto
= "";
430 host
= STARTSWITH_SET(url
, "http://", "https://");
436 if (strchr(host
, ':'))
437 u
->url
= strjoin(proto
, url
, "/upload");
442 t
= strdupa_safe(url
);
444 while (x
> 0 && t
[x
- 1] == '/')
447 u
->url
= strjoin(proto
, t
, ":" STRINGIFY(DEFAULT_PORT
), "/upload");
452 u
->state_file
= state_file
;
454 r
= sd_event_default(&u
->events
);
456 return log_error_errno(r
, "sd_event_default failed: %m");
458 r
= setup_signals(u
);
460 return log_error_errno(r
, "Failed to set up signals: %m");
462 (void) sd_watchdog_enabled(false, &u
->watchdog_usec
);
464 return load_cursor_state(u
);
467 static void destroy_uploader(Uploader
*u
) {
470 curl_easy_cleanup(u
->easy
);
471 curl_slist_free_all(u
->header
);
474 free(u
->last_cursor
);
475 free(u
->current_cursor
);
479 u
->input_event
= sd_event_source_unref(u
->input_event
);
482 close_journal_input(u
);
484 sd_event_source_unref(u
->sigterm_event
);
485 sd_event_source_unref(u
->sigint_event
);
486 sd_event_unref(u
->events
);
489 static int perform_upload(Uploader
*u
) {
495 u
->watchdog_timestamp
= now(CLOCK_MONOTONIC
);
496 code
= curl_easy_perform(u
->easy
);
499 log_error("Upload to %s failed: %.*s",
500 u
->url
, (int) sizeof(u
->error
), u
->error
);
502 log_error("Upload to %s failed: %s",
503 u
->url
, curl_easy_strerror(code
));
507 code
= curl_easy_getinfo(u
->easy
, CURLINFO_RESPONSE_CODE
, &status
);
509 return log_error_errno(SYNTHETIC_ERRNO(EUCLEAN
),
510 "Failed to retrieve response code: %s",
511 curl_easy_strerror(code
));
514 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
515 "Upload to %s failed with code %ld: %s",
516 u
->url
, status
, strna(u
->answer
));
517 else if (status
< 200)
518 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
519 "Upload to %s finished with unexpected code %ld: %s",
520 u
->url
, status
, strna(u
->answer
));
522 log_debug("Upload finished successfully with code %ld: %s",
523 status
, strna(u
->answer
));
525 free_and_replace(u
->last_cursor
, u
->current_cursor
);
527 return update_cursor_state(u
);
530 static int config_parse_path_or_ignore(
532 const char *filename
,
535 unsigned section_line
,
542 _cleanup_free_
char *n
= NULL
;
562 r
= path_simplify_and_warn(n
, PATH_CHECK_ABSOLUTE
| (fatal
? PATH_CHECK_FATAL
: 0), unit
, filename
, line
, lvalue
);
564 return fatal
? -ENOEXEC
: 0;
567 return free_and_replace(*s
, n
);
570 static int parse_config(void) {
571 const ConfigTableItem items
[] = {
572 { "Upload", "URL", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_url
},
573 { "Upload", "ServerKeyFile", config_parse_path_or_ignore
, 0, &arg_key
},
574 { "Upload", "ServerCertificateFile", config_parse_path_or_ignore
, 0, &arg_cert
},
575 { "Upload", "TrustedCertificateFile", config_parse_path_or_ignore
, 0, &arg_trust
},
576 { "Upload", "NetworkTimeoutSec", config_parse_sec
, 0, &arg_network_timeout_usec
},
580 return config_parse_many_nulstr(
581 PKGSYSCONFDIR
"/journal-upload.conf",
582 CONF_PATHS_NULSTR("systemd/journal-upload.conf.d"),
584 config_item_table_lookup
, items
,
590 static int help(void) {
591 _cleanup_free_
char *link
= NULL
;
594 r
= terminal_urlify_man("systemd-journal-upload.service", "8", &link
);
598 printf("%s -u URL {FILE|-}...\n\n"
599 "Upload journal events to a remote server.\n\n"
600 " -h --help Show this help\n"
601 " --version Show package version\n"
602 " -u --url=URL Upload to this address (default port "
603 STRINGIFY(DEFAULT_PORT
) ")\n"
604 " --key=FILENAME Specify key in PEM format (default:\n"
605 " \"" PRIV_KEY_FILE
"\")\n"
606 " --cert=FILENAME Specify certificate in PEM format (default:\n"
607 " \"" CERT_FILE
"\")\n"
608 " --trust=FILENAME|all Specify CA certificate or disable checking (default:\n"
609 " \"" TRUST_FILE
"\")\n"
610 " --system Use the system journal\n"
611 " --user Use the user journal for the current user\n"
612 " -m --merge Use all available journals\n"
613 " -M --machine=CONTAINER Operate on local container\n"
614 " -D --directory=PATH Use journal files from directory\n"
615 " --file=PATH Use this journal file\n"
616 " --cursor=CURSOR Start at the specified cursor\n"
617 " --after-cursor=CURSOR Start after the specified cursor\n"
618 " --follow[=BOOL] Do [not] wait for input\n"
619 " --save-state[=FILE] Save uploaded cursors (default \n"
621 "\nSee the %s for details.\n",
622 program_invocation_short_name
,
628 static int parse_argv(int argc
, char *argv
[]) {
643 static const struct option options
[] = {
644 { "help", no_argument
, NULL
, 'h' },
645 { "version", no_argument
, NULL
, ARG_VERSION
},
646 { "url", required_argument
, NULL
, 'u' },
647 { "key", required_argument
, NULL
, ARG_KEY
},
648 { "cert", required_argument
, NULL
, ARG_CERT
},
649 { "trust", required_argument
, NULL
, ARG_TRUST
},
650 { "system", no_argument
, NULL
, ARG_SYSTEM
},
651 { "user", no_argument
, NULL
, ARG_USER
},
652 { "merge", no_argument
, NULL
, 'm' },
653 { "machine", required_argument
, NULL
, 'M' },
654 { "directory", required_argument
, NULL
, 'D' },
655 { "file", required_argument
, NULL
, ARG_FILE
},
656 { "cursor", required_argument
, NULL
, ARG_CURSOR
},
657 { "after-cursor", required_argument
, NULL
, ARG_AFTER_CURSOR
},
658 { "follow", optional_argument
, NULL
, ARG_FOLLOW
},
659 { "save-state", optional_argument
, NULL
, ARG_SAVE_STATE
},
670 while ((c
= getopt_long(argc
, argv
, "hu:mM:D:", options
, NULL
)) >= 0)
680 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
681 "cannot use more than one --url");
688 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
689 "cannot use more than one --key");
696 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
697 "cannot use more than one --cert");
704 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
705 "cannot use more than one --trust");
711 arg_journal_type
|= SD_JOURNAL_SYSTEM
;
715 arg_journal_type
|= SD_JOURNAL_CURRENT_USER
;
724 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
725 "cannot use more than one --machine/-M");
727 arg_machine
= optarg
;
732 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
733 "cannot use more than one --directory/-D");
735 arg_directory
= optarg
;
739 r
= glob_extend(&arg_file
, optarg
, GLOB_NOCHECK
);
741 return log_error_errno(r
, "Failed to add paths: %m");
746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
747 "cannot use more than one --cursor/--after-cursor");
752 case ARG_AFTER_CURSOR
:
754 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
755 "cannot use more than one --cursor/--after-cursor");
758 arg_after_cursor
= true;
762 r
= parse_boolean_argument("--follow", optarg
, NULL
);
769 arg_save_state
= optarg
?: STATE_FILE
;
773 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
774 "Unknown option %s.",
778 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
779 "Missing argument to %s.",
783 assert_not_reached();
787 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
788 "Required --url/-u option missing.");
790 if (!!arg_key
!= !!arg_cert
)
791 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
792 "Options --key and --cert must be used together.");
794 if (optind
< argc
&& (arg_directory
|| arg_file
|| arg_machine
|| arg_journal_type
))
795 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
796 "Input arguments make no sense with journal input.");
801 static int open_journal(sd_journal
**j
) {
805 r
= sd_journal_open_directory(j
, arg_directory
, arg_journal_type
);
807 r
= sd_journal_open_files(j
, (const char**) arg_file
, 0);
808 else if (arg_machine
) {
809 #pragma GCC diagnostic push
810 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
811 /* FIXME: replace with D-Bus call OpenMachineRootDirectory() so that things also work with raw disk images */
812 r
= sd_journal_open_container(j
, arg_machine
, 0);
813 #pragma GCC diagnostic pop
815 r
= sd_journal_open(j
, (arg_merge
? 0 : SD_JOURNAL_LOCAL_ONLY
) | arg_journal_type
);
817 log_error_errno(r
, "Failed to open %s: %m",
818 arg_directory
? arg_directory
: arg_file
? "files" : "journal");
822 static int run(int argc
, char **argv
) {
823 _cleanup_(destroy_uploader
) Uploader u
= {};
824 _unused_
_cleanup_(notify_on_cleanup
) const char *notify_message
= NULL
;
828 log_show_color(true);
829 log_parse_environment();
831 /* The journal merging logic potentially needs a lot of fds. */
832 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
838 r
= parse_argv(argc
, argv
);
844 r
= setup_uploader(&u
, arg_url
, arg_save_state
);
848 sd_event_set_watchdog(u
.events
, true);
850 r
= check_cursor_updating(&u
);
854 log_debug("%s running as pid "PID_FMT
,
855 program_invocation_short_name
, getpid_cached());
857 use_journal
= optind
>= argc
;
860 r
= open_journal(&j
);
863 r
= open_journal_for_upload(&u
, j
,
864 arg_cursor
?: u
.last_cursor
,
865 arg_cursor
? arg_after_cursor
: true,
871 notify_message
= notify_start("READY=1\n"
872 "STATUS=Processing input...",
876 r
= sd_event_get_state(u
.events
);
879 if (r
== SD_EVENT_FINISHED
)
886 r
= check_journal_input(&u
);
887 } else if (u
.input
< 0 && !use_journal
) {
891 log_debug("Using %s as input.", argv
[optind
]);
892 r
= open_file_for_upload(&u
, argv
[optind
++]);
898 r
= perform_upload(&u
);
903 r
= sd_event_run(u
.events
, u
.timeout
);
905 return log_error_errno(r
, "Failed to run event loop: %m");
909 DEFINE_MAIN_FUNCTION(run
);