repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
systemd-main/src/shared/openssl-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "openssl-util.h" #include "alloc-util.h" #include "hexdecoct.h" #if HAVE_OPENSSL int openssl_hash(const EVP_MD *alg, const void *msg, size_t msg_len, uint8_t *ret_hash, size_t *ret_hash_len) { _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *ctx = NULL; unsigned len; int r; ctx = EVP_MD_CTX_new(); if (!ctx) /* This function just calls OPENSSL_zalloc, so failure * here is almost certainly a failed allocation. */ return -ENOMEM; /* The documentation claims EVP_DigestInit behaves just like * EVP_DigestInit_ex if passed NULL, except it also calls * EVP_MD_CTX_reset, which deinitializes the context. */ r = EVP_DigestInit_ex(ctx, alg, NULL); if (r == 0) return -EIO; r = EVP_DigestUpdate(ctx, msg, msg_len); if (r == 0) return -EIO; r = EVP_DigestFinal_ex(ctx, ret_hash, &len); if (r == 0) return -EIO; if (ret_hash_len) *ret_hash_len = len; return 0; } int rsa_encrypt_bytes( EVP_PKEY *pkey, const void *decrypted_key, size_t decrypted_key_size, void **ret_encrypt_key, size_t *ret_encrypt_key_size) { _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = NULL; _cleanup_free_ void *b = NULL; size_t l; ctx = EVP_PKEY_CTX_new(pkey, NULL); if (!ctx) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to allocate public key context"); if (EVP_PKEY_encrypt_init(ctx) <= 0) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize public key context"); if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to configure PKCS#1 padding"); if (EVP_PKEY_encrypt(ctx, NULL, &l, decrypted_key, decrypted_key_size) <= 0) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size"); b = malloc(l); if (!b) return -ENOMEM; if (EVP_PKEY_encrypt(ctx, b, &l, decrypted_key, decrypted_key_size) <= 0) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size"); *ret_encrypt_key = TAKE_PTR(b); *ret_encrypt_key_size = l; return 0; } int rsa_pkey_to_suitable_key_size( EVP_PKEY *pkey, size_t *ret_suitable_key_size) { size_t suitable_key_size; int bits; assert(pkey); assert(ret_suitable_key_size); /* Analyzes the specified public key and that it is RSA. If so, will return a suitable size for a * disk encryption key to encrypt with RSA for use in PKCS#11 security token schemes. */ if (EVP_PKEY_base_id(pkey) != EVP_PKEY_RSA) return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "X.509 certificate does not refer to RSA key."); bits = EVP_PKEY_bits(pkey); log_debug("Bits in RSA key: %i", bits); /* We use PKCS#1 padding for the RSA cleartext, hence let's leave some extra space for it, hence only * generate a random key half the size of the RSA length */ suitable_key_size = bits / 8 / 2; if (suitable_key_size < 1) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Uh, RSA key size too short?"); *ret_suitable_key_size = suitable_key_size; return 0; } int pubkey_fingerprint(EVP_PKEY *pk, const EVP_MD *md, void **ret, size_t *ret_size) { _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX* m = NULL; _cleanup_free_ void *d = NULL, *h = NULL; int sz, lsz, msz; unsigned umsz; unsigned char *dd; /* Calculates a message digest of the DER encoded public key */ assert(pk); assert(md); assert(ret); assert(ret_size); sz = i2d_PublicKey(pk, NULL); if (sz < 0) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to convert public key to DER format: %s", ERR_error_string(ERR_get_error(), NULL)); dd = d = malloc(sz); if (!d) return log_oom_debug(); lsz = i2d_PublicKey(pk, &dd); if (lsz < 0) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to convert public key to DER format: %s", ERR_error_string(ERR_get_error(), NULL)); m = EVP_MD_CTX_new(); if (!m) return log_oom_debug(); if (EVP_DigestInit_ex(m, md, NULL) != 1) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize %s context.", EVP_MD_name(md)); if (EVP_DigestUpdate(m, d, lsz) != 1) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run %s context.", EVP_MD_name(md)); msz = EVP_MD_size(md); assert(msz > 0); h = malloc(msz); if (!h) return log_oom_debug(); umsz = msz; if (EVP_DigestFinal_ex(m, h, &umsz) != 1) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize hash context."); assert(umsz == (unsigned) msz); *ret = TAKE_PTR(h); *ret_size = msz; return 0; } # if PREFER_OPENSSL int string_hashsum( const char *s, size_t len, const EVP_MD *md_algorithm, char **ret) { uint8_t hash[EVP_MAX_MD_SIZE]; size_t hash_size; char *enc; int r; hash_size = EVP_MD_size(md_algorithm); assert(hash_size > 0); r = openssl_hash(md_algorithm, s, len, hash, NULL); if (r < 0) return r; enc = hexmem(hash, hash_size); if (!enc) return -ENOMEM; *ret = enc; return 0; } # endif #endif int x509_fingerprint(X509 *cert, uint8_t buffer[static SHA256_DIGEST_SIZE]) { #if HAVE_OPENSSL _cleanup_free_ uint8_t *der = NULL; int dersz; assert(cert); dersz = i2d_X509(cert, &der); if (dersz < 0) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to convert PEM certificate to DER format: %s", ERR_error_string(ERR_get_error(), NULL)); sha256_direct(der, dersz, buffer); return 0; #else return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "openssl is not supported, cannot calculate X509 fingerprint: %m"); #endif }
6,848
30.562212
127
c
null
systemd-main/src/shared/output-mode.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "output-mode.h" #include "string-table.h" JsonFormatFlags output_mode_to_json_format_flags(OutputMode m) { switch (m) { case OUTPUT_JSON_SSE: return JSON_FORMAT_SSE; case OUTPUT_JSON_SEQ: return JSON_FORMAT_SEQ; case OUTPUT_JSON_PRETTY: return JSON_FORMAT_PRETTY; default: return JSON_FORMAT_NEWLINE; } } static const char *const output_mode_table[_OUTPUT_MODE_MAX] = { [OUTPUT_SHORT] = "short", [OUTPUT_SHORT_FULL] = "short-full", [OUTPUT_SHORT_ISO] = "short-iso", [OUTPUT_SHORT_ISO_PRECISE] = "short-iso-precise", [OUTPUT_SHORT_PRECISE] = "short-precise", [OUTPUT_SHORT_MONOTONIC] = "short-monotonic", [OUTPUT_SHORT_DELTA] = "short-delta", [OUTPUT_SHORT_UNIX] = "short-unix", [OUTPUT_VERBOSE] = "verbose", [OUTPUT_EXPORT] = "export", [OUTPUT_JSON] = "json", [OUTPUT_JSON_PRETTY] = "json-pretty", [OUTPUT_JSON_SSE] = "json-sse", [OUTPUT_JSON_SEQ] = "json-seq", [OUTPUT_CAT] = "cat", [OUTPUT_WITH_UNIT] = "with-unit", }; DEFINE_STRING_TABLE_LOOKUP(output_mode, OutputMode);
1,281
28.136364
64
c
null
systemd-main/src/shared/output-mode.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "json.h" #include "macro.h" typedef enum OutputMode { OUTPUT_SHORT, OUTPUT_SHORT_FULL, OUTPUT_SHORT_ISO, OUTPUT_SHORT_ISO_PRECISE, OUTPUT_SHORT_PRECISE, OUTPUT_SHORT_MONOTONIC, OUTPUT_SHORT_DELTA, OUTPUT_SHORT_UNIX, OUTPUT_VERBOSE, OUTPUT_EXPORT, OUTPUT_JSON, OUTPUT_JSON_PRETTY, OUTPUT_JSON_SSE, OUTPUT_JSON_SEQ, OUTPUT_CAT, OUTPUT_WITH_UNIT, _OUTPUT_MODE_MAX, _OUTPUT_MODE_INVALID = -EINVAL, } OutputMode; static inline bool OUTPUT_MODE_IS_JSON(OutputMode m) { return IN_SET(m, OUTPUT_JSON, OUTPUT_JSON_PRETTY, OUTPUT_JSON_SSE, OUTPUT_JSON_SEQ); } /* The output flags definitions are shared by the logs and process tree output. Some apply to both, some only to the * logs output, others only to the process tree output. */ typedef enum OutputFlags { OUTPUT_SHOW_ALL = 1 << 0, OUTPUT_FULL_WIDTH = 1 << 1, OUTPUT_COLOR = 1 << 2, /* Specific to log output */ OUTPUT_WARN_CUTOFF = 1 << 3, OUTPUT_CATALOG = 1 << 4, OUTPUT_BEGIN_NEWLINE = 1 << 5, OUTPUT_UTC = 1 << 6, OUTPUT_NO_HOSTNAME = 1 << 7, OUTPUT_TRUNCATE_NEWLINE = 1 << 8, /* Specific to process tree output */ OUTPUT_KERNEL_THREADS = 1 << 9, OUTPUT_CGROUP_XATTRS = 1 << 10, OUTPUT_CGROUP_ID = 1 << 11, } OutputFlags; JsonFormatFlags output_mode_to_json_format_flags(OutputMode m); const char* output_mode_to_string(OutputMode m) _const_; OutputMode output_mode_from_string(const char *s) _pure_;
1,780
29.706897
116
h
null
systemd-main/src/shared/pam-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <security/pam_ext.h> #include <syslog.h> #include <stdlib.h> #include "alloc-util.h" #include "errno-util.h" #include "format-util.h" #include "macro.h" #include "pam-util.h" #include "process-util.h" #include "stdio-util.h" #include "string-util.h" int pam_syslog_errno(pam_handle_t *handle, int level, int error, const char *format, ...) { va_list ap; LOCAL_ERRNO(error); va_start(ap, format); pam_vsyslog(handle, LOG_ERR, format, ap); va_end(ap); return error == -ENOMEM ? PAM_BUF_ERR : PAM_SERVICE_ERR; } int pam_syslog_pam_error(pam_handle_t *handle, int level, int error, const char *format, ...) { /* This wraps pam_syslog() but will replace @PAMERR@ with a string from pam_strerror(). * @PAMERR@ must be at the very end. */ va_list ap; va_start(ap, format); const char *p = endswith(format, "@PAMERR@"); if (p) { const char *pamerr = pam_strerror(handle, error); if (strchr(pamerr, '%')) pamerr = "n/a"; /* We cannot have any formatting chars */ char buf[p - format + strlen(pamerr) + 1]; xsprintf(buf, "%*s%s", (int)(p - format), format, pamerr); DISABLE_WARNING_FORMAT_NONLITERAL; pam_vsyslog(handle, level, buf, ap); REENABLE_WARNING; } else pam_vsyslog(handle, level, format, ap); va_end(ap); return error; } /* A small structure we store inside the PAM session object, that allows us to reuse bus connections but pins * it to the process thoroughly. */ struct PamBusData { sd_bus *bus; pam_handle_t *pam_handle; char *cache_id; }; static PamBusData *pam_bus_data_free(PamBusData *d) { /* The actual destructor */ if (!d) return NULL; /* NB: PAM sessions usually involve forking off a child process, and thus the PAM context might be * duplicated in the child. This destructor might be called twice: both in the parent and in the * child. sd_bus_flush_close_unref() however is smart enough to be a NOP when invoked in any other * process than the one it was invoked from, hence we don't need to add any extra protection here to * ensure that destruction of the bus connection in the child affects the parent's connection * somehow. */ sd_bus_flush_close_unref(d->bus); free(d->cache_id); /* Note: we don't destroy pam_handle here, because this object is pinned by the handle, and not vice versa! */ return mfree(d); } DEFINE_TRIVIAL_CLEANUP_FUNC(PamBusData*, pam_bus_data_free); static void pam_bus_data_destroy(pam_handle_t *handle, void *data, int error_status) { /* Destructor when called from PAM. Note that error_status is supposed to tell us via PAM_DATA_SILENT * whether we are called in a forked off child of the PAM session or in the original parent. We don't * bother with that however, and instead rely on the PID checks that sd_bus_flush_close_unref() does * internally anyway. That said, we still generate a warning message, since this really shouldn't * happen. */ if (error_status & PAM_DATA_SILENT) pam_syslog(handle, LOG_WARNING, "Attempted to close sd-bus after fork, this should not happen."); pam_bus_data_free(data); } static char* pam_make_bus_cache_id(const char *module_name) { char *id; /* We want to cache bus connections between hooks. But we don't want to allow them to be reused in * child processes (because sd-bus doesn't support that). We also don't want them to be reused * between our own PAM modules, because they might be linked against different versions of our * utility functions and share different state. Hence include both a module ID and a PID in the data * field ID. */ if (asprintf(&id, "system-bus-%s-" PID_FMT, ASSERT_PTR(module_name), getpid_cached()) < 0) return NULL; return id; } void pam_bus_data_disconnectp(PamBusData **_d) { PamBusData *d = *ASSERT_PTR(_d); pam_handle_t *handle; int r; /* Disconnects the connection explicitly (for use via _cleanup_()) when called */ if (!d) return; handle = ASSERT_PTR(d->pam_handle); /* Keep a reference to the session even after 'd' might be invalidated */ r = pam_set_data(handle, ASSERT_PTR(d->cache_id), NULL, NULL); if (r != PAM_SUCCESS) pam_syslog_pam_error(handle, LOG_ERR, r, "Failed to release PAM user record data, ignoring: @PAMERR@"); /* Note, the pam_set_data() call will invalidate 'd', don't access here anymore */ } int pam_acquire_bus_connection( pam_handle_t *handle, const char *module_name, sd_bus **ret_bus, PamBusData **ret_pam_bus_data) { _cleanup_(pam_bus_data_freep) PamBusData *d = NULL; _cleanup_free_ char *cache_id = NULL; int r; assert(handle); assert(module_name); assert(ret_bus); cache_id = pam_make_bus_cache_id(module_name); if (!cache_id) return pam_log_oom(handle); /* We cache the bus connection so that we can share it between the session and the authentication hooks */ r = pam_get_data(handle, cache_id, (const void**) &d); if (r == PAM_SUCCESS && d) goto success; if (!IN_SET(r, PAM_SUCCESS, PAM_NO_MODULE_DATA)) return pam_syslog_pam_error(handle, LOG_ERR, r, "Failed to get bus connection: @PAMERR@"); d = new(PamBusData, 1); if (!d) return pam_log_oom(handle); *d = (PamBusData) { .cache_id = TAKE_PTR(cache_id), .pam_handle = handle, }; r = sd_bus_open_system(&d->bus); if (r < 0) return pam_syslog_errno(handle, LOG_ERR, r, "Failed to connect to system bus: %m"); r = pam_set_data(handle, d->cache_id, d, pam_bus_data_destroy); if (r != PAM_SUCCESS) return pam_syslog_pam_error(handle, LOG_ERR, r, "Failed to set PAM bus data: @PAMERR@"); success: *ret_bus = sd_bus_ref(d->bus); if (ret_pam_bus_data) *ret_pam_bus_data = d; TAKE_PTR(d); /* don't auto-destroy anymore, it's installed now */ return PAM_SUCCESS; } int pam_release_bus_connection(pam_handle_t *handle, const char *module_name) { _cleanup_free_ char *cache_id = NULL; int r; assert(module_name); cache_id = pam_make_bus_cache_id(module_name); if (!cache_id) return pam_log_oom(handle); r = pam_set_data(handle, cache_id, NULL, NULL); if (r != PAM_SUCCESS) return pam_syslog_pam_error(handle, LOG_ERR, r, "Failed to release PAM user record data: @PAMERR@"); return PAM_SUCCESS; } void pam_cleanup_free(pam_handle_t *handle, void *data, int error_status) { /* A generic destructor for pam_set_data() that just frees the specified data */ free(data); }
7,363
35.098039
119
c
null
systemd-main/src/shared/pam-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <security/pam_modules.h> #include "sd-bus.h" int pam_syslog_errno(pam_handle_t *handle, int level, int error, const char *format, ...) _printf_(4,5); int pam_syslog_pam_error(pam_handle_t *handle, int level, int error, const char *format, ...) _printf_(4,5); /* Call pam_vsyslog if debug is enabled */ #define pam_debug_syslog(handle, debug, fmt, ...) ({ \ if (debug) \ pam_syslog(handle, LOG_DEBUG, fmt, ## __VA_ARGS__); \ }) static inline int pam_log_oom(pam_handle_t *handle) { /* This is like log_oom(), but uses PAM logging */ return pam_syslog_errno(handle, LOG_ERR, ENOMEM, "Out of memory."); } static inline int pam_bus_log_create_error(pam_handle_t *handle, int r) { /* This is like bus_log_create_error(), but uses PAM logging */ return pam_syslog_errno(handle, LOG_ERR, r, "Failed to create bus message: %m"); } static inline int pam_bus_log_parse_error(pam_handle_t *handle, int r) { /* This is like bus_log_parse_error(), but uses PAM logging */ return pam_syslog_errno(handle, LOG_ERR, r, "Failed to parse bus message: %m"); } typedef struct PamBusData PamBusData; void pam_bus_data_disconnectp(PamBusData **d); /* Use a different module name per different PAM module. They are all loaded in the same namespace, and this * helps avoid a clash in the internal data structures of sd-bus. It will be used as key for cache items. */ int pam_acquire_bus_connection(pam_handle_t *handle, const char *module_name, sd_bus **ret_bus, PamBusData **ret_bus_data); int pam_release_bus_connection(pam_handle_t *handle, const char *module_name); void pam_cleanup_free(pam_handle_t *handle, void *data, int error_status);
1,880
43.785714
123
h
null
systemd-main/src/shared/parse-argument.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "format-table.h" #include "parse-argument.h" #include "path-util.h" #include "signal-util.h" #include "stdio-util.h" #include "string-table.h" #include "string-util.h" /* All functions in this file emit warnings. */ int parse_boolean_argument(const char *optname, const char *s, bool *ret) { int r; /* Returns the result through *ret and the return value. */ if (s) { r = parse_boolean(s); if (r < 0) return log_error_errno(r, "Failed to parse boolean argument to %s: %s.", optname, s); if (ret) *ret = r; return r; } else { /* s may be NULL. This is controlled by getopt_long() parameters. */ if (ret) *ret = true; return true; } } int parse_json_argument(const char *s, JsonFormatFlags *ret) { assert(s); assert(ret); if (streq(s, "pretty")) *ret = JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR_AUTO; else if (streq(s, "short")) *ret = JSON_FORMAT_NEWLINE; else if (streq(s, "off")) *ret = JSON_FORMAT_OFF; else if (streq(s, "help")) { puts("pretty\n" "short\n" "off"); return 0; /* 0 means → we showed a brief help, exit now */ } else return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown argument to --json= switch: %s", s); return 1; /* 1 means → properly parsed */ } int parse_path_argument(const char *path, bool suppress_root, char **arg) { char *p; int r; /* * This function is intended to be used in command line parsers, to handle paths that are passed * in. It makes the path absolute, and reduces it to NULL if omitted or root (the latter optionally). * * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON SUCCESS! * Hence, do not pass in uninitialized pointers. */ if (isempty(path)) { *arg = mfree(*arg); return 0; } r = path_make_absolute_cwd(path, &p); if (r < 0) return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path); path_simplify(p); if (suppress_root && empty_or_root(p)) p = mfree(p); return free_and_replace(*arg, p); } int parse_signal_argument(const char *s, int *ret) { int r; assert(s); assert(ret); if (streq(s, "help")) { DUMP_STRING_TABLE(signal, int, _NSIG); return 0; } if (streq(s, "list")) { _cleanup_(table_unrefp) Table *table = NULL; table = table_new("signal", "name"); if (!table) return log_oom(); for (int i = 1; i < _NSIG; i++) { r = table_add_many( table, TABLE_INT, i, TABLE_SIGNAL, i); if (r < 0) return table_log_add_error(r); } r = table_print(table, NULL); if (r < 0) return table_log_print_error(r); return 0; } r = signal_from_string(s); if (r < 0) return log_error_errno(r, "Failed to parse signal string \"%s\".", s); *ret = r; return 1; /* work to do */ }
3,764
29.362903
109
c
null
systemd-main/src/shared/parse-helpers.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "af-list.h" #include "extract-word.h" #include "ip-protocol-list.h" #include "log.h" #include "parse-helpers.h" #include "parse-util.h" #include "path-util.h" #include "utf8.h" int path_simplify_and_warn( char *path, unsigned flag, const char *unit, const char *filename, unsigned line, const char *lvalue) { bool fatal = flag & PATH_CHECK_FATAL; assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)); if (!utf8_is_valid(path)) return log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path); if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) { bool absolute; absolute = path_is_absolute(path); if (!absolute && (flag & PATH_CHECK_ABSOLUTE)) return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "%s= path is not absolute%s: %s", lvalue, fatal ? "" : ", ignoring", path); if (absolute && (flag & PATH_CHECK_RELATIVE)) return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "%s= path is absolute%s: %s", lvalue, fatal ? "" : ", ignoring", path); } path_simplify(path); if (!path_is_valid(path)) return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "%s= path has invalid length (%zu bytes)%s.", lvalue, strlen(path), fatal ? "" : ", ignoring"); if (!path_is_normalized(path)) return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL), "%s= path is not normalized%s: %s", lvalue, fatal ? "" : ", ignoring", path); return 0; } static int parse_af_token( const char *token, int *family, int *ip_protocol, uint16_t *nr_ports, uint16_t *port_min) { int af; assert(token); assert(family); af = af_from_ipv4_ipv6(token); if (af == AF_UNSPEC) return -EINVAL; *family = af; return 0; } static int parse_ip_protocol_token( const char *token, int *family, int *ip_protocol, uint16_t *nr_ports, uint16_t *port_min) { int proto; assert(token); assert(ip_protocol); proto = ip_protocol_from_tcp_udp(token); if (proto < 0) return -EINVAL; *ip_protocol = proto; return 0; } static int parse_ip_ports_token( const char *token, int *family, int *ip_protocol, uint16_t *nr_ports, uint16_t *port_min) { assert(token); assert(nr_ports); assert(port_min); if (streq(token, "any")) *nr_ports = *port_min = 0; else { uint16_t mn = 0, mx = 0; int r = parse_ip_port_range(token, &mn, &mx); if (r < 0) return r; *nr_ports = mx - mn + 1; *port_min = mn; } return 0; } typedef int (*parse_token_f)( const char *, int *, int *, uint16_t *, uint16_t *); int parse_socket_bind_item( const char *str, int *address_family, int *ip_protocol, uint16_t *nr_ports, uint16_t *port_min) { /* Order of token parsers is important. */ const parse_token_f parsers[] = { &parse_af_token, &parse_ip_protocol_token, &parse_ip_ports_token, }; parse_token_f const *parser_ptr = parsers; int af = AF_UNSPEC, proto = 0, r; uint16_t nr = 0, mn = 0; const char *p = ASSERT_PTR(str); assert(address_family); assert(ip_protocol); assert(nr_ports); assert(port_min); if (isempty(p)) return -EINVAL; for (;;) { _cleanup_free_ char *token = NULL; r = extract_first_word(&p, &token, ":", EXTRACT_DONT_COALESCE_SEPARATORS); if (r == 0) break; if (r < 0) return r; if (isempty(token)) return -EINVAL; while (parser_ptr != parsers + ELEMENTSOF(parsers)) { r = (*parser_ptr)(token, &af, &proto, &nr, &mn); if (r == -ENOMEM) return r; ++parser_ptr; /* Continue to next token if parsing succeeded, * otherwise apply next parser to the same token. */ if (r >= 0) break; } if (parser_ptr == parsers + ELEMENTSOF(parsers)) break; } /* Failed to parse a token. */ if (r < 0) return r; /* Parsers applied successfully, but end of the string not reached. */ if (p) return -EINVAL; *address_family = af; *ip_protocol = proto; *nr_ports = nr; *port_min = mn; return 0; } int config_parse_path_or_ignore( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { _cleanup_free_ char *n = NULL; bool fatal = ltype; char **s = ASSERT_PTR(data); int r; assert(filename); assert(lvalue); assert(rvalue); if (isempty(rvalue)) goto finalize; n = strdup(rvalue); if (!n) return log_oom(); if (streq(n, "-")) goto finalize; r = path_simplify_and_warn(n, PATH_CHECK_ABSOLUTE | (fatal ? PATH_CHECK_FATAL : 0), unit, filename, line, lvalue); if (r < 0) return fatal ? -ENOEXEC : 0; finalize: return free_and_replace(*s, n); }
6,901
28
122
c
null
systemd-main/src/shared/parse-helpers.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdint.h> enum { PATH_CHECK_FATAL = 1 << 0, /* If not set, then error message is appended with 'ignoring'. */ PATH_CHECK_ABSOLUTE = 1 << 1, PATH_CHECK_RELATIVE = 1 << 2, }; int path_simplify_and_warn( char *path, unsigned flag, const char *unit, const char *filename, unsigned line, const char *lvalue); int parse_socket_bind_item( const char *str, int *address_family, int *ip_protocol, uint16_t *nr_ports, uint16_t *port_min); int config_parse_path_or_ignore( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
1,042
26.447368
104
h
null
systemd-main/src/shared/pcre2-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "dlfcn-util.h" #include "log.h" #include "pcre2-util.h" #if HAVE_PCRE2 static void *pcre2_dl = NULL; pcre2_match_data* (*sym_pcre2_match_data_create)(uint32_t, pcre2_general_context *); void (*sym_pcre2_match_data_free)(pcre2_match_data *); void (*sym_pcre2_code_free)(pcre2_code *); pcre2_code* (*sym_pcre2_compile)(PCRE2_SPTR, PCRE2_SIZE, uint32_t, int *, PCRE2_SIZE *, pcre2_compile_context *); int (*sym_pcre2_get_error_message)(int, PCRE2_UCHAR *, PCRE2_SIZE); int (*sym_pcre2_match)(const pcre2_code *, PCRE2_SPTR, PCRE2_SIZE, PCRE2_SIZE, uint32_t, pcre2_match_data *, pcre2_match_context *); PCRE2_SIZE* (*sym_pcre2_get_ovector_pointer)(pcre2_match_data *); DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR( pcre2_code_hash_ops_free, pcre2_code, (void (*)(const pcre2_code *, struct siphash*))trivial_hash_func, (int (*)(const pcre2_code *, const pcre2_code*))trivial_compare_func, sym_pcre2_code_free); #else const struct hash_ops pcre2_code_hash_ops_free = {}; #endif int dlopen_pcre2(void) { #if HAVE_PCRE2 /* So here's something weird: PCRE2 actually renames the symbols exported by the library via C * macros, so that the exported symbols carry a suffix "_8" but when used from C the suffix is * gone. In the argument list below we ignore this mangling. Surprisingly (at least to me), we * actually get away with that. That's because DLSYM_ARG() useses STRINGIFY() to generate a string * version of the symbol name, and that resolves the macro mapping implicitly already, so that the * string actually contains the "_8" suffix already due to that and we don't have to append it * manually anymore. C is weird. 🤯 */ return dlopen_many_sym_or_warn( &pcre2_dl, "libpcre2-8.so.0", LOG_ERR, DLSYM_ARG(pcre2_match_data_create), DLSYM_ARG(pcre2_match_data_free), DLSYM_ARG(pcre2_code_free), DLSYM_ARG(pcre2_compile), DLSYM_ARG(pcre2_get_error_message), DLSYM_ARG(pcre2_match), DLSYM_ARG(pcre2_get_ovector_pointer)); #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PCRE2 support is not compiled in."); #endif } int pattern_compile_and_log(const char *pattern, PatternCompileCase case_, pcre2_code **ret) { #if HAVE_PCRE2 PCRE2_SIZE erroroffset; _cleanup_(sym_pcre2_code_freep) pcre2_code *p = NULL; unsigned flags = 0; int errorcode, r; assert(pattern); r = dlopen_pcre2(); if (r < 0) return r; if (case_ == PATTERN_COMPILE_CASE_INSENSITIVE) flags = PCRE2_CASELESS; else if (case_ == PATTERN_COMPILE_CASE_AUTO) { _cleanup_(sym_pcre2_match_data_freep) pcre2_match_data *md = NULL; bool has_case; _cleanup_(sym_pcre2_code_freep) pcre2_code *cs = NULL; md = sym_pcre2_match_data_create(1, NULL); if (!md) return log_oom(); r = pattern_compile_and_log("[[:upper:]]", PATTERN_COMPILE_CASE_SENSITIVE, &cs); if (r < 0) return r; r = sym_pcre2_match(cs, (PCRE2_SPTR8) pattern, PCRE2_ZERO_TERMINATED, 0, 0, md, NULL); has_case = r >= 0; flags = !has_case * PCRE2_CASELESS; } log_debug("Doing case %s matching based on %s", flags & PCRE2_CASELESS ? "insensitive" : "sensitive", case_ != PATTERN_COMPILE_CASE_AUTO ? "request" : "pattern casing"); p = sym_pcre2_compile((PCRE2_SPTR8) pattern, PCRE2_ZERO_TERMINATED, flags, &errorcode, &erroroffset, NULL); if (!p) { unsigned char buf[LINE_MAX]; r = sym_pcre2_get_error_message(errorcode, buf, sizeof buf); return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad pattern \"%s\": %s", pattern, r < 0 ? "unknown error" : (char *)buf); } if (ret) *ret = TAKE_PTR(p); return 0; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PCRE2 support is not compiled in."); #endif } int pattern_matches_and_log(pcre2_code *compiled_pattern, const char *message, size_t size, size_t *ret_ovec) { #if HAVE_PCRE2 _cleanup_(sym_pcre2_match_data_freep) pcre2_match_data *md = NULL; int r; assert(compiled_pattern); assert(message); /* pattern_compile_and_log() must be called before this function is called and that function already * dlopens pcre2 so we can assert on it being available here. */ assert(pcre2_dl); md = sym_pcre2_match_data_create(1, NULL); if (!md) return log_oom(); r = sym_pcre2_match(compiled_pattern, (const unsigned char *)message, size, 0, /* start at offset 0 in the subject */ 0, /* default options */ md, NULL); if (r == PCRE2_ERROR_NOMATCH) return false; if (r < 0) { unsigned char buf[LINE_MAX]; r = sym_pcre2_get_error_message(r, buf, sizeof(buf)); return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Pattern matching failed: %s", r < 0 ? "unknown error" : (char*) buf); } if (ret_ovec) { ret_ovec[0] = sym_pcre2_get_ovector_pointer(md)[0]; ret_ovec[1] = sym_pcre2_get_ovector_pointer(md)[1]; } return true; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PCRE2 support is not compiled in."); #endif } void *pattern_free(pcre2_code *p) { #if HAVE_PCRE2 if (!p) return NULL; assert(pcre2_dl); sym_pcre2_code_free(p); return NULL; #else assert(p == NULL); return NULL; #endif }
6,352
37.041916
132
c
null
systemd-main/src/shared/pe-header.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include "macro.h" #include "sparse-endian.h" struct DosFileHeader { uint8_t Magic[2]; le16_t LastSize; le16_t nBlocks; le16_t nReloc; le16_t HdrSize; le16_t MinAlloc; le16_t MaxAlloc; le16_t ss; le16_t sp; le16_t Checksum; le16_t ip; le16_t cs; le16_t RelocPos; le16_t nOverlay; le16_t reserved[4]; le16_t OEMId; le16_t OEMInfo; le16_t reserved2[10]; le32_t ExeHeader; } _packed_; struct PeFileHeader { le16_t Machine; le16_t NumberOfSections; le32_t TimeDateStamp; le32_t PointerToSymbolTable; le32_t NumberOfSymbols; le16_t SizeOfOptionalHeader; le16_t Characteristics; } _packed_; struct PeHeader { uint8_t Magic[4]; struct PeFileHeader FileHeader; } _packed_; struct PeSectionHeader { uint8_t Name[8]; le32_t VirtualSize; le32_t VirtualAddress; le32_t SizeOfRawData; le32_t PointerToRawData; le32_t PointerToRelocations; le32_t PointerToLinenumbers; le16_t NumberOfRelocations; le16_t NumberOfLinenumbers; le32_t Characteristics; } _packed_;
1,343
21.779661
48
h
null
systemd-main/src/shared/pretty-print.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/utsname.h> #include <errno.h> #include <stdio.h> #include "alloc-util.h" #include "conf-files.h" #include "constants.h" #include "env-util.h" #include "fd-util.h" #include "fileio.h" #include "pager.h" #include "path-util.h" #include "pretty-print.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" bool urlify_enabled(void) { #if ENABLE_URLIFY static int cached_urlify_enabled = -1; if (cached_urlify_enabled < 0) { int val; val = getenv_bool("SYSTEMD_URLIFY"); if (val >= 0) cached_urlify_enabled = val; else cached_urlify_enabled = colors_enabled(); } return cached_urlify_enabled; #else return 0; #endif } int terminal_urlify(const char *url, const char *text, char **ret) { char *n; assert(url); /* Takes a URL and a pretty string and formats it as clickable link for the terminal. See * https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda for details. */ if (isempty(text)) text = url; if (urlify_enabled()) n = strjoin("\x1B]8;;", url, "\a", text, "\x1B]8;;\a"); else n = strdup(text); if (!n) return -ENOMEM; *ret = n; return 0; } int file_url_from_path(const char *path, char **ret) { _cleanup_free_ char *absolute = NULL; struct utsname u; char *url = NULL; int r; if (uname(&u) < 0) return -errno; if (!path_is_absolute(path)) { r = path_make_absolute_cwd(path, &absolute); if (r < 0) return r; path = absolute; } /* As suggested by https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda, let's include the local * hostname here. Note that we don't use gethostname_malloc() or gethostname_strict() since we are interested * in the raw string the kernel has set, whatever it may be, under the assumption that terminals are not overly * careful with validating the strings either. */ url = strjoin("file://", u.nodename, path); if (!url) return -ENOMEM; *ret = url; return 0; } int terminal_urlify_path(const char *path, const char *text, char **ret) { _cleanup_free_ char *url = NULL; int r; assert(path); /* Much like terminal_urlify() above, but takes a file system path as input * and turns it into a proper file:// URL first. */ if (isempty(path)) return -EINVAL; if (isempty(text)) text = path; if (!urlify_enabled()) { char *n; n = strdup(text); if (!n) return -ENOMEM; *ret = n; return 0; } r = file_url_from_path(path, &url); if (r < 0) return r; return terminal_urlify(url, text, ret); } int terminal_urlify_man(const char *page, const char *section, char **ret) { const char *url, *text; url = strjoina("man:", page, "(", section, ")"); text = strjoina(page, "(", section, ") man page"); return terminal_urlify(url, text, ret); } static int cat_file(const char *filename, bool newline) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *urlified = NULL; int r; f = fopen(filename, "re"); if (!f) return -errno; r = terminal_urlify_path(filename, NULL, &urlified); if (r < 0) return r; printf("%s%s# %s%s\n", newline ? "\n" : "", ansi_highlight_blue(), urlified, ansi_normal()); fflush(stdout); for (;;) { _cleanup_free_ char *line = NULL; r = read_line(f, LONG_LINE_MAX, &line); if (r < 0) return log_error_errno(r, "Failed to read \"%s\": %m", filename); if (r == 0) break; puts(line); } return 0; } int cat_files(const char *file, char **dropins, CatFlags flags) { int r; if (file) { r = cat_file(file, false); if (r == -ENOENT && (flags & CAT_FLAGS_MAIN_FILE_OPTIONAL)) printf("%s# Configuration file %s not found%s\n", ansi_highlight_magenta(), file, ansi_normal()); else if (r < 0) return log_warning_errno(r, "Failed to cat %s: %m", file); } STRV_FOREACH(path, dropins) { r = cat_file(*path, file || path != dropins); if (r < 0) return log_warning_errno(r, "Failed to cat %s: %m", *path); } return 0; } void print_separator(void) { /* Outputs a separator line that resolves to whitespace when copied from the terminal. We do that by outputting * one line filled with spaces with ANSI underline set, followed by a second (empty) line. */ if (underline_enabled()) { size_t i, c; c = columns(); flockfile(stdout); fputs_unlocked(ANSI_UNDERLINE, stdout); for (i = 0; i < c; i++) fputc_unlocked(' ', stdout); fputs_unlocked(ANSI_NORMAL "\n\n", stdout); funlockfile(stdout); } else fputs("\n\n", stdout); } static int guess_type(const char **name, char ***prefixes, bool *is_collection, const char **extension) { /* Try to figure out if name is like tmpfiles.d/ or systemd/system-presets/, * i.e. a collection of directories without a main config file. */ _cleanup_free_ char *n = NULL; bool usr = false, run = false, coll = false; const char *ext = ".conf"; /* This is static so that the array doesn't get deallocated when we exit the function */ static const char* const std_prefixes[] = { CONF_PATHS(""), NULL }; static const char* const usr_prefixes[] = { CONF_PATHS_USR(""), NULL }; static const char* const run_prefixes[] = { "/run/", NULL }; if (path_equal(*name, "environment.d")) /* Special case: we need to include /etc/environment in the search path, even * though the whole concept is called environment.d. */ *name = "environment"; n = strdup(*name); if (!n) return log_oom(); /* All systemd-style config files should support the /usr-/etc-/run split and * dropins. Let's add a blanket rule that allows us to support them without keeping * an explicit list. */ if (path_startswith(n, "systemd") && endswith(n, ".conf")) usr = true; delete_trailing_chars(n, "/"); if (endswith(n, ".d")) coll = true; if (path_equal(n, "environment")) usr = true; if (path_equal(n, "udev/hwdb.d")) ext = ".hwdb"; if (path_equal(n, "udev/rules.d")) ext = ".rules"; if (path_equal(n, "kernel/install.d")) ext = ".install"; if (path_equal(n, "systemd/ntp-units.d")) { coll = true; ext = ".list"; } if (path_equal(n, "systemd/relabel-extra.d")) { coll = run = true; ext = ".relabel"; } if (PATH_IN_SET(n, "systemd/system-preset", "systemd/user-preset")) { coll = true; ext = ".preset"; } if (path_equal(n, "systemd/user-preset")) usr = true; *prefixes = (char**) (usr ? usr_prefixes : run ? run_prefixes : std_prefixes); *is_collection = coll; *extension = ext; return 0; } int conf_files_cat(const char *root, const char *name) { _cleanup_strv_free_ char **dirs = NULL, **files = NULL; _cleanup_free_ char *path = NULL; char **prefixes = NULL; /* explicit initialization to appease gcc */ bool is_collection; const char *extension; int r; r = guess_type(&name, &prefixes, &is_collection, &extension); if (r < 0) return r; assert(prefixes); assert(extension); STRV_FOREACH(prefix, prefixes) { assert(endswith(*prefix, "/")); r = strv_extendf(&dirs, "%s%s%s", *prefix, name, is_collection ? "" : ".d"); if (r < 0) return log_error_errno(r, "Failed to build directory list: %m"); } if (DEBUG_LOGGING) { log_debug("Looking for configuration in:"); if (!is_collection) STRV_FOREACH(prefix, prefixes) log_debug(" %s%s%s", strempty(root), *prefix, name); STRV_FOREACH(t, dirs) log_debug(" %s%s/*%s", strempty(root), *t, extension); } /* First locate the main config file, if any */ if (!is_collection) { STRV_FOREACH(prefix, prefixes) { path = path_join(root, *prefix, name); if (!path) return log_oom(); if (access(path, F_OK) == 0) break; path = mfree(path); } if (!path) printf("%s# Main configuration file %s not found%s\n", ansi_highlight_magenta(), name, ansi_normal()); } /* Then locate the drop-ins, if any */ r = conf_files_list_strv(&files, extension, root, 0, (const char* const*) dirs); if (r < 0) return log_error_errno(r, "Failed to query file list: %m"); /* Show */ return cat_files(path, files, 0); }
10,523
29.952941
119
c
null
systemd-main/src/shared/ptyfwd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <signal.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/time.h> #include <termios.h> #include <unistd.h> #include "sd-event.h" #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "log.h" #include "macro.h" #include "ptyfwd.h" #include "terminal-util.h" #include "time-util.h" struct PTYForward { sd_event *event; int input_fd; int output_fd; int master; PTYForwardFlags flags; sd_event_source *stdin_event_source; sd_event_source *stdout_event_source; sd_event_source *master_event_source; sd_event_source *sigwinch_event_source; struct termios saved_stdin_attr; struct termios saved_stdout_attr; bool close_input_fd:1; bool close_output_fd:1; bool saved_stdin:1; bool saved_stdout:1; bool stdin_readable:1; bool stdin_hangup:1; bool stdout_writable:1; bool stdout_hangup:1; bool master_readable:1; bool master_writable:1; bool master_hangup:1; bool read_from_master:1; bool done:1; bool drain:1; bool last_char_set:1; char last_char; char in_buffer[LINE_MAX], out_buffer[LINE_MAX]; size_t in_buffer_full, out_buffer_full; usec_t escape_timestamp; unsigned escape_counter; PTYForwardHandler handler; void *userdata; }; #define ESCAPE_USEC (1*USEC_PER_SEC) static void pty_forward_disconnect(PTYForward *f) { if (!f) return; f->stdin_event_source = sd_event_source_unref(f->stdin_event_source); f->stdout_event_source = sd_event_source_unref(f->stdout_event_source); f->master_event_source = sd_event_source_unref(f->master_event_source); f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source); f->event = sd_event_unref(f->event); if (f->output_fd >= 0) { if (f->saved_stdout) (void) tcsetattr(f->output_fd, TCSANOW, &f->saved_stdout_attr); /* STDIN/STDOUT should not be non-blocking normally, so let's reset it */ (void) fd_nonblock(f->output_fd, false); if (f->close_output_fd) f->output_fd = safe_close(f->output_fd); } if (f->input_fd >= 0) { if (f->saved_stdin) (void) tcsetattr(f->input_fd, TCSANOW, &f->saved_stdin_attr); (void) fd_nonblock(f->input_fd, false); if (f->close_input_fd) f->input_fd = safe_close(f->input_fd); } f->saved_stdout = f->saved_stdin = false; } static int pty_forward_done(PTYForward *f, int rcode) { _cleanup_(sd_event_unrefp) sd_event *e = NULL; assert(f); if (f->done) return 0; e = sd_event_ref(f->event); f->done = true; pty_forward_disconnect(f); if (f->handler) return f->handler(f, rcode, f->userdata); else return sd_event_exit(e, rcode < 0 ? EXIT_FAILURE : rcode); } static bool look_for_escape(PTYForward *f, const char *buffer, size_t n) { const char *p; assert(f); assert(buffer); assert(n > 0); for (p = buffer; p < buffer + n; p++) { /* Check for ^] */ if (*p == 0x1D) { usec_t nw = now(CLOCK_MONOTONIC); if (f->escape_counter == 0 || nw > f->escape_timestamp + ESCAPE_USEC) { f->escape_timestamp = nw; f->escape_counter = 1; } else { (f->escape_counter)++; if (f->escape_counter >= 3) return true; } } else { f->escape_timestamp = 0; f->escape_counter = 0; } } return false; } static bool ignore_vhangup(PTYForward *f) { assert(f); if (f->flags & PTY_FORWARD_IGNORE_VHANGUP) return true; if ((f->flags & PTY_FORWARD_IGNORE_INITIAL_VHANGUP) && !f->read_from_master) return true; return false; } static bool drained(PTYForward *f) { int q = 0; assert(f); if (f->out_buffer_full > 0) return false; if (f->master_readable) return false; if (ioctl(f->master, TIOCINQ, &q) < 0) log_debug_errno(errno, "TIOCINQ failed on master: %m"); else if (q > 0) return false; if (ioctl(f->master, TIOCOUTQ, &q) < 0) log_debug_errno(errno, "TIOCOUTQ failed on master: %m"); else if (q > 0) return false; return true; } static int shovel(PTYForward *f) { ssize_t k; assert(f); while ((f->stdin_readable && f->in_buffer_full <= 0) || (f->master_writable && f->in_buffer_full > 0) || (f->master_readable && f->out_buffer_full <= 0) || (f->stdout_writable && f->out_buffer_full > 0)) { if (f->stdin_readable && f->in_buffer_full < LINE_MAX) { k = read(f->input_fd, f->in_buffer + f->in_buffer_full, LINE_MAX - f->in_buffer_full); if (k < 0) { if (errno == EAGAIN) f->stdin_readable = false; else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) { f->stdin_readable = false; f->stdin_hangup = true; f->stdin_event_source = sd_event_source_unref(f->stdin_event_source); } else { log_error_errno(errno, "read(): %m"); return pty_forward_done(f, -errno); } } else if (k == 0) { /* EOF on stdin */ f->stdin_readable = false; f->stdin_hangup = true; f->stdin_event_source = sd_event_source_unref(f->stdin_event_source); } else { /* Check if ^] has been pressed three times within one second. If we get this we quite * immediately. */ if (look_for_escape(f, f->in_buffer + f->in_buffer_full, k)) return pty_forward_done(f, -ECANCELED); f->in_buffer_full += (size_t) k; } } if (f->master_writable && f->in_buffer_full > 0) { k = write(f->master, f->in_buffer, f->in_buffer_full); if (k < 0) { if (IN_SET(errno, EAGAIN, EIO)) f->master_writable = false; else if (IN_SET(errno, EPIPE, ECONNRESET)) { f->master_writable = f->master_readable = false; f->master_hangup = true; f->master_event_source = sd_event_source_unref(f->master_event_source); } else { log_error_errno(errno, "write(): %m"); return pty_forward_done(f, -errno); } } else { assert(f->in_buffer_full >= (size_t) k); memmove(f->in_buffer, f->in_buffer + k, f->in_buffer_full - k); f->in_buffer_full -= k; } } if (f->master_readable && f->out_buffer_full < LINE_MAX) { k = read(f->master, f->out_buffer + f->out_buffer_full, LINE_MAX - f->out_buffer_full); if (k < 0) { /* Note that EIO on the master device * might be caused by vhangup() or * temporary closing of everything on * the other side, we treat it like * EAGAIN here and try again, unless * ignore_vhangup is off. */ if (errno == EAGAIN || (errno == EIO && ignore_vhangup(f))) f->master_readable = false; else if (IN_SET(errno, EPIPE, ECONNRESET, EIO)) { f->master_readable = f->master_writable = false; f->master_hangup = true; f->master_event_source = sd_event_source_unref(f->master_event_source); } else { log_error_errno(errno, "read(): %m"); return pty_forward_done(f, -errno); } } else { f->read_from_master = true; f->out_buffer_full += (size_t) k; } } if (f->stdout_writable && f->out_buffer_full > 0) { k = write(f->output_fd, f->out_buffer, f->out_buffer_full); if (k < 0) { if (errno == EAGAIN) f->stdout_writable = false; else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) { f->stdout_writable = false; f->stdout_hangup = true; f->stdout_event_source = sd_event_source_unref(f->stdout_event_source); } else { log_error_errno(errno, "write(): %m"); return pty_forward_done(f, -errno); } } else { if (k > 0) { f->last_char = f->out_buffer[k-1]; f->last_char_set = true; } assert(f->out_buffer_full >= (size_t) k); memmove(f->out_buffer, f->out_buffer + k, f->out_buffer_full - k); f->out_buffer_full -= k; } } } if (f->stdin_hangup || f->stdout_hangup || f->master_hangup) { /* Exit the loop if any side hung up and if there's * nothing more to write or nothing we could write. */ if ((f->out_buffer_full <= 0 || f->stdout_hangup) && (f->in_buffer_full <= 0 || f->master_hangup)) return pty_forward_done(f, 0); } /* If we were asked to drain, and there's nothing more to handle from the master, then call the callback * too. */ if (f->drain && drained(f)) return pty_forward_done(f, 0); return 0; } static int on_master_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) { PTYForward *f = ASSERT_PTR(userdata); assert(e); assert(e == f->master_event_source); assert(fd >= 0); assert(fd == f->master); if (revents & (EPOLLIN|EPOLLHUP)) f->master_readable = true; if (revents & (EPOLLOUT|EPOLLHUP)) f->master_writable = true; return shovel(f); } static int on_stdin_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) { PTYForward *f = ASSERT_PTR(userdata); assert(e); assert(e == f->stdin_event_source); assert(fd >= 0); assert(fd == f->input_fd); if (revents & (EPOLLIN|EPOLLHUP)) f->stdin_readable = true; return shovel(f); } static int on_stdout_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) { PTYForward *f = ASSERT_PTR(userdata); assert(e); assert(e == f->stdout_event_source); assert(fd >= 0); assert(fd == f->output_fd); if (revents & (EPOLLOUT|EPOLLHUP)) f->stdout_writable = true; return shovel(f); } static int on_sigwinch_event(sd_event_source *e, const struct signalfd_siginfo *si, void *userdata) { PTYForward *f = ASSERT_PTR(userdata); struct winsize ws; assert(e); assert(e == f->sigwinch_event_source); /* The window size changed, let's forward that. */ if (ioctl(f->output_fd, TIOCGWINSZ, &ws) >= 0) (void) ioctl(f->master, TIOCSWINSZ, &ws); return 0; } int pty_forward_new( sd_event *event, int master, PTYForwardFlags flags, PTYForward **ret) { _cleanup_(pty_forward_freep) PTYForward *f = NULL; struct winsize ws; int r; f = new(PTYForward, 1); if (!f) return -ENOMEM; *f = (struct PTYForward) { .flags = flags, .master = -EBADF, .input_fd = -EBADF, .output_fd = -EBADF, }; if (event) f->event = sd_event_ref(event); else { r = sd_event_default(&f->event); if (r < 0) return r; } if (FLAGS_SET(flags, PTY_FORWARD_READ_ONLY)) f->output_fd = STDOUT_FILENO; else { /* If we shall be invoked in interactive mode, let's switch on non-blocking mode, so that we * never end up staving one direction while we block on the other. However, let's be careful * here and not turn on O_NONBLOCK for stdin/stdout directly, but of re-opened copies of * them. This has two advantages: when we are killed abruptly the stdin/stdout fds won't be * left in O_NONBLOCK state for the next process using them. In addition, if some process * running in the background wants to continue writing to our stdout it can do so without * being confused by O_NONBLOCK. */ f->input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); if (f->input_fd < 0) { /* Handle failures gracefully, after all certain fd types cannot be reopened * (sockets, …) */ log_debug_errno(f->input_fd, "Failed to reopen stdin, using original fd: %m"); r = fd_nonblock(STDIN_FILENO, true); if (r < 0) return r; f->input_fd = STDIN_FILENO; } else f->close_input_fd = true; f->output_fd = fd_reopen(STDOUT_FILENO, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK); if (f->output_fd < 0) { log_debug_errno(f->output_fd, "Failed to reopen stdout, using original fd: %m"); r = fd_nonblock(STDOUT_FILENO, true); if (r < 0) return r; f->output_fd = STDOUT_FILENO; } else f->close_output_fd = true; } r = fd_nonblock(master, true); if (r < 0) return r; f->master = master; if (ioctl(f->output_fd, TIOCGWINSZ, &ws) < 0) /* If we can't get the resolution from the output fd, then use our internal, regular width/height, * i.e. something derived from $COLUMNS and $LINES if set. */ ws = (struct winsize) { .ws_row = lines(), .ws_col = columns(), }; (void) ioctl(master, TIOCSWINSZ, &ws); if (!(flags & PTY_FORWARD_READ_ONLY)) { assert(f->input_fd >= 0); if (tcgetattr(f->input_fd, &f->saved_stdin_attr) >= 0) { struct termios raw_stdin_attr; f->saved_stdin = true; raw_stdin_attr = f->saved_stdin_attr; cfmakeraw(&raw_stdin_attr); raw_stdin_attr.c_oflag = f->saved_stdin_attr.c_oflag; tcsetattr(f->input_fd, TCSANOW, &raw_stdin_attr); } if (tcgetattr(f->output_fd, &f->saved_stdout_attr) >= 0) { struct termios raw_stdout_attr; f->saved_stdout = true; raw_stdout_attr = f->saved_stdout_attr; cfmakeraw(&raw_stdout_attr); raw_stdout_attr.c_iflag = f->saved_stdout_attr.c_iflag; raw_stdout_attr.c_lflag = f->saved_stdout_attr.c_lflag; tcsetattr(f->output_fd, TCSANOW, &raw_stdout_attr); } r = sd_event_add_io(f->event, &f->stdin_event_source, f->input_fd, EPOLLIN|EPOLLET, on_stdin_event, f); if (r < 0 && r != -EPERM) return r; if (r >= 0) (void) sd_event_source_set_description(f->stdin_event_source, "ptyfwd-stdin"); } r = sd_event_add_io(f->event, &f->stdout_event_source, f->output_fd, EPOLLOUT|EPOLLET, on_stdout_event, f); if (r == -EPERM) /* stdout without epoll support. Likely redirected to regular file. */ f->stdout_writable = true; else if (r < 0) return r; else (void) sd_event_source_set_description(f->stdout_event_source, "ptyfwd-stdout"); r = sd_event_add_io(f->event, &f->master_event_source, master, EPOLLIN|EPOLLOUT|EPOLLET, on_master_event, f); if (r < 0) return r; (void) sd_event_source_set_description(f->master_event_source, "ptyfwd-master"); r = sd_event_add_signal(f->event, &f->sigwinch_event_source, SIGWINCH, on_sigwinch_event, f); if (r < 0) return r; (void) sd_event_source_set_description(f->sigwinch_event_source, "ptyfwd-sigwinch"); *ret = TAKE_PTR(f); return 0; } PTYForward *pty_forward_free(PTYForward *f) { pty_forward_disconnect(f); return mfree(f); } int pty_forward_get_last_char(PTYForward *f, char *ch) { assert(f); assert(ch); if (!f->last_char_set) return -ENXIO; *ch = f->last_char; return 0; } int pty_forward_set_ignore_vhangup(PTYForward *f, bool b) { int r; assert(f); if (!!(f->flags & PTY_FORWARD_IGNORE_VHANGUP) == b) return 0; SET_FLAG(f->flags, PTY_FORWARD_IGNORE_VHANGUP, b); if (!ignore_vhangup(f)) { /* We shall now react to vhangup()s? Let's check * immediately if we might be in one */ f->master_readable = true; r = shovel(f); if (r < 0) return r; } return 0; } bool pty_forward_get_ignore_vhangup(PTYForward *f) { assert(f); return !!(f->flags & PTY_FORWARD_IGNORE_VHANGUP); } bool pty_forward_is_done(PTYForward *f) { assert(f); return f->done; } void pty_forward_set_handler(PTYForward *f, PTYForwardHandler cb, void *userdata) { assert(f); f->handler = cb; f->userdata = userdata; } bool pty_forward_drain(PTYForward *f) { assert(f); /* Starts draining the forwarder. Specifically: * * - Returns true if there are no unprocessed bytes from the pty, false otherwise * * - Makes sure the handler function is called the next time the number of unprocessed bytes hits zero */ f->drain = true; return drained(f); } int pty_forward_set_priority(PTYForward *f, int64_t priority) { int r; assert(f); if (f->stdin_event_source) { r = sd_event_source_set_priority(f->stdin_event_source, priority); if (r < 0) return r; } r = sd_event_source_set_priority(f->stdout_event_source, priority); if (r < 0) return r; r = sd_event_source_set_priority(f->master_event_source, priority); if (r < 0) return r; r = sd_event_source_set_priority(f->sigwinch_event_source, priority); if (r < 0) return r; return 0; } int pty_forward_set_width_height(PTYForward *f, unsigned width, unsigned height) { struct winsize ws; assert(f); if (width == UINT_MAX && height == UINT_MAX) return 0; /* noop */ if (width != UINT_MAX && (width == 0 || width > USHRT_MAX)) return -ERANGE; if (height != UINT_MAX && (height == 0 || height > USHRT_MAX)) return -ERANGE; if (width == UINT_MAX || height == UINT_MAX) { if (ioctl(f->master, TIOCGWINSZ, &ws) < 0) return -errno; if (width != UINT_MAX) ws.ws_col = width; if (height != UINT_MAX) ws.ws_row = height; } else ws = (struct winsize) { .ws_row = height, .ws_col = width, }; if (ioctl(f->master, TIOCSWINSZ, &ws) < 0) return -errno; /* Make sure we ignore SIGWINCH window size events from now on */ f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source); return 0; }
22,974
32.886431
119
c
null
systemd-main/src/shared/ptyfwd.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "sd-event.h" #include "macro.h" typedef struct PTYForward PTYForward; typedef enum PTYForwardFlags { PTY_FORWARD_READ_ONLY = 1, /* Continue reading after hangup? */ PTY_FORWARD_IGNORE_VHANGUP = 2, /* Continue reading after hangup but only if we never read anything else? */ PTY_FORWARD_IGNORE_INITIAL_VHANGUP = 4, } PTYForwardFlags; typedef int (*PTYForwardHandler)(PTYForward *f, int rcode, void *userdata); int pty_forward_new(sd_event *event, int master, PTYForwardFlags flags, PTYForward **f); PTYForward *pty_forward_free(PTYForward *f); int pty_forward_get_last_char(PTYForward *f, char *ch); int pty_forward_set_ignore_vhangup(PTYForward *f, bool ignore_vhangup); bool pty_forward_get_ignore_vhangup(PTYForward *f); bool pty_forward_is_done(PTYForward *f); void pty_forward_set_handler(PTYForward *f, PTYForwardHandler handler, void *userdata); bool pty_forward_drain(PTYForward *f); int pty_forward_set_priority(PTYForward *f, int64_t priority); int pty_forward_set_width_height(PTYForward *f, unsigned width, unsigned height); DEFINE_TRIVIAL_CLEANUP_FUNC(PTYForward*, pty_forward_free);
1,245
27.976744
88
h
null
systemd-main/src/shared/quota-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/quota.h> #include <sys/stat.h> #include "alloc-util.h" #include "blockdev-util.h" #include "device-util.h" #include "quota-util.h" int quotactl_devnum(int cmd, dev_t devnum, int id, void *addr) { _cleanup_free_ char *devnode = NULL; int r; /* Like quotactl() but takes a dev_t instead of a path to a device node, and fixes caddr_t → void*, * like we should, today */ r = devname_from_devnum(S_IFBLK, devnum, &devnode); if (r < 0) return r; if (quotactl(cmd, devnode, id, addr) < 0) return -errno; return 0; } int quotactl_path(int cmd, const char *path, int id, void *addr) { dev_t devno; int r; /* Like quotactl() but takes a path to some fs object, and changes the backing file system. I.e. the * argument shouldn't be a block device but a regular file system object */ r = get_block_device(path, &devno); if (r < 0) return r; if (devno == 0) /* Doesn't have a block device */ return -ENODEV; return quotactl_devnum(cmd, devno, id, addr); }
1,211
27.186047
108
c
null
systemd-main/src/shared/quota-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <sys/quota.h> #include <sys/types.h> /* Wrapper around the QCMD() macro of linux/quota.h that removes some undefined behaviour. A typical quota * command such as QCMD(Q_GETQUOTA, USRQUOTA) cannot be resolved on platforms where "int" is 32-bit, as it is * larger than INT_MAX. Yikes, because that are basically all platforms Linux supports. Let's add a wrapper * that explicitly takes its arguments as unsigned 32-bit, and then converts the shift result explicitly to * int, acknowledging the undefined behaviour of the kernel headers. This doesn't remove the undefined * behaviour, but it stops ubsan from complaining about it. */ static inline int QCMD_FIXED(uint32_t cmd, uint32_t type) { return (int) QCMD(cmd, type); } int quotactl_devnum(int cmd, dev_t devnum, int id, void *addr); int quotactl_path(int cmd, const char *path, int id, void *addr);
962
47.15
109
h
null
systemd-main/src/shared/reboot-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdint.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <unistd.h> #if HAVE_XENCTRL #define __XEN_INTERFACE_VERSION__ 0x00040900 #include <xen/xen.h> #include <xen/kexec.h> #include <xen/sys/privcmd.h> #endif #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "log.h" #include "proc-cmdline.h" #include "raw-reboot.h" #include "reboot-util.h" #include "string-util.h" #include "umask-util.h" #include "virt.h" int update_reboot_parameter_and_warn(const char *parameter, bool keep) { int r; if (isempty(parameter)) { if (keep) return 0; if (unlink("/run/systemd/reboot-param") < 0) { if (errno == ENOENT) return 0; return log_warning_errno(errno, "Failed to unlink reboot parameter file: %m"); } return 0; } WITH_UMASK(0022) { r = write_string_file("/run/systemd/reboot-param", parameter, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC); if (r < 0) return log_warning_errno(r, "Failed to write reboot parameter file: %m"); } return 0; } int read_reboot_parameter(char **parameter) { int r; assert(parameter); r = read_one_line_file("/run/systemd/reboot-param", parameter); if (r < 0 && r != -ENOENT) return log_debug_errno(r, "Failed to read /run/systemd/reboot-param: %m"); return 0; } int reboot_with_parameter(RebootFlags flags) { int r; /* Reboots the system with a parameter that is read from /run/systemd/reboot-param. Returns 0 if * REBOOT_DRY_RUN was set and the actual reboot operation was hence skipped. If REBOOT_FALLBACK is * set and the reboot with parameter doesn't work out a fallback to classic reboot() is attempted. If * REBOOT_FALLBACK is not set, 0 is returned instead, which should be considered indication for the * caller to fall back to reboot() on its own, or somehow else deal with this. If REBOOT_LOG is * specified will log about what it is going to do, as well as all errors. */ if (detect_container() == 0) { _cleanup_free_ char *parameter = NULL; r = read_one_line_file("/run/systemd/reboot-param", &parameter); if (r < 0 && r != -ENOENT) log_full_errno(flags & REBOOT_LOG ? LOG_WARNING : LOG_DEBUG, r, "Failed to read reboot parameter file, ignoring: %m"); if (!isempty(parameter)) { log_full(flags & REBOOT_LOG ? LOG_INFO : LOG_DEBUG, "Rebooting with argument '%s'.", parameter); if (flags & REBOOT_DRY_RUN) return 0; (void) raw_reboot(LINUX_REBOOT_CMD_RESTART2, parameter); log_full_errno(flags & REBOOT_LOG ? LOG_WARNING : LOG_DEBUG, errno, "Failed to reboot with parameter, retrying without: %m"); } } if (!(flags & REBOOT_FALLBACK)) return 0; log_full(flags & REBOOT_LOG ? LOG_INFO : LOG_DEBUG, "Rebooting."); if (flags & REBOOT_DRY_RUN) return 0; (void) reboot(RB_AUTOBOOT); return log_full_errno(flags & REBOOT_LOG ? LOG_ERR : LOG_DEBUG, errno, "Failed to reboot: %m"); } int shall_restore_state(void) { bool ret; int r; r = proc_cmdline_get_bool("systemd.restore_state", &ret); if (r < 0) return r; return r > 0 ? ret : true; } static int xen_kexec_loaded(void) { #if HAVE_XENCTRL _cleanup_close_ int privcmd_fd = -EBADF, buf_fd = -EBADF; xen_kexec_status_t *buffer; size_t size; int r; if (access("/proc/xen", F_OK) < 0) { if (errno == ENOENT) return -EOPNOTSUPP; return log_debug_errno(errno, "Unable to test whether /proc/xen exists: %m"); } size = page_size(); if (sizeof(xen_kexec_status_t) > size) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "page_size is too small for hypercall"); privcmd_fd = open("/dev/xen/privcmd", O_RDWR|O_CLOEXEC); if (privcmd_fd < 0) return log_debug_errno(errno, "Cannot access /dev/xen/privcmd: %m"); buf_fd = open("/dev/xen/hypercall", O_RDWR|O_CLOEXEC); if (buf_fd < 0) return log_debug_errno(errno, "Cannot access /dev/xen/hypercall: %m"); buffer = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, buf_fd, 0); if (buffer == MAP_FAILED) return log_debug_errno(errno, "Cannot allocate buffer for hypercall: %m"); *buffer = (xen_kexec_status_t) { .type = KEXEC_TYPE_DEFAULT, }; privcmd_hypercall_t call = { .op = __HYPERVISOR_kexec_op, .arg = { KEXEC_CMD_kexec_status, PTR_TO_UINT64(buffer), }, }; r = RET_NERRNO(ioctl(privcmd_fd, IOCTL_PRIVCMD_HYPERCALL, &call)); if (r < 0) log_debug_errno(r, "kexec_status failed: %m"); munmap(buffer, size); return r; #else return -EOPNOTSUPP; #endif } bool kexec_loaded(void) { _cleanup_free_ char *s = NULL; int r; r = xen_kexec_loaded(); if (r >= 0) return r; r = read_one_line_file("/sys/kernel/kexec_loaded", &s); if (r < 0) { if (r != -ENOENT) log_debug_errno(r, "Unable to read /sys/kernel/kexec_loaded, ignoring: %m"); return false; } return s[0] == '1'; }
6,132
30.777202
109
c
null
systemd-main/src/shared/recovery-key.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memory-util.h" #include "random-util.h" #include "recovery-key.h" const char modhex_alphabet[16] = { 'c', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'r', 't', 'u', 'v' }; int decode_modhex_char(char x) { for (size_t i = 0; i < ELEMENTSOF(modhex_alphabet); i++) /* Check both upper and lowercase */ if (modhex_alphabet[i] == x || (modhex_alphabet[i] - 32) == x) return i; return -EINVAL; } int normalize_recovery_key(const char *password, char **ret) { _cleanup_(erase_and_freep) char *mangled = NULL; size_t l; assert(password); assert(ret); l = strlen(password); if (!IN_SET(l, RECOVERY_KEY_MODHEX_RAW_LENGTH*2, /* syntax without dashes */ RECOVERY_KEY_MODHEX_FORMATTED_LENGTH-1)) /* syntax with dashes */ return -EINVAL; mangled = new(char, RECOVERY_KEY_MODHEX_FORMATTED_LENGTH); if (!mangled) return -ENOMEM; for (size_t i = 0, j = 0; i < RECOVERY_KEY_MODHEX_RAW_LENGTH; i++) { size_t k; int a, b; if (l == RECOVERY_KEY_MODHEX_RAW_LENGTH*2) /* Syntax without dashes */ k = i * 2; else { /* Syntax with dashes */ assert(l == RECOVERY_KEY_MODHEX_FORMATTED_LENGTH-1); k = i * 2 + i / 4; if (i > 0 && i % 4 == 0 && password[k-1] != '-') return -EINVAL; } a = decode_modhex_char(password[k]); if (a < 0) return -EINVAL; b = decode_modhex_char(password[k+1]); if (b < 0) return -EINVAL; mangled[j++] = modhex_alphabet[a]; mangled[j++] = modhex_alphabet[b]; if (i % 4 == 3) mangled[j++] = '-'; } mangled[RECOVERY_KEY_MODHEX_FORMATTED_LENGTH-1] = 0; *ret = TAKE_PTR(mangled); return 0; } int make_recovery_key(char **ret) { _cleanup_(erase_and_freep) char *formatted = NULL; _cleanup_(erase_and_freep) uint8_t *key = NULL; size_t j = 0; int r; assert(ret); key = new(uint8_t, RECOVERY_KEY_MODHEX_RAW_LENGTH); if (!key) return -ENOMEM; r = crypto_random_bytes(key, RECOVERY_KEY_MODHEX_RAW_LENGTH); if (r < 0) return r; /* Let's now format it as 64 modhex chars, and after each 8 chars insert a dash */ formatted = new(char, RECOVERY_KEY_MODHEX_FORMATTED_LENGTH); if (!formatted) return -ENOMEM; for (size_t i = 0; i < RECOVERY_KEY_MODHEX_RAW_LENGTH; i++) { formatted[j++] = modhex_alphabet[key[i] >> 4]; formatted[j++] = modhex_alphabet[key[i] & 0xF]; if (i % 4 == 3) formatted[j++] = '-'; } assert(j == RECOVERY_KEY_MODHEX_FORMATTED_LENGTH); assert(formatted[RECOVERY_KEY_MODHEX_FORMATTED_LENGTH-1] == '-'); formatted[RECOVERY_KEY_MODHEX_FORMATTED_LENGTH-1] = 0; /* replace final dash with a NUL */ *ret = TAKE_PTR(formatted); return 0; }
3,510
30.918182
98
c
null
systemd-main/src/shared/recovery-key.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /* 256 bit keys = 32 bytes */ #define RECOVERY_KEY_MODHEX_RAW_LENGTH 32 /* Formatted as sequences of 64 modhex characters, with dashes inserted after multiples of 8 chars (incl. trailing NUL) */ #define RECOVERY_KEY_MODHEX_FORMATTED_LENGTH (RECOVERY_KEY_MODHEX_RAW_LENGTH*2/8*9) int make_recovery_key(char **ret); extern const char modhex_alphabet[16]; int decode_modhex_char(char x); int normalize_recovery_key(const char *password, char **ret);
515
29.352941
122
h
null
systemd-main/src/shared/resize-fs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <linux/btrfs.h> #include <linux/magic.h> #include <sys/ioctl.h> #include <sys/vfs.h> #include "blockdev-util.h" #include "fs-util.h" #include "missing_fs.h" #include "missing_magic.h" #include "missing_xfs.h" #include "resize-fs.h" #include "stat-util.h" int resize_fs(int fd, uint64_t sz, uint64_t *ret_size) { struct statfs sfs; assert(fd >= 0); /* Rounds down to next block size */ if (sz <= 0 || sz == UINT64_MAX) return -ERANGE; if (fstatfs(fd, &sfs) < 0) return -errno; if (is_fs_type(&sfs, EXT4_SUPER_MAGIC)) { uint64_t u; if (sz < EXT4_MINIMAL_SIZE) return -ERANGE; u = sz / sfs.f_bsize; if (ioctl(fd, EXT4_IOC_RESIZE_FS, &u) < 0) return -errno; if (ret_size) *ret_size = u * sfs.f_bsize; } else if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC)) { struct btrfs_ioctl_vol_args args = {}; /* 256M is the minimize size enforced by the btrfs kernel code when resizing (which is * strange btw, as mkfs.btrfs is fine creating file systems > 109M). It will return EINVAL in * that case, let's catch this error beforehand though, and report a more explanatory * error. */ if (sz < BTRFS_MINIMAL_SIZE) return -ERANGE; sz -= sz % sfs.f_bsize; xsprintf(args.name, "%" PRIu64, sz); if (ioctl(fd, BTRFS_IOC_RESIZE, &args) < 0) return -errno; if (ret_size) *ret_size = sz; } else if (is_fs_type(&sfs, XFS_SB_MAGIC)) { xfs_fsop_geom_t geo; xfs_growfs_data_t d; if (sz < XFS_MINIMAL_SIZE) return -ERANGE; if (ioctl(fd, XFS_IOC_FSGEOMETRY, &geo) < 0) return -errno; d = (xfs_growfs_data_t) { .imaxpct = geo.imaxpct, .newblocks = sz / geo.blocksize, }; if (ioctl(fd, XFS_IOC_FSGROWFSDATA, &d) < 0) return -errno; if (ret_size) *ret_size = d.newblocks * geo.blocksize; } else return -EOPNOTSUPP; return 0; } uint64_t minimal_size_by_fs_magic(statfs_f_type_t magic) { switch (magic) { case (statfs_f_type_t) EXT4_SUPER_MAGIC: return EXT4_MINIMAL_SIZE; case (statfs_f_type_t) XFS_SB_MAGIC: return XFS_MINIMAL_SIZE; case (statfs_f_type_t) BTRFS_SUPER_MAGIC: return BTRFS_MINIMAL_SIZE; default: return UINT64_MAX; } } uint64_t minimal_size_by_fs_name(const char *name) { if (streq_ptr(name, "ext4")) return EXT4_MINIMAL_SIZE; if (streq_ptr(name, "xfs")) return XFS_MINIMAL_SIZE; if (streq_ptr(name, "btrfs")) return BTRFS_MINIMAL_SIZE; return UINT64_MAX; } /* Returns true for the only fs that can online shrink *and* grow */ bool fs_can_online_shrink_and_grow(statfs_f_type_t magic) { return magic == (statfs_f_type_t) BTRFS_SUPER_MAGIC; }
3,502
26.582677
109
c
null
systemd-main/src/shared/resolve-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "conf-parser.h" #include "in-addr-util.h" #include "macro.h" /* 127.0.0.53 in native endian (The IP address we listen on with the full DNS stub, i.e. that does LLMNR/mDNS, and stuff) */ #define INADDR_DNS_STUB ((in_addr_t) 0x7f000035U) /* 127.0.0.54 in native endian (The IP address we listen on we only implement "proxy" mode) */ #define INADDR_DNS_PROXY_STUB ((in_addr_t) 0x7f000036U) /* 127.0.0.2 is an address we always map to the local hostname. This is different from 127.0.0.1 which maps to "localhost" */ #define INADDR_LOCALADDRESS ((in_addr_t) 0x7f000002U) typedef enum DnsCacheMode DnsCacheMode; enum DnsCacheMode { DNS_CACHE_MODE_NO, DNS_CACHE_MODE_YES, DNS_CACHE_MODE_NO_NEGATIVE, _DNS_CACHE_MODE_MAX, _DNS_CACHE_MODE_INVALID = -EINVAL, }; typedef enum ResolveSupport ResolveSupport; typedef enum DnssecMode DnssecMode; typedef enum DnsOverTlsMode DnsOverTlsMode; /* Do not change the order, see link_get_llmnr_support() or link_get_mdns_support(). */ enum ResolveSupport { RESOLVE_SUPPORT_NO, RESOLVE_SUPPORT_RESOLVE, RESOLVE_SUPPORT_YES, _RESOLVE_SUPPORT_MAX, _RESOLVE_SUPPORT_INVALID = -EINVAL, }; enum DnssecMode { /* No DNSSEC validation is done */ DNSSEC_NO, /* Validate locally, if the server knows DO, but if not, * don't. Don't trust the AD bit. If the server doesn't do * DNSSEC properly, downgrade to non-DNSSEC operation. Of * course, we then are vulnerable to a downgrade attack, but * that's life and what is configured. */ DNSSEC_ALLOW_DOWNGRADE, /* Insist on DNSSEC server support, and rather fail than downgrading. */ DNSSEC_YES, _DNSSEC_MODE_MAX, _DNSSEC_MODE_INVALID = -EINVAL, }; enum DnsOverTlsMode { /* No connection is made for DNS-over-TLS */ DNS_OVER_TLS_NO, /* Try to connect using DNS-over-TLS, but if connection fails, * fall back to using an unencrypted connection */ DNS_OVER_TLS_OPPORTUNISTIC, /* Enforce DNS-over-TLS and require valid server certificates */ DNS_OVER_TLS_YES, _DNS_OVER_TLS_MODE_MAX, _DNS_OVER_TLS_MODE_INVALID = -EINVAL, }; CONFIG_PARSER_PROTOTYPE(config_parse_resolve_support); CONFIG_PARSER_PROTOTYPE(config_parse_dnssec_mode); CONFIG_PARSER_PROTOTYPE(config_parse_dns_over_tls_mode); CONFIG_PARSER_PROTOTYPE(config_parse_dns_cache_mode); const char* resolve_support_to_string(ResolveSupport p) _const_; ResolveSupport resolve_support_from_string(const char *s) _pure_; const char* dnssec_mode_to_string(DnssecMode p) _const_; DnssecMode dnssec_mode_from_string(const char *s) _pure_; const char* dns_over_tls_mode_to_string(DnsOverTlsMode p) _const_; DnsOverTlsMode dns_over_tls_mode_from_string(const char *s) _pure_; bool dns_server_address_valid(int family, const union in_addr_union *sa); const char* dns_cache_mode_to_string(DnsCacheMode p) _const_; DnsCacheMode dns_cache_mode_from_string(const char *s) _pure_; /* A resolv.conf file containing the DNS server and domain data we learnt from uplink, i.e. the full uplink data */ #define PRIVATE_UPLINK_RESOLV_CONF "/run/systemd/resolve/resolv.conf" /* A resolv.conf file containing the domain data we learnt from uplink, but our own DNS server address. */ #define PRIVATE_STUB_RESOLV_CONF "/run/systemd/resolve/stub-resolv.conf" /* A static resolv.conf file containing no domains, but only our own DNS server address */ #define PRIVATE_STATIC_RESOLV_CONF ROOTLIBEXECDIR "/resolv.conf"
3,654
35.55
125
h
null
systemd-main/src/shared/rm-rf.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fcntl.h> #include <sys/stat.h> #include "alloc-util.h" #include "errno-util.h" typedef enum RemoveFlags { REMOVE_ONLY_DIRECTORIES = 1 << 0, /* Only remove empty directories, no files */ REMOVE_ROOT = 1 << 1, /* Remove the specified directory itself too, not just the contents of it */ REMOVE_PHYSICAL = 1 << 2, /* If not set, only removes files on tmpfs, never physical file systems */ REMOVE_SUBVOLUME = 1 << 3, /* Drop btrfs subvolumes in the tree too */ REMOVE_MISSING_OK = 1 << 4, /* If the top-level directory is missing, ignore the ENOENT for it */ REMOVE_CHMOD = 1 << 5, /* chmod() for write access if we cannot delete or access something */ REMOVE_CHMOD_RESTORE = 1 << 6, /* Restore the old mode before returning */ REMOVE_SYNCFS = 1 << 7, /* syncfs() the root of the specified directory after removing everything in it */ } RemoveFlags; int unlinkat_harder(int dfd, const char *filename, int unlink_flags, RemoveFlags remove_flags); int fstatat_harder(int dfd, const char *filename, struct stat *ret, int fstatat_flags, RemoveFlags remove_flags); int rm_rf_children(int fd, RemoveFlags flags, const struct stat *root_dev); int rm_rf_child(int fd, const char *name, RemoveFlags flags); int rm_rf_at(int dir_fd, const char *path, RemoveFlags flags); static inline int rm_rf(const char *path, RemoveFlags flags) { return rm_rf_at(AT_FDCWD, path, flags); } /* Useful for usage with _cleanup_(), destroys a directory and frees the pointer */ static inline char *rm_rf_physical_and_free(char *p) { PROTECT_ERRNO; if (!p) return NULL; (void) rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK|REMOVE_CHMOD); return mfree(p); } DEFINE_TRIVIAL_CLEANUP_FUNC(char*, rm_rf_physical_and_free); /* Similar as above, but also has magic btrfs subvolume powers */ static inline char *rm_rf_subvolume_and_free(char *p) { PROTECT_ERRNO; if (!p) return NULL; (void) rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_MISSING_OK|REMOVE_CHMOD); return mfree(p); } DEFINE_TRIVIAL_CLEANUP_FUNC(char*, rm_rf_subvolume_and_free);
2,399
40.37931
124
h
null
systemd-main/src/shared/seccomp-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if HAVE_SECCOMP #include <seccomp.h> #include <stdbool.h> #include <stdint.h> #include "errno-list.h" #include "parse-util.h" #include "set.h" #include "string-util.h" const char* seccomp_arch_to_string(uint32_t c); int seccomp_arch_from_string(const char *n, uint32_t *ret); int seccomp_init_for_arch(scmp_filter_ctx *ret, uint32_t arch, uint32_t default_action); bool is_seccomp_available(void); typedef struct SyscallFilterSet { const char *name; const char *help; const char *value; } SyscallFilterSet; enum { /* Please leave DEFAULT first and KNOWN last, but sort the rest alphabetically */ SYSCALL_FILTER_SET_DEFAULT, SYSCALL_FILTER_SET_AIO, SYSCALL_FILTER_SET_BASIC_IO, SYSCALL_FILTER_SET_CHOWN, SYSCALL_FILTER_SET_CLOCK, SYSCALL_FILTER_SET_CPU_EMULATION, SYSCALL_FILTER_SET_DEBUG, SYSCALL_FILTER_SET_FILE_SYSTEM, SYSCALL_FILTER_SET_IO_EVENT, SYSCALL_FILTER_SET_IPC, SYSCALL_FILTER_SET_KEYRING, SYSCALL_FILTER_SET_MEMLOCK, SYSCALL_FILTER_SET_MODULE, SYSCALL_FILTER_SET_MOUNT, SYSCALL_FILTER_SET_NETWORK_IO, SYSCALL_FILTER_SET_OBSOLETE, SYSCALL_FILTER_SET_PKEY, SYSCALL_FILTER_SET_PRIVILEGED, SYSCALL_FILTER_SET_PROCESS, SYSCALL_FILTER_SET_RAW_IO, SYSCALL_FILTER_SET_REBOOT, SYSCALL_FILTER_SET_RESOURCES, SYSCALL_FILTER_SET_SANDBOX, SYSCALL_FILTER_SET_SETUID, SYSCALL_FILTER_SET_SIGNAL, SYSCALL_FILTER_SET_SWAP, SYSCALL_FILTER_SET_SYNC, SYSCALL_FILTER_SET_SYSTEM_SERVICE, SYSCALL_FILTER_SET_TIMER, SYSCALL_FILTER_SET_KNOWN, _SYSCALL_FILTER_SET_MAX, }; assert_cc(SYSCALL_FILTER_SET_DEFAULT == 0); assert_cc(SYSCALL_FILTER_SET_KNOWN == _SYSCALL_FILTER_SET_MAX-1); extern const SyscallFilterSet syscall_filter_sets[]; const SyscallFilterSet *syscall_filter_set_find(const char *name); int seccomp_filter_set_add(Hashmap *s, bool b, const SyscallFilterSet *set); int seccomp_add_syscall_filter_item( scmp_filter_ctx *ctx, const char *name, uint32_t action, char **exclude, bool log_missing, char ***added); int seccomp_load_syscall_filter_set(uint32_t default_action, const SyscallFilterSet *set, uint32_t action, bool log_missing); int seccomp_load_syscall_filter_set_raw(uint32_t default_action, Hashmap* set, uint32_t action, bool log_missing); typedef enum SeccompParseFlags { SECCOMP_PARSE_INVERT = 1 << 0, SECCOMP_PARSE_ALLOW_LIST = 1 << 1, SECCOMP_PARSE_LOG = 1 << 2, SECCOMP_PARSE_PERMISSIVE = 1 << 3, } SeccompParseFlags; int seccomp_parse_syscall_filter( const char *name, int errno_num, Hashmap *filter, SeccompParseFlags flags, const char *unit, const char *filename, unsigned line); int seccomp_restrict_archs(Set *archs); int seccomp_restrict_namespaces(unsigned long retain); int seccomp_protect_sysctl(void); int seccomp_protect_syslog(void); int seccomp_restrict_address_families(Set *address_families, bool allow_list); int seccomp_restrict_realtime_full(int error_code); /* This is mostly for testing code. */ static inline int seccomp_restrict_realtime(void) { return seccomp_restrict_realtime_full(EPERM); } int seccomp_memory_deny_write_execute(void); int seccomp_lock_personality(unsigned long personality); int seccomp_protect_hostname(void); int seccomp_restrict_suid_sgid(void); extern uint32_t seccomp_local_archs[]; #define SECCOMP_LOCAL_ARCH_END UINT32_MAX /* Note: 0 is safe to use here because although SCMP_ARCH_NATIVE is 0, it would * never be in the seccomp_local_archs array anyway so we can use it as a * marker. */ #define SECCOMP_LOCAL_ARCH_BLOCKED 0 #define SECCOMP_FOREACH_LOCAL_ARCH(arch) \ for (unsigned _i = ({ (arch) = seccomp_local_archs[0]; 0; }); \ (arch) != SECCOMP_LOCAL_ARCH_END; \ (arch) = seccomp_local_archs[++_i]) \ if ((arch) != SECCOMP_LOCAL_ARCH_BLOCKED) /* EACCES: does not have the CAP_SYS_ADMIN or no_new_privs == 1 * ENOMEM: out of memory, failed to allocate space for a libseccomp structure, or would exceed a defined constant * EFAULT: addresses passed as args (by libseccomp) are invalid */ #define ERRNO_IS_SECCOMP_FATAL(r) \ IN_SET(abs(r), EPERM, EACCES, ENOMEM, EFAULT) DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(scmp_filter_ctx, seccomp_release, NULL); int parse_syscall_archs(char **l, Set **ret_archs); uint32_t scmp_act_kill_process(void); /* This is a special value to be used where syscall filters otherwise expect errno numbers, will be replaced with real seccomp action. */ enum { SECCOMP_ERROR_NUMBER_KILL = INT_MAX - 1, }; static inline bool seccomp_errno_or_action_is_valid(int n) { return n == SECCOMP_ERROR_NUMBER_KILL || errno_is_valid(n); } static inline int seccomp_parse_errno_or_action(const char *p) { if (streq_ptr(p, "kill")) return SECCOMP_ERROR_NUMBER_KILL; return parse_errno(p); } static inline const char *seccomp_errno_or_action_to_string(int num) { if (num == SECCOMP_ERROR_NUMBER_KILL) return "kill"; return errno_to_name(num); } int parse_syscall_and_errno(const char *in, char **name, int *error); int seccomp_suppress_sync(void); #else static inline bool is_seccomp_available(void) { return false; } #endif
5,759
32.488372
125
h
null
systemd-main/src/shared/securebits-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdio.h> #include "alloc-util.h" #include "extract-word.h" #include "securebits-util.h" #include "string-util.h" int secure_bits_to_string_alloc(int i, char **s) { _cleanup_free_ char *str = NULL; size_t len; int r; assert(s); r = asprintf(&str, "%s%s%s%s%s%s", (i & (1 << SECURE_KEEP_CAPS)) ? "keep-caps " : "", (i & (1 << SECURE_KEEP_CAPS_LOCKED)) ? "keep-caps-locked " : "", (i & (1 << SECURE_NO_SETUID_FIXUP)) ? "no-setuid-fixup " : "", (i & (1 << SECURE_NO_SETUID_FIXUP_LOCKED)) ? "no-setuid-fixup-locked " : "", (i & (1 << SECURE_NOROOT)) ? "noroot " : "", (i & (1 << SECURE_NOROOT_LOCKED)) ? "noroot-locked " : ""); if (r < 0) return -ENOMEM; len = strlen(str); if (len != 0) str[len - 1] = '\0'; *s = TAKE_PTR(str); return 0; } int secure_bits_from_string(const char *s) { int secure_bits = 0; const char *p; int r; for (p = s;;) { _cleanup_free_ char *word = NULL; r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE); if (r == -ENOMEM) return r; if (r <= 0) break; if (streq(word, "keep-caps")) secure_bits |= 1 << SECURE_KEEP_CAPS; else if (streq(word, "keep-caps-locked")) secure_bits |= 1 << SECURE_KEEP_CAPS_LOCKED; else if (streq(word, "no-setuid-fixup")) secure_bits |= 1 << SECURE_NO_SETUID_FIXUP; else if (streq(word, "no-setuid-fixup-locked")) secure_bits |= 1 << SECURE_NO_SETUID_FIXUP_LOCKED; else if (streq(word, "noroot")) secure_bits |= 1 << SECURE_NOROOT; else if (streq(word, "noroot-locked")) secure_bits |= 1 << SECURE_NOROOT_LOCKED; } return secure_bits; }
2,219
32.134328
97
c
null
systemd-main/src/shared/securebits-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "missing_securebits.h" int secure_bits_to_string_alloc(int i, char **s); int secure_bits_from_string(const char *s); static inline bool secure_bits_is_valid(int i) { return ((SECURE_ALL_BITS | SECURE_ALL_LOCKS) & i) == i; } static inline int secure_bits_to_string_alloc_with_check(int n, char **s) { if (!secure_bits_is_valid(n)) return -EINVAL; return secure_bits_to_string_alloc(n, s); }
528
24.190476
75
h
null
systemd-main/src/shared/selinux-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fcntl.h> #include <stdbool.h> #include <sys/socket.h> #include <sys/types.h> #include "macro.h" #include "label-util.h" #if HAVE_SELINUX #include <selinux/selinux.h> DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(char*, freecon, NULL); #define _cleanup_freecon_ _cleanup_(freeconp) #endif bool mac_selinux_use(void); void mac_selinux_retest(void); bool mac_selinux_enforcing(void); int mac_selinux_init(void); void mac_selinux_maybe_reload(void); void mac_selinux_finish(void); int mac_selinux_fix_full(int atfd, const char *inode_path, const char *label_path, LabelFixFlags flags); int mac_selinux_apply(const char *path, const char *label); int mac_selinux_apply_fd(int fd, const char *path, const char *label); int mac_selinux_get_create_label_from_exe(const char *exe, char **label); int mac_selinux_get_our_label(char **label); int mac_selinux_get_child_mls_label(int socket_fd, const char *exe, const char *exec_label, char **label); char* mac_selinux_free(char *label); int mac_selinux_create_file_prepare_at(int dirfd, const char *path, mode_t mode); static inline int mac_selinux_create_file_prepare(const char *path, mode_t mode) { return mac_selinux_create_file_prepare_at(AT_FDCWD, path, mode); } int mac_selinux_create_file_prepare_label(const char *path, const char *label); void mac_selinux_create_file_clear(void); int mac_selinux_create_socket_prepare(const char *label); void mac_selinux_create_socket_clear(void); int mac_selinux_bind(int fd, const struct sockaddr *addr, socklen_t addrlen); DEFINE_TRIVIAL_CLEANUP_FUNC(char*, mac_selinux_free);
1,644
31.9
106
h
null
systemd-main/src/shared/serialize.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include "alloc-util.h" #include "env-util.h" #include "escape.h" #include "fileio.h" #include "memfd-util.h" #include "missing_mman.h" #include "missing_syscall.h" #include "parse-util.h" #include "process-util.h" #include "serialize.h" #include "strv.h" #include "tmpfile-util.h" int serialize_item(FILE *f, const char *key, const char *value) { assert(f); assert(key); if (!value) return 0; /* Make sure that anything we serialize we can also read back again with read_line() with a maximum line size * of LONG_LINE_MAX. This is a safety net only. All code calling us should filter this out earlier anyway. */ if (strlen(key) + 1 + strlen(value) + 1 > LONG_LINE_MAX) { log_warning("Attempted to serialize overly long item '%s', refusing.", key); return -EINVAL; } fputs(key, f); fputc('=', f); fputs(value, f); fputc('\n', f); return 1; } int serialize_item_escaped(FILE *f, const char *key, const char *value) { _cleanup_free_ char *c = NULL; assert(f); assert(key); if (!value) return 0; c = cescape(value); if (!c) return log_oom(); return serialize_item(f, key, c); } int serialize_item_format(FILE *f, const char *key, const char *format, ...) { char buf[LONG_LINE_MAX]; va_list ap; int k; assert(f); assert(key); assert(format); va_start(ap, format); k = vsnprintf(buf, sizeof(buf), format, ap); va_end(ap); if (k < 0 || (size_t) k >= sizeof(buf) || strlen(key) + 1 + k + 1 > LONG_LINE_MAX) { log_warning("Attempted to serialize overly long item '%s', refusing.", key); return -EINVAL; } fputs(key, f); fputc('=', f); fputs(buf, f); fputc('\n', f); return 1; } int serialize_fd(FILE *f, FDSet *fds, const char *key, int fd) { int copy; assert(f); assert(key); if (fd < 0) return 0; copy = fdset_put_dup(fds, fd); if (copy < 0) return log_error_errno(copy, "Failed to add file descriptor to serialization set: %m"); return serialize_item_format(f, key, "%i", copy); } int serialize_usec(FILE *f, const char *key, usec_t usec) { assert(f); assert(key); if (usec == USEC_INFINITY) return 0; return serialize_item_format(f, key, USEC_FMT, usec); } int serialize_dual_timestamp(FILE *f, const char *name, const dual_timestamp *t) { assert(f); assert(name); assert(t); if (!dual_timestamp_is_set(t)) return 0; return serialize_item_format(f, name, USEC_FMT " " USEC_FMT, t->realtime, t->monotonic); } int serialize_strv(FILE *f, const char *key, char **l) { int ret = 0, r; /* Returns the first error, or positive if anything was serialized, 0 otherwise. */ STRV_FOREACH(i, l) { r = serialize_item_escaped(f, key, *i); if ((ret >= 0 && r < 0) || (ret == 0 && r > 0)) ret = r; } return ret; } int deserialize_strv(char ***l, const char *value) { ssize_t unescaped_len; char *unescaped; assert(l); assert(value); unescaped_len = cunescape(value, 0, &unescaped); if (unescaped_len < 0) return unescaped_len; return strv_consume(l, unescaped); } int deserialize_usec(const char *value, usec_t *ret) { int r; assert(value); r = safe_atou64(value, ret); if (r < 0) return log_debug_errno(r, "Failed to parse usec value \"%s\": %m", value); return 0; } int deserialize_dual_timestamp(const char *value, dual_timestamp *t) { uint64_t a, b; int r, pos; assert(value); assert(t); pos = strspn(value, WHITESPACE); if (value[pos] == '-') return -EINVAL; pos += strspn(value + pos, DIGITS); pos += strspn(value + pos, WHITESPACE); if (value[pos] == '-') return -EINVAL; r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos); if (r != 2) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse dual timestamp value \"%s\".", value); if (value[pos] != '\0') /* trailing garbage */ return -EINVAL; t->realtime = a; t->monotonic = b; return 0; } int deserialize_environment(const char *value, char ***list) { _cleanup_free_ char *unescaped = NULL; ssize_t l; int r; assert(value); assert(list); /* Changes the *environment strv inline. */ l = cunescape(value, 0, &unescaped); if (l < 0) return log_error_errno(l, "Failed to unescape: %m"); r = strv_env_replace_consume(list, TAKE_PTR(unescaped)); if (r < 0) return log_error_errno(r, "Failed to append environment variable: %m"); return 0; } int open_serialization_fd(const char *ident) { int fd; fd = memfd_create_wrapper(ident, MFD_CLOEXEC | MFD_NOEXEC_SEAL); if (fd < 0) { const char *path; path = getpid_cached() == 1 ? "/run/systemd" : "/tmp"; fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC); if (fd < 0) return fd; log_debug("Serializing %s to %s.", ident, path); } else log_debug("Serializing %s to memfd.", ident); return fd; }
6,006
25.117391
117
c
null
systemd-main/src/shared/serialize.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdio.h> #include "fdset.h" #include "macro.h" #include "string-util.h" #include "time-util.h" int serialize_item(FILE *f, const char *key, const char *value); int serialize_item_escaped(FILE *f, const char *key, const char *value); int serialize_item_format(FILE *f, const char *key, const char *value, ...) _printf_(3,4); int serialize_fd(FILE *f, FDSet *fds, const char *key, int fd); int serialize_usec(FILE *f, const char *key, usec_t usec); int serialize_dual_timestamp(FILE *f, const char *key, const dual_timestamp *t); int serialize_strv(FILE *f, const char *key, char **l); static inline int serialize_bool(FILE *f, const char *key, bool b) { return serialize_item(f, key, yes_no(b)); } int deserialize_usec(const char *value, usec_t *timestamp); int deserialize_dual_timestamp(const char *value, dual_timestamp *t); int deserialize_environment(const char *value, char ***environment); int deserialize_strv(char ***l, const char *value); int open_serialization_fd(const char *ident);
1,080
36.275862
90
h
null
systemd-main/src/shared/service-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <stdio.h> #include "alloc-util.h" #include "build.h" #include "pretty-print.h" #include "service-util.h" #include "terminal-util.h" static int help(const char *program_path, const char *service, const char *description, bool bus_introspect) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man(service, "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...]\n\n" "%s%s%s\n\n" "This program takes no positional arguments.\n\n" "%sOptions%s:\n" " -h --help Show this help\n" " --version Show package version\n" " --bus-introspect=PATH Write D-Bus XML introspection data\n" "\nSee the %s for details.\n" , program_path , ansi_highlight(), description, ansi_normal() , ansi_underline(), ansi_normal() , link ); return 0; /* No further action */ } int service_parse_argv( const char *service, const char *description, const BusObjectImplementation* const* bus_objects, int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_BUS_INTROSPECT, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(argv[0], service, description, bus_objects); case ARG_VERSION: return version(); case ARG_BUS_INTROSPECT: return bus_introspect_implementations( stdout, optarg, bus_objects); case '?': return -EINVAL; default: assert_not_reached(); } if (optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments."); return 1; /* Further action */ }
2,743
30.181818
110
c
null
systemd-main/src/shared/sleep-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <linux/fiemap.h> #include <sys/types.h> #include "hashmap.h" #include "time-util.h" #define DEFAULT_SUSPEND_ESTIMATION_USEC (1 * USEC_PER_HOUR) typedef enum SleepOperation { SLEEP_SUSPEND, SLEEP_HIBERNATE, SLEEP_HYBRID_SLEEP, SLEEP_SUSPEND_THEN_HIBERNATE, _SLEEP_OPERATION_MAX, _SLEEP_OPERATION_INVALID = -EINVAL, } SleepOperation; typedef struct SleepConfig { bool allow[_SLEEP_OPERATION_MAX]; char **modes[_SLEEP_OPERATION_MAX]; char **states[_SLEEP_OPERATION_MAX]; usec_t hibernate_delay_usec; usec_t suspend_estimation_usec; } SleepConfig; SleepConfig* free_sleep_config(SleepConfig *sc); DEFINE_TRIVIAL_CLEANUP_FUNC(SleepConfig*, free_sleep_config); typedef enum SwapType { SWAP_BLOCK, SWAP_FILE, _SWAP_TYPE_MAX, _SWAP_TYPE_INVALID = -EINVAL, } SwapType; /* entry in /proc/swaps */ typedef struct SwapEntry { char *path; SwapType type; uint64_t size; uint64_t used; int priority; } SwapEntry; SwapEntry* swap_entry_free(SwapEntry *se); DEFINE_TRIVIAL_CLEANUP_FUNC(SwapEntry*, swap_entry_free); /* * represents values for /sys/power/resume & /sys/power/resume_offset * and the matching /proc/swap entry. */ typedef struct HibernateLocation { dev_t devno; uint64_t offset; /* in memory pages */ SwapEntry *swap; } HibernateLocation; HibernateLocation* hibernate_location_free(HibernateLocation *hl); DEFINE_TRIVIAL_CLEANUP_FUNC(HibernateLocation*, hibernate_location_free); int read_fiemap(int fd, struct fiemap **ret); int parse_sleep_config(SleepConfig **sleep_config); int find_hibernate_location(HibernateLocation **ret_hibernate_location); int write_resume_config(dev_t devno, uint64_t offset, const char *device); int can_sleep(SleepOperation operation); int can_sleep_disk(char **types); int can_sleep_state(char **types); int get_total_suspend_interval(Hashmap *last_capacity, usec_t *ret); int fetch_batteries_capacity_by_name(Hashmap **ret_current_capacity); int get_capacity_by_name(Hashmap *capacities_by_name, const char *name); int estimate_battery_discharge_rate_per_hour( Hashmap *last_capacity, Hashmap *current_capacity, usec_t before_timestamp, usec_t after_timestamp); int check_wakeup_type(void); int battery_trip_point_alarm_exists(void); const char* sleep_operation_to_string(SleepOperation s) _const_; SleepOperation sleep_operation_from_string(const char *s) _pure_;
2,631
29.964706
74
h
null
systemd-main/src/shared/smack-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2013 Intel Corporation Author: Auke Kok <[email protected]> ***/ #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/xattr.h> #include <unistd.h> #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "label.h" #include "log.h" #include "macro.h" #include "path-util.h" #include "process-util.h" #include "smack-util.h" #include "stdio-util.h" #include "string-table.h" #include "xattr-util.h" #if ENABLE_SMACK bool mac_smack_use(void) { static int cached_use = -1; if (cached_use < 0) cached_use = access("/sys/fs/smackfs/", F_OK) >= 0; return cached_use; } static const char* const smack_attr_table[_SMACK_ATTR_MAX] = { [SMACK_ATTR_ACCESS] = "security.SMACK64", [SMACK_ATTR_EXEC] = "security.SMACK64EXEC", [SMACK_ATTR_MMAP] = "security.SMACK64MMAP", [SMACK_ATTR_TRANSMUTE] = "security.SMACK64TRANSMUTE", [SMACK_ATTR_IPIN] = "security.SMACK64IPIN", [SMACK_ATTR_IPOUT] = "security.SMACK64IPOUT", }; DEFINE_STRING_TABLE_LOOKUP(smack_attr, SmackAttr); int mac_smack_read(const char *path, SmackAttr attr, char **label) { assert(path); assert(attr >= 0 && attr < _SMACK_ATTR_MAX); assert(label); if (!mac_smack_use()) return 0; return getxattr_malloc(path, smack_attr_to_string(attr), label); } int mac_smack_read_fd(int fd, SmackAttr attr, char **label) { assert(fd >= 0); assert(attr >= 0 && attr < _SMACK_ATTR_MAX); assert(label); if (!mac_smack_use()) return 0; return fgetxattr_malloc(fd, smack_attr_to_string(attr), label); } int mac_smack_apply_at(int dir_fd, const char *path, SmackAttr attr, const char *label) { _cleanup_close_ int fd = -EBADF; assert(path); assert(attr >= 0 && attr < _SMACK_ATTR_MAX); if (!mac_smack_use()) return 0; fd = openat(dir_fd, path, O_PATH|O_CLOEXEC|O_NOFOLLOW); if (fd < 0) return -errno; return mac_smack_apply_fd(fd, attr, label); } int mac_smack_apply_fd(int fd, SmackAttr attr, const char *label) { int r; assert(fd >= 0); assert(attr >= 0 && attr < _SMACK_ATTR_MAX); if (!mac_smack_use()) return 0; if (label) r = setxattr(FORMAT_PROC_FD_PATH(fd), smack_attr_to_string(attr), label, strlen(label), 0); else r = removexattr(FORMAT_PROC_FD_PATH(fd), smack_attr_to_string(attr)); if (r < 0) return -errno; return 0; } int mac_smack_apply_pid(pid_t pid, const char *label) { const char *p; int r; assert(label); if (!mac_smack_use()) return 0; p = procfs_file_alloca(pid, "attr/current"); r = write_string_file(p, label, WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) return r; return r; } static int smack_fix_fd( int fd, const char *label_path, LabelFixFlags flags) { const char *label; struct stat st; int r; /* The caller should have done the sanity checks. */ assert(fd >= 0); assert(label_path); assert(path_is_absolute(label_path)); /* Path must be in /dev. */ if (!path_startswith(label_path, "/dev")) return 0; if (fstat(fd, &st) < 0) return -errno; /* * Label directories and character devices "*". * Label symlinks "_". * Don't change anything else. */ if (S_ISDIR(st.st_mode)) label = SMACK_STAR_LABEL; else if (S_ISLNK(st.st_mode)) label = SMACK_FLOOR_LABEL; else if (S_ISCHR(st.st_mode)) label = SMACK_STAR_LABEL; else return 0; if (setxattr(FORMAT_PROC_FD_PATH(fd), "security.SMACK64", label, strlen(label), 0) < 0) { _cleanup_free_ char *old_label = NULL; r = -errno; /* If the FS doesn't support labels, then exit without warning */ if (ERRNO_IS_NOT_SUPPORTED(r)) return 0; /* It the FS is read-only and we were told to ignore failures caused by that, suppress error */ if (r == -EROFS && (flags & LABEL_IGNORE_EROFS)) return 0; /* If the old label is identical to the new one, suppress any kind of error */ if (lgetxattr_malloc(FORMAT_PROC_FD_PATH(fd), "security.SMACK64", &old_label) >= 0 && streq(old_label, label)) return 0; return log_debug_errno(r, "Unable to fix SMACK label of %s: %m", label_path); } return 0; } int mac_smack_fix_full( int atfd, const char *inode_path, const char *label_path, LabelFixFlags flags) { _cleanup_close_ int opened_fd = -EBADF; _cleanup_free_ char *p = NULL; int r, inode_fd; assert(atfd >= 0 || atfd == AT_FDCWD); assert(atfd >= 0 || inode_path); if (!mac_smack_use()) return 0; if (inode_path) { opened_fd = openat(atfd, inode_path, O_NOFOLLOW|O_CLOEXEC|O_PATH); if (opened_fd < 0) { if ((flags & LABEL_IGNORE_ENOENT) && errno == ENOENT) return 0; return -errno; } inode_fd = opened_fd; } else inode_fd = atfd; if (!label_path) { if (path_is_absolute(inode_path)) label_path = inode_path; else { r = fd_get_path(inode_fd, &p); if (r < 0) return r; label_path = p; } } return smack_fix_fd(inode_fd, label_path, flags); } int mac_smack_copy(const char *dest, const char *src) { int r; _cleanup_free_ char *label = NULL; assert(dest); assert(src); r = mac_smack_read(src, SMACK_ATTR_ACCESS, &label); if (r < 0) return r; r = mac_smack_apply(dest, SMACK_ATTR_ACCESS, label); if (r < 0) return r; return r; } #else bool mac_smack_use(void) { return false; } int mac_smack_read(const char *path, SmackAttr attr, char **label) { return -EOPNOTSUPP; } int mac_smack_read_fd(int fd, SmackAttr attr, char **label) { return -EOPNOTSUPP; } int mac_smack_apply_at(int dir_fd, const char *path, SmackAttr attr, const char *label) { return 0; } int mac_smack_apply_fd(int fd, SmackAttr attr, const char *label) { return 0; } int mac_smack_apply_pid(pid_t pid, const char *label) { return 0; } int mac_smack_fix_full(int atfd, const char *inode_path, const char *label_path, LabelFixFlags flags) { return 0; } int mac_smack_copy(const char *dest, const char *src) { return 0; } #endif int renameat_and_apply_smack_floor_label(int fdf, const char *from, int fdt, const char *to) { assert(fdf >= 0 || fdf == AT_FDCWD); assert(fdt >= 0 || fdt == AT_FDCWD); if (renameat(fdf, from, fdt, to) < 0) return -errno; #if HAVE_SMACK_RUN_LABEL return mac_smack_apply_at(fdt, to, SMACK_ATTR_ACCESS, SMACK_FLOOR_LABEL); #else return 0; #endif } static int mac_smack_label_pre(int dir_fd, const char *path, mode_t mode) { return 0; } static int mac_smack_label_post(int dir_fd, const char *path) { return mac_smack_fix_full(dir_fd, path, NULL, 0); } int mac_smack_init(void) { static const LabelOps label_ops = { .pre = mac_smack_label_pre, .post = mac_smack_label_post, }; if (!mac_smack_use()) return 0; return label_ops_set(&label_ops); }
8,345
25.75
111
c
null
systemd-main/src/shared/smack-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2013 Intel Corporation Author: Auke Kok <[email protected]> ***/ #include <stdbool.h> #include <sys/types.h> #include "label-util.h" #include "macro.h" #define SMACK_FLOOR_LABEL "_" #define SMACK_STAR_LABEL "*" typedef enum SmackAttr { SMACK_ATTR_ACCESS, SMACK_ATTR_EXEC, SMACK_ATTR_MMAP, SMACK_ATTR_TRANSMUTE, SMACK_ATTR_IPIN, SMACK_ATTR_IPOUT, _SMACK_ATTR_MAX, _SMACK_ATTR_INVALID = -EINVAL, } SmackAttr; bool mac_smack_use(void); int mac_smack_init(void); int mac_smack_fix_full(int atfd, const char *inode_path, const char *label_path, LabelFixFlags flags); static inline int mac_smack_fix(const char *path, LabelFixFlags flags) { return mac_smack_fix_full(AT_FDCWD, path, path, flags); } const char* smack_attr_to_string(SmackAttr i) _const_; SmackAttr smack_attr_from_string(const char *s) _pure_; int mac_smack_read(const char *path, SmackAttr attr, char **label); int mac_smack_read_fd(int fd, SmackAttr attr, char **label); int mac_smack_apply_at(int dir_fd, const char *path, SmackAttr attr, const char *label); static inline int mac_smack_apply(const char *path, SmackAttr attr, const char *label) { return mac_smack_apply_at(AT_FDCWD, path, attr, label); } int mac_smack_apply_fd(int fd, SmackAttr attr, const char *label); int mac_smack_apply_pid(pid_t pid, const char *label); int mac_smack_copy(const char *dest, const char *src); int renameat_and_apply_smack_floor_label(int fdf, const char *from, int fdt, const char *to); static inline int rename_and_apply_smack_floor_label(const char *from, const char *to) { return renameat_and_apply_smack_floor_label(AT_FDCWD, from, AT_FDCWD, to); }
1,795
32.259259
102
h
null
systemd-main/src/shared/socket-label.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <netinet/in.h> #include <stdbool.h> #include <stddef.h> #include <string.h> #include <sys/un.h> #include <unistd.h> #include "alloc-util.h" #include "fd-util.h" #include "fs-util.h" #include "log.h" #include "macro.h" #include "missing_socket.h" #include "mkdir-label.h" #include "selinux-util.h" #include "socket-util.h" #include "umask-util.h" int socket_address_listen( const SocketAddress *a, int flags, int backlog, SocketAddressBindIPv6Only only, const char *bind_to_device, bool reuse_port, bool free_bind, bool transparent, mode_t directory_mode, mode_t socket_mode, const char *label) { _cleanup_close_ int fd = -EBADF; const char *p; int r; assert(a); r = socket_address_verify(a, true); if (r < 0) return r; if (socket_address_family(a) == AF_INET6 && !socket_ipv6_is_supported()) return -EAFNOSUPPORT; if (label) { r = mac_selinux_create_socket_prepare(label); if (r < 0) return r; } fd = RET_NERRNO(socket(socket_address_family(a), a->type | flags, a->protocol)); if (label) mac_selinux_create_socket_clear(); if (fd < 0) return fd; if (socket_address_family(a) == AF_INET6 && only != SOCKET_ADDRESS_DEFAULT) { r = setsockopt_int(fd, IPPROTO_IPV6, IPV6_V6ONLY, only == SOCKET_ADDRESS_IPV6_ONLY); if (r < 0) return r; } if (IN_SET(socket_address_family(a), AF_INET, AF_INET6)) { if (bind_to_device) { r = socket_bind_to_ifname(fd, bind_to_device); if (r < 0) return r; } if (reuse_port) { r = setsockopt_int(fd, SOL_SOCKET, SO_REUSEPORT, true); if (r < 0) log_warning_errno(r, "SO_REUSEPORT failed: %m"); } if (free_bind) { r = socket_set_freebind(fd, socket_address_family(a), true); if (r < 0) log_warning_errno(r, "IP_FREEBIND/IPV6_FREEBIND failed: %m"); } if (transparent) { r = socket_set_transparent(fd, socket_address_family(a), true); if (r < 0) log_warning_errno(r, "IP_TRANSPARENT/IPV6_TRANSPARENT failed: %m"); } } r = setsockopt_int(fd, SOL_SOCKET, SO_REUSEADDR, true); if (r < 0) return r; p = socket_address_get_path(a); if (p) { /* Create parents */ (void) mkdir_parents_label(p, directory_mode); /* Enforce the right access mode for the socket */ WITH_UMASK(~socket_mode) { r = mac_selinux_bind(fd, &a->sockaddr.sa, a->size); if (r == -EADDRINUSE) { /* Unlink and try again */ if (unlink(p) < 0) return r; /* didn't work, return original error */ r = mac_selinux_bind(fd, &a->sockaddr.sa, a->size); } if (r < 0) return r; } } else { if (bind(fd, &a->sockaddr.sa, a->size) < 0) return -errno; } if (socket_address_can_accept(a)) if (listen(fd, backlog) < 0) return -errno; /* Let's trigger an inotify event on the socket node, so that anyone waiting for this socket to be connectable * gets notified */ if (p) (void) touch(p); return TAKE_FD(fd); }
4,250
30.962406
118
c
null
systemd-main/src/shared/socket-netlink.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <arpa/inet.h> #include <errno.h> #include <net/if.h> #include <string.h> #include "alloc-util.h" #include "errno-util.h" #include "extract-word.h" #include "log.h" #include "memory-util.h" #include "netlink-util.h" #include "parse-util.h" #include "socket-netlink.h" #include "socket-util.h" #include "string-util.h" int socket_address_parse(SocketAddress *a, const char *s) { uint16_t port; int r; assert(a); assert(s); r = socket_address_parse_unix(a, s); if (r == -EPROTO) r = socket_address_parse_vsock(a, s); if (r != -EPROTO) return r; r = parse_ip_port(s, &port); if (r == -ERANGE) return r; /* Valid port syntax, but the numerical value is wrong for a port. */ if (r >= 0) { /* Just a port */ if (socket_ipv6_is_supported()) *a = (SocketAddress) { .sockaddr.in6 = { .sin6_family = AF_INET6, .sin6_port = htobe16(port), .sin6_addr = in6addr_any, }, .size = sizeof(struct sockaddr_in6), }; else *a = (SocketAddress) { .sockaddr.in = { .sin_family = AF_INET, .sin_port = htobe16(port), .sin_addr.s_addr = INADDR_ANY, }, .size = sizeof(struct sockaddr_in), }; } else { union in_addr_union address; int family, ifindex; r = in_addr_port_ifindex_name_from_string_auto(s, &family, &address, &port, &ifindex, NULL); if (r < 0) return r; if (port == 0) /* No port, no go. */ return -EINVAL; if (family == AF_INET) *a = (SocketAddress) { .sockaddr.in = { .sin_family = AF_INET, .sin_addr = address.in, .sin_port = htobe16(port), }, .size = sizeof(struct sockaddr_in), }; else if (family == AF_INET6) *a = (SocketAddress) { .sockaddr.in6 = { .sin6_family = AF_INET6, .sin6_addr = address.in6, .sin6_port = htobe16(port), .sin6_scope_id = ifindex, }, .size = sizeof(struct sockaddr_in6), }; else assert_not_reached(); } return 0; } int socket_address_parse_and_warn(SocketAddress *a, const char *s) { SocketAddress b; int r; /* Similar to socket_address_parse() but warns for IPv6 sockets when we don't support them. */ r = socket_address_parse(&b, s); if (r < 0) return r; if (!socket_ipv6_is_supported() && b.sockaddr.sa.sa_family == AF_INET6) { log_warning("Binding to IPv6 address not available since kernel does not support IPv6."); return -EAFNOSUPPORT; } *a = b; return 0; } int socket_address_parse_netlink(SocketAddress *a, const char *s) { _cleanup_free_ char *word = NULL; unsigned group = 0; int family, r; assert(a); assert(s); r = extract_first_word(&s, &word, NULL, 0); if (r < 0) return r; if (r == 0) return -EINVAL; family = netlink_family_from_string(word); if (family < 0) return -EINVAL; if (!isempty(s)) { r = safe_atou(s, &group); if (r < 0) return r; } *a = (SocketAddress) { .type = SOCK_RAW, .sockaddr.nl.nl_family = AF_NETLINK, .sockaddr.nl.nl_groups = group, .protocol = family, .size = sizeof(struct sockaddr_nl), }; return 0; } bool socket_address_is(const SocketAddress *a, const char *s, int type) { struct SocketAddress b; assert(a); assert(s); if (socket_address_parse(&b, s) < 0) return false; b.type = type; return socket_address_equal(a, &b); } bool socket_address_is_netlink(const SocketAddress *a, const char *s) { struct SocketAddress b; assert(a); assert(s); if (socket_address_parse_netlink(&b, s) < 0) return false; return socket_address_equal(a, &b); } int make_socket_fd(int log_level, const char* address, int type, int flags) { SocketAddress a; int fd, r; r = socket_address_parse(&a, address); if (r < 0) return log_error_errno(r, "Failed to parse socket address \"%s\": %m", address); a.type = type; fd = socket_address_listen(&a, type | flags, SOMAXCONN_DELUXE, SOCKET_ADDRESS_DEFAULT, NULL, false, false, false, 0755, 0644, NULL); if (fd < 0 || log_get_max_level() >= log_level) { _cleanup_free_ char *p = NULL; r = socket_address_print(&a, &p); if (r < 0) return log_error_errno(r, "socket_address_print(): %m"); if (fd < 0) log_error_errno(fd, "Failed to listen on %s: %m", p); else log_full(log_level, "Listening on %s", p); } return fd; } int in_addr_port_ifindex_name_from_string_auto( const char *s, int *ret_family, union in_addr_union *ret_address, uint16_t *ret_port, int *ret_ifindex, char **ret_server_name) { _cleanup_free_ char *buf1 = NULL, *buf2 = NULL, *name = NULL; int family, ifindex = 0, r; union in_addr_union a; uint16_t port = 0; const char *m; assert(s); /* This accepts the following: * 192.168.0.1:53#example.com * [2001:4860:4860::8888]:53%eth0#example.com * * If ret_port is NULL, then the port cannot be specified. * If ret_ifindex is NULL, then the interface index cannot be specified. * If ret_server_name is NULL, then server_name cannot be specified. * * ret_family is always AF_INET or AF_INET6. */ m = strchr(s, '#'); if (m) { if (!ret_server_name) return -EINVAL; if (isempty(m + 1)) return -EINVAL; name = strdup(m + 1); if (!name) return -ENOMEM; s = buf1 = strndup(s, m - s); if (!buf1) return -ENOMEM; } m = strchr(s, '%'); if (m) { if (!ret_ifindex) return -EINVAL; if (isempty(m + 1)) return -EINVAL; if (!ifname_valid_full(m + 1, IFNAME_VALID_ALTERNATIVE | IFNAME_VALID_NUMERIC)) return -EINVAL; /* We want to return -EINVAL for syntactically invalid names, * and -ENODEV for valid but nonexistent interfaces. */ ifindex = rtnl_resolve_interface(NULL, m + 1); if (ifindex < 0) return ifindex; s = buf2 = strndup(s, m - s); if (!buf2) return -ENOMEM; } m = strrchr(s, ':'); if (m) { if (*s == '[') { _cleanup_free_ char *ip_str = NULL; if (!ret_port) return -EINVAL; if (*(m - 1) != ']') return -EINVAL; family = AF_INET6; r = parse_ip_port(m + 1, &port); if (r < 0) return r; ip_str = strndup(s + 1, m - s - 2); if (!ip_str) return -ENOMEM; r = in_addr_from_string(family, ip_str, &a); if (r < 0) return r; } else { /* First try to parse the string as IPv6 address without port number */ r = in_addr_from_string(AF_INET6, s, &a); if (r < 0) { /* Then the input should be IPv4 address with port number */ _cleanup_free_ char *ip_str = NULL; if (!ret_port) return -EINVAL; family = AF_INET; ip_str = strndup(s, m - s); if (!ip_str) return -ENOMEM; r = in_addr_from_string(family, ip_str, &a); if (r < 0) return r; r = parse_ip_port(m + 1, &port); if (r < 0) return r; } else family = AF_INET6; } } else { family = AF_INET; r = in_addr_from_string(family, s, &a); if (r < 0) return r; } if (ret_family) *ret_family = family; if (ret_address) *ret_address = a; if (ret_port) *ret_port = port; if (ret_ifindex) *ret_ifindex = ifindex; if (ret_server_name) *ret_server_name = TAKE_PTR(name); return r; } struct in_addr_full *in_addr_full_free(struct in_addr_full *a) { if (!a) return NULL; free(a->server_name); free(a->cached_server_string); return mfree(a); } int in_addr_full_new( int family, const union in_addr_union *a, uint16_t port, int ifindex, const char *server_name, struct in_addr_full **ret) { _cleanup_free_ char *name = NULL; struct in_addr_full *x; assert(ret); if (!isempty(server_name)) { name = strdup(server_name); if (!name) return -ENOMEM; } x = new(struct in_addr_full, 1); if (!x) return -ENOMEM; *x = (struct in_addr_full) { .family = family, .address = *a, .port = port, .ifindex = ifindex, .server_name = TAKE_PTR(name), }; *ret = x; return 0; } int in_addr_full_new_from_string(const char *s, struct in_addr_full **ret) { _cleanup_free_ char *server_name = NULL; int family, ifindex, r; union in_addr_union a; uint16_t port; assert(s); r = in_addr_port_ifindex_name_from_string_auto(s, &family, &a, &port, &ifindex, &server_name); if (r < 0) return r; return in_addr_full_new(family, &a, port, ifindex, server_name, ret); } const char *in_addr_full_to_string(struct in_addr_full *a) { assert(a); if (!a->cached_server_string) (void) in_addr_port_ifindex_name_to_string( a->family, &a->address, a->port, a->ifindex, a->server_name, &a->cached_server_string); return a->cached_server_string; }
12,890
30.441463
108
c
null
systemd-main/src/shared/spawn-ask-password-agent.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <signal.h> #include <stdlib.h> #include <unistd.h> #include "exec-util.h" #include "log.h" #include "process-util.h" #include "spawn-ask-password-agent.h" static pid_t agent_pid = 0; int ask_password_agent_open(void) { int r; if (agent_pid > 0) return 0; /* We check STDIN here, not STDOUT, since this is about input, * not output */ if (!isatty(STDIN_FILENO)) return 0; if (!is_main_thread()) return -EPERM; r = fork_agent("(sd-askpwagent)", NULL, 0, &agent_pid, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL); if (r < 0) return log_error_errno(r, "Failed to fork TTY ask password agent: %m"); return 1; } void ask_password_agent_close(void) { if (agent_pid <= 0) return; /* Inform agent that we are done */ sigterm_wait(TAKE_PID(agent_pid)); } int ask_password_agent_open_if_enabled(BusTransport transport, bool ask_password) { /* Open the ask password agent as a child process if necessary */ if (transport != BUS_TRANSPORT_LOCAL) return 0; if (!ask_password) return 0; return ask_password_agent_open(); }
1,475
23.6
87
c
null
systemd-main/src/shared/spawn-polkit-agent.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <poll.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include "exec-util.h" #include "fd-util.h" #include "io-util.h" #include "log.h" #include "macro.h" #include "process-util.h" #include "spawn-polkit-agent.h" #include "stdio-util.h" #include "time-util.h" #if ENABLE_POLKIT static pid_t agent_pid = 0; int polkit_agent_open(void) { char notify_fd[DECIMAL_STR_MAX(int) + 1]; int pipe_fd[2], r; if (agent_pid > 0) return 0; /* Clients that run as root don't need to activate/query polkit */ if (geteuid() == 0) return 0; /* We check STDIN here, not STDOUT, since this is about input, not output */ if (!isatty(STDIN_FILENO)) return 0; if (!is_main_thread()) return -EPERM; if (pipe2(pipe_fd, 0) < 0) return -errno; xsprintf(notify_fd, "%i", pipe_fd[1]); r = fork_agent("(polkit-agent)", &pipe_fd[1], 1, &agent_pid, POLKIT_AGENT_BINARY_PATH, POLKIT_AGENT_BINARY_PATH, "--notify-fd", notify_fd, "--fallback", NULL); /* Close the writing side, because that's the one for the agent */ safe_close(pipe_fd[1]); if (r < 0) log_error_errno(r, "Failed to fork TTY ask password agent: %m"); else /* Wait until the agent closes the fd */ (void) fd_wait_for_event(pipe_fd[0], POLLHUP, USEC_INFINITY); safe_close(pipe_fd[0]); return r; } void polkit_agent_close(void) { if (agent_pid <= 0) return; /* Inform agent that we are done */ sigterm_wait(TAKE_PID(agent_pid)); } #else int polkit_agent_open(void) { return 0; } void polkit_agent_close(void) { } #endif int polkit_agent_open_if_enabled(BusTransport transport, bool ask_password) { /* Open the polkit agent as a child process if necessary */ if (transport != BUS_TRANSPORT_LOCAL) return 0; if (!ask_password) return 0; return polkit_agent_open(); }
2,281
22.525773
95
c
null
systemd-main/src/shared/test-tables.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <errno.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "string-util.h" #define _test_table(name, lookup, reverse, size, sparse) \ for (int64_t _i = -EINVAL, _boring = 0; _i < size + 1; _i++) { \ const char* _val; \ int64_t _rev; \ \ _val = lookup(_i); \ if (_val) { \ _rev = reverse(_val); \ _boring = 0; \ } else { \ _rev = reverse("--no-such--value----"); \ _boring += _i >= 0; \ } \ if (_boring == 0 || _i == size) \ printf("%s: %" PRIi64 " → %s → %" PRIi64 "\n", name, _i, strnull(_val), _rev); \ else if (_boring == 1) \ printf("%*s ...\n", (int) strlen(name), ""); \ \ if (_i >= 0 && _i < size) { \ if (sparse) \ assert_se(_rev == _i || _rev == -EINVAL); \ else \ assert_se(_val && _rev == _i); \ } else \ assert_se(!_val && _rev == -EINVAL); \ } #define test_table(lower, upper) \ _test_table(STRINGIFY(lower), lower##_to_string, lower##_from_string, _##upper##_MAX, false) #define test_table_sparse(lower, upper) \ _test_table(STRINGIFY(lower), lower##_to_string, lower##_from_string, _##upper##_MAX, true)
2,434
54.340909
104
h
null
systemd-main/src/shared/tests.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sched.h> #include <signal.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/wait.h> #include "sd-bus.h" #include "alloc-util.h" #include "bus-error.h" #include "bus-locator.h" #include "bus-util.h" #include "bus-wait-for-jobs.h" #include "cgroup-setup.h" #include "cgroup-util.h" #include "env-file.h" #include "env-util.h" #include "fd-util.h" #include "fs-util.h" #include "log.h" #include "namespace-util.h" #include "path-util.h" #include "process-util.h" #include "random-util.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" char* setup_fake_runtime_dir(void) { char t[] = "/tmp/fake-xdg-runtime-XXXXXX", *p; assert_se(mkdtemp(t)); assert_se(setenv("XDG_RUNTIME_DIR", t, 1) >= 0); assert_se(p = strdup(t)); return p; } static void load_testdata_env(void) { static bool called = false; _cleanup_free_ char *s = NULL, *d = NULL, *envpath = NULL; _cleanup_strv_free_ char **pairs = NULL; int r; if (called) return; called = true; assert_se(readlink_and_make_absolute("/proc/self/exe", &s) >= 0); assert_se(path_extract_directory(s, &d) >= 0); assert_se(envpath = path_join(d, "systemd-runtest.env")); r = load_env_file_pairs(NULL, envpath, &pairs); if (r < 0) { log_debug_errno(r, "Reading %s failed: %m", envpath); return; } STRV_FOREACH_PAIR(k, v, pairs) assert_se(setenv(*k, *v, 0) >= 0); } int get_testdata_dir(const char *suffix, char **ret) { const char *dir; char *p; load_testdata_env(); /* if the env var is set, use that */ dir = getenv("SYSTEMD_TEST_DATA"); if (!dir) dir = SYSTEMD_TEST_DATA; if (access(dir, F_OK) < 0) return log_error_errno(errno, "ERROR: $SYSTEMD_TEST_DATA directory [%s] not accessible: %m", dir); p = path_join(dir, suffix); if (!p) return log_oom(); *ret = p; return 0; } const char* get_catalog_dir(void) { const char *env; load_testdata_env(); /* if the env var is set, use that */ env = getenv("SYSTEMD_CATALOG_DIR"); if (!env) env = SYSTEMD_CATALOG_DIR; if (access(env, F_OK) < 0) { fprintf(stderr, "ERROR: $SYSTEMD_CATALOG_DIR directory [%s] does not exist\n", env); exit(EXIT_FAILURE); } return env; } bool slow_tests_enabled(void) { int r; r = getenv_bool("SYSTEMD_SLOW_TESTS"); if (r >= 0) return r; if (r != -ENXIO) log_warning_errno(r, "Cannot parse $SYSTEMD_SLOW_TESTS, ignoring."); return SYSTEMD_SLOW_TESTS_DEFAULT; } void test_setup_logging(int level) { log_set_max_level(level); log_parse_environment(); log_open(); } int log_tests_skipped(const char *message) { log_notice("%s: %s, skipping tests.", program_invocation_short_name, message); return EXIT_TEST_SKIP; } int log_tests_skipped_errno(int r, const char *message) { log_notice_errno(r, "%s: %s, skipping tests: %m", program_invocation_short_name, message); return EXIT_TEST_SKIP; } int write_tmpfile(char *pattern, const char *contents) { _cleanup_close_ int fd = -EBADF; assert(pattern); assert(contents); fd = mkostemp_safe(pattern); if (fd < 0) return fd; ssize_t l = strlen(contents); errno = 0; if (write(fd, contents, l) != l) return errno_or_else(EIO); return 0; } bool have_namespaces(void) { siginfo_t si = {}; pid_t pid; /* Checks whether namespaces are available. In some cases they aren't. We do this by calling unshare(), and we * do so in a child process in order not to affect our own process. */ pid = fork(); assert_se(pid >= 0); if (pid == 0) { /* child */ if (detach_mount_namespace() < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } assert_se(waitid(P_PID, pid, &si, WEXITED) >= 0); assert_se(si.si_code == CLD_EXITED); if (si.si_status == EXIT_SUCCESS) return true; if (si.si_status == EXIT_FAILURE) return false; assert_not_reached(); } bool can_memlock(void) { /* Let's see if we can mlock() a larger blob of memory. BPF programs are charged against * RLIMIT_MEMLOCK, hence let's first make sure we can lock memory at all, and skip the test if we * cannot. Why not check RLIMIT_MEMLOCK explicitly? Because in container environments the * RLIMIT_MEMLOCK value we see might not match the RLIMIT_MEMLOCK value actually in effect. */ void *p = mmap(NULL, CAN_MEMLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0); if (p == MAP_FAILED) return false; bool b = mlock(p, CAN_MEMLOCK_SIZE) >= 0; if (b) assert_se(munlock(p, CAN_MEMLOCK_SIZE) >= 0); assert_se(munmap(p, CAN_MEMLOCK_SIZE) >= 0); return b; } static int allocate_scope(void) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_free_ char *scope = NULL; const char *object; int r; /* Let's try to run this test in a scope of its own, with delegation turned on, so that PID 1 doesn't * interfere with our cgroup management. */ r = sd_bus_default_system(&bus); if (r < 0) return log_error_errno(r, "Failed to connect to system bus: %m"); r = bus_wait_for_jobs_new(bus, &w); if (r < 0) return log_error_errno(r, "Could not watch jobs: %m"); if (asprintf(&scope, "%s-%" PRIx64 ".scope", program_invocation_short_name, random_u64()) < 0) return log_oom(); r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit"); if (r < 0) return bus_log_create_error(r); /* Name and Mode */ r = sd_bus_message_append(m, "ss", scope, "fail"); if (r < 0) return bus_log_create_error(r); /* Properties */ r = sd_bus_message_open_container(m, 'a', "(sv)"); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached()); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append(m, "(sv)", "Delegate", "b", 1); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed"); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_close_container(m); if (r < 0) return bus_log_create_error(r); /* Auxiliary units */ r = sd_bus_message_append(m, "a(sa(sv))", 0); if (r < 0) return bus_log_create_error(r); r = sd_bus_call(bus, m, 0, &error, &reply); if (r < 0) return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r)); r = sd_bus_message_read(reply, "o", &object); if (r < 0) return bus_log_parse_error(r); r = bus_wait_for_jobs_one(w, object, false, NULL); if (r < 0) return r; return 0; } static int enter_cgroup(char **ret_cgroup, bool enter_subroot) { _cleanup_free_ char *cgroup_root = NULL, *cgroup_subroot = NULL; CGroupMask supported; int r; r = allocate_scope(); if (r < 0) log_warning_errno(r, "Couldn't allocate a scope unit for this test, proceeding without."); r = cg_pid_get_path(NULL, 0, &cgroup_root); if (r == -ENOMEDIUM) return log_warning_errno(r, "cg_pid_get_path(NULL, 0, ...) failed: %m"); assert(r >= 0); if (enter_subroot) assert_se(asprintf(&cgroup_subroot, "%s/%" PRIx64, cgroup_root, random_u64()) >= 0); else { cgroup_subroot = strdup(cgroup_root); assert_se(cgroup_subroot != NULL); } assert_se(cg_mask_supported(&supported) >= 0); /* If this fails, then we don't mind as the later cgroup operations will fail too, and it's fine if * we handle any errors at that point. */ r = cg_create_everywhere(supported, _CGROUP_MASK_ALL, cgroup_subroot); if (r < 0) return r; r = cg_attach_everywhere(supported, cgroup_subroot, 0, NULL, NULL); if (r < 0) return r; if (ret_cgroup) *ret_cgroup = TAKE_PTR(cgroup_subroot); return 0; } int enter_cgroup_subroot(char **ret_cgroup) { return enter_cgroup(ret_cgroup, true); } int enter_cgroup_root(char **ret_cgroup) { return enter_cgroup(ret_cgroup, false); } const char *ci_environment(void) { /* We return a string because we might want to provide multiple bits of information later on: not * just the general CI environment type, but also whether we're sanitizing or not, etc. The caller is * expected to use strstr on the returned value. */ static const char *ans = POINTER_MAX; int r; if (ans != POINTER_MAX) return ans; /* We allow specifying the environment with $CITYPE. Nobody uses this so far, but we are ready. */ const char *citype = getenv("CITYPE"); if (!isempty(citype)) return (ans = citype); if (getenv_bool("TRAVIS") > 0) return (ans = "travis"); if (getenv_bool("SEMAPHORE") > 0) return (ans = "semaphore"); if (getenv_bool("GITHUB_ACTIONS") > 0) return (ans = "github-actions"); if (getenv("AUTOPKGTEST_ARTIFACTS") || getenv("AUTOPKGTEST_TMP")) return (ans = "autopkgtest"); FOREACH_STRING(var, "CI", "CONTINOUS_INTEGRATION") { /* Those vars are booleans according to Semaphore and Travis docs: * https://docs.travis-ci.com/user/environment-variables/#default-environment-variables * https://docs.semaphoreci.com/ci-cd-environment/environment-variables/#ci */ r = getenv_bool(var); if (r > 0) return (ans = "unknown"); /* Some other unknown thing */ if (r == 0) return (ans = NULL); } return (ans = NULL); }
11,273
30.579832
118
c
null
systemd-main/src/shared/tests.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "sd-daemon.h" #include "argv-util.h" #include "macro.h" #include "static-destruct.h" #include "strv.h" static inline bool manager_errno_skip_test(int r) { return IN_SET(abs(r), EPERM, EACCES, EADDRINUSE, EHOSTDOWN, ENOENT, ENOMEDIUM /* cannot determine cgroup */ ); } char* setup_fake_runtime_dir(void); int enter_cgroup_subroot(char **ret_cgroup); int enter_cgroup_root(char **ret_cgroup); int get_testdata_dir(const char *suffix, char **ret); const char* get_catalog_dir(void); bool slow_tests_enabled(void); void test_setup_logging(int level); int log_tests_skipped(const char *message); int log_tests_skipped_errno(int r, const char *message); int write_tmpfile(char *pattern, const char *contents); bool have_namespaces(void); /* We use the small but non-trivial limit here */ #define CAN_MEMLOCK_SIZE (512 * 1024U) bool can_memlock(void); #define TEST_REQ_RUNNING_SYSTEMD(x) \ if (sd_booted() > 0) { \ x; \ } else { \ printf("systemd not booted, skipping '%s'\n", #x); \ } /* Provide a convenient way to check if we're running in CI. */ const char *ci_environment(void); typedef struct TestFunc { union f { void (*void_func)(void); int (*int_func)(void); } f; const char * const name; bool has_ret:1; bool sd_booted:1; } TestFunc; /* See static-destruct.h for an explanation of how this works. */ #define REGISTER_TEST(func, ...) \ _Pragma("GCC diagnostic ignored \"-Wattributes\"") \ _section_("SYSTEMD_TEST_TABLE") _alignptr_ _used_ _retain_ _variable_no_sanitize_address_ \ static const TestFunc UNIQ_T(static_test_table_entry, UNIQ) = { \ .f = (union f) &(func), \ .name = STRINGIFY(func), \ .has_ret = __builtin_types_compatible_p(typeof((union f){}.int_func), typeof(&(func))), \ ##__VA_ARGS__ \ } extern const TestFunc _weak_ __start_SYSTEMD_TEST_TABLE[]; extern const TestFunc _weak_ __stop_SYSTEMD_TEST_TABLE[]; #define TEST(name, ...) \ static void test_##name(void); \ REGISTER_TEST(test_##name, ##__VA_ARGS__); \ static void test_##name(void) #define TEST_RET(name, ...) \ static int test_##name(void); \ REGISTER_TEST(test_##name, ##__VA_ARGS__); \ static int test_##name(void) static inline int run_test_table(void) { _cleanup_strv_free_ char **tests = NULL; int r = EXIT_SUCCESS; bool ran = false; const char *e; if (!__start_SYSTEMD_TEST_TABLE) return r; e = getenv("TESTFUNCS"); if (e) { r = strv_split_full(&tests, e, ":", EXTRACT_DONT_COALESCE_SEPARATORS); if (r < 0) return log_error_errno(r, "Failed to parse $TESTFUNCS: %m"); } for (const TestFunc *t = ALIGN_PTR(__start_SYSTEMD_TEST_TABLE); t + 1 <= __stop_SYSTEMD_TEST_TABLE; t = ALIGN_PTR(t + 1)) { if (tests && !strv_contains(tests, t->name)) continue; if (t->sd_booted && sd_booted() <= 0) { log_info("/* systemd not booted, skipping %s */", t->name); if (t->has_ret && r == EXIT_SUCCESS) r = EXIT_TEST_SKIP; } else { log_info("/* %s */", t->name); if (t->has_ret) { int r2 = t->f.int_func(); if (r == EXIT_SUCCESS) r = r2; } else t->f.void_func(); } ran = true; } if (!ran) return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No matching tests found."); return r; } #define DEFINE_TEST_MAIN_FULL(log_level, intro, outro) \ int main(int argc, char *argv[]) { \ int (*_intro)(void) = intro; \ int (*_outro)(void) = outro; \ int _r, _q; \ test_setup_logging(log_level); \ save_argc_argv(argc, argv); \ _r = _intro ? _intro() : EXIT_SUCCESS; \ if (_r == EXIT_SUCCESS) \ _r = run_test_table(); \ _q = _outro ? _outro() : EXIT_SUCCESS; \ static_destruct(); \ if (_r < 0) \ return EXIT_FAILURE; \ if (_r != EXIT_SUCCESS) \ return _r; \ if (_q < 0) \ return EXIT_FAILURE; \ return _q; \ } #define DEFINE_TEST_MAIN_WITH_INTRO(log_level, intro) \ DEFINE_TEST_MAIN_FULL(log_level, intro, NULL) #define DEFINE_TEST_MAIN(log_level) \ DEFINE_TEST_MAIN_FULL(log_level, NULL, NULL)
6,161
38
105
h
null
systemd-main/src/shared/tmpfile-util-label.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/stat.h> #include "selinux-util.h" #include "tmpfile-util-label.h" #include "tmpfile-util.h" int fopen_temporary_at_label( int dir_fd, const char *target, const char *path, FILE **f, char **temp_path) { int r; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); assert(path); r = mac_selinux_create_file_prepare_at(dir_fd, target, S_IFREG); if (r < 0) return r; r = fopen_temporary_at(dir_fd, path, f, temp_path); mac_selinux_create_file_clear(); return r; }
681
21
72
c
null
systemd-main/src/shared/tmpfile-util-label.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fcntl.h> #include <stdio.h> /* These functions are split out of tmpfile-util.h (and not for example just flags to the functions they * wrap) in order to optimize linking: this way, -lselinux is needed only for the callers of these functions * that need selinux, but not for all. */ int fopen_temporary_at_label(int dir_fd, const char *target, const char *path, FILE **f, char **temp_path); static inline int fopen_temporary_label(const char *target, const char *path, FILE **f, char **temp_path) { return fopen_temporary_at_label(AT_FDCWD, target, path, f, temp_path); }
656
42.8
108
h
null
systemd-main/src/shared/udev-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if HAVE_SYS_SDT_H #define SDT_USE_VARIADIC #include <sys/sdt.h> #endif #include "sd-device.h" #include "time-util.h" #define UDEV_NAME_SIZE 512 #define UDEV_PATH_SIZE 1024 #define UDEV_LINE_SIZE 16384 typedef enum ResolveNameTiming { RESOLVE_NAME_NEVER, RESOLVE_NAME_LATE, RESOLVE_NAME_EARLY, _RESOLVE_NAME_TIMING_MAX, _RESOLVE_NAME_TIMING_INVALID = -EINVAL, } ResolveNameTiming; ResolveNameTiming resolve_name_timing_from_string(const char *s) _pure_; const char *resolve_name_timing_to_string(ResolveNameTiming i) _const_; int udev_parse_config_full( unsigned *ret_children_max, usec_t *ret_exec_delay_usec, usec_t *ret_event_timeout_usec, ResolveNameTiming *ret_resolve_name_timing, int *ret_timeout_signal); static inline int udev_parse_config(void) { return udev_parse_config_full(NULL, NULL, NULL, NULL, NULL); } int device_wait_for_initialization(sd_device *device, const char *subsystem, usec_t timeout_usec, sd_device **ret); int device_wait_for_devlink(const char *path, const char *subsystem, usec_t timeout_usec, sd_device **ret); int device_is_renaming(sd_device *dev); bool device_for_action(sd_device *dev, sd_device_action_t action); void log_device_uevent(sd_device *device, const char *str); int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos); size_t udev_replace_whitespace(const char *str, char *to, size_t len); size_t udev_replace_ifname(char *str); size_t udev_replace_chars(char *str, const char *allow); int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value); bool devpath_conflict(const char *a, const char *b); int udev_queue_is_empty(void); int udev_queue_init(void); bool udev_available(void); #if HAVE_SYS_SDT_H /* Each trace point can have different number of additional arguments. Note that when the macro is used only * additional arguments are listed in the macro invocation! * * Default arguments for each trace point are as follows: * - arg0 - action * - arg1 - sysname * - arg2 - syspath * - arg3 - subsystem */ #define DEVICE_TRACE_POINT(name, dev, ...) \ do { \ PROTECT_ERRNO; \ const char *_n = NULL, *_p = NULL, *_s = NULL; \ sd_device *_d = (dev); \ sd_device_action_t _a = _SD_DEVICE_ACTION_INVALID; \ (void) sd_device_get_action(_d, &_a); \ (void) sd_device_get_sysname(_d, &_n); \ (void) sd_device_get_syspath(_d, &_p); \ (void) sd_device_get_subsystem(_d, &_s); \ STAP_PROBEV(udev, name, device_action_to_string(_a), _n, _p, _s __VA_OPT__(,) __VA_ARGS__);\ } while (false); #else #define DEVICE_TRACE_POINT(name, dev, ...) ((void) 0) #endif
3,533
40.093023
115
h
null
systemd-main/src/shared/user-record-nss.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <grp.h> #include <gshadow.h> #include <pwd.h> #include <shadow.h> #include "group-record.h" #include "user-record.h" /* Synthesize UserRecord and GroupRecord objects from NSS data */ int nss_passwd_to_user_record(const struct passwd *pwd, const struct spwd *spwd, UserRecord **ret); int nss_spwd_for_passwd(const struct passwd *pwd, struct spwd *ret_spwd, char **ret_buffer); int nss_user_record_by_name(const char *name, bool with_shadow, UserRecord **ret); int nss_user_record_by_uid(uid_t uid, bool with_shadow, UserRecord **ret); int nss_group_to_group_record(const struct group *grp, const struct sgrp *sgrp, GroupRecord **ret); int nss_sgrp_for_group(const struct group *grp, struct sgrp *ret_sgrp, char **ret_buffer); int nss_group_record_by_name(const char *name, bool with_shadow, GroupRecord **ret); int nss_group_record_by_gid(gid_t gid, bool with_shadow, GroupRecord **ret);
965
37.64
99
h
null
systemd-main/src/shared/user-record.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <sys/types.h> #include "sd-id128.h" #include "json.h" #include "missing_resource.h" #include "time-util.h" typedef enum UserDisposition { USER_INTRINSIC, /* root and nobody */ USER_SYSTEM, /* statically allocated users for system services */ USER_DYNAMIC, /* dynamically allocated users for system services */ USER_REGULAR, /* regular (typically human users) */ USER_CONTAINER, /* UID ranges allocated for container uses */ USER_RESERVED, /* Range above 2^31 */ _USER_DISPOSITION_MAX, _USER_DISPOSITION_INVALID = -EINVAL, } UserDisposition; typedef enum UserHomeStorage { USER_CLASSIC, USER_LUKS, USER_DIRECTORY, /* A directory, and a .identity file in it, which USER_CLASSIC lacks */ USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS, _USER_STORAGE_MAX, _USER_STORAGE_INVALID = -EINVAL, } UserStorage; typedef enum UserRecordMask { /* The various sections an identity record may have, as bit mask */ USER_RECORD_REGULAR = 1U << 0, USER_RECORD_SECRET = 1U << 1, USER_RECORD_PRIVILEGED = 1U << 2, USER_RECORD_PER_MACHINE = 1U << 3, USER_RECORD_BINDING = 1U << 4, USER_RECORD_STATUS = 1U << 5, USER_RECORD_SIGNATURE = 1U << 6, _USER_RECORD_MASK_MAX = (1U << 7)-1 } UserRecordMask; typedef enum UserRecordLoadFlags { /* A set of flags used while loading a user record from JSON data. We leave the lower 6 bits free, * just as a safety precaution so that we can detect borked conversions between UserRecordMask and * UserRecordLoadFlags. */ /* What to require */ USER_RECORD_REQUIRE_REGULAR = USER_RECORD_REGULAR << 7, USER_RECORD_REQUIRE_SECRET = USER_RECORD_SECRET << 7, USER_RECORD_REQUIRE_PRIVILEGED = USER_RECORD_PRIVILEGED << 7, USER_RECORD_REQUIRE_PER_MACHINE = USER_RECORD_PER_MACHINE << 7, USER_RECORD_REQUIRE_BINDING = USER_RECORD_BINDING << 7, USER_RECORD_REQUIRE_STATUS = USER_RECORD_STATUS << 7, USER_RECORD_REQUIRE_SIGNATURE = USER_RECORD_SIGNATURE << 7, /* What to allow */ USER_RECORD_ALLOW_REGULAR = USER_RECORD_REGULAR << 14, USER_RECORD_ALLOW_SECRET = USER_RECORD_SECRET << 14, USER_RECORD_ALLOW_PRIVILEGED = USER_RECORD_PRIVILEGED << 14, USER_RECORD_ALLOW_PER_MACHINE = USER_RECORD_PER_MACHINE << 14, USER_RECORD_ALLOW_BINDING = USER_RECORD_BINDING << 14, USER_RECORD_ALLOW_STATUS = USER_RECORD_STATUS << 14, USER_RECORD_ALLOW_SIGNATURE = USER_RECORD_SIGNATURE << 14, /* What to strip */ USER_RECORD_STRIP_REGULAR = USER_RECORD_REGULAR << 21, USER_RECORD_STRIP_SECRET = USER_RECORD_SECRET << 21, USER_RECORD_STRIP_PRIVILEGED = USER_RECORD_PRIVILEGED << 21, USER_RECORD_STRIP_PER_MACHINE = USER_RECORD_PER_MACHINE << 21, USER_RECORD_STRIP_BINDING = USER_RECORD_BINDING << 21, USER_RECORD_STRIP_STATUS = USER_RECORD_STATUS << 21, USER_RECORD_STRIP_SIGNATURE = USER_RECORD_SIGNATURE << 21, /* Some special combinations that deserve explicit names */ USER_RECORD_LOAD_FULL = USER_RECORD_REQUIRE_REGULAR | USER_RECORD_ALLOW_SECRET | USER_RECORD_ALLOW_PRIVILEGED | USER_RECORD_ALLOW_PER_MACHINE | USER_RECORD_ALLOW_BINDING | USER_RECORD_ALLOW_STATUS | USER_RECORD_ALLOW_SIGNATURE, USER_RECORD_LOAD_REFUSE_SECRET = USER_RECORD_REQUIRE_REGULAR | USER_RECORD_ALLOW_PRIVILEGED | USER_RECORD_ALLOW_PER_MACHINE | USER_RECORD_ALLOW_BINDING | USER_RECORD_ALLOW_STATUS | USER_RECORD_ALLOW_SIGNATURE, USER_RECORD_LOAD_MASK_SECRET = USER_RECORD_REQUIRE_REGULAR | USER_RECORD_ALLOW_PRIVILEGED | USER_RECORD_ALLOW_PER_MACHINE | USER_RECORD_ALLOW_BINDING | USER_RECORD_ALLOW_STATUS | USER_RECORD_ALLOW_SIGNATURE | USER_RECORD_STRIP_SECRET, USER_RECORD_EXTRACT_SECRET = USER_RECORD_REQUIRE_SECRET | USER_RECORD_STRIP_REGULAR | USER_RECORD_STRIP_PRIVILEGED | USER_RECORD_STRIP_PER_MACHINE | USER_RECORD_STRIP_BINDING | USER_RECORD_STRIP_STATUS | USER_RECORD_STRIP_SIGNATURE, USER_RECORD_LOAD_SIGNABLE = USER_RECORD_REQUIRE_REGULAR | USER_RECORD_ALLOW_PRIVILEGED | USER_RECORD_ALLOW_PER_MACHINE, USER_RECORD_EXTRACT_SIGNABLE = USER_RECORD_LOAD_SIGNABLE | USER_RECORD_STRIP_SECRET | USER_RECORD_STRIP_BINDING | USER_RECORD_STRIP_STATUS | USER_RECORD_STRIP_SIGNATURE, USER_RECORD_LOAD_EMBEDDED = USER_RECORD_REQUIRE_REGULAR | USER_RECORD_ALLOW_PRIVILEGED | USER_RECORD_ALLOW_PER_MACHINE | USER_RECORD_ALLOW_SIGNATURE, USER_RECORD_EXTRACT_EMBEDDED = USER_RECORD_LOAD_EMBEDDED | USER_RECORD_STRIP_SECRET | USER_RECORD_STRIP_BINDING | USER_RECORD_STRIP_STATUS, /* Whether to log about loader errors beyond LOG_DEBUG */ USER_RECORD_LOG = 1U << 28, /* Whether to ignore errors and load what we can */ USER_RECORD_PERMISSIVE = 1U << 29, /* Whether an empty record is OK */ USER_RECORD_EMPTY_OK = 1U << 30, } UserRecordLoadFlags; static inline UserRecordLoadFlags USER_RECORD_REQUIRE(UserRecordMask m) { assert((m & ~_USER_RECORD_MASK_MAX) == 0); return m << 7; } static inline UserRecordLoadFlags USER_RECORD_ALLOW(UserRecordMask m) { assert((m & ~_USER_RECORD_MASK_MAX) == 0); return m << 14; } static inline UserRecordLoadFlags USER_RECORD_STRIP(UserRecordMask m) { assert((m & ~_USER_RECORD_MASK_MAX) == 0); return m << 21; } static inline UserRecordMask USER_RECORD_REQUIRE_MASK(UserRecordLoadFlags f) { return (f >> 7) & _USER_RECORD_MASK_MAX; } static inline UserRecordMask USER_RECORD_ALLOW_MASK(UserRecordLoadFlags f) { return ((f >> 14) & _USER_RECORD_MASK_MAX) | USER_RECORD_REQUIRE_MASK(f); } static inline UserRecordMask USER_RECORD_STRIP_MASK(UserRecordLoadFlags f) { return (f >> 21) & _USER_RECORD_MASK_MAX; } static inline JsonDispatchFlags USER_RECORD_LOAD_FLAGS_TO_JSON_DISPATCH_FLAGS(UserRecordLoadFlags flags) { return (FLAGS_SET(flags, USER_RECORD_LOG) ? JSON_LOG : 0) | (FLAGS_SET(flags, USER_RECORD_PERMISSIVE) ? JSON_PERMISSIVE : 0); } typedef struct Pkcs11EncryptedKey { /* The encrypted passphrase, which can be decrypted with the private key indicated below */ void *data; size_t size; /* Where to find the private key to decrypt the encrypted passphrase above */ char *uri; /* What to test the decrypted passphrase against to allow access (classic UNIX password hash). Note * that the decrypted passphrase is also used for unlocking LUKS and fscrypt, and if the account is * backed by LUKS or fscrypt the hashed password is only an additional layer of authentication, not * the only. */ char *hashed_password; } Pkcs11EncryptedKey; typedef struct Fido2HmacCredential { void *id; size_t size; } Fido2HmacCredential; typedef struct Fido2HmacSalt { /* The FIDO2 Cridential ID to use */ Fido2HmacCredential credential; /* The FIDO2 salt value */ void *salt; size_t salt_size; /* What to test the hashed salt value against, usually UNIX password hash here. */ char *hashed_password; /* Whether the 'up', 'uv', 'clientPin' features are enabled. */ int uv, up, client_pin; } Fido2HmacSalt; typedef struct RecoveryKey { /* The type of recovery key, must be "modhex64" right now */ char *type; /* A UNIX password hash of the normalized form of modhex64 */ char *hashed_password; } RecoveryKey; typedef enum AutoResizeMode { AUTO_RESIZE_OFF, /* no automatic grow/shrink */ AUTO_RESIZE_GROW, /* grow at login */ AUTO_RESIZE_SHRINK_AND_GROW, /* shrink at logout + grow at login */ _AUTO_RESIZE_MODE_MAX, _AUTO_RESIZE_MODE_INVALID = -EINVAL, } AutoResizeMode; #define REBALANCE_WEIGHT_OFF UINT64_C(0) #define REBALANCE_WEIGHT_DEFAULT UINT64_C(100) #define REBALANCE_WEIGHT_BACKING UINT64_C(20) #define REBALANCE_WEIGHT_MIN UINT64_C(1) #define REBALANCE_WEIGHT_MAX UINT64_C(10000) #define REBALANCE_WEIGHT_UNSET UINT64_MAX typedef struct UserRecord { /* The following three fields are not part of the JSON record */ unsigned n_ref; UserRecordMask mask; bool incomplete; /* incomplete due to security restrictions. */ char *user_name; char *realm; char *user_name_and_realm_auto; /* the user_name field concatenated with '@' and the realm, if the latter is defined */ char *real_name; char *email_address; char *password_hint; char *icon_name; char *location; UserDisposition disposition; uint64_t last_change_usec; uint64_t last_password_change_usec; char *shell; mode_t umask; char **environment; char *time_zone; char *preferred_language; int nice_level; struct rlimit *rlimits[_RLIMIT_MAX]; int locked; /* prohibit activation in general */ uint64_t not_before_usec; /* prohibit activation before this unix time */ uint64_t not_after_usec; /* prohibit activation after this unix time */ UserStorage storage; uint64_t disk_size; uint64_t disk_size_relative; /* Disk size, relative to the free bytes of the medium, normalized to UINT32_MAX = 100% */ char *skeleton_directory; mode_t access_mode; AutoResizeMode auto_resize_mode; uint64_t rebalance_weight; uint64_t tasks_max; uint64_t memory_high; uint64_t memory_max; uint64_t cpu_weight; uint64_t io_weight; bool nosuid; bool nodev; bool noexec; char **hashed_password; char **ssh_authorized_keys; char **password; char **token_pin; char *cifs_domain; char *cifs_user_name; char *cifs_service; char *cifs_extra_mount_options; char *image_path; char *image_path_auto; /* when none is configured explicitly, this is where we place the implicit image */ char *home_directory; char *home_directory_auto; /* when none is set explicitly, this is where we place the implicit home directory */ uid_t uid; gid_t gid; char **member_of; char *file_system_type; sd_id128_t partition_uuid; sd_id128_t luks_uuid; sd_id128_t file_system_uuid; int luks_discard; int luks_offline_discard; char *luks_cipher; char *luks_cipher_mode; uint64_t luks_volume_key_size; char *luks_pbkdf_hash_algorithm; char *luks_pbkdf_type; uint64_t luks_pbkdf_force_iterations; uint64_t luks_pbkdf_time_cost_usec; uint64_t luks_pbkdf_memory_cost; uint64_t luks_pbkdf_parallel_threads; uint64_t luks_sector_size; char *luks_extra_mount_options; uint64_t disk_usage; uint64_t disk_free; uint64_t disk_ceiling; uint64_t disk_floor; char *state; char *service; int signed_locally; uint64_t good_authentication_counter; uint64_t bad_authentication_counter; uint64_t last_good_authentication_usec; uint64_t last_bad_authentication_usec; uint64_t ratelimit_begin_usec; uint64_t ratelimit_count; uint64_t ratelimit_interval_usec; uint64_t ratelimit_burst; int removable; int enforce_password_policy; int auto_login; int drop_caches; uint64_t stop_delay_usec; /* How long to leave systemd --user around on log-out */ int kill_processes; /* Whether to kill user processes forcibly on log-out */ /* The following exist mostly so that we can cover the full /etc/shadow set of fields */ uint64_t password_change_min_usec; /* maps to .sp_min */ uint64_t password_change_max_usec; /* maps to .sp_max */ uint64_t password_change_warn_usec; /* maps to .sp_warn */ uint64_t password_change_inactive_usec; /* maps to .sp_inact */ int password_change_now; /* Require a password change immediately on next login (.sp_lstchg = 0) */ char **pkcs11_token_uri; Pkcs11EncryptedKey *pkcs11_encrypted_key; size_t n_pkcs11_encrypted_key; int pkcs11_protected_authentication_path_permitted; Fido2HmacCredential *fido2_hmac_credential; size_t n_fido2_hmac_credential; Fido2HmacSalt *fido2_hmac_salt; size_t n_fido2_hmac_salt; int fido2_user_presence_permitted; int fido2_user_verification_permitted; char **recovery_key_type; RecoveryKey *recovery_key; size_t n_recovery_key; char **capability_bounding_set; char **capability_ambient_set; JsonVariant *json; } UserRecord; UserRecord* user_record_new(void); UserRecord* user_record_ref(UserRecord *h); UserRecord* user_record_unref(UserRecord *h); DEFINE_TRIVIAL_CLEANUP_FUNC(UserRecord*, user_record_unref); int user_record_load(UserRecord *h, JsonVariant *v, UserRecordLoadFlags flags); int user_record_build(UserRecord **ret, ...); const char *user_record_user_name_and_realm(UserRecord *h); UserStorage user_record_storage(UserRecord *h); const char *user_record_file_system_type(UserRecord *h); const char *user_record_skeleton_directory(UserRecord *h); mode_t user_record_access_mode(UserRecord *h); const char *user_record_home_directory(UserRecord *h); const char *user_record_image_path(UserRecord *h); unsigned long user_record_mount_flags(UserRecord *h); const char *user_record_cifs_user_name(UserRecord *h); const char *user_record_shell(UserRecord *h); const char *user_record_real_name(UserRecord *h); bool user_record_luks_discard(UserRecord *h); bool user_record_luks_offline_discard(UserRecord *h); const char *user_record_luks_cipher(UserRecord *h); const char *user_record_luks_cipher_mode(UserRecord *h); uint64_t user_record_luks_volume_key_size(UserRecord *h); const char* user_record_luks_pbkdf_type(UserRecord *h); uint64_t user_record_luks_pbkdf_force_iterations(UserRecord *h); usec_t user_record_luks_pbkdf_time_cost_usec(UserRecord *h); uint64_t user_record_luks_pbkdf_memory_cost(UserRecord *h); uint64_t user_record_luks_pbkdf_parallel_threads(UserRecord *h); uint64_t user_record_luks_sector_size(UserRecord *h); const char *user_record_luks_pbkdf_hash_algorithm(UserRecord *h); gid_t user_record_gid(UserRecord *h); UserDisposition user_record_disposition(UserRecord *h); int user_record_removable(UserRecord *h); usec_t user_record_ratelimit_interval_usec(UserRecord *h); uint64_t user_record_ratelimit_burst(UserRecord *h); bool user_record_can_authenticate(UserRecord *h); bool user_record_drop_caches(UserRecord *h); AutoResizeMode user_record_auto_resize_mode(UserRecord *h); uint64_t user_record_rebalance_weight(UserRecord *h); uint64_t user_record_capability_bounding_set(UserRecord *h); uint64_t user_record_capability_ambient_set(UserRecord *h); int user_record_build_image_path(UserStorage storage, const char *user_name_and_realm, char **ret); bool user_record_equal(UserRecord *a, UserRecord *b); bool user_record_compatible(UserRecord *a, UserRecord *b); int user_record_compare_last_change(UserRecord *a, UserRecord *b); usec_t user_record_ratelimit_next_try(UserRecord *h); int user_record_clone(UserRecord *h, UserRecordLoadFlags flags, UserRecord **ret); int user_record_masked_equal(UserRecord *a, UserRecord *b, UserRecordMask mask); int user_record_test_blocked(UserRecord *h); int user_record_test_password_change_required(UserRecord *h); /* The following six are user by group-record.c, that's why we export them here */ int json_dispatch_realm(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata); int json_dispatch_gecos(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata); int json_dispatch_user_group_list(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata); int json_dispatch_user_disposition(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata); int per_machine_id_match(JsonVariant *ids, JsonDispatchFlags flags); int per_machine_hostname_match(JsonVariant *hns, JsonDispatchFlags flags); int user_group_record_mangle(JsonVariant *v, UserRecordLoadFlags load_flags, JsonVariant **ret_variant, UserRecordMask *ret_mask); const char* user_storage_to_string(UserStorage t) _const_; UserStorage user_storage_from_string(const char *s) _pure_; const char* user_disposition_to_string(UserDisposition t) _const_; UserDisposition user_disposition_from_string(const char *s) _pure_; const char* auto_resize_mode_to_string(AutoResizeMode m) _const_; AutoResizeMode auto_resize_mode_from_string(const char *s) _pure_;
18,905
40.920177
130
h
null
systemd-main/src/shared/userdb-dropin.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "format-util.h" #include "path-util.h" #include "stdio-util.h" #include "user-util.h" #include "userdb-dropin.h" static int load_user( FILE *f, const char *path, const char *name, uid_t uid, UserDBFlags flags, UserRecord **ret) { _cleanup_(json_variant_unrefp) JsonVariant *v = NULL; _cleanup_(user_record_unrefp) UserRecord *u = NULL; bool have_privileged; int r; assert(f); r = json_parse_file(f, path, 0, &v, NULL, NULL); if (r < 0) return r; if (FLAGS_SET(flags, USERDB_SUPPRESS_SHADOW) || !path || !(name || uid_is_valid(uid))) have_privileged = false; else { _cleanup_(json_variant_unrefp) JsonVariant *privileged_v = NULL; _cleanup_free_ char *d = NULL, *j = NULL; /* Let's load the "privileged" section from a companion file. But only if USERDB_AVOID_SHADOW * is not set. After all, the privileged section kinda takes the role of the data from the * shadow file, hence it makes sense to use the same flag here. * * The general assumption is that whoever provides these records makes the .user file * world-readable, but the .privilege file readable to root and the assigned UID only. But we * won't verify that here, as it would be too late. */ r = path_extract_directory(path, &d); if (r < 0) return r; if (name) { j = strjoin(d, "/", name, ".user-privileged"); if (!j) return -ENOMEM; } else { assert(uid_is_valid(uid)); if (asprintf(&j, "%s/" UID_FMT ".user-privileged", d, uid) < 0) return -ENOMEM; } r = json_parse_file(NULL, j, JSON_PARSE_SENSITIVE, &privileged_v, NULL, NULL); if (ERRNO_IS_PRIVILEGE(r)) have_privileged = false; else if (r == -ENOENT) have_privileged = true; /* if the privileged file doesn't exist, we are complete */ else if (r < 0) return r; else { r = json_variant_merge(&v, privileged_v); if (r < 0) return r; have_privileged = true; } } u = user_record_new(); if (!u) return -ENOMEM; r = user_record_load( u, v, USER_RECORD_REQUIRE_REGULAR| USER_RECORD_ALLOW_PER_MACHINE| USER_RECORD_ALLOW_BINDING| USER_RECORD_ALLOW_SIGNATURE| (have_privileged ? USER_RECORD_ALLOW_PRIVILEGED : 0)| USER_RECORD_PERMISSIVE); if (r < 0) return r; if (name && !streq_ptr(name, u->user_name)) return -EINVAL; if (uid_is_valid(uid) && uid != u->uid) return -EINVAL; u->incomplete = !have_privileged; if (ret) *ret = TAKE_PTR(u); return 0; } int dropin_user_record_by_name(const char *name, const char *path, UserDBFlags flags, UserRecord **ret) { _cleanup_free_ char *found_path = NULL; _cleanup_fclose_ FILE *f = NULL; int r; assert(name); if (path) { f = fopen(path, "re"); if (!f) return errno == ENOENT ? -ESRCH : -errno; /* We generally want ESRCH to indicate no such user */ } else { const char *j; j = strjoina(name, ".user"); if (!filename_is_valid(j)) /* Doesn't qualify as valid filename? Then it's definitely not provided as a drop-in */ return -ESRCH; r = search_and_fopen_nulstr(j, "re", NULL, USERDB_DROPIN_DIR_NULSTR("userdb"), &f, &found_path); if (r == -ENOENT) return -ESRCH; if (r < 0) return r; path = found_path; } return load_user(f, path, name, UID_INVALID, flags, ret); } int dropin_user_record_by_uid(uid_t uid, const char *path, UserDBFlags flags, UserRecord **ret) { _cleanup_free_ char *found_path = NULL; _cleanup_fclose_ FILE *f = NULL; int r; assert(uid_is_valid(uid)); if (path) { f = fopen(path, "re"); if (!f) return errno == ENOENT ? -ESRCH : -errno; } else { char buf[DECIMAL_STR_MAX(uid_t) + STRLEN(".user") + 1]; xsprintf(buf, UID_FMT ".user", uid); /* Note that we don't bother to validate this as a filename, as this is generated from a decimal * integer, i.e. is definitely OK as a filename */ r = search_and_fopen_nulstr(buf, "re", NULL, USERDB_DROPIN_DIR_NULSTR("userdb"), &f, &found_path); if (r == -ENOENT) return -ESRCH; if (r < 0) return r; path = found_path; } return load_user(f, path, NULL, uid, flags, ret); } static int load_group( FILE *f, const char *path, const char *name, gid_t gid, UserDBFlags flags, GroupRecord **ret) { _cleanup_(json_variant_unrefp) JsonVariant *v = NULL; _cleanup_(group_record_unrefp) GroupRecord *g = NULL; bool have_privileged; int r; assert(f); r = json_parse_file(f, path, 0, &v, NULL, NULL); if (r < 0) return r; if (FLAGS_SET(flags, USERDB_SUPPRESS_SHADOW) || !path || !(name || gid_is_valid(gid))) have_privileged = false; else { _cleanup_(json_variant_unrefp) JsonVariant *privileged_v = NULL; _cleanup_free_ char *d = NULL, *j = NULL; r = path_extract_directory(path, &d); if (r < 0) return r; if (name) { j = strjoin(d, "/", name, ".group-privileged"); if (!j) return -ENOMEM; } else { assert(gid_is_valid(gid)); if (asprintf(&j, "%s/" GID_FMT ".group-privileged", d, gid) < 0) return -ENOMEM; } r = json_parse_file(NULL, j, JSON_PARSE_SENSITIVE, &privileged_v, NULL, NULL); if (ERRNO_IS_PRIVILEGE(r)) have_privileged = false; else if (r == -ENOENT) have_privileged = true; /* if the privileged file doesn't exist, we are complete */ else if (r < 0) return r; else { r = json_variant_merge(&v, privileged_v); if (r < 0) return r; have_privileged = true; } } g = group_record_new(); if (!g) return -ENOMEM; r = group_record_load( g, v, USER_RECORD_REQUIRE_REGULAR| USER_RECORD_ALLOW_PER_MACHINE| USER_RECORD_ALLOW_BINDING| USER_RECORD_ALLOW_SIGNATURE| (have_privileged ? USER_RECORD_ALLOW_PRIVILEGED : 0)| USER_RECORD_PERMISSIVE); if (r < 0) return r; if (name && !streq_ptr(name, g->group_name)) return -EINVAL; if (gid_is_valid(gid) && gid != g->gid) return -EINVAL; g->incomplete = !have_privileged; if (ret) *ret = TAKE_PTR(g); return 0; } int dropin_group_record_by_name(const char *name, const char *path, UserDBFlags flags, GroupRecord **ret) { _cleanup_free_ char *found_path = NULL; _cleanup_fclose_ FILE *f = NULL; int r; assert(name); if (path) { f = fopen(path, "re"); if (!f) return errno == ENOENT ? -ESRCH : -errno; } else { const char *j; j = strjoina(name, ".group"); if (!filename_is_valid(j)) /* Doesn't qualify as valid filename? Then it's definitely not provided as a drop-in */ return -ESRCH; r = search_and_fopen_nulstr(j, "re", NULL, USERDB_DROPIN_DIR_NULSTR("userdb"), &f, &found_path); if (r == -ENOENT) return -ESRCH; if (r < 0) return r; path = found_path; } return load_group(f, path, name, GID_INVALID, flags, ret); } int dropin_group_record_by_gid(gid_t gid, const char *path, UserDBFlags flags, GroupRecord **ret) { _cleanup_free_ char *found_path = NULL; _cleanup_fclose_ FILE *f = NULL; int r; assert(gid_is_valid(gid)); if (path) { f = fopen(path, "re"); if (!f) return errno == ENOENT ? -ESRCH : -errno; } else { char buf[DECIMAL_STR_MAX(gid_t) + STRLEN(".group") + 1]; xsprintf(buf, GID_FMT ".group", gid); r = search_and_fopen_nulstr(buf, "re", NULL, USERDB_DROPIN_DIR_NULSTR("userdb"), &f, &found_path); if (r == -ENOENT) return -ESRCH; if (r < 0) return r; path = found_path; } return load_group(f, path, NULL, gid, flags, ret); }
10,440
33.232787
130
c
null
systemd-main/src/shared/userdb-dropin.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "constants.h" #include "group-record.h" #include "user-record.h" #include "userdb.h" /* This could be put together with CONF_PATHS_NULSTR, with the exception of the /run/host/ part in the * middle, which we use here, but not otherwise. */ #define USERDB_DROPIN_DIR_NULSTR(n) \ "/etc/" n "\0" \ "/run/" n "\0" \ "/run/host/" n "\0" \ "/usr/local/lib/" n "\0" \ "/usr/lib/" n "\0" \ _CONF_PATHS_SPLIT_USR_NULSTR(n) int dropin_user_record_by_name(const char *name, const char *path, UserDBFlags flags, UserRecord **ret); int dropin_user_record_by_uid(uid_t uid, const char *path, UserDBFlags flags, UserRecord **ret); int dropin_group_record_by_name(const char *name, const char *path, UserDBFlags flags, GroupRecord **ret); int dropin_group_record_by_gid(gid_t gid, const char *path, UserDBFlags flags, GroupRecord **ret);
1,063
43.333333
106
h
null
systemd-main/src/shared/userdb.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <sys/socket.h> #include <sys/un.h> #include "group-record.h" #include "user-record.h" /* Inquire local services for user/group records */ typedef struct UserDBIterator UserDBIterator; UserDBIterator *userdb_iterator_free(UserDBIterator *iterator); DEFINE_TRIVIAL_CLEANUP_FUNC(UserDBIterator*, userdb_iterator_free); typedef enum UserDBFlags { /* The main sources */ USERDB_EXCLUDE_NSS = 1 << 0, /* don't do client-side nor server-side NSS */ USERDB_EXCLUDE_VARLINK = 1 << 1, /* don't talk to any varlink services */ USERDB_EXCLUDE_DROPIN = 1 << 2, /* don't load drop-in user/group definitions */ /* Modifications */ USERDB_SUPPRESS_SHADOW = 1 << 3, /* don't do client-side shadow calls (server side might happen though) */ USERDB_EXCLUDE_DYNAMIC_USER = 1 << 4, /* exclude looking up in io.systemd.DynamicUser */ USERDB_AVOID_MULTIPLEXER = 1 << 5, /* exclude looking up via io.systemd.Multiplexer */ USERDB_DONT_SYNTHESIZE = 1 << 6, /* don't synthesize root/nobody */ /* Combinations */ USERDB_NSS_ONLY = USERDB_EXCLUDE_VARLINK|USERDB_EXCLUDE_DROPIN|USERDB_DONT_SYNTHESIZE, USERDB_DROPIN_ONLY = USERDB_EXCLUDE_NSS|USERDB_EXCLUDE_VARLINK|USERDB_DONT_SYNTHESIZE, } UserDBFlags; /* Well-known errors we'll return here: * * -ESRCH: No such user/group * -ELINK: Varlink logic turned off (and no other source available) * -EOPNOTSUPP: Enumeration not supported * -ETIMEDOUT: Time-out */ int userdb_by_name(const char *name, UserDBFlags flags, UserRecord **ret); int userdb_by_uid(uid_t uid, UserDBFlags flags, UserRecord **ret); int userdb_all(UserDBFlags flags, UserDBIterator **ret); int userdb_iterator_get(UserDBIterator *iterator, UserRecord **ret); int groupdb_by_name(const char *name, UserDBFlags flags, GroupRecord **ret); int groupdb_by_gid(gid_t gid, UserDBFlags flags, GroupRecord **ret); int groupdb_all(UserDBFlags flags, UserDBIterator **ret); int groupdb_iterator_get(UserDBIterator *iterator, GroupRecord **ret); int membershipdb_by_user(const char *name, UserDBFlags flags, UserDBIterator **ret); int membershipdb_by_group(const char *name, UserDBFlags flags, UserDBIterator **ret); int membershipdb_all(UserDBFlags flags, UserDBIterator **ret); int membershipdb_iterator_get(UserDBIterator *iterator, char **user, char **group); int membershipdb_by_group_strv(const char *name, UserDBFlags flags, char ***ret); int userdb_block_nss_systemd(int b);
2,597
43.033898
120
h
null
systemd-main/src/shared/utmp-wtmp.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/utsname.h> #include <unistd.h> #include <utmpx.h> #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "hostname-util.h" #include "io-util.h" #include "macro.h" #include "memory-util.h" #include "path-util.h" #include "string-util.h" #include "terminal-util.h" #include "time-util.h" #include "user-util.h" #include "utmp-wtmp.h" int utmp_get_runlevel(int *runlevel, int *previous) { _unused_ _cleanup_(utxent_cleanup) bool utmpx = false; struct utmpx *found, lookup = { .ut_type = RUN_LVL }; const char *e; assert(runlevel); /* If these values are set in the environment this takes * precedence. Presumably, sysvinit does this to work around a * race condition that would otherwise exist where we'd always * go to disk and hence might read runlevel data that might be * very new and not apply to the current script being executed. */ e = getenv("RUNLEVEL"); if (!isempty(e)) { *runlevel = e[0]; if (previous) *previous = 0; return 0; } if (utmpxname(_PATH_UTMPX) < 0) return -errno; utmpx = utxent_start(); found = getutxid(&lookup); if (!found) return -errno; *runlevel = found->ut_pid & 0xFF; if (previous) *previous = (found->ut_pid >> 8) & 0xFF; return 0; } static void init_timestamp(struct utmpx *store, usec_t t) { assert(store); if (t <= 0) t = now(CLOCK_REALTIME); store->ut_tv.tv_sec = t / USEC_PER_SEC; store->ut_tv.tv_usec = t % USEC_PER_SEC; } static void init_entry(struct utmpx *store, usec_t t) { struct utsname uts = {}; assert(store); init_timestamp(store, t); if (uname(&uts) >= 0) strncpy(store->ut_host, uts.release, sizeof(store->ut_host)); strncpy(store->ut_line, "~", sizeof(store->ut_line)); /* or ~~ ? */ strncpy(store->ut_id, "~~", sizeof(store->ut_id)); } static int write_entry_utmp(const struct utmpx *store) { _unused_ _cleanup_(utxent_cleanup) bool utmpx = false; assert(store); /* utmp is similar to wtmp, but there is only one entry for * each entry type resp. user; i.e. basically a key/value * table. */ if (utmpxname(_PATH_UTMPX) < 0) return -errno; utmpx = utxent_start(); if (pututxline(store)) return 0; if (errno == ENOENT) { /* If utmp/wtmp have been disabled, that's a good thing, hence ignore the error. */ log_debug_errno(errno, "Not writing utmp: %m"); return 0; } return -errno; } static int write_entry_wtmp(const struct utmpx *store) { assert(store); /* wtmp is a simple append-only file where each entry is * simply appended to the end; i.e. basically a log. */ errno = 0; updwtmpx(_PATH_WTMPX, store); if (errno == ENOENT) { /* If utmp/wtmp have been disabled, that's a good thing, hence ignore the error. */ log_debug_errno(errno, "Not writing wtmp: %m"); return 0; } if (errno == EROFS) { log_warning_errno(errno, "Failed to write wtmp record, ignoring: %m"); return 0; } return -errno; } static int write_utmp_wtmp(const struct utmpx *store_utmp, const struct utmpx *store_wtmp) { int r, s; r = write_entry_utmp(store_utmp); s = write_entry_wtmp(store_wtmp); return r < 0 ? r : s; } static int write_entry_both(const struct utmpx *store) { return write_utmp_wtmp(store, store); } int utmp_put_shutdown(void) { struct utmpx store = {}; init_entry(&store, 0); store.ut_type = RUN_LVL; strncpy(store.ut_user, "shutdown", sizeof(store.ut_user)); return write_entry_both(&store); } int utmp_put_reboot(usec_t t) { struct utmpx store = {}; init_entry(&store, t); store.ut_type = BOOT_TIME; strncpy(store.ut_user, "reboot", sizeof(store.ut_user)); return write_entry_both(&store); } static void copy_suffix(char *buf, size_t buf_size, const char *src) { size_t l; l = strlen(src); if (l < buf_size) strncpy(buf, src, buf_size); else memcpy(buf, src + l - buf_size, buf_size); } int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line, int ut_type, const char *user) { struct utmpx store = { .ut_type = INIT_PROCESS, .ut_pid = pid, .ut_session = sid, }; int r; assert(id); init_timestamp(&store, 0); /* Copy the whole string if it fits, or just the suffix without the terminating NUL. */ copy_suffix(store.ut_id, sizeof(store.ut_id), id); if (line) strncpy_exact(store.ut_line, line, sizeof(store.ut_line)); r = write_entry_both(&store); if (r < 0) return r; if (IN_SET(ut_type, LOGIN_PROCESS, USER_PROCESS)) { store.ut_type = LOGIN_PROCESS; r = write_entry_both(&store); if (r < 0) return r; } if (ut_type == USER_PROCESS) { store.ut_type = USER_PROCESS; strncpy(store.ut_user, user, sizeof(store.ut_user)-1); r = write_entry_both(&store); if (r < 0) return r; } return 0; } int utmp_put_dead_process(const char *id, pid_t pid, int code, int status) { _unused_ _cleanup_(utxent_cleanup) bool utmpx = false; struct utmpx lookup = { .ut_type = INIT_PROCESS /* looks for DEAD_PROCESS, LOGIN_PROCESS, USER_PROCESS, too */ }, store, store_wtmp, *found; assert(id); utmpx = utxent_start(); /* Copy the whole string if it fits, or just the suffix without the terminating NUL. */ copy_suffix(store.ut_id, sizeof(store.ut_id), id); found = getutxid(&lookup); if (!found) return 0; if (found->ut_pid != pid) return 0; memcpy(&store, found, sizeof(store)); store.ut_type = DEAD_PROCESS; store.ut_exit.e_termination = code; store.ut_exit.e_exit = status; zero(store.ut_user); zero(store.ut_host); zero(store.ut_tv); memcpy(&store_wtmp, &store, sizeof(store_wtmp)); /* wtmp wants the current time */ init_timestamp(&store_wtmp, 0); return write_utmp_wtmp(&store, &store_wtmp); } int utmp_put_runlevel(int runlevel, int previous) { struct utmpx store = {}; int r; assert(runlevel > 0); if (previous <= 0) { /* Find the old runlevel automatically */ r = utmp_get_runlevel(&previous, NULL); if (r < 0) { if (r != -ESRCH) return r; previous = 0; } } if (previous == runlevel) return 0; init_entry(&store, 0); store.ut_type = RUN_LVL; store.ut_pid = (runlevel & 0xFF) | ((previous & 0xFF) << 8); strncpy(store.ut_user, "runlevel", sizeof(store.ut_user)); return write_entry_both(&store); } #define TIMEOUT_USEC (50 * USEC_PER_MSEC) static int write_to_terminal(const char *tty, const char *message) { _cleanup_close_ int fd = -EBADF; const char *p; size_t left; usec_t end; assert(tty); assert(message); fd = open(tty, O_WRONLY|O_NONBLOCK|O_NOCTTY|O_CLOEXEC); if (fd < 0) return -errno; if (!isatty(fd)) return -ENOTTY; p = message; left = strlen(message); end = usec_add(now(CLOCK_MONOTONIC), TIMEOUT_USEC); while (left > 0) { ssize_t n; usec_t t; int k; t = now(CLOCK_MONOTONIC); if (t >= end) return -ETIME; k = fd_wait_for_event(fd, POLLOUT, end - t); if (k < 0) { if (ERRNO_IS_TRANSIENT(k)) continue; return k; } if (k == 0) return -ETIME; n = write(fd, p, left); if (n < 0) { if (ERRNO_IS_TRANSIENT(errno)) continue; return -errno; } assert((size_t) n <= left); p += n; left -= n; } return 0; } int utmp_wall( const char *message, const char *username, const char *origin_tty, bool (*match_tty)(const char *tty, bool is_local, void *userdata), void *userdata) { _unused_ _cleanup_(utxent_cleanup) bool utmpx = false; _cleanup_free_ char *text = NULL, *hn = NULL, *un = NULL, *stdin_tty = NULL; struct utmpx *u; int r; hn = gethostname_malloc(); if (!hn) return -ENOMEM; if (!username) { un = getlogname_malloc(); if (!un) return -ENOMEM; } if (!origin_tty) { getttyname_harder(STDIN_FILENO, &stdin_tty); origin_tty = stdin_tty; } if (asprintf(&text, "\r\n" "Broadcast message from %s@%s%s%s (%s):\r\n\r\n" "%s\r\n\r\n", un ?: username, hn, origin_tty ? " on " : "", strempty(origin_tty), FORMAT_TIMESTAMP(now(CLOCK_REALTIME)), message) < 0) return -ENOMEM; utmpx = utxent_start(); r = 0; while ((u = getutxent())) { _cleanup_free_ char *buf = NULL; const char *path; int q; if (u->ut_type != USER_PROCESS || u->ut_user[0] == 0) continue; /* This access is fine, because strlen("/dev/") < 32 (UT_LINESIZE) */ if (path_startswith(u->ut_line, "/dev/")) path = u->ut_line; else { if (asprintf(&buf, "/dev/%.*s", (int) sizeof(u->ut_line), u->ut_line) < 0) return -ENOMEM; path = buf; } /* It seems that the address field is always set for remote logins. * For local logins and other local entries, we get [0,0,0,0]. */ bool is_local = memeqzero(u->ut_addr_v6, sizeof(u->ut_addr_v6)); if (!match_tty || match_tty(path, is_local, userdata)) { q = write_to_terminal(path, text); if (q < 0) r = q; } } return r; }
11,668
27.391727
114
c
null
systemd-main/src/shared/utmp-wtmp.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <sys/types.h> #include "time-util.h" #if ENABLE_UTMP #include <utmpx.h> int utmp_get_runlevel(int *runlevel, int *previous); int utmp_put_shutdown(void); int utmp_put_reboot(usec_t timestamp); int utmp_put_runlevel(int runlevel, int previous); int utmp_put_dead_process(const char *id, pid_t pid, int code, int status); int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line, int ut_type, const char *user); int utmp_wall( const char *message, const char *username, const char *origin_tty, bool (*match_tty)(const char *tty, bool is_local, void *userdata), void *userdata); static inline bool utxent_start(void) { setutxent(); return true; } static inline void utxent_cleanup(bool *initialized) { if (initialized) endutxent(); } #else /* ENABLE_UTMP */ static inline int utmp_get_runlevel(int *runlevel, int *previous) { return -ESRCH; } static inline int utmp_put_shutdown(void) { return 0; } static inline int utmp_put_reboot(usec_t timestamp) { return 0; } static inline int utmp_put_runlevel(int runlevel, int previous) { return 0; } static inline int utmp_put_dead_process(const char *id, pid_t pid, int code, int status) { return 0; } static inline int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line, int ut_type, const char *user) { return 0; } static inline int utmp_wall( const char *message, const char *username, const char *origin_tty, bool (*match_tty)(const char *tty, bool is_local, void *userdata), void *userdata) { return 0; } #endif /* ENABLE_UTMP */
1,845
26.552239
128
h
null
systemd-main/src/shared/verb-log-control.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "bus-error.h" #include "log.h" #include "strv.h" #include "syslog-util.h" #include "verb-log-control.h" int verb_log_control_common(sd_bus *bus, const char *destination, const char *verb, const char *value) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; bool level = endswith(verb, "log-level"); const BusLocator bloc = { .destination = destination, .path = "/org/freedesktop/LogControl1", .interface = "org.freedesktop.LogControl1", }; int r; assert(bus); assert(endswith(verb, "log-level") || endswith(verb, "log-target")); if (value) { if (level) { r = log_level_from_string(value); if (r < 0) return log_error_errno(r, "\"%s\" is not a valid log level.", value); } r = bus_set_property(bus, &bloc, level ? "LogLevel" : "LogTarget", &error, "s", value); if (r < 0) return log_error_errno(r, "Failed to set log %s of %s to %s: %s", level ? "level" : "target", bloc.destination, value, bus_error_message(&error, r)); } else { _cleanup_free_ char *t = NULL; r = bus_get_property_string(bus, &bloc, level ? "LogLevel" : "LogTarget", &error, &t); if (r < 0) return log_error_errno(r, "Failed to get log %s of %s: %s", level ? "level" : "target", bloc.destination, bus_error_message(&error, r)); puts(t); } return 0; }
2,071
38.846154
104
c
null
systemd-main/src/shared/verbs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <stdbool.h> #include <stddef.h> #include "env-util.h" #include "log.h" #include "macro.h" #include "process-util.h" #include "string-util.h" #include "verbs.h" #include "virt.h" /* Wraps running_in_chroot() which is used in various places, but also adds an environment variable check so external * processes can reliably force this on. */ bool running_in_chroot_or_offline(void) { int r; /* Added to support use cases like rpm-ostree, where from %post scripts we only want to execute "preset", but * not "start"/"restart" for example. * * See docs/ENVIRONMENT.md for docs. */ r = getenv_bool("SYSTEMD_OFFLINE"); if (r < 0 && r != -ENXIO) log_debug_errno(r, "Failed to parse $SYSTEMD_OFFLINE: %m"); else if (r >= 0) return r > 0; /* We've had this condition check for a long time which basically checks for legacy chroot case like Fedora's * "mock", which is used for package builds. We don't want to try to start systemd services there, since * without --new-chroot we don't even have systemd running, and even if we did, adding a concept of background * daemons to builds would be an enormous change, requiring considering things like how the journal output is * handled, etc. And there's really not a use case today for a build talking to a service. * * Note this call itself also looks for a different variable SYSTEMD_IGNORE_CHROOT=1. */ r = running_in_chroot(); if (r < 0) log_debug_errno(r, "running_in_chroot(): %m"); return r > 0; } const Verb* verbs_find_verb(const char *name, const Verb verbs[]) { for (size_t i = 0; verbs[i].dispatch; i++) if (streq_ptr(name, verbs[i].verb) || (!name && FLAGS_SET(verbs[i].flags, VERB_DEFAULT))) return &verbs[i]; /* At the end of the list? */ return NULL; } int dispatch_verb(int argc, char *argv[], const Verb verbs[], void *userdata) { const Verb *verb; const char *name; int left; assert(verbs); assert(verbs[0].dispatch); assert(argc >= 0); assert(argv); assert(argc >= optind); left = argc - optind; argv += optind; optind = 0; name = argv[0]; verb = verbs_find_verb(name, verbs); if (!verb) { if (name) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command verb %s.", name); else return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command verb required."); } if (!name) left = 1; if (verb->min_args != VERB_ANY && (unsigned) left < verb->min_args) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too few arguments."); if (verb->max_args != VERB_ANY && (unsigned) left > verb->max_args) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments."); if ((verb->flags & VERB_ONLINE_ONLY) && running_in_chroot_or_offline()) { log_info("Running in chroot, ignoring command '%s'", name ?: verb->verb); return 0; } if (name) return verb->dispatch(left, argv, userdata); else { char* fake[2] = { (char*) verb->verb, NULL }; return verb->dispatch(1, fake, userdata); } }
3,909
33.60177
118
c
null
systemd-main/src/shared/verbs.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #define VERB_ANY (UINT_MAX) typedef enum VerbFlags { VERB_DEFAULT = 1 << 0, /* The verb to run if no verb is specified */ VERB_ONLINE_ONLY = 1 << 1, /* Just do nothing when running in chroot or offline */ } VerbFlags; typedef struct { const char *verb; unsigned min_args, max_args; VerbFlags flags; int (* const dispatch)(int argc, char *argv[], void *userdata); } Verb; bool running_in_chroot_or_offline(void); const Verb* verbs_find_verb(const char *name, const Verb verbs[]); int dispatch_verb(int argc, char *argv[], const Verb verbs[], void *userdata);
703
28.333333
92
h
null
systemd-main/src/shared/vlan-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "conf-parser.h" #include "parse-util.h" #include "string-util.h" #include "vlan-util.h" int parse_vlanid(const char *p, uint16_t *ret) { uint16_t id; int r; assert(p); assert(ret); r = safe_atou16(p, &id); if (r < 0) return r; if (!vlanid_is_valid(id)) return -ERANGE; *ret = id; return 0; } int parse_vid_range(const char *p, uint16_t *vid, uint16_t *vid_end) { unsigned lower, upper; int r; r = parse_range(p, &lower, &upper); if (r < 0) return r; if (lower > VLANID_MAX || upper > VLANID_MAX || lower > upper) return -EINVAL; *vid = lower; *vid_end = upper; return 0; } int config_parse_default_port_vlanid( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { uint16_t *id = ASSERT_PTR(data); assert(lvalue); assert(rvalue); if (streq(rvalue, "none")) { *id = 0; return 0; } return config_parse_vlanid(unit, filename, line, section, section_line, lvalue, ltype, rvalue, data, userdata); } int config_parse_vlanid( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { uint16_t *id = ASSERT_PTR(data); int r; assert(filename); assert(lvalue); assert(rvalue); r = parse_vlanid(rvalue, id); if (r == -ERANGE) { log_syntax(unit, LOG_WARNING, filename, line, r, "VLAN identifier outside of valid range 0…4094, ignoring: %s", rvalue); return 0; } if (r < 0) { log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse VLAN identifier value, ignoring: %s", rvalue); return 0; } return 0; }
2,565
24.919192
98
c
null
systemd-main/src/shared/vlan-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <inttypes.h> #include "conf-parser.h" #define VLANID_MAX 4094 #define VLANID_INVALID UINT16_MAX /* Note that we permit VLAN Id 0 here, as that is apparently OK by the Linux kernel */ static inline bool vlanid_is_valid(uint16_t id) { return id <= VLANID_MAX; } int parse_vlanid(const char *p, uint16_t *ret); int parse_vid_range(const char *p, uint16_t *vid, uint16_t *vid_end); CONFIG_PARSER_PROTOTYPE(config_parse_default_port_vlanid); CONFIG_PARSER_PROTOTYPE(config_parse_vlanid);
589
25.818182
86
h
null
systemd-main/src/shared/volatile-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include "alloc-util.h" #include "macro.h" #include "parse-util.h" #include "proc-cmdline.h" #include "string-table.h" #include "string-util.h" #include "volatile-util.h" int query_volatile_mode(VolatileMode *ret) { _cleanup_free_ char *mode = NULL; int r; r = proc_cmdline_get_key("systemd.volatile", PROC_CMDLINE_VALUE_OPTIONAL, &mode); if (r < 0) return r; if (r == 0) { *ret = VOLATILE_NO; return 0; } if (mode) { VolatileMode m; m = volatile_mode_from_string(mode); if (m < 0) return m; *ret = m; } else *ret = VOLATILE_YES; return 1; } static const char* const volatile_mode_table[_VOLATILE_MODE_MAX] = { [VOLATILE_NO] = "no", [VOLATILE_YES] = "yes", [VOLATILE_STATE] = "state", [VOLATILE_OVERLAY] = "overlay", }; DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(volatile_mode, VolatileMode, VOLATILE_YES);
1,138
23.234043
89
c
null
systemd-main/src/shared/watchdog.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "time-util.h" const char *watchdog_get_device(void); usec_t watchdog_get_last_ping(clockid_t clock); int watchdog_set_device(const char *path); int watchdog_setup(usec_t timeout); int watchdog_setup_pretimeout(usec_t usec); int watchdog_setup_pretimeout_governor(const char *governor); int watchdog_ping(void); void watchdog_close(bool disarm); usec_t watchdog_runtime_wait(void); static inline void watchdog_free_device(void) { (void) watchdog_set_device(NULL); }
570
24.954545
61
h
null
systemd-main/src/shared/wifi-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "log.h" #include "string-table.h" #include "string-util.h" #include "wifi-util.h" int wifi_get_interface(sd_netlink *genl, int ifindex, enum nl80211_iftype *ret_iftype, char **ret_ssid) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL, *reply = NULL; _cleanup_free_ char *ssid = NULL; const char *family; uint32_t iftype; size_t len; int r; assert(genl); assert(ifindex > 0); r = sd_genl_message_new(genl, NL80211_GENL_NAME, NL80211_CMD_GET_INTERFACE, &m); if (r < 0) return log_debug_errno(r, "Failed to create generic netlink message: %m"); r = sd_netlink_message_append_u32(m, NL80211_ATTR_IFINDEX, ifindex); if (r < 0) return log_debug_errno(r, "Could not append NL80211_ATTR_IFINDEX attribute: %m"); r = sd_netlink_call(genl, m, 0, &reply); if (r == -ENODEV) { /* For obsolete WEXT driver. */ log_debug_errno(r, "Failed to request information about wifi interface %d. " "The device doesn't seem to have nl80211 interface. Ignoring.", ifindex); goto nodata; } if (r < 0) return log_debug_errno(r, "Failed to request information about wifi interface %d: %m", ifindex); if (!reply) { log_debug("No reply received to request for information about wifi interface %d, ignoring.", ifindex); goto nodata; } r = sd_netlink_message_get_errno(reply); if (r < 0) return log_debug_errno(r, "Failed to get information about wifi interface %d: %m", ifindex); r = sd_genl_message_get_family_name(genl, reply, &family); if (r < 0) return log_debug_errno(r, "Failed to determine genl family: %m"); if (!streq(family, NL80211_GENL_NAME)) { log_debug("Received message of unexpected genl family '%s', ignoring.", family); goto nodata; } r = sd_netlink_message_read_u32(reply, NL80211_ATTR_IFTYPE, &iftype); if (r < 0) return log_debug_errno(r, "Failed to get NL80211_ATTR_IFTYPE attribute: %m"); r = sd_netlink_message_read_data_suffix0(reply, NL80211_ATTR_SSID, &len, (void**) &ssid); if (r < 0 && r != -ENODATA) return log_debug_errno(r, "Failed to get NL80211_ATTR_SSID attribute: %m"); if (r >= 0) { if (len == 0) { log_debug("SSID has zero length, ignoring it."); ssid = mfree(ssid); } else if (strlen_ptr(ssid) != len) { log_debug("SSID contains NUL characters, ignoring it."); ssid = mfree(ssid); } } if (ret_iftype) *ret_iftype = iftype; if (ret_ssid) *ret_ssid = TAKE_PTR(ssid); return 1; nodata: if (ret_iftype) *ret_iftype = 0; if (ret_ssid) *ret_ssid = NULL; return 0; } int wifi_get_station(sd_netlink *genl, int ifindex, struct ether_addr *ret_bssid) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL, *reply = NULL; const char *family; int r; assert(genl); assert(ifindex > 0); assert(ret_bssid); r = sd_genl_message_new(genl, NL80211_GENL_NAME, NL80211_CMD_GET_STATION, &m); if (r < 0) return log_debug_errno(r, "Failed to create generic netlink message: %m"); r = sd_netlink_message_set_flags(m, NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP); if (r < 0) return log_debug_errno(r, "Failed to set dump flag: %m"); r = sd_netlink_message_append_u32(m, NL80211_ATTR_IFINDEX, ifindex); if (r < 0) return log_debug_errno(r, "Could not append NL80211_ATTR_IFINDEX attribute: %m"); r = sd_netlink_call(genl, m, 0, &reply); if (r < 0) return log_debug_errno(r, "Failed to request information about wifi station: %m"); if (!reply) { log_debug("No reply received to request for information about wifi station, ignoring."); goto nodata; } r = sd_netlink_message_get_errno(reply); if (r < 0) return log_debug_errno(r, "Failed to get information about wifi station: %m"); r = sd_genl_message_get_family_name(genl, reply, &family); if (r < 0) return log_debug_errno(r, "Failed to determine genl family: %m"); if (!streq(family, NL80211_GENL_NAME)) { log_debug("Received message of unexpected genl family '%s', ignoring.", family); goto nodata; } r = sd_netlink_message_read_ether_addr(reply, NL80211_ATTR_MAC, ret_bssid); if (r == -ENODATA) goto nodata; if (r < 0) return log_debug_errno(r, "Failed to get NL80211_ATTR_MAC attribute: %m"); return 1; nodata: *ret_bssid = ETHER_ADDR_NULL; return 0; } static const char * const nl80211_iftype_table[NUM_NL80211_IFTYPES] = { [NL80211_IFTYPE_ADHOC] = "ad-hoc", [NL80211_IFTYPE_STATION] = "station", [NL80211_IFTYPE_AP] = "ap", [NL80211_IFTYPE_AP_VLAN] = "ap-vlan", [NL80211_IFTYPE_WDS] = "wds", [NL80211_IFTYPE_MONITOR] = "monitor", [NL80211_IFTYPE_MESH_POINT] = "mesh-point", [NL80211_IFTYPE_P2P_CLIENT] = "p2p-client", [NL80211_IFTYPE_P2P_GO] = "p2p-go", [NL80211_IFTYPE_P2P_DEVICE] = "p2p-device", [NL80211_IFTYPE_OCB] = "ocb", [NL80211_IFTYPE_NAN] = "nan", }; DEFINE_STRING_TABLE_LOOKUP(nl80211_iftype, enum nl80211_iftype); static const char * const nl80211_cmd_table[__NL80211_CMD_AFTER_LAST] = { [NL80211_CMD_GET_WIPHY] = "get_wiphy", [NL80211_CMD_SET_WIPHY] = "set_wiphy", [NL80211_CMD_NEW_WIPHY] = "new_wiphy", [NL80211_CMD_DEL_WIPHY] = "del_wiphy", [NL80211_CMD_GET_INTERFACE] = "get_interface", [NL80211_CMD_SET_INTERFACE] = "set_interface", [NL80211_CMD_NEW_INTERFACE] = "new_interface", [NL80211_CMD_DEL_INTERFACE] = "del_interface", [NL80211_CMD_GET_KEY] = "get_key", [NL80211_CMD_SET_KEY] = "set_key", [NL80211_CMD_NEW_KEY] = "new_key", [NL80211_CMD_DEL_KEY] = "del_key", [NL80211_CMD_GET_BEACON] = "get_beacon", [NL80211_CMD_SET_BEACON] = "set_beacon", [NL80211_CMD_START_AP] = "start_ap", [NL80211_CMD_STOP_AP] = "stop_ap", [NL80211_CMD_GET_STATION] = "get_station", [NL80211_CMD_SET_STATION] = "set_station", [NL80211_CMD_NEW_STATION] = "new_station", [NL80211_CMD_DEL_STATION] = "del_station", [NL80211_CMD_GET_MPATH] = "get_mpath", [NL80211_CMD_SET_MPATH] = "set_mpath", [NL80211_CMD_NEW_MPATH] = "new_mpath", [NL80211_CMD_DEL_MPATH] = "del_mpath", [NL80211_CMD_SET_BSS] = "set_bss", [NL80211_CMD_SET_REG] = "set_reg", [NL80211_CMD_REQ_SET_REG] = "req_set_reg", [NL80211_CMD_GET_MESH_CONFIG] = "get_mesh_config", [NL80211_CMD_SET_MESH_CONFIG] = "set_mesh_config", [NL80211_CMD_SET_MGMT_EXTRA_IE] = "set_mgmt_extra_ie", [NL80211_CMD_GET_REG] = "get_reg", [NL80211_CMD_GET_SCAN] = "get_scan", [NL80211_CMD_TRIGGER_SCAN] = "trigger_scan", [NL80211_CMD_NEW_SCAN_RESULTS] = "new_scan_results", [NL80211_CMD_SCAN_ABORTED] = "scan_aborted", [NL80211_CMD_REG_CHANGE] = "reg_change", [NL80211_CMD_AUTHENTICATE] = "authenticate", [NL80211_CMD_ASSOCIATE] = "associate", [NL80211_CMD_DEAUTHENTICATE] = "deauthenticate", [NL80211_CMD_DISASSOCIATE] = "disassociate", [NL80211_CMD_MICHAEL_MIC_FAILURE] = "michael_mic_failure", [NL80211_CMD_REG_BEACON_HINT] = "reg_beacon_hint", [NL80211_CMD_JOIN_IBSS] = "join_ibss", [NL80211_CMD_LEAVE_IBSS] = "leave_ibss", [NL80211_CMD_TESTMODE] = "testmode", [NL80211_CMD_CONNECT] = "connect", [NL80211_CMD_ROAM] = "roam", [NL80211_CMD_DISCONNECT] = "disconnect", [NL80211_CMD_SET_WIPHY_NETNS] = "set_wiphy_netns", [NL80211_CMD_GET_SURVEY] = "get_survey", [NL80211_CMD_NEW_SURVEY_RESULTS] = "new_survey_results", [NL80211_CMD_SET_PMKSA] = "set_pmksa", [NL80211_CMD_DEL_PMKSA] = "del_pmksa", [NL80211_CMD_FLUSH_PMKSA] = "flush_pmksa", [NL80211_CMD_REMAIN_ON_CHANNEL] = "remain_on_channel", [NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL] = "cancel_remain_on_channel", [NL80211_CMD_SET_TX_BITRATE_MASK] = "set_tx_bitrate_mask", [NL80211_CMD_REGISTER_FRAME] = "register_frame", [NL80211_CMD_FRAME] = "frame", [NL80211_CMD_FRAME_TX_STATUS] = "frame_tx_status", [NL80211_CMD_SET_POWER_SAVE] = "set_power_save", [NL80211_CMD_GET_POWER_SAVE] = "get_power_save", [NL80211_CMD_SET_CQM] = "set_cqm", [NL80211_CMD_NOTIFY_CQM] = "notify_cqm", [NL80211_CMD_SET_CHANNEL] = "set_channel", [NL80211_CMD_SET_WDS_PEER] = "set_wds_peer", [NL80211_CMD_FRAME_WAIT_CANCEL] = "frame_wait_cancel", [NL80211_CMD_JOIN_MESH] = "join_mesh", [NL80211_CMD_LEAVE_MESH] = "leave_mesh", [NL80211_CMD_UNPROT_DEAUTHENTICATE] = "unprot_deauthenticate", [NL80211_CMD_UNPROT_DISASSOCIATE] = "unprot_disassociate", [NL80211_CMD_NEW_PEER_CANDIDATE] = "new_peer_candidate", [NL80211_CMD_GET_WOWLAN] = "get_wowlan", [NL80211_CMD_SET_WOWLAN] = "set_wowlan", [NL80211_CMD_START_SCHED_SCAN] = "start_sched_scan", [NL80211_CMD_STOP_SCHED_SCAN] = "stop_sched_scan", [NL80211_CMD_SCHED_SCAN_RESULTS] = "sched_scan_results", [NL80211_CMD_SCHED_SCAN_STOPPED] = "sched_scan_stopped", [NL80211_CMD_SET_REKEY_OFFLOAD] = "set_rekey_offload", [NL80211_CMD_PMKSA_CANDIDATE] = "pmksa_candidate", [NL80211_CMD_TDLS_OPER] = "tdls_oper", [NL80211_CMD_TDLS_MGMT] = "tdls_mgmt", [NL80211_CMD_UNEXPECTED_FRAME] = "unexpected_frame", [NL80211_CMD_PROBE_CLIENT] = "probe_client", [NL80211_CMD_REGISTER_BEACONS] = "register_beacons", [NL80211_CMD_UNEXPECTED_4ADDR_FRAME] = "unexpected_4addr_frame", [NL80211_CMD_SET_NOACK_MAP] = "set_noack_map", [NL80211_CMD_CH_SWITCH_NOTIFY] = "ch_switch_notify", [NL80211_CMD_START_P2P_DEVICE] = "start_p2p_device", [NL80211_CMD_STOP_P2P_DEVICE] = "stop_p2p_device", [NL80211_CMD_CONN_FAILED] = "conn_failed", [NL80211_CMD_SET_MCAST_RATE] = "set_mcast_rate", [NL80211_CMD_SET_MAC_ACL] = "set_mac_acl", [NL80211_CMD_RADAR_DETECT] = "radar_detect", [NL80211_CMD_GET_PROTOCOL_FEATURES] = "get_protocol_features", [NL80211_CMD_UPDATE_FT_IES] = "update_ft_ies", [NL80211_CMD_FT_EVENT] = "ft_event", [NL80211_CMD_CRIT_PROTOCOL_START] = "crit_protocol_start", [NL80211_CMD_CRIT_PROTOCOL_STOP] = "crit_protocol_stop", [NL80211_CMD_GET_COALESCE] = "get_coalesce", [NL80211_CMD_SET_COALESCE] = "set_coalesce", [NL80211_CMD_CHANNEL_SWITCH] = "channel_switch", [NL80211_CMD_VENDOR] = "vendor", [NL80211_CMD_SET_QOS_MAP] = "set_qos_map", [NL80211_CMD_ADD_TX_TS] = "add_tx_ts", [NL80211_CMD_DEL_TX_TS] = "del_tx_ts", [NL80211_CMD_GET_MPP] = "get_mpp", [NL80211_CMD_JOIN_OCB] = "join_ocb", [NL80211_CMD_LEAVE_OCB] = "leave_ocb", [NL80211_CMD_CH_SWITCH_STARTED_NOTIFY] = "ch_switch_started_notify", [NL80211_CMD_TDLS_CHANNEL_SWITCH] = "tdls_channel_switch", [NL80211_CMD_TDLS_CANCEL_CHANNEL_SWITCH] = "tdls_cancel_channel_switch", [NL80211_CMD_WIPHY_REG_CHANGE] = "wiphy_reg_change", [NL80211_CMD_ABORT_SCAN] = "abort_scan", [NL80211_CMD_START_NAN] = "start_nan", [NL80211_CMD_STOP_NAN] = "stop_nan", [NL80211_CMD_ADD_NAN_FUNCTION] = "add_nan_function", [NL80211_CMD_DEL_NAN_FUNCTION] = "del_nan_function", [NL80211_CMD_CHANGE_NAN_CONFIG] = "change_nan_config", [NL80211_CMD_NAN_MATCH] = "nan_match", [NL80211_CMD_SET_MULTICAST_TO_UNICAST] = "set_multicast_to_unicast", [NL80211_CMD_UPDATE_CONNECT_PARAMS] = "update_connect_params", [NL80211_CMD_SET_PMK] = "set_pmk", [NL80211_CMD_DEL_PMK] = "del_pmk", [NL80211_CMD_PORT_AUTHORIZED] = "port_authorized", [NL80211_CMD_RELOAD_REGDB] = "reload_regdb", [NL80211_CMD_EXTERNAL_AUTH] = "external_auth", [NL80211_CMD_STA_OPMODE_CHANGED] = "sta_opmode_changed", [NL80211_CMD_CONTROL_PORT_FRAME] = "control_port_frame", [NL80211_CMD_GET_FTM_RESPONDER_STATS] = "get_ftm_responder_stats", [NL80211_CMD_PEER_MEASUREMENT_START] = "peer_measurement_start", [NL80211_CMD_PEER_MEASUREMENT_RESULT] = "peer_measurement_result", [NL80211_CMD_PEER_MEASUREMENT_COMPLETE] = "peer_measurement_complete", [NL80211_CMD_NOTIFY_RADAR] = "notify_radar", [NL80211_CMD_UPDATE_OWE_INFO] = "update_owe_info", [NL80211_CMD_PROBE_MESH_LINK] = "probe_mesh_link", [NL80211_CMD_SET_TID_CONFIG] = "set_tid_config", [NL80211_CMD_UNPROT_BEACON] = "unprot_beacon", [NL80211_CMD_CONTROL_PORT_FRAME_TX_STATUS] = "control_port_frame_tx_status", [NL80211_CMD_SET_SAR_SPECS] = "set_sar_specs", [NL80211_CMD_OBSS_COLOR_COLLISION] = "obss_color_collision", [NL80211_CMD_COLOR_CHANGE_REQUEST] = "color_change_request", [NL80211_CMD_COLOR_CHANGE_STARTED] = "color_change_started", [NL80211_CMD_COLOR_CHANGE_ABORTED] = "color_change_aborted", [NL80211_CMD_COLOR_CHANGE_COMPLETED] = "color_change_completed", }; DEFINE_STRING_TABLE_LOOKUP_TO_STRING(nl80211_cmd, int);
14,205
45.273616
118
c
null
systemd-main/src/shared/wifi-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <linux/nl80211.h> #include "sd-netlink.h" #include "ether-addr-util.h" int wifi_get_interface(sd_netlink *genl, int ifindex, enum nl80211_iftype *ret_iftype, char **ret_ssid); int wifi_get_station(sd_netlink *genl, int ifindex, struct ether_addr *ret_bssid); const char *nl80211_iftype_to_string(enum nl80211_iftype iftype) _const_; enum nl80211_iftype nl80211_iftype_from_string(const char *s) _pure_; const char *nl80211_cmd_to_string(int cmd) _const_;
532
30.352941
104
h
null
systemd-main/src/shared/xml.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stddef.h> #include "macro.h" #include "string-util.h" #include "xml.h" enum { STATE_NULL, STATE_TEXT, STATE_TAG, STATE_ATTRIBUTE, }; static void inc_lines(unsigned *line, const char *s, size_t n) { const char *p = s; if (!line) return; for (;;) { const char *f; f = memchr(p, '\n', n); if (!f) return; n -= (f - p) + 1; p = f + 1; (*line)++; } } /* We don't actually do real XML here. We only read a simplistic * subset, that is a bit less strict that XML and lacks all the more * complex features, like entities, or namespaces. However, we do * support some HTML5-like simplifications */ int xml_tokenize(const char **p, char **name, void **state, unsigned *line) { const char *c, *e, *b; char *ret; int t; assert(p); assert(*p); assert(name); assert(state); t = PTR_TO_INT(*state); c = *p; if (t == STATE_NULL) { if (line) *line = 1; t = STATE_TEXT; } for (;;) { if (*c == 0) return XML_END; switch (t) { case STATE_TEXT: { int x; e = strchrnul(c, '<'); if (e > c) { /* More text... */ ret = strndup(c, e - c); if (!ret) return -ENOMEM; inc_lines(line, c, e - c); *name = ret; *p = e; *state = INT_TO_PTR(STATE_TEXT); return XML_TEXT; } assert(*e == '<'); b = c + 1; if (startswith(b, "!--")) { /* A comment */ e = strstrafter(b + 3, "-->"); if (!e) return -EINVAL; inc_lines(line, b, e - b); c = e; continue; } if (*b == '?') { /* Processing instruction */ e = strstrafter(b + 1, "?>"); if (!e) return -EINVAL; inc_lines(line, b, e - b); c = e; continue; } if (*b == '!') { /* DTD */ e = strchr(b + 1, '>'); if (!e) return -EINVAL; inc_lines(line, b, e + 1 - b); c = e + 1; continue; } if (*b == '/') { /* A closing tag */ x = XML_TAG_CLOSE; b++; } else x = XML_TAG_OPEN; e = strpbrk(b, WHITESPACE "/>"); if (!e) return -EINVAL; ret = strndup(b, e - b); if (!ret) return -ENOMEM; *name = ret; *p = e; *state = INT_TO_PTR(STATE_TAG); return x; } case STATE_TAG: b = c + strspn(c, WHITESPACE); if (*b == 0) return -EINVAL; inc_lines(line, c, b - c); e = b + strcspn(b, WHITESPACE "=/>"); if (e > b) { /* An attribute */ ret = strndup(b, e - b); if (!ret) return -ENOMEM; *name = ret; *p = e; *state = INT_TO_PTR(STATE_ATTRIBUTE); return XML_ATTRIBUTE_NAME; } if (startswith(b, "/>")) { /* An empty tag */ *name = NULL; /* For empty tags we return a NULL name, the caller must be prepared for that */ *p = b + 2; *state = INT_TO_PTR(STATE_TEXT); return XML_TAG_CLOSE_EMPTY; } if (*b != '>') return -EINVAL; c = b + 1; t = STATE_TEXT; continue; case STATE_ATTRIBUTE: if (*c == '=') { c++; if (IN_SET(*c, '\'', '"')) { /* Tag with a quoted value */ e = strchr(c+1, *c); if (!e) return -EINVAL; inc_lines(line, c, e - c); ret = strndup(c+1, e - c - 1); if (!ret) return -ENOMEM; *name = ret; *p = e + 1; *state = INT_TO_PTR(STATE_TAG); return XML_ATTRIBUTE_VALUE; } /* Tag with a value without quotes */ b = strpbrk(c, WHITESPACE ">"); if (!b) b = c; ret = strndup(c, b - c); if (!ret) return -ENOMEM; *name = ret; *p = b; *state = INT_TO_PTR(STATE_TAG); return XML_ATTRIBUTE_VALUE; } t = STATE_TAG; continue; } } assert_not_reached(); }
7,229
29.378151
126
c
null
systemd-main/src/shared/linux/auto_dev-ioctl.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 2008 Red Hat, Inc. All rights reserved. * Copyright 2008 Ian Kent <[email protected]> * * This file is part of the Linux kernel and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. */ #ifndef _LINUX_AUTO_DEV_IOCTL_H #define _LINUX_AUTO_DEV_IOCTL_H #include <linux/auto_fs.h> #include <linux/string.h> #define AUTOFS_DEVICE_NAME "autofs" #define AUTOFS_DEV_IOCTL_VERSION_MAJOR 1 #define AUTOFS_DEV_IOCTL_VERSION_MINOR 0 #define AUTOFS_DEV_IOCTL_SIZE sizeof(struct autofs_dev_ioctl) /* * An ioctl interface for autofs mount point control. */ struct args_protover { __u32 version; }; struct args_protosubver { __u32 sub_version; }; struct args_openmount { __u32 devid; }; struct args_ready { __u32 token; }; struct args_fail { __u32 token; __s32 status; }; struct args_setpipefd { __s32 pipefd; }; struct args_timeout { __u64 timeout; }; struct args_requester { __u32 uid; __u32 gid; }; struct args_expire { __u32 how; }; struct args_askumount { __u32 may_umount; }; struct args_ismountpoint { union { struct args_in { __u32 type; } in; struct args_out { __u32 devid; __u32 magic; } out; }; }; /* * All the ioctls use this structure. * When sending a path size must account for the total length * of the chunk of memory otherwise it is the size of the * structure. */ struct autofs_dev_ioctl { __u32 ver_major; __u32 ver_minor; __u32 size; /* total size of data passed in * including this struct */ __s32 ioctlfd; /* automount command fd */ /* Command parameters */ union { struct args_protover protover; struct args_protosubver protosubver; struct args_openmount openmount; struct args_ready ready; struct args_fail fail; struct args_setpipefd setpipefd; struct args_timeout timeout; struct args_requester requester; struct args_expire expire; struct args_askumount askumount; struct args_ismountpoint ismountpoint; }; char path[]; }; static __inline__ void init_autofs_dev_ioctl(struct autofs_dev_ioctl *in) { memset(in, 0, AUTOFS_DEV_IOCTL_SIZE); in->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR; in->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR; in->size = AUTOFS_DEV_IOCTL_SIZE; in->ioctlfd = -1; } enum { /* Get various version info */ AUTOFS_DEV_IOCTL_VERSION_CMD = 0x71, AUTOFS_DEV_IOCTL_PROTOVER_CMD, AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, /* Open mount ioctl fd */ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, /* Close mount ioctl fd */ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, /* Mount/expire status returns */ AUTOFS_DEV_IOCTL_READY_CMD, AUTOFS_DEV_IOCTL_FAIL_CMD, /* Activate/deactivate autofs mount */ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, AUTOFS_DEV_IOCTL_CATATONIC_CMD, /* Expiry timeout */ AUTOFS_DEV_IOCTL_TIMEOUT_CMD, /* Get mount last requesting uid and gid */ AUTOFS_DEV_IOCTL_REQUESTER_CMD, /* Check for eligible expire candidates */ AUTOFS_DEV_IOCTL_EXPIRE_CMD, /* Request busy status */ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, /* Check if path is a mountpoint */ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, }; #ifndef AUTOFS_IOCTL #define AUTOFS_IOCTL 0x93 #endif #define AUTOFS_DEV_IOCTL_VERSION \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_VERSION_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_PROTOVER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_PROTOVER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_PROTOSUBVER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_OPENMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_CLOSEMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_READY \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_READY_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_FAIL \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_FAIL_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_SETPIPEFD \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_CATATONIC \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_CATATONIC_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_TIMEOUT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_TIMEOUT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_REQUESTER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_REQUESTER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_EXPIRE \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_EXPIRE_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_ASKUMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_ISMOUNTPOINT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, struct autofs_dev_ioctl) #endif /* _LINUX_AUTO_DEV_IOCTL_H */
5,040
21.809955
73
h
null
systemd-main/src/shared/linux/bpf_common.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BPF_COMMON_H__ #define __LINUX_BPF_COMMON_H__ /* Instruction classes */ #define BPF_CLASS(code) ((code) & 0x07) #define BPF_LD 0x00 #define BPF_LDX 0x01 #define BPF_ST 0x02 #define BPF_STX 0x03 #define BPF_ALU 0x04 #define BPF_JMP 0x05 #define BPF_RET 0x06 #define BPF_MISC 0x07 /* ld/ldx fields */ #define BPF_SIZE(code) ((code) & 0x18) #define BPF_W 0x00 /* 32-bit */ #define BPF_H 0x08 /* 16-bit */ #define BPF_B 0x10 /* 8-bit */ /* eBPF BPF_DW 0x18 64-bit */ #define BPF_MODE(code) ((code) & 0xe0) #define BPF_IMM 0x00 #define BPF_ABS 0x20 #define BPF_IND 0x40 #define BPF_MEM 0x60 #define BPF_LEN 0x80 #define BPF_MSH 0xa0 /* alu/jmp fields */ #define BPF_OP(code) ((code) & 0xf0) #define BPF_ADD 0x00 #define BPF_SUB 0x10 #define BPF_MUL 0x20 #define BPF_DIV 0x30 #define BPF_OR 0x40 #define BPF_AND 0x50 #define BPF_LSH 0x60 #define BPF_RSH 0x70 #define BPF_NEG 0x80 #define BPF_MOD 0x90 #define BPF_XOR 0xa0 #define BPF_JA 0x00 #define BPF_JEQ 0x10 #define BPF_JGT 0x20 #define BPF_JGE 0x30 #define BPF_JSET 0x40 #define BPF_SRC(code) ((code) & 0x08) #define BPF_K 0x00 #define BPF_X 0x08 #ifndef BPF_MAXINSNS #define BPF_MAXINSNS 4096 #endif #endif /* __LINUX_BPF_COMMON_H__ */
1,367
22.586207
62
h
null
systemd-main/src/shared/linux/bpf_insn.h
/* SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) */ /* eBPF instruction mini library */ #ifndef __BPF_INSN_H #define __BPF_INSN_H struct bpf_insn; /* ALU ops on registers, bpf_add|sub|...: dst_reg += src_reg */ #define BPF_ALU64_REG(OP, DST, SRC) \ ((struct bpf_insn) { \ .code = BPF_ALU64 | BPF_OP(OP) | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = 0 }) #define BPF_ALU32_REG(OP, DST, SRC) \ ((struct bpf_insn) { \ .code = BPF_ALU | BPF_OP(OP) | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = 0 }) /* ALU ops on immediates, bpf_add|sub|...: dst_reg += imm32 */ #define BPF_ALU64_IMM(OP, DST, IMM) \ ((struct bpf_insn) { \ .code = BPF_ALU64 | BPF_OP(OP) | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = 0, \ .imm = IMM }) #define BPF_ALU32_IMM(OP, DST, IMM) \ ((struct bpf_insn) { \ .code = BPF_ALU | BPF_OP(OP) | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = 0, \ .imm = IMM }) /* Short form of mov, dst_reg = src_reg */ #define BPF_MOV64_REG(DST, SRC) \ ((struct bpf_insn) { \ .code = BPF_ALU64 | BPF_MOV | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = 0 }) #define BPF_MOV32_REG(DST, SRC) \ ((struct bpf_insn) { \ .code = BPF_ALU | BPF_MOV | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = 0 }) /* Short form of mov, dst_reg = imm32 */ #define BPF_MOV64_IMM(DST, IMM) \ ((struct bpf_insn) { \ .code = BPF_ALU64 | BPF_MOV | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = 0, \ .imm = IMM }) #define BPF_MOV32_IMM(DST, IMM) \ ((struct bpf_insn) { \ .code = BPF_ALU | BPF_MOV | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = 0, \ .imm = IMM }) /* BPF_LD_IMM64 macro encodes single 'load 64-bit immediate' insn */ #define BPF_LD_IMM64(DST, IMM) \ BPF_LD_IMM64_RAW(DST, 0, IMM) #define BPF_LD_IMM64_RAW(DST, SRC, IMM) \ ((struct bpf_insn) { \ .code = BPF_LD | BPF_DW | BPF_IMM, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = (__u32) (IMM) }), \ ((struct bpf_insn) { \ .code = 0, /* zero is reserved opcode */ \ .dst_reg = 0, \ .src_reg = 0, \ .off = 0, \ .imm = ((__u64) (IMM)) >> 32 }) #ifndef BPF_PSEUDO_MAP_FD # define BPF_PSEUDO_MAP_FD 1 #endif /* pseudo BPF_LD_IMM64 insn used to refer to process-local map_fd */ #define BPF_LD_MAP_FD(DST, MAP_FD) \ BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD) /* Direct packet access, R0 = *(uint *) (skb->data + imm32) */ #define BPF_LD_ABS(SIZE, IMM) \ ((struct bpf_insn) { \ .code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \ .dst_reg = 0, \ .src_reg = 0, \ .off = 0, \ .imm = IMM }) /* Memory load, dst_reg = *(uint *) (src_reg + off16) */ #define BPF_LDX_MEM(SIZE, DST, SRC, OFF) \ ((struct bpf_insn) { \ .code = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = 0 }) /* Memory store, *(uint *) (dst_reg + off16) = src_reg */ #define BPF_STX_MEM(SIZE, DST, SRC, OFF) \ ((struct bpf_insn) { \ .code = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = 0 }) /* * Atomic operations: * * BPF_ADD *(uint *) (dst_reg + off16) += src_reg * BPF_AND *(uint *) (dst_reg + off16) &= src_reg * BPF_OR *(uint *) (dst_reg + off16) |= src_reg * BPF_XOR *(uint *) (dst_reg + off16) ^= src_reg * BPF_ADD | BPF_FETCH src_reg = atomic_fetch_add(dst_reg + off16, src_reg); * BPF_AND | BPF_FETCH src_reg = atomic_fetch_and(dst_reg + off16, src_reg); * BPF_OR | BPF_FETCH src_reg = atomic_fetch_or(dst_reg + off16, src_reg); * BPF_XOR | BPF_FETCH src_reg = atomic_fetch_xor(dst_reg + off16, src_reg); * BPF_XCHG src_reg = atomic_xchg(dst_reg + off16, src_reg) * BPF_CMPXCHG r0 = atomic_cmpxchg(dst_reg + off16, r0, src_reg) */ #define BPF_ATOMIC_OP(SIZE, OP, DST, SRC, OFF) \ ((struct bpf_insn) { \ .code = BPF_STX | BPF_SIZE(SIZE) | BPF_ATOMIC, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = OP }) /* Legacy alias */ #define BPF_STX_XADD(SIZE, DST, SRC, OFF) BPF_ATOMIC_OP(SIZE, BPF_ADD, DST, SRC, OFF) /* Memory store, *(uint *) (dst_reg + off16) = imm32 */ #define BPF_ST_MEM(SIZE, DST, OFF, IMM) \ ((struct bpf_insn) { \ .code = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, \ .dst_reg = DST, \ .src_reg = 0, \ .off = OFF, \ .imm = IMM }) /* Conditional jumps against registers, if (dst_reg 'op' src_reg) goto pc + off16 */ #define BPF_JMP_REG(OP, DST, SRC, OFF) \ ((struct bpf_insn) { \ .code = BPF_JMP | BPF_OP(OP) | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = 0 }) /* Like BPF_JMP_REG, but with 32-bit wide operands for comparison. */ #define BPF_JMP32_REG(OP, DST, SRC, OFF) \ ((struct bpf_insn) { \ .code = BPF_JMP32 | BPF_OP(OP) | BPF_X, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = 0 }) /* Conditional jumps against immediates, if (dst_reg 'op' imm32) goto pc + off16 */ #define BPF_JMP_IMM(OP, DST, IMM, OFF) \ ((struct bpf_insn) { \ .code = BPF_JMP | BPF_OP(OP) | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = OFF, \ .imm = IMM }) /* Like BPF_JMP_IMM, but with 32-bit wide operands for comparison. */ #define BPF_JMP32_IMM(OP, DST, IMM, OFF) \ ((struct bpf_insn) { \ .code = BPF_JMP32 | BPF_OP(OP) | BPF_K, \ .dst_reg = DST, \ .src_reg = 0, \ .off = OFF, \ .imm = IMM }) #define BPF_JMP_A(OFF) \ ((struct bpf_insn) { \ .code = BPF_JMP | BPF_JA, \ .dst_reg = 0, \ .src_reg = 0, \ .off = OFF, \ .imm = 0 }) /* Raw code statement block */ #define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM) \ ((struct bpf_insn) { \ .code = CODE, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = IMM }) /* Program exit */ #define BPF_EXIT_INSN() \ ((struct bpf_insn) { \ .code = BPF_JMP | BPF_EXIT, \ .dst_reg = 0, \ .src_reg = 0, \ .off = 0, \ .imm = 0 }) #endif
6,606
26.301653
85
h
null
systemd-main/src/shared/linux/dm-ioctl.h
/* SPDX-License-Identifier: LGPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (C) 2001 - 2003 Sistina Software (UK) Limited. * Copyright (C) 2004 - 2009 Red Hat, Inc. All rights reserved. * * This file is released under the LGPL. */ #ifndef _LINUX_DM_IOCTL_V4_H #define _LINUX_DM_IOCTL_V4_H #include <linux/types.h> #define DM_DIR "mapper" /* Slashes not supported */ #define DM_CONTROL_NODE "control" #define DM_MAX_TYPE_NAME 16 #define DM_NAME_LEN 128 #define DM_UUID_LEN 129 /* * A traditional ioctl interface for the device mapper. * * Each device can have two tables associated with it, an * 'active' table which is the one currently used by io passing * through the device, and an 'inactive' one which is a table * that is being prepared as a replacement for the 'active' one. * * DM_VERSION: * Just get the version information for the ioctl interface. * * DM_REMOVE_ALL: * Remove all dm devices, destroy all tables. Only really used * for debug. * * DM_LIST_DEVICES: * Get a list of all the dm device names. * * DM_DEV_CREATE: * Create a new device, neither the 'active' or 'inactive' table * slots will be filled. The device will be in suspended state * after creation, however any io to the device will get errored * since it will be out-of-bounds. * * DM_DEV_REMOVE: * Remove a device, destroy any tables. * * DM_DEV_RENAME: * Rename a device or set its uuid if none was previously supplied. * * DM_SUSPEND: * This performs both suspend and resume, depending which flag is * passed in. * Suspend: This command will not return until all pending io to * the device has completed. Further io will be deferred until * the device is resumed. * Resume: It is no longer an error to issue this command on an * unsuspended device. If a table is present in the 'inactive' * slot, it will be moved to the active slot, then the old table * from the active slot will be _destroyed_. Finally the device * is resumed. * * DM_DEV_STATUS: * Retrieves the status for the table in the 'active' slot. * * DM_DEV_WAIT: * Wait for a significant event to occur to the device. This * could either be caused by an event triggered by one of the * targets of the table in the 'active' slot, or a table change. * * DM_TABLE_LOAD: * Load a table into the 'inactive' slot for the device. The * device does _not_ need to be suspended prior to this command. * * DM_TABLE_CLEAR: * Destroy any table in the 'inactive' slot (ie. abort). * * DM_TABLE_DEPS: * Return a set of device dependencies for the 'active' table. * * DM_TABLE_STATUS: * Return the targets status for the 'active' table. * * DM_TARGET_MSG: * Pass a message string to the target at a specific offset of a device. * * DM_DEV_SET_GEOMETRY: * Set the geometry of a device by passing in a string in this format: * * "cylinders heads sectors_per_track start_sector" * * Beware that CHS geometry is nearly obsolete and only provided * for compatibility with dm devices that can be booted by a PC * BIOS. See struct hd_geometry for range limits. Also note that * the geometry is erased if the device size changes. */ /* * All ioctl arguments consist of a single chunk of memory, with * this structure at the start. If a uuid is specified any * lookup (eg. for a DM_INFO) will be done on that, *not* the * name. */ struct dm_ioctl { /* * The version number is made up of three parts: * major - no backward or forward compatibility, * minor - only backwards compatible, * patch - both backwards and forwards compatible. * * All clients of the ioctl interface should fill in the * version number of the interface that they were * compiled with. * * All recognised ioctl commands (ie. those that don't * return -ENOTTY) fill out this field, even if the * command failed. */ __u32 version[3]; /* in/out */ __u32 data_size; /* total size of data passed in * including this struct */ __u32 data_start; /* offset to start of data * relative to start of this struct */ __u32 target_count; /* in/out */ __s32 open_count; /* out */ __u32 flags; /* in/out */ /* * event_nr holds either the event number (input and output) or the * udev cookie value (input only). * The DM_DEV_WAIT ioctl takes an event number as input. * The DM_SUSPEND, DM_DEV_REMOVE and DM_DEV_RENAME ioctls * use the field as a cookie to return in the DM_COOKIE * variable with the uevents they issue. * For output, the ioctls return the event number, not the cookie. */ __u32 event_nr; /* in/out */ __u32 padding; __u64 dev; /* in/out */ char name[DM_NAME_LEN]; /* device name */ char uuid[DM_UUID_LEN]; /* unique identifier for * the block device */ char data[7]; /* padding or data */ }; /* * Used to specify tables. These structures appear after the * dm_ioctl. */ struct dm_target_spec { __u64 sector_start; __u64 length; __s32 status; /* used when reading from kernel only */ /* * Location of the next dm_target_spec. * - When specifying targets on a DM_TABLE_LOAD command, this value is * the number of bytes from the start of the "current" dm_target_spec * to the start of the "next" dm_target_spec. * - When retrieving targets on a DM_TABLE_STATUS command, this value * is the number of bytes from the start of the first dm_target_spec * (that follows the dm_ioctl struct) to the start of the "next" * dm_target_spec. */ __u32 next; char target_type[DM_MAX_TYPE_NAME]; /* * Parameter string starts immediately after this object. * Be careful to add padding after string to ensure correct * alignment of subsequent dm_target_spec. */ }; /* * Used to retrieve the target dependencies. */ struct dm_target_deps { __u32 count; /* Array size */ __u32 padding; /* unused */ __u64 dev[]; /* out */ }; /* * Used to get a list of all dm devices. */ struct dm_name_list { __u64 dev; __u32 next; /* offset to the next record from the _start_ of this */ char name[]; /* * The following members can be accessed by taking a pointer that * points immediately after the terminating zero character in "name" * and aligning this pointer to next 8-byte boundary. * Uuid is present if the flag DM_NAME_LIST_FLAG_HAS_UUID is set. * * __u32 event_nr; * __u32 flags; * char uuid[0]; */ }; #define DM_NAME_LIST_FLAG_HAS_UUID 1 #define DM_NAME_LIST_FLAG_DOESNT_HAVE_UUID 2 /* * Used to retrieve the target versions */ struct dm_target_versions { __u32 next; __u32 version[3]; char name[]; }; /* * Used to pass message to a target */ struct dm_target_msg { __u64 sector; /* Device sector */ char message[]; }; /* * If you change this make sure you make the corresponding change * to dm-ioctl.c:lookup_ioctl() */ enum { /* Top level cmds */ DM_VERSION_CMD = 0, DM_REMOVE_ALL_CMD, DM_LIST_DEVICES_CMD, /* device level cmds */ DM_DEV_CREATE_CMD, DM_DEV_REMOVE_CMD, DM_DEV_RENAME_CMD, DM_DEV_SUSPEND_CMD, DM_DEV_STATUS_CMD, DM_DEV_WAIT_CMD, /* Table level cmds */ DM_TABLE_LOAD_CMD, DM_TABLE_CLEAR_CMD, DM_TABLE_DEPS_CMD, DM_TABLE_STATUS_CMD, /* Added later */ DM_LIST_VERSIONS_CMD, DM_TARGET_MSG_CMD, DM_DEV_SET_GEOMETRY_CMD, DM_DEV_ARM_POLL_CMD, DM_GET_TARGET_VERSION_CMD, }; #define DM_IOCTL 0xfd #define DM_VERSION _IOWR(DM_IOCTL, DM_VERSION_CMD, struct dm_ioctl) #define DM_REMOVE_ALL _IOWR(DM_IOCTL, DM_REMOVE_ALL_CMD, struct dm_ioctl) #define DM_LIST_DEVICES _IOWR(DM_IOCTL, DM_LIST_DEVICES_CMD, struct dm_ioctl) #define DM_DEV_CREATE _IOWR(DM_IOCTL, DM_DEV_CREATE_CMD, struct dm_ioctl) #define DM_DEV_REMOVE _IOWR(DM_IOCTL, DM_DEV_REMOVE_CMD, struct dm_ioctl) #define DM_DEV_RENAME _IOWR(DM_IOCTL, DM_DEV_RENAME_CMD, struct dm_ioctl) #define DM_DEV_SUSPEND _IOWR(DM_IOCTL, DM_DEV_SUSPEND_CMD, struct dm_ioctl) #define DM_DEV_STATUS _IOWR(DM_IOCTL, DM_DEV_STATUS_CMD, struct dm_ioctl) #define DM_DEV_WAIT _IOWR(DM_IOCTL, DM_DEV_WAIT_CMD, struct dm_ioctl) #define DM_DEV_ARM_POLL _IOWR(DM_IOCTL, DM_DEV_ARM_POLL_CMD, struct dm_ioctl) #define DM_TABLE_LOAD _IOWR(DM_IOCTL, DM_TABLE_LOAD_CMD, struct dm_ioctl) #define DM_TABLE_CLEAR _IOWR(DM_IOCTL, DM_TABLE_CLEAR_CMD, struct dm_ioctl) #define DM_TABLE_DEPS _IOWR(DM_IOCTL, DM_TABLE_DEPS_CMD, struct dm_ioctl) #define DM_TABLE_STATUS _IOWR(DM_IOCTL, DM_TABLE_STATUS_CMD, struct dm_ioctl) #define DM_LIST_VERSIONS _IOWR(DM_IOCTL, DM_LIST_VERSIONS_CMD, struct dm_ioctl) #define DM_GET_TARGET_VERSION _IOWR(DM_IOCTL, DM_GET_TARGET_VERSION_CMD, struct dm_ioctl) #define DM_TARGET_MSG _IOWR(DM_IOCTL, DM_TARGET_MSG_CMD, struct dm_ioctl) #define DM_DEV_SET_GEOMETRY _IOWR(DM_IOCTL, DM_DEV_SET_GEOMETRY_CMD, struct dm_ioctl) #define DM_VERSION_MAJOR 4 #define DM_VERSION_MINOR 27 #define DM_VERSION_PATCHLEVEL 0 #define DM_VERSION_EXTRA "-ioctl (2022-02-22)" /* Status bits */ #define DM_READONLY_FLAG (1 << 0) /* In/Out */ #define DM_SUSPEND_FLAG (1 << 1) /* In/Out */ #define DM_PERSISTENT_DEV_FLAG (1 << 3) /* In */ /* * Flag passed into ioctl STATUS command to get table information * rather than current status. */ #define DM_STATUS_TABLE_FLAG (1 << 4) /* In */ /* * Flags that indicate whether a table is present in either of * the two table slots that a device has. */ #define DM_ACTIVE_PRESENT_FLAG (1 << 5) /* Out */ #define DM_INACTIVE_PRESENT_FLAG (1 << 6) /* Out */ /* * Indicates that the buffer passed in wasn't big enough for the * results. */ #define DM_BUFFER_FULL_FLAG (1 << 8) /* Out */ /* * This flag is now ignored. */ #define DM_SKIP_BDGET_FLAG (1 << 9) /* In */ /* * Set this to avoid attempting to freeze any filesystem when suspending. */ #define DM_SKIP_LOCKFS_FLAG (1 << 10) /* In */ /* * Set this to suspend without flushing queued ios. * Also disables flushing uncommitted changes in the thin target before * generating statistics for DM_TABLE_STATUS and DM_DEV_WAIT. */ #define DM_NOFLUSH_FLAG (1 << 11) /* In */ /* * If set, any table information returned will relate to the inactive * table instead of the live one. Always check DM_INACTIVE_PRESENT_FLAG * is set before using the data returned. */ #define DM_QUERY_INACTIVE_TABLE_FLAG (1 << 12) /* In */ /* * If set, a uevent was generated for which the caller may need to wait. */ #define DM_UEVENT_GENERATED_FLAG (1 << 13) /* Out */ /* * If set, rename changes the uuid not the name. Only permitted * if no uuid was previously supplied: an existing uuid cannot be changed. */ #define DM_UUID_FLAG (1 << 14) /* In */ /* * If set, all buffers are wiped after use. Use when sending * or requesting sensitive data such as an encryption key. */ #define DM_SECURE_DATA_FLAG (1 << 15) /* In */ /* * If set, a message generated output data. */ #define DM_DATA_OUT_FLAG (1 << 16) /* Out */ /* * If set with DM_DEV_REMOVE or DM_REMOVE_ALL this indicates that if * the device cannot be removed immediately because it is still in use * it should instead be scheduled for removal when it gets closed. * * On return from DM_DEV_REMOVE, DM_DEV_STATUS or other ioctls, this * flag indicates that the device is scheduled to be removed when it * gets closed. */ #define DM_DEFERRED_REMOVE (1 << 17) /* In/Out */ /* * If set, the device is suspended internally. */ #define DM_INTERNAL_SUSPEND_FLAG (1 << 18) /* Out */ /* * If set, returns in the in buffer passed by UM, the raw table information * that would be measured by IMA subsystem on device state change. */ #define DM_IMA_MEASUREMENT_FLAG (1 << 19) /* In */ #endif /* _LINUX_DM_IOCTL_H */
11,598
29.049223
89
h
null
systemd-main/src/shutdown/detach-dm.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2010 ProFUSION embedded systems ***/ #include <linux/dm-ioctl.h> #include <sys/ioctl.h> #include "sd-device.h" #include "alloc-util.h" #include "blockdev-util.h" #include "detach-dm.h" #include "device-util.h" #include "devnum-util.h" #include "errno-util.h" #include "fd-util.h" #include "sync-util.h" typedef struct DeviceMapper { char *path; dev_t devnum; LIST_FIELDS(struct DeviceMapper, device_mapper); } DeviceMapper; static void device_mapper_free(DeviceMapper **head, DeviceMapper *m) { assert(head); assert(m); LIST_REMOVE(device_mapper, *head, m); free(m->path); free(m); } static void device_mapper_list_free(DeviceMapper **head) { assert(head); while (*head) device_mapper_free(head, *head); } static int dm_list_get(DeviceMapper **head) { _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL; int r; assert(head); r = sd_device_enumerator_new(&e); if (r < 0) return r; r = sd_device_enumerator_allow_uninitialized(e); if (r < 0) return r; r = sd_device_enumerator_add_match_subsystem(e, "block", true); if (r < 0) return r; r = sd_device_enumerator_add_match_sysname(e, "dm-*"); if (r < 0) return r; FOREACH_DEVICE(e, d) { _cleanup_free_ char *p = NULL; const char *dn; DeviceMapper *m; dev_t devnum; if (sd_device_get_devnum(d, &devnum) < 0 || sd_device_get_devname(d, &dn) < 0) continue; p = strdup(dn); if (!p) return -ENOMEM; m = new(DeviceMapper, 1); if (!m) return -ENOMEM; *m = (DeviceMapper) { .path = TAKE_PTR(p), .devnum = devnum, }; LIST_PREPEND(device_mapper, *head, m); } return 0; } static int delete_dm(DeviceMapper *m) { _cleanup_close_ int fd = -EBADF; int r; assert(m); assert(major(m->devnum) != 0); assert(m->path); fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC); if (fd < 0) return -errno; r = fsync_path_at(AT_FDCWD, m->path); if (r < 0) log_debug_errno(r, "Failed to sync DM block device %s, ignoring: %m", m->path); return RET_NERRNO(ioctl(fd, DM_DEV_REMOVE, &(struct dm_ioctl) { .version = { DM_VERSION_MAJOR, DM_VERSION_MINOR, DM_VERSION_PATCHLEVEL }, .data_size = sizeof(struct dm_ioctl), .dev = m->devnum, })); } static int dm_points_list_detach(DeviceMapper **head, bool *changed, bool last_try) { int n_failed = 0, r; dev_t rootdev = 0, usrdev = 0; assert(head); assert(changed); (void) get_block_device("/", &rootdev); (void) get_block_device("/usr", &usrdev); LIST_FOREACH(device_mapper, m, *head) { if ((major(rootdev) != 0 && rootdev == m->devnum) || (major(usrdev) != 0 && usrdev == m->devnum)) { log_debug("Not detaching DM %s that backs the OS itself, skipping.", m->path); n_failed ++; continue; } log_info("Detaching DM %s (" DEVNUM_FORMAT_STR ").", m->path, DEVNUM_FORMAT_VAL(m->devnum)); r = delete_dm(m); if (r < 0) { log_full_errno(last_try ? LOG_ERR : LOG_INFO, r, "Could not detach DM %s: %m", m->path); n_failed++; continue; } *changed = true; device_mapper_free(head, m); } return n_failed; } int dm_detach_all(bool *changed, bool last_try) { _cleanup_(device_mapper_list_free) LIST_HEAD(DeviceMapper, dm_list_head); int r; assert(changed); LIST_HEAD_INIT(dm_list_head); r = dm_list_get(&dm_list_head); if (r < 0) return r; return dm_points_list_detach(&dm_list_head, changed, last_try); }
4,574
26.232143
112
c
null
systemd-main/src/shutdown/detach-md.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2010 ProFUSION embedded systems ***/ #include <linux/major.h> #include <linux/raid/md_u.h> #include <sys/ioctl.h> #include <unistd.h> #include "sd-device.h" #include "alloc-util.h" #include "blockdev-util.h" #include "detach-md.h" #include "device-util.h" #include "devnum-util.h" #include "errno-util.h" #include "fd-util.h" #include "string-util.h" typedef struct RaidDevice { char *path; dev_t devnum; LIST_FIELDS(struct RaidDevice, raid_device); } RaidDevice; static void raid_device_free(RaidDevice **head, RaidDevice *m) { assert(head); assert(m); LIST_REMOVE(raid_device, *head, m); free(m->path); free(m); } static void raid_device_list_free(RaidDevice **head) { assert(head); while (*head) raid_device_free(head, *head); } static int md_list_get(RaidDevice **head) { _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL; int r; assert(head); r = sd_device_enumerator_new(&e); if (r < 0) return r; r = sd_device_enumerator_allow_uninitialized(e); if (r < 0) return r; r = sd_device_enumerator_add_match_subsystem(e, "block", true); if (r < 0) return r; r = sd_device_enumerator_add_match_sysname(e, "md*"); if (r < 0) return r; /* Filter out partitions. */ r = sd_device_enumerator_add_match_property(e, "DEVTYPE", "disk"); if (r < 0) return r; FOREACH_DEVICE(e, d) { _cleanup_free_ char *p = NULL; const char *dn, *md_level; RaidDevice *m; dev_t devnum; if (sd_device_get_devnum(d, &devnum) < 0 || sd_device_get_devname(d, &dn) < 0) continue; r = sd_device_get_property_value(d, "MD_LEVEL", &md_level); if (r < 0) { log_warning_errno(r, "Failed to get MD_LEVEL property for %s, ignoring: %m", dn); continue; } /* MD "containers" are a special type of MD devices, used for external metadata. Since it * doesn't provide RAID functionality in itself we don't need to stop it. */ if (streq(md_level, "container")) continue; p = strdup(dn); if (!p) return -ENOMEM; m = new(RaidDevice, 1); if (!m) return -ENOMEM; *m = (RaidDevice) { .path = TAKE_PTR(p), .devnum = devnum, }; LIST_PREPEND(raid_device, *head, m); } return 0; } static int delete_md(RaidDevice *m) { _cleanup_close_ int fd = -EBADF; assert(m); assert(major(m->devnum) != 0); assert(m->path); fd = open(m->path, O_RDONLY|O_CLOEXEC|O_EXCL); if (fd < 0) return -errno; if (fsync(fd) < 0) log_debug_errno(errno, "Failed to sync MD block device %s, ignoring: %m", m->path); return RET_NERRNO(ioctl(fd, STOP_ARRAY, NULL)); } static int md_points_list_detach(RaidDevice **head, bool *changed, bool last_try) { int n_failed = 0, r; dev_t rootdev = 0, usrdev = 0; assert(head); assert(changed); (void) get_block_device("/", &rootdev); (void) get_block_device("/usr", &usrdev); LIST_FOREACH(raid_device, m, *head) { if ((major(rootdev) != 0 && rootdev == m->devnum) || (major(usrdev) != 0 && usrdev == m->devnum)) { log_debug("Not detaching MD %s that backs the OS itself, skipping.", m->path); n_failed ++; continue; } log_info("Stopping MD %s (" DEVNUM_FORMAT_STR ").", m->path, DEVNUM_FORMAT_VAL(m->devnum)); r = delete_md(m); if (r < 0) { log_full_errno(last_try ? LOG_ERR : LOG_INFO, r, "Could not stop MD %s: %m", m->path); n_failed++; continue; } *changed = true; raid_device_free(head, m); } return n_failed; } int md_detach_all(bool *changed, bool last_try) { _cleanup_(raid_device_list_free) LIST_HEAD(RaidDevice, md_list_head); int r; assert(changed); LIST_HEAD_INIT(md_list_head); r = md_list_get(&md_list_head); if (r < 0) return r; return md_points_list_detach(&md_list_head, changed, last_try); }
4,943
27.090909
110
c
null
systemd-main/src/shutdown/detach-swap.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2010 ProFUSION embedded systems ***/ #include <sys/swap.h> #include "alloc-util.h" #include "detach-swap.h" #include "libmount-util.h" static void swap_device_free(SwapDevice **head, SwapDevice *m) { assert(head); assert(m); LIST_REMOVE(swap_device, *head, m); free(m->path); free(m); } void swap_devices_list_free(SwapDevice **head) { assert(head); while (*head) swap_device_free(head, *head); } int swap_list_get(const char *swaps, SwapDevice **head) { _cleanup_(mnt_free_tablep) struct libmnt_table *t = NULL; _cleanup_(mnt_free_iterp) struct libmnt_iter *i = NULL; int r; assert(head); t = mnt_new_table(); i = mnt_new_iter(MNT_ITER_FORWARD); if (!t || !i) return log_oom(); r = mnt_table_parse_swaps(t, swaps); if (r == -ENOENT) /* no /proc/swaps is fine */ return 0; if (r < 0) return log_error_errno(r, "Failed to parse %s: %m", swaps ?: "/proc/swaps"); for (;;) { struct libmnt_fs *fs; _cleanup_free_ SwapDevice *swap = NULL; const char *source; r = mnt_table_next_fs(t, i, &fs); if (r == 1) /* EOF */ break; if (r < 0) return log_error_errno(r, "Failed to get next entry from %s: %m", swaps ?: "/proc/swaps"); source = mnt_fs_get_source(fs); if (!source) continue; swap = new0(SwapDevice, 1); if (!swap) return log_oom(); swap->path = strdup(source); if (!swap->path) return log_oom(); LIST_PREPEND(swap_device, *head, TAKE_PTR(swap)); } return 0; } static int swap_points_list_off(SwapDevice **head, bool *changed) { int n_failed = 0; assert(head); assert(changed); LIST_FOREACH(swap_device, m, *head) { log_info("Deactivating swap %s.", m->path); if (swapoff(m->path) < 0) { log_warning_errno(errno, "Could not deactivate swap %s: %m", m->path); n_failed++; continue; } *changed = true; swap_device_free(head, m); } return n_failed; } int swapoff_all(bool *changed) { _cleanup_(swap_devices_list_free) LIST_HEAD(SwapDevice, swap_list_head); int r; assert(changed); LIST_HEAD_INIT(swap_list_head); r = swap_list_get(NULL, &swap_list_head); if (r < 0) return r; return swap_points_list_off(&swap_list_head, changed); }
2,948
25.567568
114
c
null
systemd-main/src/shutdown/test-umount.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "detach-swap.h" #include "errno-util.h" #include "log.h" #include "path-util.h" #include "string-util.h" #include "tests.h" #include "umount.h" static void test_mount_points_list_one(const char *fname) { _cleanup_(mount_points_list_free) LIST_HEAD(MountPoint, mp_list_head); _cleanup_free_ char *testdata_fname = NULL; log_info("/* %s(\"%s\") */", __func__, fname ?: "/proc/self/mountinfo"); if (fname) { assert_se(get_testdata_dir(fname, &testdata_fname) >= 0); fname = testdata_fname; } LIST_HEAD_INIT(mp_list_head); assert_se(mount_points_list_get(fname, &mp_list_head) >= 0); LIST_FOREACH(mount_point, m, mp_list_head) log_debug("path=%s o=%s f=0x%lx try-ro=%s", m->path, strempty(m->remount_options), m->remount_flags, yes_no(m->try_remount_ro)); } TEST(mount_points_list) { test_mount_points_list_one(NULL); test_mount_points_list_one("/test-umount/empty.mountinfo"); test_mount_points_list_one("/test-umount/garbled.mountinfo"); test_mount_points_list_one("/test-umount/rhbug-1554943.mountinfo"); } static void test_swap_list_one(const char *fname) { _cleanup_(swap_devices_list_free) LIST_HEAD(SwapDevice, sd_list_head); _cleanup_free_ char *testdata_fname = NULL; int r; log_info("/* %s(\"%s\") */", __func__, fname ?: "/proc/swaps"); if (fname) { assert_se(get_testdata_dir(fname, &testdata_fname) >= 0); fname = testdata_fname; } LIST_HEAD_INIT(sd_list_head); r = swap_list_get(fname, &sd_list_head); if (ERRNO_IS_PRIVILEGE(r)) return; assert_se(r >= 0); LIST_FOREACH(swap_device, m, sd_list_head) log_debug("path=%s", m->path); } TEST(swap_list) { test_swap_list_one(NULL); test_swap_list_one("/test-umount/example.swaps"); } DEFINE_TEST_MAIN(LOG_DEBUG);
2,179
30.594203
80
c
null
systemd-main/src/shutdown/umount.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2010 ProFUSION embedded systems ***/ #include <stdbool.h> #include "list.h" int umount_all(bool *changed, bool last_try); /* This is exported just for testing */ typedef struct MountPoint { char *path; char *remount_options; unsigned long remount_flags; bool try_remount_ro; bool umount_lazily; bool leaf; LIST_FIELDS(struct MountPoint, mount_point); } MountPoint; int mount_points_list_get(const char *mountinfo, MountPoint **head); void mount_points_list_free(MountPoint **head);
625
22.185185
68
h
null
systemd-main/src/socket-activate/socket-activate.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <sys/epoll.h> #include <sys/prctl.h> #include <sys/wait.h> #include <unistd.h> #include "sd-daemon.h" #include "alloc-util.h" #include "build.h" #include "env-util.h" #include "errno-util.h" #include "escape.h" #include "fd-util.h" #include "log.h" #include "macro.h" #include "main-func.h" #include "pretty-print.h" #include "process-util.h" #include "signal-util.h" #include "socket-netlink.h" #include "socket-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" static char **arg_listen = NULL; static bool arg_accept = false; static int arg_socket_type = SOCK_STREAM; static char **arg_args = NULL; static char **arg_setenv = NULL; static char **arg_fdnames = NULL; static bool arg_inetd = false; static int add_epoll(int epoll_fd, int fd) { struct epoll_event ev = { .events = EPOLLIN, .data.fd = fd, }; assert(epoll_fd >= 0); assert(fd >= 0); if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) return log_error_errno(errno, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd, fd); return 0; } static int open_sockets(int *ret_epoll_fd, bool accept) { _cleanup_close_ int epoll_fd = -EBADF; int n, r, count = 0; assert(ret_epoll_fd); n = sd_listen_fds(true); if (n < 0) return log_error_errno(n, "Failed to read listening file descriptors from environment: %m"); if (n > 0) { log_info("Received %i descriptors via the environment.", n); for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) { r = fd_cloexec(fd, arg_accept); if (r < 0) return r; count++; } } /* Close logging and all other descriptors */ if (arg_listen) { _cleanup_free_ int *except = new(int, n); if (!except) return log_oom(); for (int i = 0; i < n; i++) except[i] = SD_LISTEN_FDS_START + i; log_close(); log_set_open_when_needed(true); log_settle_target(); r = close_all_fds(except, n); if (r < 0) return log_error_errno(r, "Failed to close all file descriptors: %m"); } /* Note: we leak some fd's on error here. It doesn't matter much, since the program will exit * immediately anyway, but would be a pain to fix. */ STRV_FOREACH(address, arg_listen) { r = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept * SOCK_CLOEXEC)); if (r < 0) return log_error_errno(r, "Failed to open '%s': %m", *address); assert(r == SD_LISTEN_FDS_START + count); count++; } if (arg_listen) { log_open(); log_set_open_when_needed(false); } epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) return log_error_errno(errno, "Failed to create epoll object: %m"); for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) { _cleanup_free_ char *name = NULL; getsockname_pretty(fd, &name); log_info("Listening on %s as %i.", strna(name), fd); r = add_epoll(epoll_fd, fd); if (r < 0) return r; } *ret_epoll_fd = TAKE_FD(epoll_fd); return count; } static int exec_process(const char *name, char **argv, int start_fd, size_t n_fds) { _cleanup_strv_free_ char **envp = NULL; int r; if (arg_inetd && n_fds != 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--inetd only supported for single file descriptors."); FOREACH_STRING(var, "TERM", "PATH", "USER", "HOME") { const char *n; n = strv_find_prefix(environ, var); if (!n) continue; r = strv_extend(&envp, n); if (r < 0) return r; } if (arg_inetd) { assert(n_fds == 1); r = rearrange_stdio(start_fd, start_fd, STDERR_FILENO); /* invalidates start_fd on success + error */ if (r < 0) return log_error_errno(r, "Failed to move fd to stdin+stdout: %m"); } else { if (start_fd != SD_LISTEN_FDS_START) { assert(n_fds == 1); if (dup2(start_fd, SD_LISTEN_FDS_START) < 0) return log_error_errno(errno, "Failed to dup connection: %m"); safe_close(start_fd); } r = strv_extendf(&envp, "LISTEN_FDS=%zu", n_fds); if (r < 0) return r; r = strv_extendf(&envp, "LISTEN_PID=" PID_FMT, getpid_cached()); if (r < 0) return r; if (arg_fdnames) { _cleanup_free_ char *names = NULL; size_t len; len = strv_length(arg_fdnames); if (len == 1) for (size_t i = 1; i < n_fds; i++) { r = strv_extend(&arg_fdnames, arg_fdnames[0]); if (r < 0) return log_oom(); } else if (len != n_fds) log_warning("The number of fd names is different than number of fds: %zu vs %zu", len, n_fds); names = strv_join(arg_fdnames, ":"); if (!names) return log_oom(); char *t = strjoin("LISTEN_FDNAMES=", names); if (!t) return log_oom(); r = strv_consume(&envp, t); if (r < 0) return r; } } STRV_FOREACH(s, arg_setenv) { r = strv_env_replace_strdup(&envp, *s); if (r < 0) return r; } _cleanup_free_ char *joined = strv_join(argv, " "); if (!joined) return log_oom(); log_info("Execing %s (%s)", name, joined); execvpe(name, argv, envp); return log_error_errno(errno, "Failed to execp %s (%s): %m", name, joined); } static int fork_and_exec_process(const char *child, char **argv, int fd) { _cleanup_free_ char *joined = NULL; pid_t child_pid; int r; joined = strv_join(argv, " "); if (!joined) return log_oom(); r = safe_fork("(activate)", FORK_RESET_SIGNALS | FORK_DEATHSIG | FORK_RLIMIT_NOFILE_SAFE | FORK_LOG, &child_pid); if (r < 0) return r; if (r == 0) { /* In the child */ exec_process(child, argv, fd, 1); _exit(EXIT_FAILURE); } log_info("Spawned %s (%s) as PID " PID_FMT ".", child, joined, child_pid); return 0; } static int do_accept(const char *name, char **argv, int fd) { _cleanup_free_ char *local = NULL, *peer = NULL; _cleanup_close_ int fd_accepted = -EBADF; fd_accepted = accept4(fd, NULL, NULL, 0); if (fd_accepted < 0) { if (ERRNO_IS_ACCEPT_AGAIN(errno)) return 0; return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd); } (void) getsockname_pretty(fd_accepted, &local); (void) getpeername_pretty(fd_accepted, true, &peer); log_info("Connection from %s to %s", strna(peer), strna(local)); return fork_and_exec_process(name, argv, fd_accepted); } /* SIGCHLD handler. */ static void sigchld_hdl(int sig) { PROTECT_ERRNO; for (;;) { siginfo_t si; int r; si.si_pid = 0; r = waitid(P_ALL, 0, &si, WEXITED | WNOHANG); if (r < 0) { if (errno != ECHILD) log_error_errno(errno, "Failed to reap children: %m"); return; } if (si.si_pid == 0) return; log_info("Child %d died with code %d", si.si_pid, si.si_status); } } static int install_chld_handler(void) { static const struct sigaction act = { .sa_flags = SA_NOCLDSTOP | SA_RESTART, .sa_handler = sigchld_hdl, }; if (sigaction(SIGCHLD, &act, 0) < 0) return log_error_errno(errno, "Failed to install SIGCHLD handler: %m"); return 0; } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-socket-activate", "1", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...]\n" "\n%sListen on sockets and launch child on connection.%s\n" "\nOptions:\n" " -h --help Show this help and exit\n" " --version Print version string and exit\n" " -l --listen=ADDR Listen for raw connections at ADDR\n" " -d --datagram Listen on datagram instead of stream socket\n" " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n" " -a --accept Spawn separate child for each connection\n" " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n" " --fdname=NAME[:NAME...] Specify names for file descriptors\n" " --inetd Enable inetd file descriptor passing protocol\n" "\nNote: file descriptors from sd_listen_fds() will be passed through.\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_FDNAME, ARG_SEQPACKET, ARG_INETD, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "datagram", no_argument, NULL, 'd' }, { "seqpacket", no_argument, NULL, ARG_SEQPACKET }, { "listen", required_argument, NULL, 'l' }, { "accept", no_argument, NULL, 'a' }, { "setenv", required_argument, NULL, 'E' }, { "environment", required_argument, NULL, 'E' }, /* legacy alias */ { "fdname", required_argument, NULL, ARG_FDNAME }, { "inetd", no_argument, NULL, ARG_INETD }, {} }; int c, r; assert(argc >= 0); assert(argv); /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long() * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */ optind = 0; while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case 'l': r = strv_extend(&arg_listen, optarg); if (r < 0) return log_oom(); break; case 'd': if (arg_socket_type == SOCK_SEQPACKET) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--datagram may not be combined with --seqpacket."); arg_socket_type = SOCK_DGRAM; break; case ARG_SEQPACKET: if (arg_socket_type == SOCK_DGRAM) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--seqpacket may not be combined with --datagram."); arg_socket_type = SOCK_SEQPACKET; break; case 'a': arg_accept = true; break; case 'E': r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg); if (r < 0) return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg); break; case ARG_FDNAME: { _cleanup_strv_free_ char **names = NULL; names = strv_split(optarg, ":"); if (!names) return log_oom(); STRV_FOREACH(s, names) if (!fdname_is_valid(*s)) { _cleanup_free_ char *esc = NULL; esc = cescape(*s); log_warning("File descriptor name \"%s\" is not valid.", esc); } /* Empty optargs means one empty name */ r = strv_extend_strv(&arg_fdnames, strv_isempty(names) ? STRV_MAKE("") : names, false); if (r < 0) return log_error_errno(r, "strv_extend_strv: %m"); break; } case ARG_INETD: arg_inetd = true; break; case '?': return -EINVAL; default: assert_not_reached(); } if (optind == argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s: command to execute is missing.", program_invocation_short_name); if (arg_socket_type == SOCK_DGRAM && arg_accept) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Datagram sockets do not accept connections. " "The --datagram and --accept options may not be combined."); arg_args = argv + optind; return 1 /* work to do */; } static int run(int argc, char **argv) { _cleanup_close_ int epoll_fd = -EBADF; _cleanup_strv_free_ char **exec_argv = NULL; int r, n; log_show_color(true); log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; exec_argv = strv_copy(arg_args); if (!exec_argv) return log_oom(); assert(!strv_isempty(exec_argv)); r = install_chld_handler(); if (r < 0) return r; n = open_sockets(&epoll_fd, arg_accept); if (n < 0) return n; if (n == 0) return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No sockets to listen on specified or passed in."); for (;;) { struct epoll_event event; if (epoll_wait(epoll_fd, &event, 1, -1) < 0) { if (errno == EINTR) continue; return log_error_errno(errno, "epoll_wait() failed: %m"); } log_info("Communication attempt on fd %i.", event.data.fd); if (arg_accept) { r = do_accept(exec_argv[0], exec_argv, event.data.fd); if (r < 0) return r; } else break; } return exec_process(exec_argv[0], exec_argv, SD_LISTEN_FDS_START, (size_t) n); } DEFINE_MAIN_FUNCTION(run);
17,191
33.66129
126
c
null
systemd-main/src/socket-proxy/socket-proxyd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <sys/un.h> #include <unistd.h> #include "sd-daemon.h" #include "sd-event.h" #include "sd-resolve.h" #include "alloc-util.h" #include "build.h" #include "daemon-util.h" #include "errno-util.h" #include "fd-util.h" #include "log.h" #include "main-func.h" #include "parse-util.h" #include "path-util.h" #include "pretty-print.h" #include "resolve-private.h" #include "set.h" #include "socket-util.h" #include "string-util.h" #define BUFFER_SIZE (256 * 1024) static unsigned arg_connections_max = 256; static const char *arg_remote_host = NULL; static usec_t arg_exit_idle_time = USEC_INFINITY; typedef struct Context { sd_event *event; sd_resolve *resolve; sd_event_source *idle_time; Set *listen; Set *connections; } Context; typedef struct Connection { Context *context; int server_fd, client_fd; int server_to_client_buffer[2]; /* a pipe */ int client_to_server_buffer[2]; /* a pipe */ size_t server_to_client_buffer_full, client_to_server_buffer_full; size_t server_to_client_buffer_size, client_to_server_buffer_size; sd_event_source *server_event_source, *client_event_source; sd_resolve_query *resolve_query; } Connection; static void connection_free(Connection *c) { assert(c); if (c->context) set_remove(c->context->connections, c); sd_event_source_unref(c->server_event_source); sd_event_source_unref(c->client_event_source); safe_close(c->server_fd); safe_close(c->client_fd); safe_close_pair(c->server_to_client_buffer); safe_close_pair(c->client_to_server_buffer); sd_resolve_query_unref(c->resolve_query); free(c); } static int idle_time_cb(sd_event_source *s, uint64_t usec, void *userdata) { Context *c = userdata; int r; if (!set_isempty(c->connections)) { log_warning("Idle timer fired even though there are connections, ignoring"); return 0; } r = sd_event_exit(c->event, 0); if (r < 0) { log_warning_errno(r, "Error while stopping event loop, ignoring: %m"); return 0; } return 0; } static int connection_release(Connection *c) { Context *context = ASSERT_PTR(ASSERT_PTR(c)->context); int r; connection_free(c); if (arg_exit_idle_time < USEC_INFINITY && set_isempty(context->connections)) { if (context->idle_time) { r = sd_event_source_set_time_relative(context->idle_time, arg_exit_idle_time); if (r < 0) return log_error_errno(r, "Error while setting idle time: %m"); r = sd_event_source_set_enabled(context->idle_time, SD_EVENT_ONESHOT); if (r < 0) return log_error_errno(r, "Error while enabling idle time: %m"); } else { r = sd_event_add_time_relative( context->event, &context->idle_time, CLOCK_MONOTONIC, arg_exit_idle_time, 0, idle_time_cb, context); if (r < 0) return log_error_errno(r, "Failed to create idle timer: %m"); } } return 0; } static void context_clear(Context *context) { assert(context); set_free_with_destructor(context->listen, sd_event_source_unref); set_free_with_destructor(context->connections, connection_free); sd_event_unref(context->event); sd_resolve_unref(context->resolve); sd_event_source_unref(context->idle_time); } static int connection_create_pipes(Connection *c, int buffer[static 2], size_t *sz) { int r; assert(c); assert(buffer); assert(sz); if (buffer[0] >= 0) return 0; r = pipe2(buffer, O_CLOEXEC|O_NONBLOCK); if (r < 0) return log_error_errno(errno, "Failed to allocate pipe buffer: %m"); (void) fcntl(buffer[0], F_SETPIPE_SZ, BUFFER_SIZE); r = fcntl(buffer[0], F_GETPIPE_SZ); if (r < 0) return log_error_errno(errno, "Failed to get pipe buffer size: %m"); assert(r > 0); *sz = r; return 0; } static int connection_shovel( Connection *c, int *from, int buffer[2], int *to, size_t *full, size_t *sz, sd_event_source **from_source, sd_event_source **to_source) { bool shoveled; assert(c); assert(from); assert(buffer); assert(buffer[0] >= 0); assert(buffer[1] >= 0); assert(to); assert(full); assert(sz); assert(from_source); assert(to_source); do { ssize_t z; shoveled = false; if (*full < *sz && *from >= 0 && *to >= 0) { z = splice(*from, NULL, buffer[1], NULL, *sz - *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK); if (z > 0) { *full += z; shoveled = true; } else if (z == 0 || ERRNO_IS_DISCONNECT(errno)) { *from_source = sd_event_source_unref(*from_source); *from = safe_close(*from); } else if (!ERRNO_IS_TRANSIENT(errno)) return log_error_errno(errno, "Failed to splice: %m"); } if (*full > 0 && *to >= 0) { z = splice(buffer[0], NULL, *to, NULL, *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK); if (z > 0) { *full -= z; shoveled = true; } else if (z == 0 || ERRNO_IS_DISCONNECT(errno)) { *to_source = sd_event_source_unref(*to_source); *to = safe_close(*to); } else if (!ERRNO_IS_TRANSIENT(errno)) return log_error_errno(errno, "Failed to splice: %m"); } } while (shoveled); return 0; } static int connection_enable_event_sources(Connection *c); static int traffic_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) { Connection *c = ASSERT_PTR(userdata); int r; assert(s); assert(fd >= 0); r = connection_shovel(c, &c->server_fd, c->server_to_client_buffer, &c->client_fd, &c->server_to_client_buffer_full, &c->server_to_client_buffer_size, &c->server_event_source, &c->client_event_source); if (r < 0) goto quit; r = connection_shovel(c, &c->client_fd, c->client_to_server_buffer, &c->server_fd, &c->client_to_server_buffer_full, &c->client_to_server_buffer_size, &c->client_event_source, &c->server_event_source); if (r < 0) goto quit; /* EOF on both sides? */ if (c->server_fd < 0 && c->client_fd < 0) goto quit; /* Server closed, and all data written to client? */ if (c->server_fd < 0 && c->server_to_client_buffer_full <= 0) goto quit; /* Client closed, and all data written to server? */ if (c->client_fd < 0 && c->client_to_server_buffer_full <= 0) goto quit; r = connection_enable_event_sources(c); if (r < 0) goto quit; return 1; quit: connection_release(c); return 0; /* ignore errors, continue serving */ } static int connection_enable_event_sources(Connection *c) { uint32_t a = 0, b = 0; int r; assert(c); if (c->server_to_client_buffer_full > 0) b |= EPOLLOUT; if (c->server_to_client_buffer_full < c->server_to_client_buffer_size) a |= EPOLLIN; if (c->client_to_server_buffer_full > 0) a |= EPOLLOUT; if (c->client_to_server_buffer_full < c->client_to_server_buffer_size) b |= EPOLLIN; if (c->server_event_source) r = sd_event_source_set_io_events(c->server_event_source, a); else if (c->server_fd >= 0) r = sd_event_add_io(c->context->event, &c->server_event_source, c->server_fd, a, traffic_cb, c); else r = 0; if (r < 0) return log_error_errno(r, "Failed to set up server event source: %m"); if (c->client_event_source) r = sd_event_source_set_io_events(c->client_event_source, b); else if (c->client_fd >= 0) r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, b, traffic_cb, c); else r = 0; if (r < 0) return log_error_errno(r, "Failed to set up client event source: %m"); return 0; } static int connection_complete(Connection *c) { int r; assert(c); r = connection_create_pipes(c, c->server_to_client_buffer, &c->server_to_client_buffer_size); if (r < 0) goto fail; r = connection_create_pipes(c, c->client_to_server_buffer, &c->client_to_server_buffer_size); if (r < 0) goto fail; r = connection_enable_event_sources(c); if (r < 0) goto fail; return 0; fail: connection_release(c); return 0; /* ignore errors, continue serving */ } static int connect_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) { Connection *c = ASSERT_PTR(userdata); socklen_t solen; int error, r; assert(s); assert(fd >= 0); solen = sizeof(error); r = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &solen); if (r < 0) { log_error_errno(errno, "Failed to issue SO_ERROR: %m"); goto fail; } if (error != 0) { log_error_errno(error, "Failed to connect to remote host: %m"); goto fail; } c->client_event_source = sd_event_source_unref(c->client_event_source); return connection_complete(c); fail: connection_release(c); return 0; /* ignore errors, continue serving */ } static int connection_start(Connection *c, struct sockaddr *sa, socklen_t salen) { int r; assert(c); assert(sa); assert(salen); c->client_fd = socket(sa->sa_family, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0); if (c->client_fd < 0) { log_error_errno(errno, "Failed to get remote socket: %m"); goto fail; } r = connect(c->client_fd, sa, salen); if (r < 0) { if (errno == EINPROGRESS) { r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, EPOLLOUT, connect_cb, c); if (r < 0) { log_error_errno(r, "Failed to add connection socket: %m"); goto fail; } r = sd_event_source_set_enabled(c->client_event_source, SD_EVENT_ONESHOT); if (r < 0) { log_error_errno(r, "Failed to enable oneshot event source: %m"); goto fail; } } else { log_error_errno(errno, "Failed to connect to remote host: %m"); goto fail; } } else { r = connection_complete(c); if (r < 0) goto fail; } return 0; fail: connection_release(c); return 0; /* ignore errors, continue serving */ } static int resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, Connection *c) { assert(q); assert(c); if (ret != 0) { log_error("Failed to resolve host: %s", gai_strerror(ret)); goto fail; } c->resolve_query = sd_resolve_query_unref(c->resolve_query); return connection_start(c, ai->ai_addr, ai->ai_addrlen); fail: connection_release(c); return 0; /* ignore errors, continue serving */ } static int resolve_remote(Connection *c) { static const struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM, }; const char *node, *service; int r; if (IN_SET(arg_remote_host[0], '/', '@')) { union sockaddr_union sa; int sa_len; r = sockaddr_un_set_path(&sa.un, arg_remote_host); if (r < 0) { log_error_errno(r, "Specified address doesn't fit in an AF_UNIX address, refusing: %m"); goto fail; } sa_len = r; return connection_start(c, &sa.sa, sa_len); } service = strrchr(arg_remote_host, ':'); if (service) { node = strndupa_safe(arg_remote_host, service - arg_remote_host); service++; } else { node = arg_remote_host; service = "80"; } log_debug("Looking up address info for %s:%s", node, service); r = resolve_getaddrinfo(c->context->resolve, &c->resolve_query, node, service, &hints, resolve_handler, NULL, c); if (r < 0) { log_error_errno(r, "Failed to resolve remote host: %m"); goto fail; } return 0; fail: connection_release(c); return 0; /* ignore errors, continue serving */ } static int add_connection_socket(Context *context, int fd) { Connection *c; int r; assert(context); assert(fd >= 0); if (set_size(context->connections) > arg_connections_max) { log_warning("Hit connection limit, refusing connection."); safe_close(fd); return 0; } if (context->idle_time) { r = sd_event_source_set_enabled(context->idle_time, SD_EVENT_OFF); if (r < 0) log_warning_errno(r, "Unable to disable idle timer, continuing: %m"); } c = new(Connection, 1); if (!c) { log_oom(); return 0; } *c = (Connection) { .context = context, .server_fd = fd, .client_fd = -EBADF, .server_to_client_buffer = PIPE_EBADF, .client_to_server_buffer = PIPE_EBADF, }; r = set_ensure_put(&context->connections, NULL, c); if (r < 0) { free(c); log_oom(); return 0; } return resolve_remote(c); } static int accept_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) { _cleanup_free_ char *peer = NULL; Context *context = ASSERT_PTR(userdata); int nfd = -EBADF, r; assert(s); assert(fd >= 0); assert(revents & EPOLLIN); nfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC); if (nfd < 0) { if (!ERRNO_IS_ACCEPT_AGAIN(errno)) log_warning_errno(errno, "Failed to accept() socket: %m"); } else { (void) getpeername_pretty(nfd, true, &peer); log_debug("New connection from %s", strna(peer)); r = add_connection_socket(context, nfd); if (r < 0) { log_warning_errno(r, "Failed to accept connection, ignoring: %m"); safe_close(nfd); } } r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT); if (r < 0) return log_error_errno(r, "Error while re-enabling listener with ONESHOT: %m"); return 1; } static int add_listen_socket(Context *context, int fd) { sd_event_source *source; int r; assert(context); assert(fd >= 0); r = sd_is_socket(fd, 0, SOCK_STREAM, 1); if (r < 0) return log_error_errno(r, "Failed to determine socket type: %m"); if (r == 0) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Passed in socket is not a stream socket."); r = fd_nonblock(fd, true); if (r < 0) return log_error_errno(r, "Failed to mark file descriptor non-blocking: %m"); r = sd_event_add_io(context->event, &source, fd, EPOLLIN, accept_cb, context); if (r < 0) return log_error_errno(r, "Failed to add event source: %m"); r = set_ensure_put(&context->listen, NULL, source); if (r < 0) { sd_event_source_unref(source); return log_error_errno(r, "Failed to add source to set: %m"); } r = sd_event_source_set_exit_on_failure(source, true); if (r < 0) return log_error_errno(r, "Failed to enable exit-on-failure logic: %m"); /* Set the watcher to oneshot in case other processes are also * watching to accept(). */ r = sd_event_source_set_enabled(source, SD_EVENT_ONESHOT); if (r < 0) return log_error_errno(r, "Failed to enable oneshot mode: %m"); return 0; } static int help(void) { _cleanup_free_ char *link = NULL; _cleanup_free_ char *time_link = NULL; int r; r = terminal_urlify_man("systemd-socket-proxyd", "8", &link); if (r < 0) return log_oom(); r = terminal_urlify_man("systemd.time", "7", &time_link); if (r < 0) return log_oom(); printf("%1$s [HOST:PORT]\n" "%1$s [SOCKET]\n\n" "Bidirectionally proxy local sockets to another (possibly remote) socket.\n\n" " -c --connections-max= Set the maximum number of connections to be accepted\n" " --exit-idle-time= Exit when without a connection for this duration. See\n" " the %3$s for time span format\n" " -h --help Show this help\n" " --version Show package version\n" "\nSee the %2$s for details.\n", program_invocation_short_name, link, time_link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_EXIT_IDLE, ARG_IGNORE_ENV }; static const struct option options[] = { { "connections-max", required_argument, NULL, 'c' }, { "exit-idle-time", required_argument, NULL, ARG_EXIT_IDLE }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, {} }; int c, r; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "c:h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case 'c': r = safe_atou(optarg, &arg_connections_max); if (r < 0) { log_error("Failed to parse --connections-max= argument: %s", optarg); return r; } if (arg_connections_max < 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Connection limit is too low."); break; case ARG_EXIT_IDLE: r = parse_sec(optarg, &arg_exit_idle_time); if (r < 0) return log_error_errno(r, "Failed to parse --exit-idle-time= argument: %s", optarg); break; case '?': return -EINVAL; default: assert_not_reached(); } if (optind >= argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not enough parameters."); if (argc != optind+1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many parameters."); arg_remote_host = argv[optind]; return 1; } static int run(int argc, char *argv[]) { _cleanup_(context_clear) Context context = {}; _unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL; int r, n, fd; log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; r = sd_event_default(&context.event); if (r < 0) return log_error_errno(r, "Failed to allocate event loop: %m"); r = sd_resolve_default(&context.resolve); if (r < 0) return log_error_errno(r, "Failed to allocate resolver: %m"); r = sd_resolve_attach_event(context.resolve, context.event, 0); if (r < 0) return log_error_errno(r, "Failed to attach resolver: %m"); sd_event_set_watchdog(context.event, true); r = sd_listen_fds(1); if (r < 0) return log_error_errno(r, "Failed to receive sockets from parent."); if (r == 0) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Didn't get any sockets passed in."); n = r; for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) { r = add_listen_socket(&context, fd); if (r < 0) return r; } notify_stop = notify_start(NOTIFY_READY, NOTIFY_STOPPING); r = sd_event_loop(context.event); if (r < 0) return log_error_errno(r, "Failed to run event loop: %m"); return 0; } DEFINE_MAIN_FUNCTION(run);
23,186
31.070539
127
c
null
systemd-main/src/stdio-bridge/stdio-bridge.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <string.h> #include <unistd.h> #include "sd-bus.h" #include "sd-daemon.h" #include "alloc-util.h" #include "build.h" #include "bus-internal.h" #include "bus-util.h" #include "errno-util.h" #include "io-util.h" #include "log.h" #include "main-func.h" #include "version.h" #define DEFAULT_BUS_PATH "unix:path=/run/dbus/system_bus_socket" static const char *arg_bus_path = DEFAULT_BUS_PATH; static BusTransport arg_transport = BUS_TRANSPORT_LOCAL; static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM; static int help(void) { printf("%s [OPTIONS...]\n\n" "Forward messages between a pipe or socket and a D-Bus bus.\n\n" " -h --help Show this help\n" " --version Show package version\n" " -p --bus-path=PATH Path to the bus address (default: %s)\n" " --system Connect to system bus\n" " --user Connect to user bus\n" " -M --machine=CONTAINER Name of local container to connect to\n", program_invocation_short_name, DEFAULT_BUS_PATH); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_MACHINE, ARG_USER, ARG_SYSTEM, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "bus-path", required_argument, NULL, 'p' }, { "user", no_argument, NULL, ARG_USER }, { "system", no_argument, NULL, ARG_SYSTEM }, { "machine", required_argument, NULL, 'M' }, {}, }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "hp:M:", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_USER: arg_runtime_scope = RUNTIME_SCOPE_USER; break; case ARG_SYSTEM: arg_runtime_scope = RUNTIME_SCOPE_SYSTEM; break; case 'p': arg_bus_path = optarg; break; case 'M': arg_bus_path = optarg; arg_transport = BUS_TRANSPORT_MACHINE; break; case '?': return -EINVAL; default: return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown option code %c", c); } return 1; } static int run(int argc, char *argv[]) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *a = NULL, *b = NULL; sd_id128_t server_id; bool is_unix; int r, in_fd, out_fd; log_set_target(LOG_TARGET_JOURNAL_OR_KMSG); log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; r = sd_listen_fds(0); if (r == 0) { in_fd = STDIN_FILENO; out_fd = STDOUT_FILENO; } else if (r == 1) { in_fd = SD_LISTEN_FDS_START; out_fd = SD_LISTEN_FDS_START; } else return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "More than one file descriptor was passed."); is_unix = sd_is_socket(in_fd, AF_UNIX, 0, 0) > 0 && sd_is_socket(out_fd, AF_UNIX, 0, 0) > 0; r = sd_bus_new(&a); if (r < 0) return log_error_errno(r, "Failed to allocate bus: %m"); if (arg_transport == BUS_TRANSPORT_MACHINE) r = bus_set_address_machine(a, arg_runtime_scope, arg_bus_path); else r = sd_bus_set_address(a, arg_bus_path); if (r < 0) return log_error_errno(r, "Failed to set address to connect to: %m"); r = sd_bus_negotiate_fds(a, is_unix); if (r < 0) return log_error_errno(r, "Failed to set FD negotiation: %m"); r = sd_bus_start(a); if (r < 0) return log_error_errno(r, "Failed to start bus client: %m"); r = sd_bus_get_bus_id(a, &server_id); if (r < 0) return log_error_errno(r, "Failed to get server ID: %m"); r = sd_bus_new(&b); if (r < 0) return log_error_errno(r, "Failed to allocate bus: %m"); r = sd_bus_set_fd(b, in_fd, out_fd); if (r < 0) return log_error_errno(r, "Failed to set fds: %m"); r = sd_bus_set_server(b, 1, server_id); if (r < 0) return log_error_errno(r, "Failed to set server mode: %m"); r = sd_bus_negotiate_fds(b, is_unix); if (r < 0) return log_error_errno(r, "Failed to set FD negotiation: %m"); r = sd_bus_set_anonymous(b, true); if (r < 0) return log_error_errno(r, "Failed to set anonymous authentication: %m"); r = sd_bus_start(b); if (r < 0) return log_error_errno(r, "Failed to start bus client: %m"); for (;;) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; int events_a, events_b, fd; usec_t timeout_a, timeout_b, t; assert_cc(sizeof(usec_t) == sizeof(uint64_t)); r = sd_bus_process(a, &m); if (r < 0) return log_error_errno(r, "Failed to process bus a: %m"); if (m) { r = sd_bus_send(b, m, NULL); if (r < 0) return log_error_errno(r, "Failed to send message: %m"); } if (r > 0) continue; r = sd_bus_process(b, &m); if (r < 0) { /* treat 'connection reset by peer' as clean exit condition */ if (ERRNO_IS_DISCONNECT(r)) return 0; return log_error_errno(r, "Failed to process bus: %m"); } if (m) { r = sd_bus_send(a, m, NULL); if (r < 0) return log_error_errno(r, "Failed to send message: %m"); } if (r > 0) continue; fd = sd_bus_get_fd(a); if (fd < 0) return log_error_errno(fd, "Failed to get fd: %m"); events_a = sd_bus_get_events(a); if (events_a < 0) return log_error_errno(events_a, "Failed to get events mask: %m"); r = sd_bus_get_timeout(a, &timeout_a); if (r < 0) return log_error_errno(r, "Failed to get timeout: %m"); events_b = sd_bus_get_events(b); if (events_b < 0) return log_error_errno(events_b, "Failed to get events mask: %m"); r = sd_bus_get_timeout(b, &timeout_b); if (r < 0) return log_error_errno(r, "Failed to get timeout: %m"); t = usec_sub_unsigned(MIN(timeout_a, timeout_b), now(CLOCK_MONOTONIC)); struct pollfd p[3] = { { .fd = fd, .events = events_a }, { .fd = STDIN_FILENO, .events = events_b & POLLIN }, { .fd = STDOUT_FILENO, .events = events_b & POLLOUT }, }; r = ppoll_usec(p, ELEMENTSOF(p), t); if (r < 0) { if (ERRNO_IS_TRANSIENT(r)) /* don't be bothered by signals, i.e. EINTR */ continue; return log_error_errno(r, "ppoll() failed: %m"); } } return 0; } DEFINE_MAIN_FUNCTION(run);
8,601
32.601563
109
c
null
systemd-main/src/sulogin-shell/sulogin-shell.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2017 Felipe Sateler ***/ #include <errno.h> #include <sys/prctl.h> #include "sd-bus.h" #include "bus-error.h" #include "bus-locator.h" #include "bus-unit-util.h" #include "bus-util.h" #include "constants.h" #include "env-util.h" #include "initrd-util.h" #include "log.h" #include "main-func.h" #include "proc-cmdline.h" #include "process-util.h" #include "signal-util.h" #include "special.h" #include "unit-def.h" static int target_is_inactive(sd_bus *bus, const char *target) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_free_ char *path = NULL, *state = NULL; int r; path = unit_dbus_path_from_name(target); if (!path) return log_oom(); r = sd_bus_get_property_string(bus, "org.freedesktop.systemd1", path, "org.freedesktop.systemd1.Unit", "ActiveState", &error, &state); if (r < 0) return log_error_errno(r, "Failed to retrieve unit state: %s", bus_error_message(&error, r)); return streq_ptr(state, "inactive"); } static int start_target(sd_bus *bus, const char *target) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; int r; log_info("Starting %s", target); /* Start this unit only if we can replace basic.target with it */ r = bus_call_method( bus, bus_systemd_mgr, "StartUnit", &error, NULL, "ss", target, "isolate"); if (r < 0) return log_error_errno(r, "Failed to start %s: %s", target, bus_error_message(&error, r)); return 0; } static int fork_wait(const char* const cmdline[]) { pid_t pid; int r; r = safe_fork("(sulogin)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { /* Child */ execv(cmdline[0], (char**) cmdline); log_error_errno(errno, "Failed to execute %s: %m", cmdline[0]); _exit(EXIT_FAILURE); /* Operational error */ } return wait_for_terminate_and_check(cmdline[0], pid, WAIT_LOG_ABNORMAL); } static void print_mode(const char* mode) { printf("You are in %s mode. After logging in, type \"journalctl -xb\" to view\n" "system logs, \"systemctl reboot\" to reboot, or \"exit\"\n" "to continue bootup.\n", mode); fflush(stdout); } static int run(int argc, char *argv[]) { const char* sulogin_cmdline[] = { SULOGIN, NULL, /* --force */ NULL }; bool force = false; int r; log_setup(); print_mode(argc > 1 ? argv[1] : ""); if (getenv_bool("SYSTEMD_SULOGIN_FORCE") > 0) force = true; if (!force) { /* We look the argument in the kernel cmdline under the same name as the environment variable * to express that this is not supported at the same level as the regular kernel cmdline * switches. */ r = proc_cmdline_get_bool("SYSTEMD_SULOGIN_FORCE", &force); if (r < 0) log_debug_errno(r, "Failed to parse SYSTEMD_SULOGIN_FORCE from kernel command line, ignoring: %m"); } if (force) /* allows passwordless logins if root account is locked. */ sulogin_cmdline[1] = "--force"; for (;;) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; (void) fork_wait(sulogin_cmdline); r = bus_connect_system_systemd(&bus); if (r < 0) { log_warning_errno(r, "Failed to get D-Bus connection: %m"); goto fallback; } log_info("Reloading system manager configuration."); r = bus_service_manager_reload(bus); if (r < 0) goto fallback; const char *target = in_initrd() ? SPECIAL_INITRD_TARGET : SPECIAL_DEFAULT_TARGET; r = target_is_inactive(bus, target); if (r < 0) goto fallback; if (!r) { log_warning("%s is not inactive. Please review the %s setting.", target, target); goto fallback; } if (start_target(bus, target) >= 0) break; fallback: log_warning("Fallback to the single-user shell."); } return 0; } DEFINE_MAIN_FUNCTION(run);
5,103
31.303797
123
c
null
systemd-main/src/sysctl/sysctl.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include "build.h" #include "conf-files.h" #include "constants.h" #include "creds-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "glob-util.h" #include "hashmap.h" #include "log.h" #include "main-func.h" #include "pager.h" #include "path-util.h" #include "pretty-print.h" #include "string-util.h" #include "strv.h" #include "sysctl-util.h" static char **arg_prefixes = NULL; static bool arg_cat_config = false; static bool arg_strict = false; static PagerFlags arg_pager_flags = 0; STATIC_DESTRUCTOR_REGISTER(arg_prefixes, strv_freep); typedef struct Option { char *key; char *value; bool ignore_failure; } Option; static Option *option_free(Option *o) { if (!o) return NULL; free(o->key); free(o->value); return mfree(o); } DEFINE_TRIVIAL_CLEANUP_FUNC(Option*, option_free); DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(option_hash_ops, char, string_hash_func, string_compare_func, Option, option_free); static bool test_prefix(const char *p) { if (strv_isempty(arg_prefixes)) return true; return path_startswith_strv(p, arg_prefixes); } static Option *option_new( const char *key, const char *value, bool ignore_failure) { _cleanup_(option_freep) Option *o = NULL; assert(key); o = new(Option, 1); if (!o) return NULL; *o = (Option) { .key = strdup(key), .value = value ? strdup(value) : NULL, .ignore_failure = ignore_failure, }; if (!o->key) return NULL; if (value && !o->value) return NULL; return TAKE_PTR(o); } static int sysctl_write_or_warn(const char *key, const char *value, bool ignore_failure, bool ignore_enoent) { int r; r = sysctl_write(key, value); if (r < 0) { /* Proceed without failing if ignore_failure is true. * If the sysctl is not available in the kernel or we are running with reduced privileges and * cannot write it, then log about the issue, and proceed without failing. Unless strict mode * (arg_strict = true) is enabled, in which case we should fail. (EROFS is treated as a * permission problem here, since that's how container managers usually protected their * sysctls.) * In all other cases log an error and make the tool fail. */ if (ignore_failure || (!arg_strict && (r == -EROFS || ERRNO_IS_PRIVILEGE(r)))) log_debug_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key); else if (ignore_enoent && r == -ENOENT) log_warning_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key); else return log_error_errno(r, "Couldn't write '%s' to '%s': %m", value, key); } return 0; } static int apply_glob_option_with_prefix(OrderedHashmap *sysctl_options, Option *option, const char *prefix) { _cleanup_strv_free_ char **paths = NULL; _cleanup_free_ char *pattern = NULL; int r, k; assert(sysctl_options); assert(option); if (prefix) { _cleanup_free_ char *key = NULL; r = path_glob_can_match(option->key, prefix, &key); if (r < 0) return log_error_errno(r, "Failed to check if the glob '%s' matches prefix '%s': %m", option->key, prefix); if (r == 0) { log_debug("The glob '%s' does not match prefix '%s'.", option->key, prefix); return 0; } log_debug("The glob '%s' is prefixed with '%s': '%s'", option->key, prefix, key); if (!string_is_glob(key)) { /* The prefixed pattern is not glob anymore. Let's skip to call glob(). */ if (ordered_hashmap_contains(sysctl_options, key)) { log_debug("Not setting %s (explicit setting exists).", key); return 0; } return sysctl_write_or_warn(key, option->value, /* ignore_failure = */ option->ignore_failure, /* ignore_enoent = */ true); } pattern = path_join("/proc/sys", key); } else pattern = path_join("/proc/sys", option->key); if (!pattern) return log_oom(); r = glob_extend(&paths, pattern, GLOB_NOCHECK); if (r < 0) { if (r == -ENOENT) { log_debug("No match for glob: %s", option->key); return 0; } if (option->ignore_failure || ERRNO_IS_PRIVILEGE(r)) { log_debug_errno(r, "Failed to resolve glob '%s', ignoring: %m", option->key); return 0; } else return log_error_errno(r, "Couldn't resolve glob '%s': %m", option->key); } STRV_FOREACH(s, paths) { const char *key; assert_se(key = path_startswith(*s, "/proc/sys")); if (ordered_hashmap_contains(sysctl_options, key)) { log_debug("Not setting %s (explicit setting exists).", key); continue; } k = sysctl_write_or_warn(key, option->value, /* ignore_failure = */ option->ignore_failure, /* ignore_enoent = */ !arg_strict); if (k < 0 && r >= 0) r = k; } return r; } static int apply_glob_option(OrderedHashmap *sysctl_options, Option *option) { int r = 0, k; if (strv_isempty(arg_prefixes)) return apply_glob_option_with_prefix(sysctl_options, option, NULL); STRV_FOREACH(i, arg_prefixes) { k = apply_glob_option_with_prefix(sysctl_options, option, *i); if (k < 0 && r >= 0) r = k; } return r; } static int apply_all(OrderedHashmap *sysctl_options) { Option *option; int r = 0; ORDERED_HASHMAP_FOREACH(option, sysctl_options) { int k; /* Ignore "negative match" options, they are there only to exclude stuff from globs. */ if (!option->value) continue; if (string_is_glob(option->key)) k = apply_glob_option(sysctl_options, option); else k = sysctl_write_or_warn(option->key, option->value, /* ignore_failure = */ option->ignore_failure, /* ignore_enoent = */ !arg_strict); if (k < 0 && r >= 0) r = k; } return r; } static int parse_file(OrderedHashmap **sysctl_options, const char *path, bool ignore_enoent) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *pp = NULL; unsigned c = 0; int r; assert(path); r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("sysctl.d"), &f, &pp); if (r < 0) { if (ignore_enoent && r == -ENOENT) return 0; return log_error_errno(r, "Failed to open file '%s', ignoring: %m", path); } log_debug("Parsing %s", pp); for (;;) { _cleanup_(option_freep) Option *new_option = NULL; _cleanup_free_ char *l = NULL; bool ignore_failure = false; Option *existing; char *p, *value; int k; k = read_line(f, LONG_LINE_MAX, &l); if (k == 0) break; if (k < 0) return log_error_errno(k, "Failed to read file '%s', ignoring: %m", pp); c++; p = strstrip(l); if (isempty(p)) continue; if (strchr(COMMENTS "\n", *p)) continue; value = strchr(p, '='); if (value) { if (p[0] == '-') { ignore_failure = true; p++; } *value = 0; value++; value = strstrip(value); } else { if (p[0] == '-') /* We have a "negative match" option. Let's continue with value==NULL. */ p++; else { log_syntax(NULL, LOG_WARNING, pp, c, 0, "Line is not an assignment, ignoring: %s", p); if (r == 0) r = -EINVAL; continue; } } p = strstrip(p); p = sysctl_normalize(p); /* We can't filter out globs at this point, we'll need to do that later. */ if (!string_is_glob(p) && !test_prefix(p)) continue; existing = ordered_hashmap_get(*sysctl_options, p); if (existing) { if (streq_ptr(value, existing->value)) { existing->ignore_failure = existing->ignore_failure || ignore_failure; continue; } log_debug("Overwriting earlier assignment of %s at '%s:%u'.", p, pp, c); option_free(ordered_hashmap_remove(*sysctl_options, p)); } new_option = option_new(p, value, ignore_failure); if (!new_option) return log_oom(); k = ordered_hashmap_ensure_put(sysctl_options, &option_hash_ops, new_option->key, new_option); if (k < 0) return log_error_errno(k, "Failed to add sysctl variable %s to hashmap: %m", p); TAKE_PTR(new_option); } return r; } static int read_credential_lines(OrderedHashmap **sysctl_options) { _cleanup_free_ char *j = NULL; const char *d; int r; r = get_credentials_dir(&d); if (r == -ENXIO) return 0; if (r < 0) return log_error_errno(r, "Failed to get credentials directory: %m"); j = path_join(d, "sysctl.extra"); if (!j) return log_oom(); (void) parse_file(sysctl_options, j, /* ignore_enoent= */ true); return 0; } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-sysctl.service", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n" "Applies kernel sysctl settings.\n\n" " -h --help Show this help\n" " --version Show package version\n" " --cat-config Show configuration files\n" " --prefix=PATH Only apply rules with the specified prefix\n" " --no-pager Do not pipe output into a pager\n" "\nSee the %s for details.\n", program_invocation_short_name, link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_CAT_CONFIG, ARG_PREFIX, ARG_NO_PAGER, ARG_STRICT, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "cat-config", no_argument, NULL, ARG_CAT_CONFIG }, { "prefix", required_argument, NULL, ARG_PREFIX }, { "no-pager", no_argument, NULL, ARG_NO_PAGER }, { "strict", no_argument, NULL, ARG_STRICT }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_CAT_CONFIG: arg_cat_config = true; break; case ARG_PREFIX: { const char *s; char *p; /* We used to require people to specify absolute paths * in /proc/sys in the past. This is kinda useless, but * we need to keep compatibility. We now support any * sysctl name available. */ sysctl_normalize(optarg); s = path_startswith(optarg, "/proc/sys"); p = strdup(s ?: optarg); if (!p) return log_oom(); if (strv_consume(&arg_prefixes, p) < 0) return log_oom(); break; } case ARG_NO_PAGER: arg_pager_flags |= PAGER_DISABLE; break; case ARG_STRICT: arg_strict = true; break; case '?': return -EINVAL; default: assert_not_reached(); } if (arg_cat_config && argc > optind) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Positional arguments are not allowed with --cat-config"); return 1; } static int run(int argc, char *argv[]) { _cleanup_ordered_hashmap_free_ OrderedHashmap *sysctl_options = NULL; int r, k; r = parse_argv(argc, argv); if (r <= 0) return r; log_setup(); umask(0022); if (argc > optind) { int i; r = 0; for (i = optind; i < argc; i++) { k = parse_file(&sysctl_options, argv[i], false); if (k < 0 && r == 0) r = k; } } else { _cleanup_strv_free_ char **files = NULL; r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char**) CONF_PATHS_STRV("sysctl.d")); if (r < 0) return log_error_errno(r, "Failed to enumerate sysctl.d files: %m"); if (arg_cat_config) { pager_open(arg_pager_flags); return cat_files(NULL, files, 0); } STRV_FOREACH(f, files) { k = parse_file(&sysctl_options, *f, true); if (k < 0 && r == 0) r = k; } k = read_credential_lines(&sysctl_options); if (k < 0 && r == 0) r = k; } k = apply_all(sysctl_options); if (k < 0 && r == 0) r = k; return r; } DEFINE_MAIN_FUNCTION(run);
16,585
32.238477
121
c
null
systemd-main/src/system-update-generator/system-update-generator.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <unistd.h> #include "fs-util.h" #include "generator.h" #include "initrd-util.h" #include "log.h" #include "path-util.h" #include "proc-cmdline.h" #include "special.h" #include "string-util.h" #include "unit-file.h" /* * Implements the logic described in systemd.offline-updates(7). */ static const char *arg_dest = NULL; static int generate_symlink(void) { FOREACH_STRING(p, "/system-update", "/etc/system-update") { if (laccess(p, F_OK) >= 0) { _cleanup_free_ char *j = NULL; j = path_join(arg_dest, SPECIAL_DEFAULT_TARGET); if (!j) return log_oom(); if (symlink(SYSTEM_DATA_UNIT_DIR "/system-update.target", j) < 0) return log_error_errno(errno, "Failed to create symlink %s: %m", j); return 1; } if (errno != ENOENT) log_warning_errno(errno, "Failed to check if %s symlink exists, ignoring: %m", p); } return 0; } static int parse_proc_cmdline_item(const char *key, const char *value, void *data) { assert(key); /* Check if a run level is specified on the kernel command line. The * command line has higher priority than any on-disk configuration, so * it'll make any symlink we create moot. */ if (streq(key, "systemd.unit") && !proc_cmdline_value_missing(key, value)) log_warning("Offline system update overridden by kernel command line systemd.unit= setting"); else if (!value && runlevel_to_target(key)) log_warning("Offline system update overridden by runlevel \"%s\" on the kernel command line", key); return 0; } static int run(const char *dest, const char *dest_early, const char *dest_late) { int r; assert_se(arg_dest = dest_early); if (in_initrd()) { log_debug("Skipping generator, running in the initrd."); return EXIT_SUCCESS; } r = generate_symlink(); if (r <= 0) return r; /* We parse the command line only to emit warnings. */ r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0); if (r < 0) log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m"); return 0; } DEFINE_MAIN_GENERATOR_FUNCTION(run);
2,562
29.879518
115
c
null
systemd-main/src/systemctl/fuzz-systemctl-parse-argv.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include <unistd.h> #include "env-util.h" #include "fd-util.h" #include "fuzz.h" #include "nulstr-util.h" #include "selinux-util.h" #include "static-destruct.h" #include "stdio-util.h" #include "strv.h" #include "systemctl.h" #include "systemctl-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_strv_free_ char **argv = NULL; _cleanup_close_ int orig_stdout_fd = -EBADF; int r; if (size > 16*1024) return 0; /* See the comment below about the limit for strv_length(). */ /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); arg_pager_flags = PAGER_DISABLE; /* We shouldn't execute the pager */ argv = strv_parse_nulstr((const char *)data, size); if (!argv) return log_oom(); if (!argv[0]) return 0; /* argv[0] should always be present, but may be zero-length. */ if (strv_length(argv) > 1024) return 0; /* oss-fuzz reports timeouts which are caused by appending to a very long strv. * The code is indeed not very efficient, but it's designed for normal command-line * use, where we don't expect more than a dozen of entries. The fact that it is * slow with ~100k entries is not particularly interesting. Let's just refuse such * long command lines. */ if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0) { orig_stdout_fd = fcntl(fileno(stdout), F_DUPFD_CLOEXEC, 3); if (orig_stdout_fd < 0) log_warning_errno(orig_stdout_fd, "Failed to duplicate fd 1: %m"); else assert_se(freopen("/dev/null", "w", stdout)); opterr = 0; /* do not print errors */ } optind = 0; /* this tells the getopt machinery to reinitialize */ r = systemctl_dispatch_parse_argv(strv_length(argv), argv); if (r < 0) log_error_errno(r, "Failed to parse args: %m"); else log_info(r == 0 ? "Done!" : "Action!"); if (orig_stdout_fd >= 0) assert_se(freopen(FORMAT_PROC_FD_PATH(orig_stdout_fd), "w", stdout)); release_busses(); /* We open the bus for communication with logind. * It needs to be closed to avoid apparent leaks. */ mac_selinux_finish(); /* Call static destructors to do global state cleanup. We do it here, and not in fuzz-main.c so that * any global state is destroyed between fuzzer runs. */ static_destruct(); return 0; }
2,919
36.922078
109
c
null
systemd-main/src/systemctl/systemctl-cancel-job.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "parse-util.h" #include "systemctl-cancel-job.h" #include "systemctl-trivial-method.h" #include "systemctl-util.h" #include "systemctl.h" int verb_cancel(int argc, char *argv[], void *userdata) { sd_bus *bus; int r; if (argc <= 1) /* Shortcut to trivial_method() if no argument is given */ return verb_trivial_method(argc, argv, userdata); r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); STRV_FOREACH(name, strv_skip(argv, 1)) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; uint32_t id; int q; q = safe_atou32(*name, &id); if (q < 0) return log_error_errno(q, "Failed to parse job id \"%s\": %m", *name); q = bus_call_method(bus, bus_systemd_mgr, "CancelJob", &error, NULL, "u", id); if (q < 0) { log_error_errno(q, "Failed to cancel job %"PRIu32": %s", id, bus_error_message(&error, q)); if (r == 0) r = q; } } return r; }
1,335
30.069767
115
c
null
systemd-main/src/systemctl/systemctl-clean-or-freeze.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "bus-wait-for-units.h" #include "systemctl-clean-or-freeze.h" #include "systemctl-util.h" #include "systemctl.h" int verb_clean_or_freeze(int argc, char *argv[], void *userdata) { _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *w = NULL; _cleanup_strv_free_ char **names = NULL; int r, ret = EXIT_SUCCESS; const char *method; sd_bus *bus; r = acquire_bus(BUS_FULL, &bus); if (r < 0) return r; polkit_agent_open_maybe(); if (!arg_clean_what) { arg_clean_what = strv_new("cache", "runtime", "fdstore"); if (!arg_clean_what) return log_oom(); } r = expand_unit_names(bus, strv_skip(argv, 1), NULL, &names, NULL); if (r < 0) return log_error_errno(r, "Failed to expand names: %m"); if (!arg_no_block) { r = bus_wait_for_units_new(bus, &w); if (r < 0) return log_error_errno(r, "Failed to allocate unit waiter: %m"); } if (streq(argv[0], "clean")) method = "CleanUnit"; else if (streq(argv[0], "freeze")) method = "FreezeUnit"; else if (streq(argv[0], "thaw")) method = "ThawUnit"; else assert_not_reached(); STRV_FOREACH(name, names) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; if (w) { /* If we shall wait for the cleaning to complete, let's add a ref on the unit first */ r = bus_call_method(bus, bus_systemd_mgr, "RefUnit", &error, NULL, "s", *name); if (r < 0) { log_error_errno(r, "Failed to add reference to unit %s: %s", *name, bus_error_message(&error, r)); if (ret == EXIT_SUCCESS) ret = r; continue; } } r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append(m, "s", *name); if (r < 0) return bus_log_create_error(r); if (streq(method, "CleanUnit")) { r = sd_bus_message_append_strv(m, arg_clean_what); if (r < 0) return bus_log_create_error(r); } r = sd_bus_call(bus, m, 0, &error, NULL); if (r < 0) { log_error_errno(r, "Failed to %s unit %s: %s", argv[0], *name, bus_error_message(&error, r)); if (ret == EXIT_SUCCESS) { ret = r; continue; } } if (w) { r = bus_wait_for_units_add_unit(w, *name, BUS_WAIT_REFFED|BUS_WAIT_FOR_MAINTENANCE_END, NULL, NULL); if (r < 0) return log_error_errno(r, "Failed to watch unit %s: %m", *name); } } r = bus_wait_for_units_run(w); if (r < 0) return log_error_errno(r, "Failed to wait for units: %m"); if (r == BUS_WAIT_FAILURE) ret = EXIT_FAILURE; return ret; }
3,748
36.118812
130
c
null
systemd-main/src/systemctl/systemctl-compat-halt.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <unistd.h> #include "sd-daemon.h" #include "alloc-util.h" #include "pretty-print.h" #include "process-util.h" #include "reboot-util.h" #include "systemctl-compat-halt.h" #include "systemctl-compat-telinit.h" #include "systemctl-logind.h" #include "systemctl-start-unit.h" #include "systemctl-util.h" #include "systemctl.h" #include "terminal-util.h" #include "utmp-wtmp.h" static int halt_help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("halt", "8", &link); if (r < 0) return log_oom(); /* Note: if you are tempted to add new command line switches here, please do not. Let this * compatibility command rest in peace. Its interface is not even owned by us as much as it is by * sysvinit. If you add something new, add it to "systemctl halt", "systemctl reboot", "systemctl * poweroff" instead. */ printf("%s [OPTIONS...]%s\n" "\n%s%s the system.%s\n" "\nOptions:\n" " --help Show this help\n" " --halt Halt the machine\n" " -p --poweroff Switch off the machine\n" " --reboot Reboot the machine\n" " -f --force Force immediate halt/power-off/reboot\n" " -w --wtmp-only Don't halt/power-off/reboot, just write wtmp record\n" " -d --no-wtmp Don't write wtmp record\n" " --no-wall Don't send wall message before halt/power-off/reboot\n" "\n%sThis is a compatibility interface, please use the more powerful 'systemctl %s' command instead.%s\n" "\nSee the %s for details.\n", program_invocation_short_name, arg_action == ACTION_REBOOT ? " [ARG]" : "", ansi_highlight(), arg_action == ACTION_REBOOT ? "Reboot" : arg_action == ACTION_POWEROFF ? "Power off" : "Halt", ansi_normal(), ansi_highlight_red(), arg_action == ACTION_REBOOT ? "reboot" : arg_action == ACTION_POWEROFF ? "poweroff" : "halt", ansi_normal(), link); return 0; } int halt_parse_argv(int argc, char *argv[]) { enum { ARG_HELP = 0x100, ARG_HALT, ARG_REBOOT, ARG_NO_WALL }; static const struct option options[] = { { "help", no_argument, NULL, ARG_HELP }, { "halt", no_argument, NULL, ARG_HALT }, { "poweroff", no_argument, NULL, 'p' }, { "reboot", no_argument, NULL, ARG_REBOOT }, { "force", no_argument, NULL, 'f' }, { "wtmp-only", no_argument, NULL, 'w' }, { "no-wtmp", no_argument, NULL, 'd' }, { "no-sync", no_argument, NULL, 'n' }, { "no-wall", no_argument, NULL, ARG_NO_WALL }, {} }; int c, r, runlevel; assert(argc >= 0); assert(argv); /* called in sysvinit system as last command in shutdown/reboot so this is always forceful */ if (utmp_get_runlevel(&runlevel, NULL) >= 0) if (IN_SET(runlevel, '0', '6')) arg_force = 2; while ((c = getopt_long(argc, argv, "pfwdnih", options, NULL)) >= 0) switch (c) { case ARG_HELP: return halt_help(); case ARG_HALT: arg_action = ACTION_HALT; break; case 'p': if (arg_action != ACTION_REBOOT) arg_action = ACTION_POWEROFF; break; case ARG_REBOOT: arg_action = ACTION_REBOOT; break; case 'f': arg_force = 2; break; case 'w': arg_dry_run = true; break; case 'd': arg_no_wtmp = true; break; case 'n': arg_no_sync = true; break; case ARG_NO_WALL: arg_no_wall = true; break; case 'i': case 'h': /* Compatibility nops */ break; case '?': return -EINVAL; default: assert_not_reached(); } if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) { r = update_reboot_parameter_and_warn(argc == optind + 1 ? argv[optind] : NULL, false); if (r < 0) return r; } else if (optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments."); return 1; } int halt_main(void) { int r; if (arg_force == 0) { /* always try logind first */ if (arg_when > 0) r = logind_schedule_shutdown(arg_action); else { r = logind_check_inhibitors(arg_action); if (r < 0) return r; r = logind_reboot(arg_action); } if (r >= 0) return r; if (IN_SET(r, -EACCES, -EOPNOTSUPP, -EINPROGRESS)) /* Requested operation requires auth, is not supported on the local system or already in * progress */ return r; /* on all other errors, try low-level operation */ /* In order to minimize the difference between operation with and without logind, we explicitly * enable non-blocking mode for this, as logind's shutdown operations are always non-blocking. */ arg_no_block = true; if (!arg_dry_run) return start_with_fallback(); } if (geteuid() != 0) { (void) must_be_root(); return -EPERM; } if (!arg_no_wtmp) { if (sd_booted() > 0) log_debug("Not writing utmp record, assuming that systemd-update-utmp is used."); else { r = utmp_put_shutdown(); if (r < 0) log_warning_errno(r, "Failed to write utmp record: %m"); } } if (arg_dry_run) return 0; r = halt_now(arg_action); return log_error_errno(r, "Failed to %s: %m", action_table[arg_action].verb); }
7,379
35.176471
120
c
null
systemd-main/src/systemctl/systemctl-compat-runlevel.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "alloc-util.h" #include "pretty-print.h" #include "systemctl-compat-runlevel.h" #include "systemctl.h" #include "terminal-util.h" #include "utmp-wtmp.h" static int runlevel_help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("runlevel", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...]\n" "\n%sPrints the previous and current runlevel of the init system.%s\n" "\nOptions:\n" " --help Show this help\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } int runlevel_parse_argv(int argc, char *argv[]) { enum { ARG_HELP = 0x100, }; static const struct option options[] = { { "help", no_argument, NULL, ARG_HELP }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) switch (c) { case ARG_HELP: return runlevel_help(); case '?': return -EINVAL; default: assert_not_reached(); } if (optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments."); return 1; } int runlevel_main(void) { int r, runlevel, previous; r = utmp_get_runlevel(&runlevel, &previous); if (r < 0) { puts("unknown"); return r; } printf("%c %c\n", previous <= 0 ? 'N' : previous, runlevel <= 0 ? 'N' : runlevel); return 0; }
2,026
23.421687
85
c
null
systemd-main/src/systemctl/systemctl-compat-shutdown.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "alloc-util.h" #include "pretty-print.h" #include "reboot-util.h" #include "systemctl-compat-shutdown.h" #include "systemctl-sysv-compat.h" #include "systemctl.h" #include "terminal-util.h" static int shutdown_help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("shutdown", "8", &link); if (r < 0) return log_oom(); /* Note: if you are tempted to add new command line switches here, please do not. Let this * compatibility command rest in peace. Its interface is not even owned by us as much as it is by * sysvinit. If you add something new, add it to "systemctl halt", "systemctl reboot", "systemctl * poweroff" instead. */ printf("%s [OPTIONS...] [TIME] [WALL...]\n" "\n%sShut down the system.%s\n" "\nOptions:\n" " --help Show this help\n" " -H --halt Halt the machine\n" " -P --poweroff Power-off the machine\n" " -r --reboot Reboot the machine\n" " -h Equivalent to --poweroff, overridden by --halt\n" " -k Don't halt/power-off/reboot, just send warnings\n" " --no-wall Don't send wall message before halt/power-off/reboot\n" " -c Cancel a pending shutdown\n" " --show Show pending shutdown\n" "\n%sThis is a compatibility interface, please use the more powerful 'systemctl reboot',\n" "'systemctl poweroff', 'systemctl reboot' commands instead.%s\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), ansi_highlight_red(), ansi_normal(), link); return 0; } int shutdown_parse_argv(int argc, char *argv[]) { enum { ARG_HELP = 0x100, ARG_NO_WALL, ARG_SHOW }; static const struct option options[] = { { "help", no_argument, NULL, ARG_HELP }, { "halt", no_argument, NULL, 'H' }, { "poweroff", no_argument, NULL, 'P' }, { "reboot", no_argument, NULL, 'r' }, { "kexec", no_argument, NULL, 'K' }, /* not documented extension */ { "no-wall", no_argument, NULL, ARG_NO_WALL }, { "show", no_argument, NULL, ARG_SHOW }, {} }; char **wall = NULL; int c, r; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "HPrhkKat:fFc", options, NULL)) >= 0) switch (c) { case ARG_HELP: return shutdown_help(); case 'H': arg_action = ACTION_HALT; break; case 'P': arg_action = ACTION_POWEROFF; break; case 'r': if (kexec_loaded()) arg_action = ACTION_KEXEC; else arg_action = ACTION_REBOOT; break; case 'K': arg_action = ACTION_KEXEC; break; case 'h': if (arg_action != ACTION_HALT) arg_action = ACTION_POWEROFF; break; case 'k': arg_dry_run = true; break; case ARG_NO_WALL: arg_no_wall = true; break; case 'a': case 't': /* Note that we also ignore any passed argument to -t, not just the -t itself */ case 'f': case 'F': /* Compatibility nops */ break; case 'c': arg_action = ACTION_CANCEL_SHUTDOWN; break; case ARG_SHOW: arg_action = ACTION_SHOW_SHUTDOWN; break; case '?': return -EINVAL; default: assert_not_reached(); } if (argc > optind && arg_action != ACTION_CANCEL_SHUTDOWN) { r = parse_shutdown_time_spec(argv[optind], &arg_when); if (r < 0) { log_error("Failed to parse time specification: %s", argv[optind]); return r; } } else arg_when = now(CLOCK_REALTIME) + USEC_PER_MINUTE; if (argc > optind && arg_action == ACTION_CANCEL_SHUTDOWN) /* No time argument for shutdown cancel */ wall = argv + optind; else if (argc > optind + 1) /* We skip the time argument */ wall = argv + optind + 1; if (wall) { char **copy = strv_copy(wall); if (!copy) return log_oom(); strv_free_and_replace(arg_wall, copy); } optind = argc; return 1; }
5,586
33.91875
106
c
null
systemd-main/src/systemctl/systemctl-compat-telinit.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <unistd.h> #include "alloc-util.h" #include "pretty-print.h" #include "rlimit-util.h" #include "systemctl-compat-telinit.h" #include "systemctl-daemon-reload.h" #include "systemctl-start-unit.h" #include "systemctl-sysv-compat.h" #include "systemctl.h" #include "terminal-util.h" static int telinit_help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("telinit", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] COMMAND\n\n" "%sSend control commands to the init daemon.%s\n" "\nCommands:\n" " 0 Power-off the machine\n" " 6 Reboot the machine\n" " 2, 3, 4, 5 Start runlevelX.target unit\n" " 1, s, S Enter rescue mode\n" " q, Q Reload init daemon configuration\n" " u, U Reexecute init daemon\n" "\nOptions:\n" " --help Show this help\n" " --no-wall Don't send wall message before halt/power-off/reboot\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } int telinit_parse_argv(int argc, char *argv[]) { enum { ARG_HELP = 0x100, ARG_NO_WALL }; static const struct option options[] = { { "help", no_argument, NULL, ARG_HELP }, { "no-wall", no_argument, NULL, ARG_NO_WALL }, {} }; static const struct { char from; enum action to; } table[] = { { '0', ACTION_POWEROFF }, { '6', ACTION_REBOOT }, { '1', ACTION_RESCUE }, { '2', ACTION_RUNLEVEL2 }, { '3', ACTION_RUNLEVEL3 }, { '4', ACTION_RUNLEVEL4 }, { '5', ACTION_RUNLEVEL5 }, { 's', ACTION_RESCUE }, { 'S', ACTION_RESCUE }, { 'q', ACTION_RELOAD }, { 'Q', ACTION_RELOAD }, { 'u', ACTION_REEXEC }, { 'U', ACTION_REEXEC } }; unsigned i; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "", options, NULL)) >= 0) switch (c) { case ARG_HELP: return telinit_help(); case ARG_NO_WALL: arg_no_wall = true; break; case '?': return -EINVAL; default: assert_not_reached(); } if (optind >= argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s: required argument missing.", program_invocation_short_name); if (optind + 1 < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments."); if (strlen(argv[optind]) != 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected single character argument."); for (i = 0; i < ELEMENTSOF(table); i++) if (table[i].from == argv[optind][0]) break; if (i >= ELEMENTSOF(table)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'.", argv[optind]); arg_action = table[i].to; optind++; return 1; } int start_with_fallback(void) { int r; /* First, try systemd via D-Bus. */ r = verb_start(0, NULL, NULL); if (r == 0) return 0; #if HAVE_SYSV_COMPAT /* Nothing else worked, so let's try /dev/initctl */ if (talk_initctl(action_to_runlevel()) > 0) return 0; #endif return log_error_errno(r, "Failed to talk to init daemon: %m"); } int reload_with_fallback(void) { assert(IN_SET(arg_action, ACTION_RELOAD, ACTION_REEXEC)); /* First, try systemd via D-Bus */ if (daemon_reload(arg_action, /* graceful= */ true) > 0) return 0; /* That didn't work, so let's try signals */ if (kill(1, arg_action == ACTION_RELOAD ? SIGHUP : SIGTERM) < 0) return log_error_errno(errno, "kill() failed: %m"); return 0; } int exec_telinit(char *argv[]) { (void) rlimit_nofile_safe(); (void) execv(TELINIT, argv); return log_error_errno(SYNTHETIC_ERRNO(EIO), "Couldn't find an alternative telinit implementation to spawn."); }
5,078
29.596386
96
c
null
systemd-main/src/systemctl/systemctl-daemon-reload.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-daemon-reload.h" #include "systemctl-util.h" #include "systemctl.h" int daemon_reload(enum action action, bool graceful) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; const char *method; sd_bus *bus; int r; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); switch (action) { case ACTION_RELOAD: method = "Reload"; break; case ACTION_REEXEC: method = "Reexecute"; break; default: return -EINVAL; } r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method); if (r < 0) return bus_log_create_error(r); /* Reloading the daemon may take long, hence set a longer timeout here */ r = sd_bus_call(bus, m, DAEMON_RELOAD_TIMEOUT_SEC, &error, NULL); /* On reexecution, we expect a disconnect, not a reply */ if (IN_SET(r, -ETIMEDOUT, -ECONNRESET) && action == ACTION_REEXEC) return 1; if (r < 0) { if (graceful) { /* If graceful mode is selected, debug log, but don't fail */ log_debug_errno(r, "Failed to reload daemon via the bus, ignoring: %s", bus_error_message(&error, r)); return 0; } return log_error_errno(r, "Failed to reload daemon: %s", bus_error_message(&error, r)); } return 1; } int verb_daemon_reload(int argc, char *argv[], void *userdata) { enum action a; int r; assert(argc >= 1); if (streq(argv[0], "daemon-reexec")) a = ACTION_REEXEC; else if (streq(argv[0], "daemon-reload")) a = ACTION_RELOAD; else assert_not_reached(); r = daemon_reload(a, /* graceful= */ false); if (r < 0) return r; return 0; }
2,207
27.675325
126
c
null
systemd-main/src/systemctl/systemctl-enable.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "locale-util.h" #include "path-util.h" #include "systemctl-daemon-reload.h" #include "systemctl-enable.h" #include "systemctl-start-unit.h" #include "systemctl-sysv-compat.h" #include "systemctl-util.h" #include "systemctl.h" static int normalize_filenames(char **names) { int r; STRV_FOREACH(u, names) if (!path_is_absolute(*u)) { char* normalized_path; if (!isempty(arg_root)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Non-absolute paths are not allowed when --root is used: %s", *u); if (!strchr(*u, '/')) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Link argument must contain at least one directory separator.\n" "If you intended to link a file in the current directory, try ./%s instead.", *u); r = path_make_absolute_cwd(*u, &normalized_path); if (r < 0) return r; free_and_replace(*u, normalized_path); } return 0; } static int normalize_names(char **names) { bool was_path = false; STRV_FOREACH(u, names) { int r; if (!is_path(*u)) continue; r = free_and_strdup(u, basename(*u)); if (r < 0) return log_error_errno(r, "Failed to normalize unit file path: %m"); was_path = true; } if (was_path) log_warning("Warning: Can't execute disable on the unit file path. Proceeding with the unit name."); return 0; } int verb_enable(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **names = NULL; const char *verb = argv[0]; int carries_install_info = -1; bool ignore_carries_install_info = arg_quiet || arg_no_warn; int r; if (!argv[1]) return 0; r = mangle_names("to enable", strv_skip(argv, 1), &names); if (r < 0) return r; r = enable_sysv_units(verb, names); if (r < 0) return r; /* If the operation was fully executed by the SysV compat, let's finish early */ if (strv_isempty(names)) { if (arg_no_reload || install_client_side()) return 0; r = daemon_reload(ACTION_RELOAD, /* graceful= */ false); return r > 0 ? 0 : r; } if (streq(verb, "disable")) { r = normalize_names(names); if (r < 0) return r; } if (streq(verb, "link")) { r = normalize_filenames(names); if (r < 0) return r; } if (install_client_side()) { UnitFileFlags flags; InstallChange *changes = NULL; size_t n_changes = 0; CLEANUP_ARRAY(changes, n_changes, install_changes_free); flags = unit_file_flags_from_args(); if (streq(verb, "enable")) { r = unit_file_enable(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); carries_install_info = r; } else if (streq(verb, "disable")) { r = unit_file_disable(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); carries_install_info = r; } else if (streq(verb, "reenable")) { r = unit_file_reenable(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); carries_install_info = r; } else if (streq(verb, "link")) r = unit_file_link(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); else if (streq(verb, "preset")) r = unit_file_preset(arg_runtime_scope, flags, arg_root, names, arg_preset_mode, &changes, &n_changes); else if (streq(verb, "mask")) r = unit_file_mask(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); else if (streq(verb, "unmask")) r = unit_file_unmask(arg_runtime_scope, flags, arg_root, names, &changes, &n_changes); else if (streq(verb, "revert")) r = unit_file_revert(arg_runtime_scope, arg_root, names, &changes, &n_changes); else assert_not_reached(); install_changes_dump(r, verb, changes, n_changes, arg_quiet); if (r < 0) return r; } else { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; bool expect_carries_install_info = false; bool send_runtime = true, send_force = true, send_preset_mode = false; const char *method; sd_bus *bus; if (STR_IN_SET(verb, "mask", "unmask")) { _cleanup_(lookup_paths_free) LookupPaths lp = {}; r = lookup_paths_init_or_warn(&lp, arg_runtime_scope, 0, arg_root); if (r < 0) return r; STRV_FOREACH(name, names) { r = unit_exists(&lp, *name); if (r < 0) return r; if (r == 0) log_notice("Unit %s does not exist, proceeding anyway.", *name); } } r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); if (streq(verb, "enable")) { method = "EnableUnitFiles"; expect_carries_install_info = true; } else if (streq(verb, "disable")) { method = "DisableUnitFilesWithFlagsAndInstallInfo"; expect_carries_install_info = true; send_force = false; } else if (streq(verb, "reenable")) { method = "ReenableUnitFiles"; expect_carries_install_info = true; } else if (streq(verb, "link")) method = "LinkUnitFiles"; else if (streq(verb, "preset")) { if (arg_preset_mode != UNIT_FILE_PRESET_FULL) { method = "PresetUnitFilesWithMode"; send_preset_mode = true; } else method = "PresetUnitFiles"; expect_carries_install_info = true; ignore_carries_install_info = true; } else if (streq(verb, "mask")) method = "MaskUnitFiles"; else if (streq(verb, "unmask")) { method = "UnmaskUnitFiles"; send_force = false; } else if (streq(verb, "revert")) { method = "RevertUnitFiles"; send_runtime = send_force = false; } else assert_not_reached(); r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, method); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append_strv(m, names); if (r < 0) return bus_log_create_error(r); if (send_preset_mode) { r = sd_bus_message_append(m, "s", unit_file_preset_mode_to_string(arg_preset_mode)); if (r < 0) return bus_log_create_error(r); } if (send_runtime) { if (streq(method, "DisableUnitFilesWithFlagsAndInstallInfo")) r = sd_bus_message_append(m, "t", arg_runtime ? (uint64_t) UNIT_FILE_RUNTIME : UINT64_C(0)); else r = sd_bus_message_append(m, "b", arg_runtime); if (r < 0) return bus_log_create_error(r); } if (send_force) { r = sd_bus_message_append(m, "b", arg_force); if (r < 0) return bus_log_create_error(r); } r = sd_bus_call(bus, m, 0, &error, &reply); if (r < 0) return log_error_errno(r, "Failed to %s unit: %s", verb, bus_error_message(&error, r)); if (expect_carries_install_info) { r = sd_bus_message_read(reply, "b", &carries_install_info); if (r < 0) return bus_log_parse_error(r); } r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet); if (r < 0) return r; /* Try to reload if enabled */ if (!arg_no_reload) { r = daemon_reload(ACTION_RELOAD, /* graceful= */ false); if (r < 0) return r; } } if (carries_install_info == 0 && !ignore_carries_install_info) log_notice("The unit files have no installation config (WantedBy=, RequiredBy=, UpheldBy=,\n" "Also=, or Alias= settings in the [Install] section, and DefaultInstance= for\n" "template units). This means they are not meant to be enabled or disabled using systemctl.\n" " \n" /* trick: the space is needed so that the line does not get stripped from output */ "Possible reasons for having this kind of units are:\n" "%1$s A unit may be statically enabled by being symlinked from another unit's\n" " .wants/ or .requires/ directory.\n" "%1$s A unit's purpose may be to act as a helper for some other unit which has\n" " a requirement dependency on it.\n" "%1$s A unit may be started when needed via activation (socket, path, timer,\n" " D-Bus, udev, scripted systemctl call, ...).\n" "%1$s In case of template units, the unit is meant to be enabled with some\n" " instance name specified.", special_glyph(SPECIAL_GLYPH_BULLET)); if (streq(verb, "disable") && arg_runtime_scope == RUNTIME_SCOPE_USER && !arg_quiet && !arg_no_warn) { /* If some of the units are disabled in user scope but still enabled in global scope, * we emit a warning for that. */ _cleanup_strv_free_ char **enabled_in_global_scope = NULL; STRV_FOREACH(name, names) { UnitFileState state; r = unit_file_get_state(RUNTIME_SCOPE_GLOBAL, arg_root, *name, &state); if (r == -ENOENT) continue; if (r < 0) return log_error_errno(r, "Failed to get unit file state for %s: %m", *name); if (IN_SET(state, UNIT_FILE_ENABLED, UNIT_FILE_ENABLED_RUNTIME)) { r = strv_extend(&enabled_in_global_scope, *name); if (r < 0) return log_oom(); } } if (!strv_isempty(enabled_in_global_scope)) { _cleanup_free_ char *units = NULL; units = strv_join(enabled_in_global_scope, ", "); if (!units) return log_oom(); log_notice("The following unit files have been enabled in global scope. This means\n" "they will still be started automatically after a successful disablement\n" "in user scope:\n" "%s", units); } } if (arg_now && STR_IN_SET(argv[0], "enable", "disable", "mask")) { sd_bus *bus; size_t len, i; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; len = strv_length(names); { char *new_args[len + 2]; new_args[0] = (char*) (streq(argv[0], "enable") ? "start" : "stop"); for (i = 0; i < len; i++) new_args[i + 1] = basename(names[i]); new_args[i + 1] = NULL; r = verb_start(len + 1, new_args, userdata); } } return 0; }
14,056
42.119632
132
c
null
systemd-main/src/systemctl/systemctl-is-active.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "pretty-print.h" #include "syslog-util.h" #include "systemctl-is-active.h" #include "systemctl-sysv-compat.h" #include "systemctl-util.h" #include "systemctl.h" static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) { _cleanup_strv_free_ char **names = NULL; UnitActiveState active_state; sd_bus *bus; bool not_found = true, ok = false; int r; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = expand_unit_names(bus, args, NULL, &names, NULL); if (r < 0) return log_error_errno(r, "Failed to expand names: %m"); STRV_FOREACH(name, names) { _cleanup_free_ char *load_state = NULL; r = get_state_one_unit(bus, *name, &active_state); if (r < 0) return r; r = unit_load_state(bus, *name, &load_state); if (r < 0) return r; if (!arg_quiet) puts(unit_active_state_to_string(active_state)); for (int i = 0; i < nb_states; ++i) if (good_states[i] == active_state) { ok = true; break; } if (!streq(load_state, "not-found")) not_found = false; } /* We use LSB code 4 ("program or service status is unknown") * when the corresponding unit file doesn't exist. */ return ok ? EXIT_SUCCESS : not_found ? EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN : code; } int verb_is_active(int argc, char *argv[], void *userdata) { static const UnitActiveState states[] = { UNIT_ACTIVE, UNIT_RELOADING, }; /* According to LSB: 3, "program is not running" */ return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1)); } int verb_is_failed(int argc, char *argv[], void *userdata) { static const UnitActiveState states[] = { UNIT_FAILED, }; return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1)); }
2,427
32.260274
116
c
null
systemd-main/src/systemctl/systemctl-is-enabled.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-is-enabled.h" #include "systemctl-sysv-compat.h" #include "systemctl-util.h" #include "systemctl.h" static int show_installation_targets_client_side(const char *name) { InstallChange *changes = NULL; size_t n_changes = 0; UnitFileFlags flags; char **p; int r; CLEANUP_ARRAY(changes, n_changes, install_changes_free); p = STRV_MAKE(name); flags = UNIT_FILE_DRY_RUN | (arg_runtime ? UNIT_FILE_RUNTIME : 0); r = unit_file_disable(RUNTIME_SCOPE_SYSTEM, flags, NULL, p, &changes, &n_changes); if (r < 0) return log_error_errno(r, "Failed to get file links for %s: %m", name); for (size_t i = 0; i < n_changes; i++) if (changes[i].type == INSTALL_CHANGE_UNLINK) printf(" %s\n", changes[i].path); return 0; } static int show_installation_targets(sd_bus *bus, const char *name) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; const char *link; int r; r = bus_call_method(bus, bus_systemd_mgr, "GetUnitFileLinks", &error, &reply, "sb", name, arg_runtime); if (r < 0) return log_error_errno(r, "Failed to get unit file links for %s: %s", name, bus_error_message(&error, r)); r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "s"); if (r < 0) return bus_log_parse_error(r); while ((r = sd_bus_message_read(reply, "s", &link)) > 0) printf(" %s\n", link); if (r < 0) return bus_log_parse_error(r); r = sd_bus_message_exit_container(reply); if (r < 0) return bus_log_parse_error(r); return 0; } int verb_is_enabled(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **names = NULL; bool not_found, enabled; int r; r = mangle_names("to check", strv_skip(argv, 1), &names); if (r < 0) return r; r = enable_sysv_units(argv[0], names); if (r < 0) return r; not_found = r == 0; /* Doesn't have SysV support or SYSV_UNIT_NOT_FOUND */ enabled = r == SYSV_UNIT_ENABLED; if (install_client_side()) { STRV_FOREACH(name, names) { UnitFileState state; r = unit_file_get_state(arg_runtime_scope, arg_root, *name, &state); if (r == -ENOENT) { if (!arg_quiet) puts("not-found"); continue; } else if (r < 0) return log_error_errno(r, "Failed to get unit file state for %s: %m", *name); else not_found = false; if (IN_SET(state, UNIT_FILE_ENABLED, UNIT_FILE_ENABLED_RUNTIME, UNIT_FILE_STATIC, UNIT_FILE_ALIAS, UNIT_FILE_INDIRECT, UNIT_FILE_GENERATED)) enabled = true; if (!arg_quiet) { puts(unit_file_state_to_string(state)); if (arg_full) { r = show_installation_targets_client_side(*name); if (r < 0) return r; } } } r = 0; } else { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; sd_bus *bus; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; STRV_FOREACH(name, names) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; const char *s; r = bus_call_method(bus, bus_systemd_mgr, "GetUnitFileState", &error, &reply, "s", *name); if (r == -ENOENT) { sd_bus_error_free(&error); if (!arg_quiet) puts("not-found"); continue; } else if (r < 0) return log_error_errno(r, "Failed to get unit file state for %s: %s", *name, bus_error_message(&error, r)); else not_found = false; r = sd_bus_message_read(reply, "s", &s); if (r < 0) return bus_log_parse_error(r); if (STR_IN_SET(s, "enabled", "enabled-runtime", "static", "alias", "indirect", "generated")) enabled = true; if (!arg_quiet) { puts(s); if (arg_full) { r = show_installation_targets(bus, *name); if (r < 0) return r; } } } } return enabled ? EXIT_SUCCESS : not_found ? EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN : EXIT_FAILURE; }
6,053
37.316456
122
c
null
systemd-main/src/systemctl/systemctl-is-system-running.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-event.h" #include "sd-daemon.h" #include "systemctl-util.h" #include "systemctl-is-system-running.h" #include "virt.h" #include "systemctl.h" #include "bus-util.h" #include "bus-locator.h" #include "bus-error.h" static int match_startup_finished(sd_bus_message *m, void *userdata, sd_bus_error *error) { char **state = ASSERT_PTR(userdata); int r; r = bus_get_property_string(sd_bus_message_get_bus(m), bus_systemd_mgr, "SystemState", NULL, state); sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), r); return 0; } int verb_is_system_running(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot_startup_finished = NULL; _cleanup_(sd_event_unrefp) sd_event* event = NULL; _cleanup_free_ char *state = NULL; sd_bus *bus; int r; if (running_in_chroot() > 0 || (arg_transport == BUS_TRANSPORT_LOCAL && !sd_booted())) { if (!arg_quiet) puts("offline"); return EXIT_FAILURE; } r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; if (arg_wait) { r = sd_event_default(&event); if (r >= 0) r = sd_bus_attach_event(bus, event, 0); if (r >= 0) r = bus_match_signal_async( bus, &slot_startup_finished, bus_systemd_mgr, "StartupFinished", match_startup_finished, NULL, &state); if (r < 0) { log_warning_errno(r, "Failed to request match for StartupFinished: %m"); arg_wait = false; } } r = bus_get_property_string(bus, bus_systemd_mgr, "SystemState", &error, &state); if (r < 0) { log_warning_errno(r, "Failed to query system state: %s", bus_error_message(&error, r)); if (!arg_quiet) puts("unknown"); return EXIT_FAILURE; } if (arg_wait && STR_IN_SET(state, "initializing", "starting")) { r = sd_event_loop(event); if (r < 0) { log_warning_errno(r, "Failed to get property from event loop: %m"); if (!arg_quiet) puts("unknown"); return EXIT_FAILURE; } } if (!arg_quiet) puts(state); return streq(state, "running") ? EXIT_SUCCESS : EXIT_FAILURE; }
2,911
34.084337
108
c
null
systemd-main/src/systemctl/systemctl-kill.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-kill.h" #include "systemctl-util.h" #include "systemctl.h" int verb_kill(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **names = NULL; const char *kill_whom; sd_bus *bus; int r, q; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); kill_whom = arg_kill_whom ?: "all"; /* --fail was specified */ if (streq(arg_job_mode(), "fail")) kill_whom = strjoina(kill_whom, "-fail"); r = expand_unit_names(bus, strv_skip(argv, 1), NULL, &names, NULL); if (r < 0) return log_error_errno(r, "Failed to expand names: %m"); STRV_FOREACH(name, names) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; if (arg_kill_value_set) q = bus_call_method( bus, bus_systemd_mgr, "QueueSignalUnit", &error, NULL, "ssii", *name, kill_whom, arg_signal, arg_kill_value); else q = bus_call_method( bus, bus_systemd_mgr, "KillUnit", &error, NULL, "ssi", *name, kill_whom, arg_signal); if (q < 0) { log_error_errno(q, "Failed to kill unit %s: %s", *name, bus_error_message(&error, q)); if (r == 0) r = q; } } return r; }
2,044
33.661017
110
c
null
systemd-main/src/systemctl/systemctl-list-dependencies.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "locale-util.h" #include "sort-util.h" #include "special.h" #include "systemctl-list-dependencies.h" #include "systemctl-util.h" #include "systemctl.h" #include "terminal-util.h" static int list_dependencies_print(const char *name, UnitActiveState state, int level, unsigned branches, bool last) { _cleanup_free_ char *n = NULL; size_t max_len = MAX(columns(),20u); size_t len = 0; if (arg_plain || state == _UNIT_ACTIVE_STATE_INVALID) printf(" "); else { const char *on; switch (state) { case UNIT_ACTIVE: case UNIT_RELOADING: case UNIT_ACTIVATING: on = ansi_highlight_green(); break; case UNIT_INACTIVE: case UNIT_DEACTIVATING: on = ansi_normal(); break; default: on = ansi_highlight_red(); break; } printf("%s%s%s ", on, special_glyph(unit_active_state_to_glyph(state)), ansi_normal()); } if (!arg_plain) { for (int i = level - 1; i >= 0; i--) { len += 2; if (len > max_len - 3 && !arg_full) { printf("%s...\n",max_len % 2 ? "" : " "); return 0; } printf("%s", special_glyph(branches & (1 << i) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE)); } len += 2; if (len > max_len - 3 && !arg_full) { printf("%s...\n",max_len % 2 ? "" : " "); return 0; } printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH)); } if (arg_full) { printf("%s\n", name); return 0; } n = ellipsize(name, max_len-len, 100); if (!n) return log_oom(); printf("%s\n", n); return 0; } static int list_dependencies_compare(char * const *a, char * const *b) { if (unit_name_to_type(*a) == UNIT_TARGET && unit_name_to_type(*b) != UNIT_TARGET) return 1; if (unit_name_to_type(*a) != UNIT_TARGET && unit_name_to_type(*b) == UNIT_TARGET) return -1; return strcasecmp(*a, *b); } static int list_dependencies_one( sd_bus *bus, const char *name, int level, char ***units, unsigned branches) { _cleanup_strv_free_ char **deps = NULL; int r; bool circular = false; assert(bus); assert(name); assert(units); r = strv_extend(units, name); if (r < 0) return log_oom(); r = unit_get_dependencies(bus, name, &deps); if (r < 0) return r; typesafe_qsort(deps, strv_length(deps), list_dependencies_compare); STRV_FOREACH(c, deps) { _cleanup_free_ char *load_state = NULL, *sub_state = NULL; UnitActiveState active_state; if (strv_contains(*units, *c)) { circular = true; continue; } if (arg_types && !strv_contains(arg_types, unit_type_suffix(*c))) continue; r = get_state_one_unit(bus, *c, &active_state); if (r < 0) return r; if (arg_states) { r = unit_load_state(bus, *c, &load_state); if (r < 0) return r; r = get_sub_state_one_unit(bus, *c, &sub_state); if (r < 0) return r; if (!strv_overlap(arg_states, STRV_MAKE(unit_active_state_to_string(active_state), load_state, sub_state))) continue; } r = list_dependencies_print(*c, active_state, level, branches, /* last = */ c[1] == NULL && !circular); if (r < 0) return r; if (arg_all || unit_name_to_type(*c) == UNIT_TARGET) { r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (c[1] == NULL ? 0 : 1)); if (r < 0) return r; } } if (circular && !arg_plain) { r = list_dependencies_print("...", _UNIT_ACTIVE_STATE_INVALID, level, branches, /* last = */ true); if (r < 0) return r; } if (!arg_plain) strv_remove(*units, name); return 0; } int verb_list_dependencies(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **units = NULL, **done = NULL; char **patterns; sd_bus *bus; int r; /* We won't be able to preserve the tree structure if --type= or --state= is used */ arg_plain = arg_plain || arg_types || arg_states; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; patterns = strv_skip(argv, 1); if (strv_isempty(patterns)) { units = strv_new(SPECIAL_DEFAULT_TARGET); if (!units) return log_oom(); } else { r = expand_unit_names(bus, patterns, NULL, &units, NULL); if (r < 0) return log_error_errno(r, "Failed to expand names: %m"); } pager_open(arg_pager_flags); STRV_FOREACH(u, units) { if (u != units) puts(""); puts(*u); r = list_dependencies_one(bus, *u, 0, &done, 0); if (r < 0) return r; } return 0; }
6,252
30.741117
131
c
null
systemd-main/src/systemctl/systemctl-list-jobs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "locale-util.h" #include "systemctl-list-jobs.h" #include "systemctl-util.h" #include "systemctl.h" #include "terminal-util.h" static int output_waiting_jobs(sd_bus *bus, Table *table, uint32_t id, const char *method, const char *prefix) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; const char *name, *type; uint32_t other_id; int r; assert(bus); r = bus_call_method(bus, bus_systemd_mgr, method, &error, &reply, "u", id); if (r < 0) return log_debug_errno(r, "Failed to get waiting jobs for job %" PRIu32, id); r = sd_bus_message_enter_container(reply, 'a', "(usssoo)"); if (r < 0) return bus_log_parse_error(r); while ((r = sd_bus_message_read(reply, "(usssoo)", &other_id, &name, &type, NULL, NULL, NULL)) > 0) { _cleanup_free_ char *row = NULL; int rc; if (asprintf(&row, "%s %u (%s/%s)", prefix, other_id, name, type) < 0) return log_oom(); rc = table_add_many(table, TABLE_STRING, special_glyph(SPECIAL_GLYPH_TREE_RIGHT), TABLE_STRING, row, TABLE_EMPTY, TABLE_EMPTY); if (rc < 0) return table_log_add_error(r); } if (r < 0) return bus_log_parse_error(r); r = sd_bus_message_exit_container(reply); if (r < 0) return bus_log_parse_error(r); return 0; } struct job_info { uint32_t id; const char *name, *type, *state; }; static int output_jobs_list(sd_bus *bus, const struct job_info* jobs, unsigned n, bool skipped) { _cleanup_(table_unrefp) Table *table = NULL; const char *on, *off; int r; assert(n == 0 || jobs); if (n == 0) { if (arg_legend != 0) { on = ansi_highlight_green(); off = ansi_normal(); printf("%sNo jobs %s.%s\n", on, skipped ? "listed" : "running", off); } return 0; } pager_open(arg_pager_flags); table = table_new("job", "unit", "type", "state"); if (!table) return log_oom(); table_set_header(table, arg_legend != 0); if (arg_full) table_set_width(table, 0); table_set_ersatz_string(table, TABLE_ERSATZ_DASH); for (const struct job_info *j = jobs; j < jobs + n; j++) { if (streq(j->state, "running")) on = ansi_highlight(); else on = ""; r = table_add_many(table, TABLE_UINT, j->id, TABLE_STRING, j->name, TABLE_SET_COLOR, on, TABLE_STRING, j->type, TABLE_STRING, j->state, TABLE_SET_COLOR, on); if (r < 0) return table_log_add_error(r); if (arg_jobs_after) output_waiting_jobs(bus, table, j->id, "GetJobAfter", "\twaiting for job"); if (arg_jobs_before) output_waiting_jobs(bus, table, j->id, "GetJobBefore", "\tblocking job"); } r = table_print(table, NULL); if (r < 0) return log_error_errno(r, "Failed to print the table: %m"); if (arg_legend != 0) { on = ansi_highlight(); off = ansi_normal(); printf("\n%s%u jobs listed%s.\n", on, n, off); } return 0; } static bool output_show_job(struct job_info *job, char **patterns) { return strv_fnmatch_or_empty(patterns, job->name, FNM_NOESCAPE); } int verb_list_jobs(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_free_ struct job_info *jobs = NULL; const char *name, *type, *state; bool skipped = false; unsigned c = 0; sd_bus *bus; uint32_t id; int r; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = bus_call_method(bus, bus_systemd_mgr, "ListJobs", &error, &reply, NULL); if (r < 0) return log_error_errno(r, "Failed to list jobs: %s", bus_error_message(&error, r)); r = sd_bus_message_enter_container(reply, 'a', "(usssoo)"); if (r < 0) return bus_log_parse_error(r); while ((r = sd_bus_message_read(reply, "(usssoo)", &id, &name, &type, &state, NULL, NULL)) > 0) { struct job_info job = { id, name, type, state }; if (!output_show_job(&job, strv_skip(argv, 1))) { skipped = true; continue; } if (!GREEDY_REALLOC(jobs, c + 1)) return log_oom(); jobs[c++] = job; } if (r < 0) return bus_log_parse_error(r); r = sd_bus_message_exit_container(reply); if (r < 0) return bus_log_parse_error(r); pager_open(arg_pager_flags); return output_jobs_list(bus, jobs, c, skipped); }
5,820
32.262857
112
c
null
systemd-main/src/systemctl/systemctl-list-machines.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "sd-login.h" #include "bus-map-properties.h" #include "hostname-util.h" #include "locale-util.h" #include "memory-util.h" #include "sort-util.h" #include "systemctl-list-machines.h" #include "systemctl-util.h" #include "systemctl.h" #include "terminal-util.h" const struct bus_properties_map machine_info_property_map[] = { /* Might good to keep same order here as in bus_manager_vtable[], server side */ { "Version", "s", NULL, offsetof(struct machine_info, version) }, { "Tainted", "s", NULL, offsetof(struct machine_info, tainted) }, { "UserspaceTimestamp", "t", NULL, offsetof(struct machine_info, timestamp) }, { "NNames", "u", NULL, offsetof(struct machine_info, n_names) }, { "NFailedUnits", "u", NULL, offsetof(struct machine_info, n_failed_units) }, { "NJobs", "u", NULL, offsetof(struct machine_info, n_jobs) }, { "ControlGroup", "s", NULL, offsetof(struct machine_info, control_group) }, { "SystemState", "s", NULL, offsetof(struct machine_info, state) }, {} }; void machine_info_clear(struct machine_info *info) { assert(info); free(info->name); free(info->version); free(info->tainted); free(info->control_group); free(info->state); zero(*info); } static void free_machines_list(struct machine_info *machine_infos, int n) { if (!machine_infos) return; for (int i = 0; i < n; i++) machine_info_clear(&machine_infos[i]); free(machine_infos); } static int compare_machine_info(const struct machine_info *a, const struct machine_info *b) { int r; r = CMP(b->is_host, a->is_host); if (r != 0) return r; return strcasecmp(a->name, b->name); } static int get_machine_properties(sd_bus *bus, struct machine_info *mi) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *container = NULL; int r; assert(mi); if (!bus) { r = sd_bus_open_system_machine(&container, mi->name); if (r < 0) return r; bus = container; } r = bus_map_all_properties( bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", machine_info_property_map, BUS_MAP_STRDUP, NULL, NULL, mi); if (r < 0) return r; return 0; } static bool output_show_machine(const char *name, char **patterns) { return strv_fnmatch_or_empty(patterns, name, FNM_NOESCAPE); } static int get_machine_list( sd_bus *bus, struct machine_info **_machine_infos, char **patterns) { struct machine_info *machine_infos = NULL; _cleanup_strv_free_ char **m = NULL; _cleanup_free_ char *hn = NULL; int c = 0, r; hn = gethostname_malloc(); if (!hn) return log_oom(); if (output_show_machine(hn, patterns)) { if (!GREEDY_REALLOC0(machine_infos, c+1)) return log_oom(); machine_infos[c].is_host = true; machine_infos[c].name = TAKE_PTR(hn); (void) get_machine_properties(bus, &machine_infos[c]); c++; } r = sd_get_machine_names(&m); if (r < 0) return log_error_errno(r, "Failed to get machine list: %m"); STRV_FOREACH(i, m) { _cleanup_free_ char *class = NULL; if (!output_show_machine(*i, patterns)) continue; sd_machine_get_class(*i, &class); if (!streq_ptr(class, "container")) continue; if (!GREEDY_REALLOC0(machine_infos, c+1)) { free_machines_list(machine_infos, c); return log_oom(); } machine_infos[c].is_host = false; machine_infos[c].name = strdup(*i); if (!machine_infos[c].name) { free_machines_list(machine_infos, c); return log_oom(); } (void) get_machine_properties(NULL, &machine_infos[c]); c++; } *_machine_infos = machine_infos; return c; } static int output_machines_list(struct machine_info *machine_infos, unsigned n) { _cleanup_(table_unrefp) Table *table = NULL; bool state_missing = false; int r; assert(machine_infos || n == 0); table = table_new("", "name", "state", "failed", "jobs"); if (!table) return log_oom(); table_set_header(table, arg_legend != 0); if (arg_plain) { /* Hide the 'glyph' column when --plain is requested */ r = table_hide_column_from_display(table, 0); if (r < 0) return log_error_errno(r, "Failed to hide column: %m"); } if (arg_full) table_set_width(table, 0); table_set_ersatz_string(table, TABLE_ERSATZ_DASH); for (struct machine_info *m = machine_infos; m < machine_infos + n; m++) { _cleanup_free_ char *mname = NULL; const char *on_state = "", *on_failed = ""; bool circle = false; if (streq_ptr(m->state, "degraded")) { on_state = ansi_highlight_red(); circle = true; } else if (!streq_ptr(m->state, "running")) { on_state = ansi_highlight_yellow(); circle = true; } if (m->n_failed_units > 0) on_failed = ansi_highlight_red(); else on_failed = ""; if (!m->state) state_missing = true; if (m->is_host) mname = strjoin(strna(m->name), " (host)"); r = table_add_many(table, TABLE_STRING, circle ? special_glyph(SPECIAL_GLYPH_BLACK_CIRCLE) : " ", TABLE_SET_COLOR, on_state, TABLE_STRING, m->is_host ? mname : strna(m->name), TABLE_STRING, strna(m->state), TABLE_SET_COLOR, on_state, TABLE_UINT32, m->n_failed_units, TABLE_SET_COLOR, on_failed, TABLE_UINT32, m->n_jobs); if (r < 0) return table_log_add_error(r); } r = output_table(table); if (r < 0) return r; if (arg_legend != 0) { printf("\n"); if (state_missing && geteuid() != 0) printf("Notice: some information only available to privileged users was not shown.\n"); printf("%u machines listed.\n", n); } return 0; } int verb_list_machines(int argc, char *argv[], void *userdata) { struct machine_info *machine_infos = NULL; sd_bus *bus; int r, rc; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = get_machine_list(bus, &machine_infos, strv_skip(argv, 1)); if (r < 0) return r; pager_open(arg_pager_flags); typesafe_qsort(machine_infos, r, compare_machine_info); rc = output_machines_list(machine_infos, r); free_machines_list(machine_infos, r); return rc; }
8,135
31.806452
111
c
null
systemd-main/src/systemctl/systemctl-list-machines.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <stdbool.h> #include "bus-map-properties.h" #include "time-util.h" int verb_list_machines(int argc, char *argv[], void *userdata); struct machine_info { bool is_host; char *name; char *version; char *tainted; uint64_t timestamp; uint32_t n_names; uint32_t n_failed_units; uint32_t n_jobs; char *control_group; char *state; }; void machine_info_clear(struct machine_info *info); extern const struct bus_properties_map machine_info_property_map[];
625
21.357143
67
h
null
systemd-main/src/systemctl/systemctl-log-setting.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "pretty-print.h" #include "syslog-util.h" #include "systemctl-log-setting.h" #include "systemctl-util.h" #include "systemctl.h" #include "verb-log-control.h" static void give_log_control1_hint(const char *name) { _cleanup_free_ char *link = NULL; if (arg_quiet) return; (void) terminal_urlify_man("org.freedesktop.LogControl1", "5", &link); log_notice("Hint: the service must declare BusName= and implement the appropriate D-Bus interface.\n" " See the %s for details.", link ?: "org.freedesktop.LogControl1(5) man page"); } int verb_log_setting(int argc, char *argv[], void *userdata) { sd_bus *bus; int r; assert(argc >= 1 && argc <= 2); r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; return verb_log_control_common(bus, "org.freedesktop.systemd1", argv[0], argv[1]); } static int service_name_to_dbus(sd_bus *bus, const char *name, char **ret_dbus_name) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_free_ char *bus_name = NULL; int r; /* First, look for the BusName= property */ _cleanup_free_ char *dbus_path = unit_dbus_path_from_name(name); if (!dbus_path) return log_oom(); r = sd_bus_get_property_string( bus, "org.freedesktop.systemd1", dbus_path, "org.freedesktop.systemd1.Service", "BusName", &error, &bus_name); if (r < 0) return log_error_errno(r, "Failed to obtain BusName= property of %s: %s", name, bus_error_message(&error, r)); if (isempty(bus_name)) { log_error("Unit %s doesn't declare BusName=.", name); give_log_control1_hint(name); return -ENOLINK; } *ret_dbus_name = TAKE_PTR(bus_name); return 0; } int verb_service_log_setting(int argc, char *argv[], void *userdata) { sd_bus *bus; _cleanup_free_ char *unit = NULL, *dbus_name = NULL; int r; assert(argc >= 2 && argc <= 3); r = acquire_bus(BUS_FULL, &bus); if (r < 0) return r; r = unit_name_mangle_with_suffix(argv[1], argv[0], arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".service", &unit); if (r < 0) return log_error_errno(r, "Failed to mangle unit name: %m"); r = service_name_to_dbus(bus, unit, &dbus_name); if (r < 0) return r; r = verb_log_control_common(bus, dbus_name, argv[0], argv[2]); if (r == -EBADR) give_log_control1_hint(dbus_name); return r; }
3,130
31.278351
109
c
null
systemd-main/src/systemctl/systemctl-reset-failed.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-reset-failed.h" #include "systemctl-trivial-method.h" #include "systemctl-util.h" #include "systemctl.h" int verb_reset_failed(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **names = NULL; sd_bus *bus; int r, q; if (argc <= 1) /* Shortcut to trivial_method() if no argument is given */ return verb_trivial_method(argc, argv, userdata); r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); r = expand_unit_names(bus, strv_skip(argv, 1), NULL, &names, NULL); if (r < 0) return log_error_errno(r, "Failed to expand names: %m"); STRV_FOREACH(name, names) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; q = bus_call_method(bus, bus_systemd_mgr, "ResetFailedUnit", &error, NULL, "s", *name); if (q < 0) { log_error_errno(q, "Failed to reset failed state of unit %s: %s", *name, bus_error_message(&error, q)); if (r == 0) r = q; } } return r; }
1,328
31.414634
127
c
null
systemd-main/src/systemctl/systemctl-service-watchdogs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "parse-util.h" #include "systemctl-service-watchdogs.h" #include "systemctl-util.h" #include "systemctl.h" int verb_service_watchdogs(int argc, char *argv[], void *userdata) { sd_bus *bus; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; int b, r; assert(argv); r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; if (argc == 1) { /* get ServiceWatchdogs */ r = bus_get_property_trivial(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, 'b', &b); if (r < 0) return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r)); printf("%s\n", yes_no(!!b)); } else { /* set ServiceWatchdogs */ assert(argc == 2); b = parse_boolean(argv[1]); if (b < 0) return log_error_errno(b, "Failed to parse service-watchdogs argument: %m"); r = bus_set_property(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, "b", b); if (r < 0) return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r)); } return 0; }
1,434
31.613636
124
c
null
systemd-main/src/systemctl/systemctl-set-default.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "proc-cmdline.h" #include "systemctl-daemon-reload.h" #include "systemctl-set-default.h" #include "systemctl-util.h" #include "systemctl.h" static int parse_proc_cmdline_item(const char *key, const char *value, void *data) { char **ret = data; if (streq(key, "systemd.unit")) { if (proc_cmdline_value_missing(key, value)) return 0; if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) { log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value); return 0; } return free_and_strdup_warn(ret, key); } else if (!value) { if (runlevel_to_target(key)) return free_and_strdup_warn(ret, key); } return 0; } static void emit_cmdline_warning(void) { if (arg_quiet || arg_root) /* don't bother checking the commandline if we're operating on a container */ return; _cleanup_free_ char *override = NULL; int r; r = proc_cmdline_parse(parse_proc_cmdline_item, &override, 0); if (r < 0) log_debug_errno(r, "Failed to parse kernel command line, ignoring: %m"); if (override) log_notice("Note: found \"%s\" on the kernel commandline, which overrides the default unit.", override); } static int determine_default(char **ret_name) { int r; if (install_client_side()) { r = unit_file_get_default(arg_runtime_scope, arg_root, ret_name); if (r == -ERFKILL) return log_error_errno(r, "Failed to get default target: Unit file is masked."); if (r < 0) return log_error_errno(r, "Failed to get default target: %m"); return 0; } else { sd_bus *bus; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; const char *name; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = bus_call_method(bus, bus_systemd_mgr, "GetDefaultTarget", &error, &reply, NULL); if (r < 0) return log_error_errno(r, "Failed to get default target: %s", bus_error_message(&error, r)); r = sd_bus_message_read(reply, "s", &name); if (r < 0) return bus_log_parse_error(r); return free_and_strdup_warn(ret_name, name); } } int verb_get_default(int argc, char *argv[], void *userdata) { _cleanup_free_ char *name = NULL; int r; r = determine_default(&name); if (r < 0) return r; printf("%s\n", name); emit_cmdline_warning(); return 0; } int verb_set_default(int argc, char *argv[], void *userdata) { _cleanup_free_ char *unit = NULL; int r; assert(argc >= 2); assert(argv); r = unit_name_mangle_with_suffix(argv[1], "set-default", arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".target", &unit); if (r < 0) return log_error_errno(r, "Failed to mangle unit name: %m"); if (install_client_side()) { InstallChange *changes = NULL; size_t n_changes = 0; CLEANUP_ARRAY(changes, n_changes, install_changes_free); r = unit_file_set_default(arg_runtime_scope, UNIT_FILE_FORCE, arg_root, unit, &changes, &n_changes); install_changes_dump(r, "set default", changes, n_changes, arg_quiet); if (r < 0) return r; } else { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; sd_bus *bus; polkit_agent_open_maybe(); r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = bus_call_method(bus, bus_systemd_mgr, "SetDefaultTarget", &error, &reply, "sb", unit, 1); if (r < 0) return log_error_errno(r, "Failed to set default target: %s", bus_error_message(&error, r)); r = bus_deserialize_and_dump_unit_file_changes(reply, arg_quiet); if (r < 0) return r; /* Try to reload if enabled */ if (!arg_no_reload) { r = daemon_reload(ACTION_RELOAD, /* graceful= */ false); if (r < 0) return r; } } emit_cmdline_warning(); if (!arg_quiet) { _cleanup_free_ char *final = NULL; r = determine_default(&final); if (r < 0) return r; if (!streq(final, unit)) log_notice("Note: \"%s\" is the default unit (possibly a runtime override).", final); } return 0; }
5,529
33.347826
116
c
null
systemd-main/src/systemctl/systemctl-set-property.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-set-property.h" #include "systemctl-util.h" #include "systemctl.h" static int set_property_one(sd_bus *bus, const char *name, char **properties) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; int r; r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "SetUnitProperties"); if (r < 0) return bus_log_create_error(r); UnitType t = unit_name_to_type(name); if (t < 0) return log_error_errno(t, "Invalid unit type: %s", name); r = sd_bus_message_append(m, "sb", name, arg_runtime); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)"); if (r < 0) return bus_log_create_error(r); r = bus_append_unit_property_assignment_many(m, t, properties); if (r < 0) return r; r = sd_bus_message_close_container(m); if (r < 0) return bus_log_create_error(r); r = sd_bus_call(bus, m, 0, &error, NULL); if (r < 0) return log_error_errno(r, "Failed to set unit properties on %s: %s", name, bus_error_message(&error, r)); return 0; } int verb_set_property(int argc, char *argv[], void *userdata) { sd_bus *bus; _cleanup_strv_free_ char **names = NULL; int r, k; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); r = expand_unit_names(bus, STRV_MAKE(argv[1]), NULL, &names, NULL); if (r < 0) return log_error_errno(r, "Failed to expand '%s' into names: %m", argv[1]); r = 0; STRV_FOREACH(name, names) { k = set_property_one(bus, *name, strv_skip(argv, 2)); if (k < 0 && r >= 0) r = k; } return r; }
2,165
30.391304
91
c
null
systemd-main/src/systemctl/systemctl-start-special.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "bootspec.h" #include "bus-error.h" #include "bus-locator.h" #include "efivars.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "reboot-util.h" #include "systemctl-logind.h" #include "systemctl-start-special.h" #include "systemctl-start-unit.h" #include "systemctl-trivial-method.h" #include "systemctl-util.h" #include "systemctl.h" static int load_kexec_kernel(void) { _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL; _cleanup_free_ char *kernel = NULL, *initrd = NULL, *options = NULL; const BootEntry *e; pid_t pid; int r; if (kexec_loaded()) { log_debug("Kexec kernel already loaded."); return 0; } if (access(KEXEC, X_OK) < 0) return log_error_errno(errno, KEXEC" is not available: %m"); r = boot_config_load_auto(&config, NULL, NULL); if (r == -ENOKEY) /* The call doesn't log about ENOKEY, let's do so here. */ return log_error_errno(r, "No kexec kernel loaded and autodetection failed.\n%s", is_efi_boot() ? "Cannot automatically load kernel: ESP mount point not found." : "Automatic loading works only on systems booted with EFI."); if (r < 0) return r; r = boot_config_select_special_entries(&config, /* skip_efivars= */ false); if (r < 0) return r; e = boot_config_default_entry(&config); if (!e) return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No boot loader entry suitable as default, refusing to guess."); log_debug("Found default boot loader entry in file \"%s\"", e->path); if (!e->kernel) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Boot entry does not refer to Linux kernel, which is not supported currently."); if (strv_length(e->initrd) > 1) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Boot entry specifies multiple initrds, which is not supported currently."); kernel = path_join(e->root, e->kernel); if (!kernel) return log_oom(); if (!strv_isempty(e->initrd)) { initrd = path_join(e->root, e->initrd[0]); if (!initrd) return log_oom(); } options = strv_join(e->options, " "); if (!options) return log_oom(); log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "%s "KEXEC" --load \"%s\" --append \"%s\"%s%s%s", arg_dry_run ? "Would run" : "Running", kernel, options, initrd ? " --initrd \"" : NULL, strempty(initrd), initrd ? "\"" : ""); if (arg_dry_run) return 0; r = safe_fork("(kexec)", FORK_WAIT|FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { const char* const args[] = { KEXEC, "--load", kernel, "--append", options, initrd ? "--initrd" : NULL, initrd, NULL }; /* Child */ execv(args[0], (char * const *) args); _exit(EXIT_FAILURE); } return 0; } static int set_exit_code(uint8_t code) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; sd_bus *bus; int r; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; r = bus_call_method(bus, bus_systemd_mgr, "SetExitCode", &error, NULL, "y", code); if (r < 0) return log_error_errno(r, "Failed to set exit code: %s", bus_error_message(&error, r)); return 0; } int verb_start_special(int argc, char *argv[], void *userdata) { bool termination_action; /* An action that terminates the manager, can be performed also by * signal. */ enum action a; int r; assert(argv); a = verb_to_action(argv[0]); r = logind_check_inhibitors(a); if (r < 0) return r; if (arg_force >= 2) { r = must_be_root(); if (r < 0) return r; } r = prepare_firmware_setup(); if (r < 0) return r; r = prepare_boot_loader_menu(); if (r < 0) return r; r = prepare_boot_loader_entry(); if (r < 0) return r; if (a == ACTION_REBOOT) { if (arg_reboot_argument) { r = update_reboot_parameter_and_warn(arg_reboot_argument, false); if (r < 0) return r; } } else if (a == ACTION_KEXEC) { r = load_kexec_kernel(); if (r < 0 && arg_force >= 1) log_notice("Failed to load kexec kernel, continuing without."); else if (r < 0) return r; } else if (a == ACTION_EXIT && argc > 1) { uint8_t code; /* If the exit code is not given on the command line, don't reset it to zero: just keep it as * it might have been set previously. */ r = safe_atou8(argv[1], &code); if (r < 0) return log_error_errno(r, "Invalid exit code."); r = set_exit_code(code); if (r < 0) return r; } termination_action = IN_SET(a, ACTION_HALT, ACTION_POWEROFF, ACTION_REBOOT); if (termination_action && arg_force >= 2) return halt_now(a); if (arg_force >= 1 && (termination_action || IN_SET(a, ACTION_KEXEC, ACTION_EXIT))) r = verb_trivial_method(argc, argv, userdata); else { /* First try logind, to allow authentication with polkit */ switch (a) { case ACTION_POWEROFF: case ACTION_REBOOT: case ACTION_KEXEC: case ACTION_HALT: case ACTION_SOFT_REBOOT: if (arg_when == 0) r = logind_reboot(a); else if (arg_when != USEC_INFINITY) r = logind_schedule_shutdown(a); else /* arg_when == USEC_INFINITY */ r = logind_cancel_shutdown(); if (r >= 0 || IN_SET(r, -EACCES, -EOPNOTSUPP, -EINPROGRESS)) /* The latter indicates that the requested operation requires auth, * is not supported or already in progress, in which cases we ignore the error. */ return r; /* On all other errors, try low-level operation. In order to minimize the difference * between operation with and without logind, we explicitly enable non-blocking mode * for this, as logind's shutdown operations are always non-blocking. */ arg_no_block = true; break; case ACTION_SUSPEND: case ACTION_HIBERNATE: case ACTION_HYBRID_SLEEP: case ACTION_SUSPEND_THEN_HIBERNATE: r = logind_reboot(a); if (r >= 0 || IN_SET(r, -EACCES, -EOPNOTSUPP, -EINPROGRESS)) return r; arg_no_block = true; break; case ACTION_EXIT: /* Since exit is so close in behaviour to power-off/reboot, let's also make * it asynchronous, in order to not confuse the user needlessly with unexpected * behaviour. */ arg_no_block = true; break; default: ; } r = verb_start(argc, argv, userdata); } if (termination_action && arg_force < 2 && IN_SET(r, -ENOENT, -ETIMEDOUT)) log_notice("It is possible to perform action directly, see discussion of --force --force in man:systemctl(1)."); return r; } int verb_start_system_special(int argc, char *argv[], void *userdata) { /* Like start_special above, but raises an error when running in user mode */ if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad action for %s mode.", runtime_scope_cmdline_option_to_string(arg_runtime_scope)); return verb_start_special(argc, argv, userdata); }
9,606
35.528517
128
c
null
systemd-main/src/systemctl/systemctl-switch-root.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "argv-util.h" #include "bus-error.h" #include "bus-locator.h" #include "chase.h" #include "parse-util.h" #include "path-util.h" #include "proc-cmdline.h" #include "signal-util.h" #include "stat-util.h" #include "systemctl.h" #include "systemctl-switch-root.h" #include "systemctl-util.h" static int same_file_in_root( const char *root, const char *a, const char *b) { struct stat sta, stb; int r; r = chase_and_stat(a, root, CHASE_PREFIX_ROOT, NULL, &sta); if (r < 0) return r; r = chase_and_stat(b, root, CHASE_PREFIX_ROOT, NULL, &stb); if (r < 0) return r; return stat_inode_same(&sta, &stb); } int verb_switch_root(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_free_ char *cmdline_init = NULL; const char *root, *init; sd_bus *bus; int r; if (arg_transport != BUS_TRANSPORT_LOCAL) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot switch root remotely."); if (argc > 3) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too many arguments."); if (argc >= 2) { root = argv[1]; if (!path_is_valid(root)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid root path: %s", root); if (!path_is_absolute(root)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Root path is not absolute: %s", root); if (path_equal(root, "/")) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot switch to current root directory: %s", root); } else root = "/sysroot"; if (argc >= 3) init = argv[2]; else { r = proc_cmdline_get_key("init", 0, &cmdline_init); if (r < 0) log_debug_errno(r, "Failed to parse /proc/cmdline: %m"); init = cmdline_init; } init = empty_to_null(init); if (init) { if (!path_is_valid(init)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid path to init binary: %s", init); if (!path_is_absolute(init)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path to init binary is not absolute: %s", init); /* If the passed init is actually the same as the systemd binary, then let's suppress it. */ if (same_file_in_root(root, SYSTEMD_BINARY_PATH, init) > 0) init = NULL; } /* Instruct PID1 to exclude us from its killing spree applied during the transition. Otherwise we * would exit with a failure status even though the switch to the new root has succeed. */ assert(saved_argv); assert(saved_argv[0]); saved_argv[0][0] = '@'; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; /* If we are slow to exit after the root switch, the new systemd instance will send us a signal to * terminate. Just ignore it and exit normally. This way the unit does not end up as failed. */ r = ignore_signals(SIGTERM); if (r < 0) log_warning_errno(r, "Failed to change disposition of SIGTERM to ignore: %m"); log_debug("Switching root - root: %s; init: %s", root, strna(init)); r = bus_call_method(bus, bus_systemd_mgr, "SwitchRoot", &error, NULL, "ss", root, init); if (r < 0) { (void) default_signals(SIGTERM); return log_error_errno(r, "Failed to switch root: %s", bus_error_message(&error, r)); } return 0; }
3,935
35.444444
125
c
null
systemd-main/src/systemctl/systemctl-sysv-compat.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "env-util.h" #include "fd-util.h" #include "initreq.h" #include "install.h" #include "io-util.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "strv.h" #include "systemctl-sysv-compat.h" #include "systemctl.h" int talk_initctl(char rl) { #if HAVE_SYSV_COMPAT _cleanup_close_ int fd = -EBADF; const char *path; int r; /* Try to switch to the specified SysV runlevel. Returns == 0 if the operation does not apply on this * system, and > 0 on success. */ if (rl == 0) return 0; FOREACH_STRING(_path, "/run/initctl", "/dev/initctl") { path = _path; fd = open(path, O_WRONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY); if (fd < 0 && errno != ENOENT) return log_error_errno(errno, "Failed to open %s: %m", path); if (fd >= 0) break; } if (fd < 0) return 0; struct init_request request = { .magic = INIT_MAGIC, .sleeptime = 0, .cmd = INIT_CMD_RUNLVL, .runlevel = rl, }; r = loop_write(fd, &request, sizeof(request), false); if (r < 0) return log_error_errno(r, "Failed to write to %s: %m", path); return 1; #else return -EOPNOTSUPP; #endif } int parse_shutdown_time_spec(const char *t, usec_t *ret) { assert(t); assert(ret); if (streq(t, "now")) *ret = 0; else if (!strchr(t, ':')) { uint64_t u; if (safe_atou64(t, &u) < 0) return -EINVAL; *ret = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u; } else { char *e = NULL; long hour, minute; struct tm tm = {}; time_t s; usec_t n; errno = 0; hour = strtol(t, &e, 10); if (errno > 0 || *e != ':' || hour < 0 || hour > 23) return -EINVAL; minute = strtol(e+1, &e, 10); if (errno > 0 || *e != 0 || minute < 0 || minute > 59) return -EINVAL; n = now(CLOCK_REALTIME); s = (time_t) (n / USEC_PER_SEC); assert_se(localtime_r(&s, &tm)); tm.tm_hour = (int) hour; tm.tm_min = (int) minute; tm.tm_sec = 0; s = mktime(&tm); assert(s >= 0); *ret = (usec_t) s * USEC_PER_SEC; while (*ret <= n) *ret += USEC_PER_DAY; } return 0; } int enable_sysv_units(const char *verb, char **args) { int r = 0; #if HAVE_SYSV_COMPAT _cleanup_(lookup_paths_free) LookupPaths paths = {}; unsigned f = 0; SysVUnitEnableState enable_state = SYSV_UNIT_NOT_FOUND; /* Processes all SysV units, and reshuffles the array so that afterwards only the native units remain */ if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM) return 0; if (getenv_bool("SYSTEMCTL_SKIP_SYSV") > 0) return 0; if (!STR_IN_SET(verb, "enable", "disable", "is-enabled")) return 0; r = lookup_paths_init_or_warn(&paths, arg_runtime_scope, LOOKUP_PATHS_EXCLUDE_GENERATED, arg_root); if (r < 0) return r; r = 0; while (args[f]) { const char *argv[] = { ROOTLIBEXECDIR "/systemd-sysv-install", NULL, /* --root= */ NULL, /* verb */ NULL, /* service */ NULL, }; _cleanup_free_ char *p = NULL, *q = NULL, *l = NULL, *v = NULL; bool found_native = false, found_sysv; const char *name; unsigned c = 1; pid_t pid; int j; name = args[f++]; if (!endswith(name, ".service")) continue; if (path_is_absolute(name)) continue; j = unit_file_exists(arg_runtime_scope, &paths, name); if (j < 0 && !IN_SET(j, -ELOOP, -ERFKILL, -EADDRNOTAVAIL)) return log_error_errno(j, "Failed to look up unit file state: %m"); found_native = j != 0; /* If we have both a native unit and a SysV script, enable/disable them both (below); for * is-enabled, prefer the native unit */ if (found_native && streq(verb, "is-enabled")) continue; p = path_join(arg_root, SYSTEM_SYSVINIT_PATH, name); if (!p) return log_oom(); p[strlen(p) - STRLEN(".service")] = 0; found_sysv = access(p, F_OK) >= 0; if (!found_sysv) continue; if (!arg_quiet) { if (found_native) log_info("Synchronizing state of %s with SysV service script with %s.", name, argv[0]); else log_info("%s is not a native service, redirecting to systemd-sysv-install.", name); } if (!isempty(arg_root)) { q = strjoin("--root=", arg_root); if (!q) return log_oom(); argv[c++] = q; } /* Let's copy the verb, since it's still pointing directly into the original argv[] array we * got passed, but safe_fork() is likely going to rewrite that for the new child */ v = strdup(verb); if (!v) return log_oom(); argv[c++] = v; argv[c++] = basename(p); argv[c] = NULL; l = strv_join((char**)argv, " "); if (!l) return log_oom(); if (!arg_quiet) log_info("Executing: %s", l); j = safe_fork("(sysv-install)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (j < 0) return j; if (j == 0) { /* Child */ execv(argv[0], (char**) argv); log_error_errno(errno, "Failed to execute %s: %m", argv[0]); _exit(EXIT_FAILURE); } j = wait_for_terminate_and_check("sysv-install", pid, WAIT_LOG_ABNORMAL); if (j < 0) return j; if (streq(verb, "is-enabled")) { if (j == EXIT_SUCCESS) { if (!arg_quiet) puts("enabled"); enable_state = SYSV_UNIT_ENABLED; } else { if (!arg_quiet) puts("disabled"); if (enable_state != SYSV_UNIT_ENABLED) enable_state = SYSV_UNIT_DISABLED; } } else if (j != EXIT_SUCCESS) return -EBADE; /* We don't warn here, under the assumption the script already showed an explanation */ if (found_native) continue; /* Remove this entry, so that we don't try enabling it as native unit */ assert(f > 0); f--; assert(args[f] == name); strv_remove(args + f, name); } if (streq(verb, "is-enabled")) return enable_state; #endif return r; } int action_to_runlevel(void) { #if HAVE_SYSV_COMPAT static const char table[_ACTION_MAX] = { [ACTION_HALT] = '0', [ACTION_POWEROFF] = '0', [ACTION_REBOOT] = '6', [ACTION_RUNLEVEL2] = '2', [ACTION_RUNLEVEL3] = '3', [ACTION_RUNLEVEL4] = '4', [ACTION_RUNLEVEL5] = '5', [ACTION_RESCUE] = '1' }; assert(arg_action >= 0 && arg_action < _ACTION_MAX); return table[arg_action]; #else return -EOPNOTSUPP; #endif }
8,941
31.398551
126
c
null
systemd-main/src/systemctl/systemctl-sysv-compat.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "time-util.h" int talk_initctl(char runlevel); int parse_shutdown_time_spec(const char *t, usec_t *ret); /* The init script exit codes for the LSB 'status' verb. (This is different from the 'start' verb, whose exit codes are defined in exit-status.h.) 0 program is running or service is OK 1 program is dead and /var/run pid file exists 2 program is dead and /var/lock lock file exists 3 program is not running 4 program or service status is unknown 5-99 reserved for future LSB use 100-149 reserved for distribution use 150-199 reserved for application use 200-254 reserved https://refspecs.linuxbase.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html */ enum { EXIT_PROGRAM_RUNNING_OR_SERVICE_OK = 0, EXIT_PROGRAM_DEAD_AND_PID_EXISTS = 1, EXIT_PROGRAM_DEAD_AND_LOCK_FILE_EXISTS = 2, EXIT_PROGRAM_NOT_RUNNING = 3, EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN = 4, }; typedef enum SysVUnitEnableState { SYSV_UNIT_NOT_FOUND = 0, SYSV_UNIT_DISABLED, SYSV_UNIT_ENABLED, } SysVUnitEnableState; int enable_sysv_units(const char *verb, char **args); int action_to_runlevel(void) _pure_;
1,338
30.880952
109
h
null
systemd-main/src/systemctl/systemctl-trivial-method.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-error.h" #include "bus-locator.h" #include "systemctl-trivial-method.h" #include "systemctl-util.h" #include "systemctl.h" /* A generic implementation for cases we just need to invoke a simple method call on the Manager object. */ int verb_trivial_method(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; const char *method; sd_bus *bus; int r; if (arg_dry_run) return 0; r = acquire_bus(BUS_MANAGER, &bus); if (r < 0) return r; polkit_agent_open_maybe(); method = streq(argv[0], "clear-jobs") || streq(argv[0], "cancel") ? "ClearJobs" : streq(argv[0], "reset-failed") ? "ResetFailed" : streq(argv[0], "halt") ? "Halt" : streq(argv[0], "reboot") ? "Reboot" : streq(argv[0], "kexec") ? "KExec" : streq(argv[0], "soft-reboot") ? "SoftReboot" : streq(argv[0], "exit") ? "Exit" : /* poweroff */ "PowerOff"; r = bus_call_method(bus, bus_systemd_mgr, method, &error, NULL, NULL); if (r < 0 && arg_action == ACTION_SYSTEMCTL) return log_error_errno(r, "Failed to execute operation: %s", bus_error_message(&error, r)); /* Note that for the legacy commands (i.e. those with action != ACTION_SYSTEMCTL) we support * fallbacks to the old ways of doing things, hence don't log any error in that case here. */ return r < 0 ? r : 0; }
1,725
36.521739
107
c