From: Sven Eden Date: Wed, 30 Nov 2016 08:44:44 +0000 (+0100) Subject: Prep v220: Remove all source files, taht are not needed to build elogind. X-Git-Tag: v226.4~1^2~155 X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=commitdiff_plain;h=821db1ad3458f312617c894af7feadf2c87dfff6 Prep v220: Remove all source files, taht are not needed to build elogind. Prep v220: Remove not needed headers, round 1 Prep v220: Remove not needed headers, round 2 Prep v220: Remove not needed headers, round 3 Prep v220: Remove empty source directories Prep v220: Remove non-empty source directories, that aren't needed by elogind Prep v220: Remove all root directories that aren't referenced by the elogind build chain. Prep v220: remove superfluous src/import directory and systemd configurations and policies. --- diff --git a/.gitignore b/.gitignore index 763fd972c..cccb49d17 100644 --- a/.gitignore +++ b/.gitignore @@ -286,3 +286,8 @@ config.status configure stamp-* /pwx_* +/cleanup_*.sh +/elogind +/elogind-cgroups-agent +/rebuild_all.sh +/src/libelogind/libelogind.pc diff --git a/rules/60-evdev.rules b/rules/60-evdev.rules deleted file mode 100644 index e81966fbe..000000000 --- a/rules/60-evdev.rules +++ /dev/null @@ -1,19 +0,0 @@ -# do not edit this file, it will be overwritten on update - -ACTION=="remove", GOTO="evdev_end" -KERNEL!="event*", GOTO="evdev_end" - -# skip later rules when we find something for this input device -IMPORT{builtin}="hwdb --subsystem=input --lookup-prefix=evdev:", \ - RUN{builtin}+="keyboard", GOTO="evdev_end" - -# AT keyboard matching by the machine's DMI data -ENV{ID_INPUT_KEY}=="?*", DRIVERS=="atkbd", \ - IMPORT{builtin}="hwdb 'evdev:atkbd:$attr{[dmi/id]modalias}'", \ - RUN{builtin}+="keyboard", GOTO="keyboard_end" - -# device matching the input device name and the machine's DMI data -KERNELS=="input*", IMPORT{builtin}="hwdb 'evdev:name:$attr{name}:$attr{[dmi/id]modalias}'", \ - RUN{builtin}+="keyboard", GOTO="evdev_end" - -LABEL="evdev_end" diff --git a/shell-completion/bash/udevadm b/shell-completion/bash/udevadm deleted file mode 100644 index b828b8dd7..000000000 --- a/shell-completion/bash/udevadm +++ /dev/null @@ -1,97 +0,0 @@ -# udevadm(8) completion -*- shell-script -*- -# -# This file is part of systemd. -# -# Copyright 2010 Ran Benita -# -# systemd is free software; you can redistribute it and/or modify it -# under the terms of the GNU Lesser General Public License as published by -# the Free Software Foundation; either version 2.1 of the License, or -# (at your option) any later version. -# -# systemd is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with systemd; If not, see . - -__contains_word () { - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done -} - -__get_all_sysdevs() { - local -a devs=(/sys/bus/*/devices/*/ /sys/class/*/*/) - printf '%s\n' "${devs[@]%/}" -} - -_udevadm() { - local i verb comps - local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} - local OPTS='-h --help --version --debug' - - local verbs=(info trigger settle control monitor hwdb test-builtin test) - - for ((i=0; i < COMP_CWORD; i++)); do - if __contains_word "${COMP_WORDS[i]}" "${verbs[@]}" && - ! __contains_word "${COMP_WORDS[i-1]}" ${OPTS[ARG]}; then - verb=${COMP_WORDS[i]} - break - fi - done - - if [[ -z $verb ]]; then - COMPREPLY=( $(compgen -W '${OPTS[*]} ${verbs[*]}' -- "$cur") ) - return 0 - fi - - case $verb in - 'info') - if [[ $cur = -* ]]; then - comps='--help --query= --path= --name= --root --attribute-walk --export-db --cleanup-db' - else - comps=$( __get_all_sysdevs ) - fi - ;; - 'trigger') - comps='--help --verbose --dry-run --type= --action= --subsystem-match= - --subsystem-nomatch= --attr-match= --attr-nomatch= --property-match= - --tag-match= --sysname-match= --parent-match=' - ;; - 'settle') - comps='--help --timeout= --seq-start= --seq-end= --exit-if-exists= --quiet' - ;; - 'control') - comps='--help --exit --log-priority= --stop-exec-queue --start-exec-queue - --reload --property= --children-max= --timeout=' - ;; - 'monitor') - comps='--help --kernel --udev --property --subsystem-match= --tag-match=' - ;; - 'hwdb') - comps='--help --update --test=' - ;; - 'test') - if [[ $cur = -* ]]; then - comps='--help --action=' - else - comps=$( __get_all_sysdevs ) - fi - ;; - 'test-builtin') - comps='blkid btrfs hwdb input_id keyboard kmod net_id net_setup_link path_id usb_id uaccess' - ;; - *) - comps=${VERBS[*]} - ;; - esac - - COMPREPLY=( $(compgen -W '$comps' -- "$cur") ) - return 0 -} - -complete -F _udevadm udevadm diff --git a/shell-completion/zsh/_udevadm b/shell-completion/zsh/_udevadm deleted file mode 100644 index e5d252c81..000000000 --- a/shell-completion/zsh/_udevadm +++ /dev/null @@ -1,141 +0,0 @@ -#compdef udevadm - -_udevadm_info(){ - _arguments \ - '--query=[Query the database for specified type of device data. It needs the --path or --name to identify the specified device.]:type:(name symlink path property all)' \ - '--path=[The devpath of the device to query.]:sys files:_files -P /sys/ -W /sys' \ - '--name=[The name of the device node or a symlink to query]:device files:_files -P /dev/ -W /dev' \ - '--root[Print absolute paths in name or symlink query.]' \ - '--attribute-walk[Print all sysfs properties of the specified device that can be used in udev rules to match the specified device]' \ - '--export[Print output as key/value pairs.]' \ - '--export-prefix=[Add a prefix to the key name of exported values.]:prefix' \ - '--device-id-of-file=[Print major/minor numbers of the underlying device, where the file lives on.]:files:_udevadm_mounts' \ - '--export-db[Export the content of the udev database.]' \ - '--cleanup-db[Cleanup the udev database.]' -} - -_udevadm_trigger(){ - _arguments \ - '--verbose[Print the list of devices which will be triggered.]' \ - '--dry-run[Do not actually trigger the event.]' \ - '--type=[Trigger a specific type of devices.]:types:(devices subsystems failed)' \ - '--action=[Type of event to be triggered.]:actions:(add change remove)' \ - '--subsystem-match=[Trigger events for devices which belong to a matching subsystem.]' \ - '--subsystem-nomatch=[Do not trigger events for devices which belong to a matching subsystem.]' \ - '--attr-match=attribute=[Trigger events for devices with a matching sysfs attribute.]' \ - '--attr-nomatch=attribute=[Do not trigger events for devices with a matching sysfs attribute.]' \ - '--property-match=[Trigger events for devices with a matching property value.]' \ - '--tag-match=property[Trigger events for devices with a matching tag.]' \ - '--sysname-match=[Trigger events for devices with a matching sys device name.]' \ - '--parent-match=[Trigger events for all children of a given device.]' -} - -_udevadm_settle(){ - _arguments \ - '--timeout=[Maximum number of seconds to wait for the event queue to become empty.]' \ - '--seq-start=[Wait only for events after the given sequence number.]' \ - '--seq-end=[Wait only for events before the given sequence number.]' \ - '--exit-if-exists=[Stop waiting if file exists.]:files:_files' \ - '--quiet[Do not print any output, like the remaining queue entries when reaching the timeout.]' \ - '--help[Print help text.]' -} - -_udevadm_control(){ - _arguments \ - '--exit[Signal and wait for systemd-udevd to exit.]' \ - '--log-priority=[Set the internal log level of systemd-udevd.]:priorities:(err info debug)' \ - '--stop-exec-queue[Signal systemd-udevd to stop executing new events. Incoming events will be queued.]' \ - '--start-exec-queue[Signal systemd-udevd to enable the execution of events.]' \ - '--reload[Signal systemd-udevd to reload the rules files and other databases like the kernel module index.]' \ - '--property=[Set a global property for all events.]' \ - '--children-max=[Set the maximum number of events.]' \ - '--timeout=[The maximum number of seconds to wait for a reply from systemd-udevd.]' \ - '--help[Print help text.]' -} - -_udevadm_monitor(){ - _arguments \ - '--kernel[Print the kernel uevents.]' \ - '--udev[Print the udev event after the rule processing.]' \ - '--property[Also print the properties of the event.]' \ - '--subsystem-match=[Filter events by subsystem/\[devtype\].]' \ - '--tag-match=[Filter events by property.]' \ - '--help[Print help text.]' -} - -_udevadm_test(){ - _arguments \ - '--action=[The action string.]:actions:(add change remove)' \ - '--subsystem=[The subsystem string.]' \ - '--help[Print help text.]' \ - '*::devpath:_files -P /sys/ -W /sys' -} - -_udevadm_test-builtin(){ - if (( CURRENT == 2 )); then - _arguments \ - '--help[Print help text]' \ - '*::builtins:(blkid btrfs hwdb input_id net_id net_setup_link kmod path_id usb_id uaccess)' - elif (( CURRENT == 3 )); then - _arguments \ - '--help[Print help text]' \ - '*::syspath:_files -P /sys -W /sys' - else - _arguments \ - '--help[Print help text]' - fi -} - -_udevadm_mounts(){ - local dev_tmp dpath_tmp mp_tmp mline - - tmp=( "${(@f)$(< /etc/mtab)}" ) - dev_tmp=( "${(@)${(@)tmp%% *}:#none}" ) - mp_tmp=( "${(@)${(@)tmp#* }%% *}" ) - - local MATCH - mp_tmp=("${(@q)mp_tmp//(#m)\\[0-7](#c3)/${(#)$(( 8#${MATCH[2,-1]} ))}}") - dpath_tmp=( "${(@Mq)dev_tmp:#/*}" ) - dev_tmp=( "${(@q)dev_tmp:#/*}" ) - - _alternative \ - 'device-paths: device path:compadd -a dpath_tmp' \ - 'directories:mount point:compadd -a mp_tmp' -} - - -_udevadm_command(){ - local -a _udevadm_cmds - _udevadm_cmds=( - 'info:query sysfs or the udev database' - 'trigger:request events from the kernel' - 'settle:wait for the event queue to finish' - 'control:control the udev daemon' - 'monitor:listen to kernel and udev events' - 'test:test an event run' - 'test-builtin:test a built-in command' - ) - - if ((CURRENT == 1)); then - _describe -t commands 'udevadm commands' _udevadm_cmds - else - local curcontext="$curcontext" - cmd="${${_udevadm_cmds[(r)$words[1]:*]%%:*}}" - if (($#cmd)); then - if (( $+functions[_udevadm_$cmd] )); then - _udevadm_$cmd - else - _message "no options for $cmd" - fi - else - _message "no more options" - fi - fi -} - - -_arguments \ - '--debug[Print debug messages to stderr]' \ - '--version[Print version number]' \ - '--help[Print help text]' \ - '*::udevadm commands:_udevadm_command' diff --git a/src/journal/audit-type.c b/src/journal/audit-type.c deleted file mode 100644 index 4888c7d05..000000000 --- a/src/journal/audit-type.c +++ /dev/null @@ -1,32 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2015 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#ifdef HAVE_AUDIT -# include -#endif - -#include "audit-type.h" -#include "macro.h" -#include "missing.h" - -#include "audit_type-to-name.h" diff --git a/src/journal/audit-type.h b/src/journal/audit-type.h deleted file mode 100644 index fa5284e02..000000000 --- a/src/journal/audit-type.h +++ /dev/null @@ -1,39 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2015 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "macro.h" - -const char *audit_type_to_string(int type); -int audit_type_from_string(const char *s); - -/* This is inspired by DNS TYPEnnn formatting */ -#define audit_type_name_alloca(type) \ - ({ \ - const char *_s_; \ - _s_ = audit_type_to_string(type); \ - if (!_s_) { \ - _s_ = alloca(strlen("AUDIT") + DECIMAL_STR_MAX(int)); \ - sprintf((char*) _s_, "AUDIT%04i", type); \ - } \ - _s_; \ - }) diff --git a/src/journal/test-audit-type.c b/src/journal/test-audit-type.c deleted file mode 100644 index 7946cf3c4..000000000 --- a/src/journal/test-audit-type.c +++ /dev/null @@ -1,44 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2015 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "audit-type.h" - -static void print_audit_label(int i) { - const char *name; - - name = audit_type_name_alloca(i); - /* This is a separate function only because of alloca */ - printf("%i → %s → %s\n", i, audit_type_to_string(i), name); -} - -static void test_audit_type(void) { - int i; - - for (i = 0; i <= AUDIT_KERNEL; i++) - print_audit_label(i); -} - -int main(int argc, char **argv) { - test_audit_type(); -} diff --git a/src/libelogind/sd-bus/bus-dump.c b/src/libelogind/sd-bus/bus-dump.c deleted file mode 100644 index 9db86adb7..000000000 --- a/src/libelogind/sd-bus/bus-dump.c +++ /dev/null @@ -1,604 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "util.h" -#include "capability.h" -#include "strv.h" -#include "macro.h" -#include "cap-list.h" -#include "formats-util.h" -#include "terminal-util.h" - -#include "bus-message.h" -#include "bus-internal.h" -#include "bus-type.h" -#include "bus-dump.h" - -static char *indent(unsigned level, unsigned flags) { - char *p; - unsigned n, i = 0; - - n = 0; - - if (flags & BUS_MESSAGE_DUMP_SUBTREE_ONLY && level > 0) - level -= 1; - - if (flags & BUS_MESSAGE_DUMP_WITH_HEADER) - n += 2; - - p = new(char, n + level*8 + 1); - if (!p) - return NULL; - - if (flags & BUS_MESSAGE_DUMP_WITH_HEADER) { - p[i++] = ' '; - p[i++] = ' '; - } - - memset(p + i, ' ', level*8); - p[i + level*8] = 0; - - return p; -} - -int bus_message_dump(sd_bus_message *m, FILE *f, unsigned flags) { - unsigned level = 1; - int r; - - assert(m); - - if (!f) - f = stdout; - - if (flags & BUS_MESSAGE_DUMP_WITH_HEADER) { - fprintf(f, - "%s%s%s Type=%s%s%s Endian=%c Flags=%u Version=%u Priority=%"PRIi64, - m->header->type == SD_BUS_MESSAGE_METHOD_ERROR ? ansi_highlight_red() : - m->header->type == SD_BUS_MESSAGE_METHOD_RETURN ? ansi_highlight_green() : - m->header->type != SD_BUS_MESSAGE_SIGNAL ? ansi_highlight() : "", draw_special_char(DRAW_TRIANGULAR_BULLET), ansi_highlight_off(), - ansi_highlight(), bus_message_type_to_string(m->header->type), ansi_highlight_off(), - m->header->endian, - m->header->flags, - m->header->version, - m->priority); - - /* Display synthetic message serial number in a more readable - * format than (uint32_t) -1 */ - if (BUS_MESSAGE_COOKIE(m) == 0xFFFFFFFFULL) - fprintf(f, " Cookie=-1"); - else - fprintf(f, " Cookie=%" PRIu64, BUS_MESSAGE_COOKIE(m)); - - if (m->reply_cookie != 0) - fprintf(f, " ReplyCookie=%" PRIu64, m->reply_cookie); - - fputs("\n", f); - - if (m->sender) - fprintf(f, " Sender=%s%s%s", ansi_highlight(), m->sender, ansi_highlight_off()); - if (m->destination) - fprintf(f, " Destination=%s%s%s", ansi_highlight(), m->destination, ansi_highlight_off()); - if (m->path) - fprintf(f, " Path=%s%s%s", ansi_highlight(), m->path, ansi_highlight_off()); - if (m->interface) - fprintf(f, " Interface=%s%s%s", ansi_highlight(), m->interface, ansi_highlight_off()); - if (m->member) - fprintf(f, " Member=%s%s%s", ansi_highlight(), m->member, ansi_highlight_off()); - - if (m->sender || m->destination || m->path || m->interface || m->member) - fputs("\n", f); - - if (sd_bus_error_is_set(&m->error)) - fprintf(f, - " ErrorName=%s%s%s" - " ErrorMessage=%s\"%s\"%s\n", - ansi_highlight_red(), strna(m->error.name), ansi_highlight_off(), - ansi_highlight_red(), strna(m->error.message), ansi_highlight_off()); - - if (m->monotonic != 0) - fprintf(f, " Monotonic="USEC_FMT, m->monotonic); - if (m->realtime != 0) - fprintf(f, " Realtime="USEC_FMT, m->realtime); - if (m->seqnum != 0) - fprintf(f, " SequenceNumber=%"PRIu64, m->seqnum); - - if (m->monotonic != 0 || m->realtime != 0 || m->seqnum != 0) - fputs("\n", f); - - bus_creds_dump(&m->creds, f, true); - } - - r = sd_bus_message_rewind(m, !(flags & BUS_MESSAGE_DUMP_SUBTREE_ONLY)); - if (r < 0) - return log_error_errno(r, "Failed to rewind: %m"); - - if (!(flags & BUS_MESSAGE_DUMP_SUBTREE_ONLY)) { - _cleanup_free_ char *prefix = NULL; - - prefix = indent(0, flags); - if (!prefix) - return log_oom(); - - fprintf(f, "%sMESSAGE \"%s\" {\n", prefix, strempty(m->root_container.signature)); - } - - for (;;) { - _cleanup_free_ char *prefix = NULL; - const char *contents = NULL; - char type; - union { - uint8_t u8; - uint16_t u16; - int16_t s16; - uint32_t u32; - int32_t s32; - uint64_t u64; - int64_t s64; - double d64; - const char *string; - int i; - } basic; - - r = sd_bus_message_peek_type(m, &type, &contents); - if (r < 0) - return log_error_errno(r, "Failed to peek type: %m"); - - if (r == 0) { - if (level <= 1) - break; - - r = sd_bus_message_exit_container(m); - if (r < 0) - return log_error_errno(r, "Failed to exit container: %m"); - - level--; - - prefix = indent(level, flags); - if (!prefix) - return log_oom(); - - fprintf(f, "%s};\n", prefix); - continue; - } - - prefix = indent(level, flags); - if (!prefix) - return log_oom(); - - if (bus_type_is_container(type) > 0) { - r = sd_bus_message_enter_container(m, type, contents); - if (r < 0) - return log_error_errno(r, "Failed to enter container: %m"); - - if (type == SD_BUS_TYPE_ARRAY) - fprintf(f, "%sARRAY \"%s\" {\n", prefix, contents); - else if (type == SD_BUS_TYPE_VARIANT) - fprintf(f, "%sVARIANT \"%s\" {\n", prefix, contents); - else if (type == SD_BUS_TYPE_STRUCT) - fprintf(f, "%sSTRUCT \"%s\" {\n", prefix, contents); - else if (type == SD_BUS_TYPE_DICT_ENTRY) - fprintf(f, "%sDICT_ENTRY \"%s\" {\n", prefix, contents); - - level ++; - - continue; - } - - r = sd_bus_message_read_basic(m, type, &basic); - if (r < 0) - return log_error_errno(r, "Failed to get basic: %m"); - - assert(r > 0); - - switch (type) { - - case SD_BUS_TYPE_BYTE: - fprintf(f, "%sBYTE %s%u%s;\n", prefix, ansi_highlight(), basic.u8, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_BOOLEAN: - fprintf(f, "%sBOOLEAN %s%s%s;\n", prefix, ansi_highlight(), true_false(basic.i), ansi_highlight_off()); - break; - - case SD_BUS_TYPE_INT16: - fprintf(f, "%sINT16 %s%i%s;\n", prefix, ansi_highlight(), basic.s16, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_UINT16: - fprintf(f, "%sUINT16 %s%u%s;\n", prefix, ansi_highlight(), basic.u16, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_INT32: - fprintf(f, "%sINT32 %s%i%s;\n", prefix, ansi_highlight(), basic.s32, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_UINT32: - fprintf(f, "%sUINT32 %s%u%s;\n", prefix, ansi_highlight(), basic.u32, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_INT64: - fprintf(f, "%sINT64 %s%"PRIi64"%s;\n", prefix, ansi_highlight(), basic.s64, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_UINT64: - fprintf(f, "%sUINT64 %s%"PRIu64"%s;\n", prefix, ansi_highlight(), basic.u64, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_DOUBLE: - fprintf(f, "%sDOUBLE %s%g%s;\n", prefix, ansi_highlight(), basic.d64, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_STRING: - fprintf(f, "%sSTRING \"%s%s%s\";\n", prefix, ansi_highlight(), basic.string, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_OBJECT_PATH: - fprintf(f, "%sOBJECT_PATH \"%s%s%s\";\n", prefix, ansi_highlight(), basic.string, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_SIGNATURE: - fprintf(f, "%sSIGNATURE \"%s%s%s\";\n", prefix, ansi_highlight(), basic.string, ansi_highlight_off()); - break; - - case SD_BUS_TYPE_UNIX_FD: - fprintf(f, "%sUNIX_FD %s%i%s;\n", prefix, ansi_highlight(), basic.i, ansi_highlight_off()); - break; - - default: - assert_not_reached("Unknown basic type."); - } - } - - if (!(flags & BUS_MESSAGE_DUMP_SUBTREE_ONLY)) { - _cleanup_free_ char *prefix = NULL; - - prefix = indent(0, flags); - if (!prefix) - return log_oom(); - - fprintf(f, "%s};\n\n", prefix); - } - - return 0; -} - -static void dump_capabilities( - sd_bus_creds *c, - FILE *f, - const char *name, - bool terse, - int (*has)(sd_bus_creds *c, int capability)) { - - unsigned long i, last_cap; - unsigned n = 0; - int r; - - assert(c); - assert(f); - assert(name); - assert(has); - - i = 0; - r = has(c, i); - if (r < 0) - return; - - fprintf(f, "%s%s=%s", terse ? " " : "", name, terse ? "" : ansi_highlight()); - last_cap = cap_last_cap(); - - for (;;) { - if (r > 0) { - - if (n > 0) - fputc(' ', f); - if (n % 4 == 3) - fprintf(f, terse ? "\n " : "\n "); - - fprintf(f, "%s", strna(capability_to_name(i))); - n++; - } - - i++; - - if (i > last_cap) - break; - - r = has(c, i); - } - - fputs("\n", f); - - if (!terse) - fputs(ansi_highlight_off(), f); -} - -int bus_creds_dump(sd_bus_creds *c, FILE *f, bool terse) { - uid_t owner, audit_loginuid; - uint32_t audit_sessionid; - char **cmdline = NULL, **well_known = NULL; - const char *prefix, *color, *suffix, *s; - int r, q, v, w, z; - - assert(c); - - if (!f) - f = stdout; - - if (terse) { - prefix = " "; - suffix = ""; - color = ""; - } else { - const char *off; - - prefix = ""; - color = ansi_highlight(); - - off = ansi_highlight_off(); - suffix = strjoina(off, "\n"); - } - - if (c->mask & SD_BUS_CREDS_PID) - fprintf(f, "%sPID=%s"PID_FMT"%s", prefix, color, c->pid, suffix); - if (c->mask & SD_BUS_CREDS_TID) - fprintf(f, "%sTID=%s"PID_FMT"%s", prefix, color, c->tid, suffix); - if (c->mask & SD_BUS_CREDS_PPID) { - if (c->ppid == 0) - fprintf(f, "%sPPID=%sn/a%s", prefix, color, suffix); - else - fprintf(f, "%sPPID=%s"PID_FMT"%s", prefix, color, c->ppid, suffix); - } - if (c->mask & SD_BUS_CREDS_TTY) - fprintf(f, "%sTTY=%s%s%s", prefix, color, strna(c->tty), suffix); - - if (terse && ((c->mask & (SD_BUS_CREDS_PID|SD_BUS_CREDS_TID|SD_BUS_CREDS_PPID|SD_BUS_CREDS_TTY)))) - fputs("\n", f); - - if (c->mask & SD_BUS_CREDS_UID) - fprintf(f, "%sUID=%s"UID_FMT"%s", prefix, color, c->uid, suffix); - if (c->mask & SD_BUS_CREDS_EUID) - fprintf(f, "%sEUID=%s"UID_FMT"%s", prefix, color, c->euid, suffix); - if (c->mask & SD_BUS_CREDS_SUID) - fprintf(f, "%sSUID=%s"UID_FMT"%s", prefix, color, c->suid, suffix); - if (c->mask & SD_BUS_CREDS_FSUID) - fprintf(f, "%sFSUID=%s"UID_FMT"%s", prefix, color, c->fsuid, suffix); - r = sd_bus_creds_get_owner_uid(c, &owner); - if (r >= 0) - fprintf(f, "%sOwnerUID=%s"UID_FMT"%s", prefix, color, owner, suffix); - if (c->mask & SD_BUS_CREDS_GID) - fprintf(f, "%sGID=%s"GID_FMT"%s", prefix, color, c->gid, suffix); - if (c->mask & SD_BUS_CREDS_EGID) - fprintf(f, "%sEGID=%s"GID_FMT"%s", prefix, color, c->egid, suffix); - if (c->mask & SD_BUS_CREDS_SGID) - fprintf(f, "%sSGID=%s"GID_FMT"%s", prefix, color, c->sgid, suffix); - if (c->mask & SD_BUS_CREDS_FSGID) - fprintf(f, "%sFSGID=%s"GID_FMT"%s", prefix, color, c->fsgid, suffix); - - if (c->mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) { - unsigned i; - - fprintf(f, "%sSupplementaryGIDs=%s", prefix, color); - for (i = 0; i < c->n_supplementary_gids; i++) - fprintf(f, "%s" GID_FMT, i > 0 ? " " : "", c->supplementary_gids[i]); - fprintf(f, "%s", suffix); - } - - if (terse && ((c->mask & (SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_SUID|SD_BUS_CREDS_FSUID| - SD_BUS_CREDS_GID|SD_BUS_CREDS_EGID|SD_BUS_CREDS_SGID|SD_BUS_CREDS_FSGID| - SD_BUS_CREDS_SUPPLEMENTARY_GIDS)) || r >= 0)) - fputs("\n", f); - - if (c->mask & SD_BUS_CREDS_COMM) - fprintf(f, "%sComm=%s%s%s", prefix, color, c->comm, suffix); - if (c->mask & SD_BUS_CREDS_TID_COMM) - fprintf(f, "%sTIDComm=%s%s%s", prefix, color, c->tid_comm, suffix); - if (c->mask & SD_BUS_CREDS_EXE) - fprintf(f, "%sExe=%s%s%s", prefix, color, strna(c->exe), suffix); - - if (terse && (c->mask & (SD_BUS_CREDS_EXE|SD_BUS_CREDS_COMM|SD_BUS_CREDS_TID_COMM))) - fputs("\n", f); - - r = sd_bus_creds_get_cmdline(c, &cmdline); - if (r >= 0) { - char **i; - - fprintf(f, "%sCommandLine=%s", prefix, color); - STRV_FOREACH(i, cmdline) { - if (i != cmdline) - fputc(' ', f); - - fputs(*i, f); - } - - fprintf(f, "%s", suffix); - } else if (r != -ENODATA) - fprintf(f, "%sCommandLine=%sn/a%s", prefix, color, suffix); - - if (c->mask & SD_BUS_CREDS_SELINUX_CONTEXT) - fprintf(f, "%sLabel=%s%s%s", prefix, color, c->label, suffix); - if (c->mask & SD_BUS_CREDS_DESCRIPTION) - fprintf(f, "%sDescription=%s%s%s", prefix, color, c->description, suffix); - - if (terse && (c->mask & (SD_BUS_CREDS_SELINUX_CONTEXT|SD_BUS_CREDS_DESCRIPTION))) - fputs("\n", f); - - if (c->mask & SD_BUS_CREDS_CGROUP) - fprintf(f, "%sCGroup=%s%s%s", prefix, color, c->cgroup, suffix); - s = NULL; - r = sd_bus_creds_get_unit(c, &s); - if (r != -ENODATA) - fprintf(f, "%sUnit=%s%s%s", prefix, color, strna(s), suffix); - s = NULL; - v = sd_bus_creds_get_slice(c, &s); - if (v != -ENODATA) - fprintf(f, "%sSlice=%s%s%s", prefix, color, strna(s), suffix); - s = NULL; - q = sd_bus_creds_get_user_unit(c, &s); - if (q != -ENODATA) - fprintf(f, "%sUserUnit=%s%s%s", prefix, color, strna(s), suffix); - s = NULL; - w = sd_bus_creds_get_user_slice(c, &s); - if (w != -ENODATA) - fprintf(f, "%sUserSlice=%s%s%s", prefix, color, strna(s), suffix); - s = NULL; - z = sd_bus_creds_get_session(c, &s); - if (z != -ENODATA) - fprintf(f, "%sSession=%s%s%s", prefix, color, strna(s), suffix); - - if (terse && ((c->mask & SD_BUS_CREDS_CGROUP) || r != -ENODATA || q != -ENODATA || v != -ENODATA || w != -ENODATA || z != -ENODATA)) - fputs("\n", f); - - r = sd_bus_creds_get_audit_login_uid(c, &audit_loginuid); - if (r >= 0) - fprintf(f, "%sAuditLoginUID=%s"UID_FMT"%s", prefix, color, audit_loginuid, suffix); - else if (r != -ENODATA) - fprintf(f, "%sAuditLoginUID=%sn/a%s", prefix, color, suffix); - q = sd_bus_creds_get_audit_session_id(c, &audit_sessionid); - if (q >= 0) - fprintf(f, "%sAuditSessionID=%s%"PRIu32"%s", prefix, color, audit_sessionid, suffix); - else if (q != -ENODATA) - fprintf(f, "%sAuditSessionID=%sn/a%s", prefix, color, suffix); - - if (terse && (r != -ENODATA || q != -ENODATA)) - fputs("\n", f); - - if (c->mask & SD_BUS_CREDS_UNIQUE_NAME) - fprintf(f, "%sUniqueName=%s%s%s", prefix, color, c->unique_name, suffix); - - if (sd_bus_creds_get_well_known_names(c, &well_known) >= 0) { - char **i; - - fprintf(f, "%sWellKnownNames=%s", prefix, color); - STRV_FOREACH(i, well_known) { - if (i != well_known) - fputc(' ', f); - - fputs(*i, f); - } - - fprintf(f, "%s", suffix); - } - - if (terse && (c->mask & SD_BUS_CREDS_UNIQUE_NAME || well_known)) - fputc('\n', f); - - dump_capabilities(c, f, "EffectiveCapabilities", terse, sd_bus_creds_has_effective_cap); - dump_capabilities(c, f, "PermittedCapabilities", terse, sd_bus_creds_has_permitted_cap); - dump_capabilities(c, f, "InheritableCapabilities", terse, sd_bus_creds_has_inheritable_cap); - dump_capabilities(c, f, "BoundingCapabilities", terse, sd_bus_creds_has_bounding_cap); - - return 0; -} - -/* - * For details about the file format, see: - * - * http://wiki.wireshark.org/Development/LibpcapFileFormat - */ - -typedef struct _packed_ pcap_hdr_s { - uint32_t magic_number; /* magic number */ - uint16_t version_major; /* major version number */ - uint16_t version_minor; /* minor version number */ - int32_t thiszone; /* GMT to local correction */ - uint32_t sigfigs; /* accuracy of timestamps */ - uint32_t snaplen; /* max length of captured packets, in octets */ - uint32_t network; /* data link type */ -} pcap_hdr_t ; - -typedef struct _packed_ pcaprec_hdr_s { - uint32_t ts_sec; /* timestamp seconds */ - uint32_t ts_usec; /* timestamp microseconds */ - uint32_t incl_len; /* number of octets of packet saved in file */ - uint32_t orig_len; /* actual length of packet */ -} pcaprec_hdr_t; - -int bus_pcap_header(size_t snaplen, FILE *f) { - - pcap_hdr_t hdr = { - .magic_number = 0xa1b2c3d4U, - .version_major = 2, - .version_minor = 4, - .thiszone = 0, /* UTC */ - .sigfigs = 0, - .network = 231, /* D-Bus */ - }; - - if (!f) - f = stdout; - - assert(snaplen > 0); - assert((size_t) (uint32_t) snaplen == snaplen); - - hdr.snaplen = (uint32_t) snaplen; - - fwrite(&hdr, 1, sizeof(hdr), f); - fflush(f); - - return 0; -} - -int bus_message_pcap_frame(sd_bus_message *m, size_t snaplen, FILE *f) { - struct bus_body_part *part; - pcaprec_hdr_t hdr = {}; - struct timeval tv; - unsigned i; - size_t w; - - if (!f) - f = stdout; - - assert(m); - assert(snaplen > 0); - assert((size_t) (uint32_t) snaplen == snaplen); - - if (m->realtime != 0) - timeval_store(&tv, m->realtime); - else - assert_se(gettimeofday(&tv, NULL) >= 0); - - hdr.ts_sec = tv.tv_sec; - hdr.ts_usec = tv.tv_usec; - hdr.orig_len = BUS_MESSAGE_SIZE(m); - hdr.incl_len = MIN(hdr.orig_len, snaplen); - - /* write the pcap header */ - fwrite(&hdr, 1, sizeof(hdr), f); - - /* write the dbus header */ - w = MIN(BUS_MESSAGE_BODY_BEGIN(m), snaplen); - fwrite(m->header, 1, w, f); - snaplen -= w; - - /* write the dbus body */ - MESSAGE_FOREACH_PART(part, i, m) { - if (snaplen <= 0) - break; - - w = MIN(part->size, snaplen); - fwrite(part->data, 1, w, f); - snaplen -= w; - } - - fflush(f); - - return 0; -} diff --git a/src/libelogind/sd-bus/bus-dump.h b/src/libelogind/sd-bus/bus-dump.h deleted file mode 100644 index d2522edeb..000000000 --- a/src/libelogind/sd-bus/bus-dump.h +++ /dev/null @@ -1,39 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "sd-bus.h" - -enum { - BUS_MESSAGE_DUMP_WITH_HEADER = 1, - BUS_MESSAGE_DUMP_SUBTREE_ONLY = 2, -}; - -int bus_message_dump(sd_bus_message *m, FILE *f, unsigned flags); - -int bus_creds_dump(sd_bus_creds *c, FILE *f, bool terse); - -int bus_pcap_header(size_t snaplen, FILE *f); -int bus_message_pcap_frame(sd_bus_message *m, size_t snaplen, FILE *f); diff --git a/src/libelogind/sd-bus/busctl-introspect.c b/src/libelogind/sd-bus/busctl-introspect.c deleted file mode 100644 index 15c10da7e..000000000 --- a/src/libelogind/sd-bus/busctl-introspect.c +++ /dev/null @@ -1,793 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "util.h" -#include "xml.h" -#include "sd-bus-vtable.h" - -#include "busctl-introspect.h" - -#define NODE_DEPTH_MAX 16 - -typedef struct Context { - const XMLIntrospectOps *ops; - void *userdata; - - char *interface_name; - uint64_t interface_flags; - - char *member_name; - char *member_signature; - char *member_result; - uint64_t member_flags; - bool member_writable; - - const char *current; - void *xml_state; -} Context; - -static void context_reset_member(Context *c) { - free(c->member_name); - free(c->member_signature); - free(c->member_result); - - c->member_name = c->member_signature = c->member_result = NULL; - c->member_flags = 0; - c->member_writable = false; -} - -static void context_reset_interface(Context *c) { - free(c->interface_name); - c->interface_name = NULL; - c->interface_flags = 0; - - context_reset_member(c); -} - -static int parse_xml_annotation(Context *context, uint64_t *flags) { - - enum { - STATE_ANNOTATION, - STATE_NAME, - STATE_VALUE - } state = STATE_ANNOTATION; - - _cleanup_free_ char *field = NULL, *value = NULL; - - assert(context); - - for (;;) { - _cleanup_free_ char *name = NULL; - - int t; - - t = xml_tokenize(&context->current, &name, &context->xml_state, NULL); - if (t < 0) { - log_error("XML parse error."); - return t; - } - - if (t == XML_END) { - log_error("Premature end of XML data."); - return -EBADMSG; - } - - switch (state) { - - case STATE_ANNOTATION: - - if (t == XML_ATTRIBUTE_NAME) { - - if (streq_ptr(name, "name")) - state = STATE_NAME; - - else if (streq_ptr(name, "value")) - state = STATE_VALUE; - - else { - log_error("Unexpected attribute %s.", name); - return -EBADMSG; - } - - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "annotation"))) { - - if (flags) { - if (streq_ptr(field, "org.freedesktop.DBus.Deprecated")) { - - if (streq_ptr(value, "true")) - *flags |= SD_BUS_VTABLE_DEPRECATED; - - } else if (streq_ptr(field, "org.freedesktop.DBus.Method.NoReply")) { - - if (streq_ptr(value, "true")) - *flags |= SD_BUS_VTABLE_METHOD_NO_REPLY; - - } else if (streq_ptr(field, "org.freedesktop.DBus.Property.EmitsChangedSignal")) { - - if (streq_ptr(value, "const")) - *flags = (*flags & ~(SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION|SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE)) | SD_BUS_VTABLE_PROPERTY_CONST; - else if (streq_ptr(value, "invalidates")) - *flags = (*flags & ~(SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE|SD_BUS_VTABLE_PROPERTY_CONST)) | SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION; - else if (streq_ptr(value, "false")) - *flags = *flags & ~(SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE|SD_BUS_VTABLE_PROPERTY_CONST|SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION); - } - } - - return 0; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in . (1)"); - return -EINVAL; - } - - break; - - case STATE_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - free(field); - field = name; - name = NULL; - - state = STATE_ANNOTATION; - } else { - log_error("Unexpected token in . (2)"); - return -EINVAL; - } - - break; - - case STATE_VALUE: - - if (t == XML_ATTRIBUTE_VALUE) { - free(value); - value = name; - name = NULL; - - state = STATE_ANNOTATION; - } else { - log_error("Unexpected token in . (3)"); - return -EINVAL; - } - - break; - - default: - assert_not_reached("Bad state"); - } - } -} - -static int parse_xml_node(Context *context, const char *prefix, unsigned n_depth) { - - enum { - STATE_NODE, - STATE_NODE_NAME, - STATE_INTERFACE, - STATE_INTERFACE_NAME, - STATE_METHOD, - STATE_METHOD_NAME, - STATE_METHOD_ARG, - STATE_METHOD_ARG_NAME, - STATE_METHOD_ARG_TYPE, - STATE_METHOD_ARG_DIRECTION, - STATE_SIGNAL, - STATE_SIGNAL_NAME, - STATE_SIGNAL_ARG, - STATE_SIGNAL_ARG_NAME, - STATE_SIGNAL_ARG_TYPE, - STATE_PROPERTY, - STATE_PROPERTY_NAME, - STATE_PROPERTY_TYPE, - STATE_PROPERTY_ACCESS, - } state = STATE_NODE; - - _cleanup_free_ char *node_path = NULL, *argument_type = NULL, *argument_direction = NULL; - const char *np = prefix; - int r; - - assert(context); - assert(prefix); - - if (n_depth > NODE_DEPTH_MAX) { - log_error(" depth too high."); - return -EINVAL; - } - - for (;;) { - _cleanup_free_ char *name = NULL; - int t; - - t = xml_tokenize(&context->current, &name, &context->xml_state, NULL); - if (t < 0) { - log_error("XML parse error."); - return t; - } - - if (t == XML_END) { - log_error("Premature end of XML data."); - return -EBADMSG; - } - - switch (state) { - - case STATE_NODE: - if (t == XML_ATTRIBUTE_NAME) { - - if (streq_ptr(name, "name")) - state = STATE_NODE_NAME; - else { - log_error("Unexpected attribute %s.", name); - return -EBADMSG; - } - - } else if (t == XML_TAG_OPEN) { - - if (streq_ptr(name, "interface")) - state = STATE_INTERFACE; - else if (streq_ptr(name, "node")) { - - r = parse_xml_node(context, np, n_depth+1); - if (r < 0) - return r; - } else { - log_error("Unexpected tag %s.", name); - return -EBADMSG; - } - - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "node"))) { - - if (context->ops->on_path) { - r = context->ops->on_path(node_path ? node_path : np, context->userdata); - if (r < 0) - return r; - } - - return 0; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in . (1)"); - return -EINVAL; - } - - break; - - case STATE_NODE_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - - free(node_path); - - if (name[0] == '/') { - node_path = name; - name = NULL; - } else { - - if (endswith(prefix, "/")) - node_path = strappend(prefix, name); - else - node_path = strjoin(prefix, "/", name, NULL); - if (!node_path) - return log_oom(); - } - - np = node_path; - state = STATE_NODE; - } else { - log_error("Unexpected token in . (2)"); - return -EINVAL; - } - - break; - - case STATE_INTERFACE: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_INTERFACE_NAME; - else { - log_error("Unexpected attribute %s.", name); - return -EBADMSG; - } - - } else if (t == XML_TAG_OPEN) { - if (streq_ptr(name, "method")) - state = STATE_METHOD; - else if (streq_ptr(name, "signal")) - state = STATE_SIGNAL; - else if (streq_ptr(name, "property")) { - context->member_flags |= SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE; - state = STATE_PROPERTY; - } else if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, &context->interface_flags); - if (r < 0) - return r; - } else { - log_error("Unexpected tag %s.", name); - return -EINVAL; - } - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "interface"))) { - - if (n_depth == 0) { - if (context->ops->on_interface) { - r = context->ops->on_interface(context->interface_name, context->interface_flags, context->userdata); - if (r < 0) - return r; - } - - context_reset_interface(context); - } - - state = STATE_NODE; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in . (1)"); - return -EINVAL; - } - - break; - - case STATE_INTERFACE_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - if (n_depth == 0) { - free(context->interface_name); - context->interface_name = name; - name = NULL; - } - - state = STATE_INTERFACE; - } else { - log_error("Unexpected token in . (2)"); - return -EINVAL; - } - - break; - - case STATE_METHOD: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_METHOD_NAME; - else { - log_error("Unexpected attribute %s", name); - return -EBADMSG; - } - } else if (t == XML_TAG_OPEN) { - if (streq_ptr(name, "arg")) - state = STATE_METHOD_ARG; - else if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, &context->member_flags); - if (r < 0) - return r; - } else { - log_error("Unexpected tag %s.", name); - return -EINVAL; - } - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "method"))) { - - if (n_depth == 0) { - if (context->ops->on_method) { - r = context->ops->on_method(context->interface_name, context->member_name, context->member_signature, context->member_result, context->member_flags, context->userdata); - if (r < 0) - return r; - } - - context_reset_member(context); - } - - state = STATE_INTERFACE; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in (1)."); - return -EINVAL; - } - - break; - - case STATE_METHOD_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - - if (n_depth == 0) { - free(context->member_name); - context->member_name = name; - name = NULL; - } - - state = STATE_METHOD; - } else { - log_error("Unexpected token in (2)."); - return -EINVAL; - } - - break; - - case STATE_METHOD_ARG: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_METHOD_ARG_NAME; - else if (streq_ptr(name, "type")) - state = STATE_METHOD_ARG_TYPE; - else if (streq_ptr(name, "direction")) - state = STATE_METHOD_ARG_DIRECTION; - else { - log_error("Unexpected method attribute %s.", name); - return -EBADMSG; - } - } else if (t == XML_TAG_OPEN) { - if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, NULL); - if (r < 0) - return r; - } else { - log_error("Unexpected method tag %s.", name); - return -EINVAL; - } - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "arg"))) { - - if (n_depth == 0) { - - if (argument_type) { - if (!argument_direction || streq(argument_direction, "in")) { - if (!strextend(&context->member_signature, argument_type, NULL)) - return log_oom(); - } else if (streq(argument_direction, "out")) { - if (!strextend(&context->member_result, argument_type, NULL)) - return log_oom(); - } - } - - free(argument_type); - free(argument_direction); - argument_type = argument_direction = NULL; - } - - state = STATE_METHOD; - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in method . (1)"); - return -EINVAL; - } - - break; - - case STATE_METHOD_ARG_NAME: - - if (t == XML_ATTRIBUTE_VALUE) - state = STATE_METHOD_ARG; - else { - log_error("Unexpected token in method . (2)"); - return -EINVAL; - } - - break; - - case STATE_METHOD_ARG_TYPE: - - if (t == XML_ATTRIBUTE_VALUE) { - free(argument_type); - argument_type = name; - name = NULL; - - state = STATE_METHOD_ARG; - } else { - log_error("Unexpected token in method . (3)"); - return -EINVAL; - } - - break; - - case STATE_METHOD_ARG_DIRECTION: - - if (t == XML_ATTRIBUTE_VALUE) { - free(argument_direction); - argument_direction = name; - name = NULL; - - state = STATE_METHOD_ARG; - } else { - log_error("Unexpected token in method . (4)"); - return -EINVAL; - } - - break; - - case STATE_SIGNAL: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_SIGNAL_NAME; - else { - log_error("Unexpected attribute %s.", name); - return -EBADMSG; - } - } else if (t == XML_TAG_OPEN) { - if (streq_ptr(name, "arg")) - state = STATE_SIGNAL_ARG; - else if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, &context->member_flags); - if (r < 0) - return r; - } else { - log_error("Unexpected tag %s.", name); - return -EINVAL; - } - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "signal"))) { - - if (n_depth == 0) { - if (context->ops->on_signal) { - r = context->ops->on_signal(context->interface_name, context->member_name, context->member_signature, context->member_flags, context->userdata); - if (r < 0) - return r; - } - - context_reset_member(context); - } - - state = STATE_INTERFACE; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in . (1)"); - return -EINVAL; - } - - break; - - case STATE_SIGNAL_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - - if (n_depth == 0) { - free(context->member_name); - context->member_name = name; - name = NULL; - } - - state = STATE_SIGNAL; - } else { - log_error("Unexpected token in . (2)"); - return -EINVAL; - } - - break; - - - case STATE_SIGNAL_ARG: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_SIGNAL_ARG_NAME; - else if (streq_ptr(name, "type")) - state = STATE_SIGNAL_ARG_TYPE; - else { - log_error("Unexpected signal attribute %s.", name); - return -EBADMSG; - } - } else if (t == XML_TAG_OPEN) { - if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, NULL); - if (r < 0) - return r; - } else { - log_error("Unexpected signal tag %s.", name); - return -EINVAL; - } - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "arg"))) { - - if (argument_type) { - if (!strextend(&context->member_signature, argument_type, NULL)) - return log_oom(); - - free(argument_type); - argument_type = NULL; - } - - state = STATE_SIGNAL; - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in signal (1)."); - return -EINVAL; - } - - break; - - case STATE_SIGNAL_ARG_NAME: - - if (t == XML_ATTRIBUTE_VALUE) - state = STATE_SIGNAL_ARG; - else { - log_error("Unexpected token in signal (2)."); - return -EINVAL; - } - - break; - - case STATE_SIGNAL_ARG_TYPE: - - if (t == XML_ATTRIBUTE_VALUE) { - free(argument_type); - argument_type = name; - name = NULL; - - state = STATE_SIGNAL_ARG; - } else { - log_error("Unexpected token in signal (3)."); - return -EINVAL; - } - - break; - - case STATE_PROPERTY: - - if (t == XML_ATTRIBUTE_NAME) { - if (streq_ptr(name, "name")) - state = STATE_PROPERTY_NAME; - else if (streq_ptr(name, "type")) - state = STATE_PROPERTY_TYPE; - else if (streq_ptr(name, "access")) - state = STATE_PROPERTY_ACCESS; - else { - log_error("Unexpected attribute %s.", name); - return -EBADMSG; - } - } else if (t == XML_TAG_OPEN) { - - if (streq_ptr(name, "annotation")) { - r = parse_xml_annotation(context, &context->member_flags); - if (r < 0) - return r; - } else { - log_error("Unexpected tag %s.", name); - return -EINVAL; - } - - } else if (t == XML_TAG_CLOSE_EMPTY || - (t == XML_TAG_CLOSE && streq_ptr(name, "property"))) { - - if (n_depth == 0) { - if (context->ops->on_property) { - r = context->ops->on_property(context->interface_name, context->member_name, context->member_signature, context->member_writable, context->member_flags, context->userdata); - if (r < 0) - return r; - } - - context_reset_member(context); - } - - state = STATE_INTERFACE; - - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in . (1)"); - return -EINVAL; - } - - break; - - case STATE_PROPERTY_NAME: - - if (t == XML_ATTRIBUTE_VALUE) { - - if (n_depth == 0) { - free(context->member_name); - context->member_name = name; - name = NULL; - } - state = STATE_PROPERTY; - } else { - log_error("Unexpected token in . (2)"); - return -EINVAL; - } - - break; - - case STATE_PROPERTY_TYPE: - - if (t == XML_ATTRIBUTE_VALUE) { - - if (n_depth == 0) { - free(context->member_signature); - context->member_signature = name; - name = NULL; - } - - state = STATE_PROPERTY; - } else { - log_error("Unexpected token in . (3)"); - return -EINVAL; - } - - break; - - case STATE_PROPERTY_ACCESS: - - if (t == XML_ATTRIBUTE_VALUE) { - - if (streq(name, "readwrite") || streq(name, "write")) - context->member_writable = true; - - state = STATE_PROPERTY; - } else { - log_error("Unexpected token in . (4)"); - return -EINVAL; - } - - break; - } - } -} - -int parse_xml_introspect(const char *prefix, const char *xml, const XMLIntrospectOps *ops, void *userdata) { - Context context = { - .ops = ops, - .userdata = userdata, - .current = xml, - }; - - int r; - - assert(prefix); - assert(xml); - assert(ops); - - for (;;) { - _cleanup_free_ char *name = NULL; - - r = xml_tokenize(&context.current, &name, &context.xml_state, NULL); - if (r < 0) { - log_error("XML parse error"); - goto finish; - } - - if (r == XML_END) { - r = 0; - break; - } - - if (r == XML_TAG_OPEN) { - - if (streq(name, "node")) { - r = parse_xml_node(&context, prefix, 0); - if (r < 0) - goto finish; - } else { - log_error("Unexpected tag '%s' in introspection data.", name); - r = -EBADMSG; - goto finish; - } - } else if (r != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token."); - r = -EBADMSG; - goto finish; - } - } - -finish: - context_reset_interface(&context); - - return r; -} diff --git a/src/libelogind/sd-bus/busctl-introspect.h b/src/libelogind/sd-bus/busctl-introspect.h deleted file mode 100644 index ea807d597..000000000 --- a/src/libelogind/sd-bus/busctl-introspect.h +++ /dev/null @@ -1,34 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -typedef struct XMLIntrospectOps { - int (*on_path)(const char *path, void *userdata); - int (*on_interface)(const char *name, uint64_t flags, void *userdata); - int (*on_method)(const char *interface, const char *name, const char *signature, const char *result, uint64_t flags, void *userdata); - int (*on_signal)(const char *interface, const char *name, const char *signature, uint64_t flags, void *userdata); - int (*on_property)(const char *interface, const char *name, const char *signature, bool writable, uint64_t flags, void *userdata); -} XMLIntrospectOps; - -int parse_xml_introspect(const char *prefix, const char *xml, const XMLIntrospectOps *ops, void *userdata); diff --git a/src/libelogind/sd-bus/test-bus-cleanup.c b/src/libelogind/sd-bus/test-bus-cleanup.c deleted file mode 100644 index f58688059..000000000 --- a/src/libelogind/sd-bus/test-bus-cleanup.c +++ /dev/null @@ -1,96 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#include "sd-bus.h" -#include "bus-util.h" -#include "bus-internal.h" -#include "bus-message.h" -#include "refcnt.h" - -static void test_bus_new(void) { - _cleanup_bus_unref_ sd_bus *bus = NULL; - - assert_se(sd_bus_new(&bus) == 0); - printf("after new: refcount %u\n", REFCNT_GET(bus->n_ref)); -} - -static int test_bus_open(void) { - _cleanup_bus_unref_ sd_bus *bus = NULL; - int r; - - r = sd_bus_open_system(&bus); - if (r == -ECONNREFUSED || r == -ENOENT) - return r; - - assert_se(r >= 0); - printf("after open: refcount %u\n", REFCNT_GET(bus->n_ref)); - - return 0; -} - -static void test_bus_new_method_call(void) { - sd_bus *bus = NULL; - _cleanup_bus_message_unref_ sd_bus_message *m = NULL; - - assert_se(sd_bus_open_system(&bus) >= 0); - - assert_se(sd_bus_message_new_method_call(bus, &m, "a.service.name", "/an/object/path", "an.interface.name", "AMethodName") >= 0); - - printf("after message_new_method_call: refcount %u\n", REFCNT_GET(bus->n_ref)); - - sd_bus_unref(bus); - printf("after bus_unref: refcount %u\n", m->n_ref); -} - -static void test_bus_new_signal(void) { - sd_bus *bus = NULL; - _cleanup_bus_message_unref_ sd_bus_message *m = NULL; - - assert_se(sd_bus_open_system(&bus) >= 0); - - assert_se(sd_bus_message_new_signal(bus, &m, "/an/object/path", "an.interface.name", "Name") >= 0); - - printf("after message_new_signal: refcount %u\n", REFCNT_GET(bus->n_ref)); - - sd_bus_unref(bus); - printf("after bus_unref: refcount %u\n", m->n_ref); -} - -int main(int argc, char **argv) { - int r; - - log_parse_environment(); - log_open(); - - test_bus_new(); - r = test_bus_open(); - if (r < 0) { - log_info("Failed to connect to bus, skipping tests."); - return EXIT_TEST_SKIP; - } - - test_bus_new_method_call(); - test_bus_new_signal(); - - return EXIT_SUCCESS; -} diff --git a/src/libelogind/sd-bus/test-bus-creds.c b/src/libelogind/sd-bus/test-bus-creds.c deleted file mode 100644 index edd5033db..000000000 --- a/src/libelogind/sd-bus/test-bus-creds.c +++ /dev/null @@ -1,45 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "sd-bus.h" -#include "bus-dump.h" -#include "bus-util.h" - -int main(int argc, char *argv[]) { - _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL; - int r; - - r = sd_bus_creds_new_from_pid(&creds, 0, _SD_BUS_CREDS_ALL); - assert_se(r >= 0); - - bus_creds_dump(creds, NULL, true); - - creds = sd_bus_creds_unref(creds); - - r = sd_bus_creds_new_from_pid(&creds, 1, _SD_BUS_CREDS_ALL); - if (r != -EACCES) { - assert_se(r >= 0); - putchar('\n'); - bus_creds_dump(creds, NULL, true); - } - - return 0; -} diff --git a/src/libelogind/sd-bus/test-bus-error.c b/src/libelogind/sd-bus/test-bus-error.c deleted file mode 100644 index 5753c04b0..000000000 --- a/src/libelogind/sd-bus/test-bus-error.c +++ /dev/null @@ -1,202 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "sd-bus.h" -#include "bus-error.h" -#include "bus-util.h" -#include "errno-list.h" -#include "bus-common-errors.h" - -static void test_error(void) { - _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL, second = SD_BUS_ERROR_NULL; - const sd_bus_error const_error = SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_FILE_EXISTS, "const error"); - const sd_bus_error temporarily_const_error = { - .name = SD_BUS_ERROR_ACCESS_DENIED, - .message = "oh! no", - ._need_free = -1 - }; - - assert_se(!sd_bus_error_is_set(&error)); - assert_se(sd_bus_error_set(&error, SD_BUS_ERROR_NOT_SUPPORTED, "xxx") == -EOPNOTSUPP); - assert_se(streq(error.name, SD_BUS_ERROR_NOT_SUPPORTED)); - assert_se(streq(error.message, "xxx")); - assert_se(sd_bus_error_has_name(&error, SD_BUS_ERROR_NOT_SUPPORTED)); - assert_se(sd_bus_error_get_errno(&error) == EOPNOTSUPP); - assert_se(sd_bus_error_is_set(&error)); - sd_bus_error_free(&error); - - assert_se(!sd_bus_error_is_set(&error)); - assert_se(sd_bus_error_setf(&error, SD_BUS_ERROR_FILE_NOT_FOUND, "yyy %i", -1) == -ENOENT); - assert_se(streq(error.name, SD_BUS_ERROR_FILE_NOT_FOUND)); - assert_se(streq(error.message, "yyy -1")); - assert_se(sd_bus_error_has_name(&error, SD_BUS_ERROR_FILE_NOT_FOUND)); - assert_se(sd_bus_error_get_errno(&error) == ENOENT); - assert_se(sd_bus_error_is_set(&error)); - - assert_se(!sd_bus_error_is_set(&second)); - assert_se(second._need_free == 0); - assert_se(error._need_free > 0); - assert_se(sd_bus_error_copy(&second, &error) == -ENOENT); - assert_se(second._need_free > 0); - assert_se(streq(error.name, second.name)); - assert_se(streq(error.message, second.message)); - assert_se(sd_bus_error_get_errno(&second) == ENOENT); - assert_se(sd_bus_error_has_name(&second, SD_BUS_ERROR_FILE_NOT_FOUND)); - assert_se(sd_bus_error_is_set(&second)); - - sd_bus_error_free(&error); - sd_bus_error_free(&second); - - assert_se(!sd_bus_error_is_set(&second)); - assert_se(const_error._need_free == 0); - assert_se(sd_bus_error_copy(&second, &const_error) == -EEXIST); - assert_se(second._need_free == 0); - assert_se(streq(const_error.name, second.name)); - assert_se(streq(const_error.message, second.message)); - assert_se(sd_bus_error_get_errno(&second) == EEXIST); - assert_se(sd_bus_error_has_name(&second, SD_BUS_ERROR_FILE_EXISTS)); - assert_se(sd_bus_error_is_set(&second)); - sd_bus_error_free(&second); - - assert_se(!sd_bus_error_is_set(&second)); - assert_se(temporarily_const_error._need_free < 0); - assert_se(sd_bus_error_copy(&second, &temporarily_const_error) == -EACCES); - assert_se(second._need_free > 0); - assert_se(streq(temporarily_const_error.name, second.name)); - assert_se(streq(temporarily_const_error.message, second.message)); - assert_se(sd_bus_error_get_errno(&second) == EACCES); - assert_se(sd_bus_error_has_name(&second, SD_BUS_ERROR_ACCESS_DENIED)); - assert_se(sd_bus_error_is_set(&second)); - - assert_se(!sd_bus_error_is_set(&error)); - assert_se(sd_bus_error_set_const(&error, "System.Error.EUCLEAN", "Hallo") == -EUCLEAN); - assert_se(streq(error.name, "System.Error.EUCLEAN")); - assert_se(streq(error.message, "Hallo")); - assert_se(sd_bus_error_has_name(&error, "System.Error.EUCLEAN")); - assert_se(sd_bus_error_get_errno(&error) == EUCLEAN); - assert_se(sd_bus_error_is_set(&error)); - sd_bus_error_free(&error); - - assert_se(!sd_bus_error_is_set(&error)); - assert_se(sd_bus_error_set_errno(&error, EBUSY) == -EBUSY); - assert_se(streq(error.name, "System.Error.EBUSY")); - assert_se(streq(error.message, strerror(EBUSY))); - assert_se(sd_bus_error_has_name(&error, "System.Error.EBUSY")); - assert_se(sd_bus_error_get_errno(&error) == EBUSY); - assert_se(sd_bus_error_is_set(&error)); - sd_bus_error_free(&error); - - assert_se(!sd_bus_error_is_set(&error)); - assert_se(sd_bus_error_set_errnof(&error, EIO, "Waldi %c", 'X') == -EIO); - assert_se(streq(error.name, SD_BUS_ERROR_IO_ERROR)); - assert_se(streq(error.message, "Waldi X")); - assert_se(sd_bus_error_has_name(&error, SD_BUS_ERROR_IO_ERROR)); - assert_se(sd_bus_error_get_errno(&error) == EIO); - assert_se(sd_bus_error_is_set(&error)); -} - -extern const sd_bus_error_map __start_BUS_ERROR_MAP[]; -extern const sd_bus_error_map __stop_BUS_ERROR_MAP[]; - -static void dump_mapping_table(void) { - const sd_bus_error_map *m; - - printf("----- errno mappings ------\n"); - m = __start_BUS_ERROR_MAP; - while (m < __stop_BUS_ERROR_MAP) { - - if (m->code == BUS_ERROR_MAP_END_MARKER) { - m = ALIGN8_PTR(m+1); - continue; - } - - printf("%s -> %i/%s\n", strna(m->name), m->code, strna(errno_to_name(m->code))); - m ++; - } - printf("---------------------------\n"); -} - -static void test_errno_mapping_standard(void) { - assert_se(sd_bus_error_set(NULL, "System.Error.EUCLEAN", NULL) == -EUCLEAN); - assert_se(sd_bus_error_set(NULL, "System.Error.EBUSY", NULL) == -EBUSY); - assert_se(sd_bus_error_set(NULL, "System.Error.EINVAL", NULL) == -EINVAL); - assert_se(sd_bus_error_set(NULL, "System.Error.WHATSIT", NULL) == -EIO); -} - -BUS_ERROR_MAP_ELF_REGISTER const sd_bus_error_map test_errors[] = { - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error", 5), - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-2", 52), - SD_BUS_ERROR_MAP_END -}; - -BUS_ERROR_MAP_ELF_REGISTER const sd_bus_error_map test_errors2[] = { - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-3", 33), - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-4", 44), - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-33", 333), - SD_BUS_ERROR_MAP_END -}; - -static const sd_bus_error_map test_errors3[] = { - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-88", 888), - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-99", 999), - SD_BUS_ERROR_MAP_END -}; - -static const sd_bus_error_map test_errors4[] = { - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-77", 777), - SD_BUS_ERROR_MAP("org.freedesktop.custom-dbus-error-78", 778), - SD_BUS_ERROR_MAP_END -}; - -static void test_errno_mapping_custom(void) { - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error", NULL) == -5); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-2", NULL) == -52); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-x", NULL) == -EIO); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-33", NULL) == -333); - - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-88", NULL) == -EIO); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-99", NULL) == -EIO); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-77", NULL) == -EIO); - - assert_se(sd_bus_error_add_map(test_errors3) > 0); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-88", NULL) == -888); - assert_se(sd_bus_error_add_map(test_errors4) > 0); - assert_se(sd_bus_error_add_map(test_errors4) == 0); - assert_se(sd_bus_error_add_map(test_errors3) == 0); - - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-99", NULL) == -999); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-77", NULL) == -777); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-78", NULL) == -778); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-2", NULL) == -52); - assert_se(sd_bus_error_set(NULL, "org.freedesktop.custom-dbus-error-y", NULL) == -EIO); - - assert_se(sd_bus_error_set(NULL, BUS_ERROR_NO_SUCH_UNIT, NULL) == -ENOENT); -} - -int main(int argc, char *argv[]) { - dump_mapping_table(); - - test_error(); - test_errno_mapping_standard(); - test_errno_mapping_custom(); - - return 0; -} diff --git a/src/libelogind/sd-bus/test-bus-introspect.c b/src/libelogind/sd-bus/test-bus-introspect.c deleted file mode 100644 index b2caa0287..000000000 --- a/src/libelogind/sd-bus/test-bus-introspect.c +++ /dev/null @@ -1,65 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "log.h" -#include "bus-introspect.h" - -static int prop_get(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error) { - return -EINVAL; -} - -static int prop_set(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error) { - return -EINVAL; -} - -static const sd_bus_vtable vtable[] = { - SD_BUS_VTABLE_START(0), - SD_BUS_METHOD("Hello", "ssas", "a(uu)", NULL, 0), - SD_BUS_METHOD("DeprecatedHello", "", "", NULL, SD_BUS_VTABLE_DEPRECATED), - SD_BUS_METHOD("DeprecatedHelloNoReply", "", "", NULL, SD_BUS_VTABLE_DEPRECATED|SD_BUS_VTABLE_METHOD_NO_REPLY), - SD_BUS_SIGNAL("Wowza", "sss", 0), - SD_BUS_SIGNAL("DeprecatedWowza", "ut", SD_BUS_VTABLE_DEPRECATED), - SD_BUS_WRITABLE_PROPERTY("AProperty", "s", prop_get, prop_set, 0, 0), - SD_BUS_PROPERTY("AReadOnlyDeprecatedProperty", "(ut)", prop_get, 0, SD_BUS_VTABLE_DEPRECATED), - SD_BUS_PROPERTY("ChangingProperty", "t", prop_get, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE), - SD_BUS_PROPERTY("Invalidating", "t", prop_get, 0, SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION), - SD_BUS_PROPERTY("Constant", "t", prop_get, 0, SD_BUS_VTABLE_PROPERTY_CONST), - SD_BUS_VTABLE_END -}; - -int main(int argc, char *argv[]) { - struct introspect intro; - - log_set_max_level(LOG_DEBUG); - - assert_se(introspect_begin(&intro, false) >= 0); - - fprintf(intro.f, " \n"); - assert_se(introspect_write_interface(&intro, vtable) >= 0); - fputs(" \n", intro.f); - - fflush(intro.f); - fputs(intro.introspection, stdout); - - introspect_free(&intro); - - return 0; -} diff --git a/src/libelogind/sd-bus/test-bus-kernel-benchmark.c b/src/libelogind/sd-bus/test-bus-kernel-benchmark.c deleted file mode 100644 index f480b655d..000000000 --- a/src/libelogind/sd-bus/test-bus-kernel-benchmark.c +++ /dev/null @@ -1,308 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#include "util.h" -#include "time-util.h" - -#include "sd-bus.h" -#include "bus-kernel.h" -#include "bus-internal.h" -#include "bus-util.h" - -#define MAX_SIZE (2*1024*1024) - -static usec_t arg_loop_usec = 100 * USEC_PER_MSEC; - -static void server(sd_bus *b, size_t *result) { - int r; - - for (;;) { - _cleanup_bus_message_unref_ sd_bus_message *m = NULL; - - r = sd_bus_process(b, &m); - assert_se(r >= 0); - - if (r == 0) - assert_se(sd_bus_wait(b, USEC_INFINITY) >= 0); - if (!m) - continue; - - if (sd_bus_message_is_method_call(m, "benchmark.server", "Ping")) - assert_se(sd_bus_reply_method_return(m, NULL) >= 0); - else if (sd_bus_message_is_method_call(m, "benchmark.server", "Work")) { - const void *p; - size_t sz; - - /* Make sure the mmap is mapped */ - assert_se(sd_bus_message_read_array(m, 'y', &p, &sz) > 0); - - r = sd_bus_reply_method_return(m, NULL); - assert_se(r >= 0); - } else if (sd_bus_message_is_method_call(m, "benchmark.server", "Exit")) { - uint64_t res; - assert_se(sd_bus_message_read(m, "t", &res) > 0); - - *result = res; - return; - - } else - assert_not_reached("Unknown method"); - } -} - -static void transaction(sd_bus *b, size_t sz, const char *server_name) { - _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL; - uint8_t *p; - - assert_se(sd_bus_message_new_method_call(b, &m, server_name, "/", "benchmark.server", "Work") >= 0); - assert_se(sd_bus_message_append_array_space(m, 'y', sz, (void**) &p) >= 0); - - memset(p, 0x80, sz); - - assert_se(sd_bus_call(b, m, 0, NULL, &reply) >= 0); -} - -static void client_bisect(const char *address, const char *server_name) { - _cleanup_bus_message_unref_ sd_bus_message *x = NULL; - size_t lsize, rsize, csize; - sd_bus *b; - int r; - - r = sd_bus_new(&b); - assert_se(r >= 0); - - r = sd_bus_set_address(b, address); - assert_se(r >= 0); - - r = sd_bus_start(b); - assert_se(r >= 0); - - r = sd_bus_call_method(b, server_name, "/", "benchmark.server", "Ping", NULL, NULL, NULL); - assert_se(r >= 0); - - lsize = 1; - rsize = MAX_SIZE; - - printf("SIZE\tCOPY\tMEMFD\n"); - - for (;;) { - usec_t t; - unsigned n_copying, n_memfd; - - csize = (lsize + rsize) / 2; - - if (csize <= lsize) - break; - - if (csize <= 0) - break; - - printf("%zu\t", csize); - - b->use_memfd = 0; - - t = now(CLOCK_MONOTONIC); - for (n_copying = 0;; n_copying++) { - transaction(b, csize, server_name); - if (now(CLOCK_MONOTONIC) >= t + arg_loop_usec) - break; - } - printf("%u\t", (unsigned) ((n_copying * USEC_PER_SEC) / arg_loop_usec)); - - b->use_memfd = -1; - - t = now(CLOCK_MONOTONIC); - for (n_memfd = 0;; n_memfd++) { - transaction(b, csize, server_name); - if (now(CLOCK_MONOTONIC) >= t + arg_loop_usec) - break; - } - printf("%u\n", (unsigned) ((n_memfd * USEC_PER_SEC) / arg_loop_usec)); - - if (n_copying == n_memfd) - break; - - if (n_copying > n_memfd) - lsize = csize; - else - rsize = csize; - } - - b->use_memfd = 1; - assert_se(sd_bus_message_new_method_call(b, &x, server_name, "/", "benchmark.server", "Exit") >= 0); - assert_se(sd_bus_message_append(x, "t", csize) >= 0); - assert_se(sd_bus_send(b, x, NULL) >= 0); - - sd_bus_unref(b); -} - -static void client_chart(const char *address, const char *server_name) { - _cleanup_bus_message_unref_ sd_bus_message *x = NULL; - size_t csize; - sd_bus *b; - int r; - - r = sd_bus_new(&b); - assert_se(r >= 0); - - r = sd_bus_set_address(b, address); - assert_se(r >= 0); - - r = sd_bus_start(b); - assert_se(r >= 0); - - assert_se(sd_bus_call_method(b, server_name, "/", "benchmark.server", "Ping", NULL, NULL, NULL) >= 0); - - printf("SIZE\tCOPY\tMEMFD\n"); - - for (csize = 1; csize <= MAX_SIZE; csize *= 2) { - usec_t t; - unsigned n_copying, n_memfd; - - printf("%zu\t", csize); - - b->use_memfd = 0; - - t = now(CLOCK_MONOTONIC); - for (n_copying = 0;; n_copying++) { - transaction(b, csize, server_name); - if (now(CLOCK_MONOTONIC) >= t + arg_loop_usec) - break; - } - - printf("%u\t", (unsigned) ((n_copying * USEC_PER_SEC) / arg_loop_usec)); - - b->use_memfd = -1; - - t = now(CLOCK_MONOTONIC); - for (n_memfd = 0;; n_memfd++) { - transaction(b, csize, server_name); - if (now(CLOCK_MONOTONIC) >= t + arg_loop_usec) - break; - } - - printf("%u\n", (unsigned) ((n_memfd * USEC_PER_SEC) / arg_loop_usec)); - } - - b->use_memfd = 1; - assert_se(sd_bus_message_new_method_call(b, &x, server_name, "/", "benchmark.server", "Exit") >= 0); - assert_se(sd_bus_message_append(x, "t", csize) >= 0); - assert_se(sd_bus_send(b, x, NULL) >= 0); - - sd_bus_unref(b); -} - -int main(int argc, char *argv[]) { - enum { - MODE_BISECT, - MODE_CHART, - } mode = MODE_BISECT; - int i; - _cleanup_free_ char *name = NULL, *bus_name = NULL, *address = NULL, *server_name = NULL; - _cleanup_close_ int bus_ref = -1; - const char *unique; - cpu_set_t cpuset; - size_t result; - sd_bus *b; - pid_t pid; - int r; - - for (i = 1; i < argc; i++) { - if (streq(argv[i], "chart")) { - mode = MODE_CHART; - continue; - } - - assert_se(parse_sec(argv[i], &arg_loop_usec) >= 0); - } - - assert_se(arg_loop_usec > 0); - - assert_se(asprintf(&name, "deine-mutter-%u", (unsigned) getpid()) >= 0); - - bus_ref = bus_kernel_create_bus(name, false, &bus_name); - if (bus_ref == -ENOENT) - exit(EXIT_TEST_SKIP); - - assert_se(bus_ref >= 0); - - address = strappend("kernel:path=", bus_name); - assert_se(address); - - r = sd_bus_new(&b); - assert_se(r >= 0); - - r = sd_bus_set_address(b, address); - assert_se(r >= 0); - - r = sd_bus_start(b); - assert_se(r >= 0); - - r = sd_bus_get_unique_name(b, &unique); - assert_se(r >= 0); - - server_name = strdup(unique); - assert_se(server_name); - - sync(); - setpriority(PRIO_PROCESS, 0, -19); - - pid = fork(); - assert_se(pid >= 0); - - if (pid == 0) { - CPU_ZERO(&cpuset); - CPU_SET(0, &cpuset); - pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); - - safe_close(bus_ref); - sd_bus_unref(b); - - switch (mode) { - case MODE_BISECT: - client_bisect(address, server_name); - break; - - case MODE_CHART: - client_chart(address, server_name); - break; - } - - _exit(0); - } - - CPU_ZERO(&cpuset); - CPU_SET(1, &cpuset); - pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); - - server(b, &result); - - if (mode == MODE_BISECT) - printf("Copying/memfd are equally fast at %zu bytes\n", result); - - assert_se(waitpid(pid, NULL, 0) == pid); - - sd_bus_unref(b); - - return 0; -} diff --git a/src/libelogind/sd-bus/test-bus-server.c b/src/libelogind/sd-bus/test-bus-server.c deleted file mode 100644 index 080d8eddb..000000000 --- a/src/libelogind/sd-bus/test-bus-server.c +++ /dev/null @@ -1,218 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "log.h" -#include "util.h" -#include "macro.h" - -#include "sd-bus.h" -#include "bus-internal.h" -#include "bus-util.h" - -struct context { - int fds[2]; - - bool client_negotiate_unix_fds; - bool server_negotiate_unix_fds; - - bool client_anonymous_auth; - bool server_anonymous_auth; -}; - -static void *server(void *p) { - struct context *c = p; - sd_bus *bus = NULL; - sd_id128_t id; - bool quit = false; - int r; - - assert_se(sd_id128_randomize(&id) >= 0); - - assert_se(sd_bus_new(&bus) >= 0); - assert_se(sd_bus_set_fd(bus, c->fds[0], c->fds[0]) >= 0); - assert_se(sd_bus_set_server(bus, 1, id) >= 0); - assert_se(sd_bus_set_anonymous(bus, c->server_anonymous_auth) >= 0); - assert_se(sd_bus_negotiate_fds(bus, c->server_negotiate_unix_fds) >= 0); - assert_se(sd_bus_start(bus) >= 0); - - while (!quit) { - _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL; - - r = sd_bus_process(bus, &m); - if (r < 0) { - log_error_errno(r, "Failed to process requests: %m"); - goto fail; - } - - if (r == 0) { - r = sd_bus_wait(bus, (uint64_t) -1); - if (r < 0) { - log_error_errno(r, "Failed to wait: %m"); - goto fail; - } - - continue; - } - - if (!m) - continue; - - log_info("Got message! member=%s", strna(sd_bus_message_get_member(m))); - - if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.test", "Exit")) { - - assert_se((sd_bus_can_send(bus, 'h') >= 1) == (c->server_negotiate_unix_fds && c->client_negotiate_unix_fds)); - - r = sd_bus_message_new_method_return(m, &reply); - if (r < 0) { - log_error_errno(r, "Failed to allocate return: %m"); - goto fail; - } - - quit = true; - - } else if (sd_bus_message_is_method_call(m, NULL, NULL)) { - r = sd_bus_message_new_method_error( - m, - &reply, - &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_UNKNOWN_METHOD, "Unknown method.")); - if (r < 0) { - log_error_errno(r, "Failed to allocate return: %m"); - goto fail; - } - } - - if (reply) { - r = sd_bus_send(bus, reply, NULL); - if (r < 0) { - log_error_errno(r, "Failed to send reply: %m"); - goto fail; - } - } - } - - r = 0; - -fail: - if (bus) { - sd_bus_flush(bus); - sd_bus_unref(bus); - } - - return INT_TO_PTR(r); -} - -static int client(struct context *c) { - _cleanup_bus_message_unref_ sd_bus_message *m = NULL, *reply = NULL; - _cleanup_bus_unref_ sd_bus *bus = NULL; - sd_bus_error error = SD_BUS_ERROR_NULL; - int r; - - assert_se(sd_bus_new(&bus) >= 0); - assert_se(sd_bus_set_fd(bus, c->fds[1], c->fds[1]) >= 0); - assert_se(sd_bus_negotiate_fds(bus, c->client_negotiate_unix_fds) >= 0); - assert_se(sd_bus_set_anonymous(bus, c->client_anonymous_auth) >= 0); - assert_se(sd_bus_start(bus) >= 0); - - r = sd_bus_message_new_method_call( - bus, - &m, - "org.freedesktop.systemd.test", - "/", - "org.freedesktop.systemd.test", - "Exit"); - if (r < 0) - return log_error_errno(r, "Failed to allocate method call: %m"); - - r = sd_bus_call(bus, m, 0, &error, &reply); - if (r < 0) { - log_error("Failed to issue method call: %s", bus_error_message(&error, -r)); - return r; - } - - return 0; -} - -static int test_one(bool client_negotiate_unix_fds, bool server_negotiate_unix_fds, - bool client_anonymous_auth, bool server_anonymous_auth) { - - struct context c; - pthread_t s; - void *p; - int r, q; - - zero(c); - - assert_se(socketpair(AF_UNIX, SOCK_STREAM, 0, c.fds) >= 0); - - c.client_negotiate_unix_fds = client_negotiate_unix_fds; - c.server_negotiate_unix_fds = server_negotiate_unix_fds; - c.client_anonymous_auth = client_anonymous_auth; - c.server_anonymous_auth = server_anonymous_auth; - - r = pthread_create(&s, NULL, server, &c); - if (r != 0) - return -r; - - r = client(&c); - - q = pthread_join(s, &p); - if (q != 0) - return -q; - - if (r < 0) - return r; - - if (PTR_TO_INT(p) < 0) - return PTR_TO_INT(p); - - return 0; -} - -int main(int argc, char *argv[]) { - int r; - - r = test_one(true, true, false, false); - assert_se(r >= 0); - - r = test_one(true, false, false, false); - assert_se(r >= 0); - - r = test_one(false, true, false, false); - assert_se(r >= 0); - - r = test_one(false, false, false, false); - assert_se(r >= 0); - - r = test_one(true, true, true, true); - assert_se(r >= 0); - - r = test_one(true, true, false, true); - assert_se(r >= 0); - - r = test_one(true, true, true, false); - assert_se(r == -EPERM); - - return EXIT_SUCCESS; -} diff --git a/src/libelogind/sd-bus/test-bus-zero-copy.c b/src/libelogind/sd-bus/test-bus-zero-copy.c deleted file mode 100644 index 2d062fc9b..000000000 --- a/src/libelogind/sd-bus/test-bus-zero-copy.c +++ /dev/null @@ -1,209 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#include "util.h" -#include "log.h" -#include "memfd-util.h" - -#include "sd-bus.h" -#include "bus-message.h" -#include "bus-kernel.h" -#include "bus-dump.h" - -#define FIRST_ARRAY 17 -#define SECOND_ARRAY 33 - -#define STRING_SIZE 123 - -int main(int argc, char *argv[]) { - _cleanup_free_ char *name = NULL, *bus_name = NULL, *address = NULL; - const char *unique; - uint8_t *p; - sd_bus *a, *b; - int r, bus_ref; - sd_bus_message *m; - int f; - uint64_t sz; - uint32_t u32; - size_t i, l; - char *s; - _cleanup_close_ int sfd = -1; - - log_set_max_level(LOG_DEBUG); - - assert_se(asprintf(&name, "deine-mutter-%u", (unsigned) getpid()) >= 0); - - bus_ref = bus_kernel_create_bus(name, false, &bus_name); - if (bus_ref == -ENOENT) - return EXIT_TEST_SKIP; - - assert_se(bus_ref >= 0); - - address = strappend("kernel:path=", bus_name); - assert_se(address); - - r = sd_bus_new(&a); - assert_se(r >= 0); - - r = sd_bus_new(&b); - assert_se(r >= 0); - - r = sd_bus_set_address(a, address); - assert_se(r >= 0); - - r = sd_bus_set_address(b, address); - assert_se(r >= 0); - - r = sd_bus_start(a); - assert_se(r >= 0); - - r = sd_bus_start(b); - assert_se(r >= 0); - - r = sd_bus_get_unique_name(a, &unique); - assert_se(r >= 0); - - r = sd_bus_message_new_method_call(b, &m, unique, "/a/path", "an.inter.face", "AMethod"); - assert_se(r >= 0); - - r = sd_bus_message_open_container(m, 'r', "aysay"); - assert_se(r >= 0); - - r = sd_bus_message_append_array_space(m, 'y', FIRST_ARRAY, (void**) &p); - assert_se(r >= 0); - - p[0] = '<'; - memset(p+1, 'L', FIRST_ARRAY-2); - p[FIRST_ARRAY-1] = '>'; - - f = memfd_new_and_map(NULL, STRING_SIZE, (void**) &s); - assert_se(f >= 0); - - s[0] = '<'; - for (i = 1; i < STRING_SIZE-2; i++) - s[i] = '0' + (i % 10); - s[STRING_SIZE-2] = '>'; - s[STRING_SIZE-1] = 0; - munmap(s, STRING_SIZE); - - r = memfd_get_size(f, &sz); - assert_se(r >= 0); - assert_se(sz == STRING_SIZE); - - r = sd_bus_message_append_string_memfd(m, f, 0, (uint64_t) -1); - assert_se(r >= 0); - - close(f); - - f = memfd_new_and_map(NULL, SECOND_ARRAY, (void**) &p); - assert_se(f >= 0); - - p[0] = '<'; - memset(p+1, 'P', SECOND_ARRAY-2); - p[SECOND_ARRAY-1] = '>'; - munmap(p, SECOND_ARRAY); - - r = memfd_get_size(f, &sz); - assert_se(r >= 0); - assert_se(sz == SECOND_ARRAY); - - r = sd_bus_message_append_array_memfd(m, 'y', f, 0, (uint64_t) -1); - assert_se(r >= 0); - - close(f); - - r = sd_bus_message_close_container(m); - assert_se(r >= 0); - - r = sd_bus_message_append(m, "u", 4711); - assert_se(r >= 0); - - assert_se((sfd = memfd_new_and_map(NULL, 6, (void**) &p)) >= 0); - memcpy(p, "abcd\0", 6); - munmap(p, 6); - assert_se(sd_bus_message_append_string_memfd(m, sfd, 1, 4) >= 0); - - r = bus_message_seal(m, 55, 99*USEC_PER_SEC); - assert_se(r >= 0); - - bus_message_dump(m, stdout, BUS_MESSAGE_DUMP_WITH_HEADER); - - r = sd_bus_send(b, m, NULL); - assert_se(r >= 0); - - sd_bus_message_unref(m); - - r = sd_bus_process(a, &m); - assert_se(r > 0); - - bus_message_dump(m, stdout, BUS_MESSAGE_DUMP_WITH_HEADER); - sd_bus_message_rewind(m, true); - - r = sd_bus_message_enter_container(m, 'r', "aysay"); - assert_se(r > 0); - - r = sd_bus_message_read_array(m, 'y', (const void**) &p, &l); - assert_se(r > 0); - assert_se(l == FIRST_ARRAY); - - assert_se(p[0] == '<'); - for (i = 1; i < l-1; i++) - assert_se(p[i] == 'L'); - assert_se(p[l-1] == '>'); - - r = sd_bus_message_read(m, "s", &s); - assert_se(r > 0); - - assert_se(s[0] == '<'); - for (i = 1; i < STRING_SIZE-2; i++) - assert_se(s[i] == (char) ('0' + (i % 10))); - assert_se(s[STRING_SIZE-2] == '>'); - assert_se(s[STRING_SIZE-1] == 0); - - r = sd_bus_message_read_array(m, 'y', (const void**) &p, &l); - assert_se(r > 0); - assert_se(l == SECOND_ARRAY); - - assert_se(p[0] == '<'); - for (i = 1; i < l-1; i++) - assert_se(p[i] == 'P'); - assert_se(p[l-1] == '>'); - - r = sd_bus_message_exit_container(m); - assert_se(r > 0); - - r = sd_bus_message_read(m, "u", &u32); - assert_se(r > 0); - assert_se(u32 == 4711); - - r = sd_bus_message_read(m, "s", &s); - assert_se(r > 0); - assert_se(streq_ptr(s, "bcd")); - - sd_bus_message_unref(m); - - sd_bus_unref(a); - sd_bus_unref(b); - - return 0; -} diff --git a/src/libelogind/sd-event/event-util.h b/src/libelogind/sd-event/event-util.h deleted file mode 100644 index e7cad9be4..000000000 --- a/src/libelogind/sd-event/event-util.h +++ /dev/null @@ -1,31 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "util.h" -#include "sd-event.h" - -DEFINE_TRIVIAL_CLEANUP_FUNC(sd_event*, sd_event_unref); -DEFINE_TRIVIAL_CLEANUP_FUNC(sd_event_source*, sd_event_source_unref); - -#define _cleanup_event_unref_ _cleanup_(sd_event_unrefp) -#define _cleanup_event_source_unref_ _cleanup_(sd_event_source_unrefp) diff --git a/src/libelogind/sd-resolve/resolve-util.h b/src/libelogind/sd-resolve/resolve-util.h deleted file mode 100644 index 019cdaffe..000000000 --- a/src/libelogind/sd-resolve/resolve-util.h +++ /dev/null @@ -1,31 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Daniel Buch - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "util.h" -#include "sd-resolve.h" - -DEFINE_TRIVIAL_CLEANUP_FUNC(sd_resolve*, sd_resolve_unref); -DEFINE_TRIVIAL_CLEANUP_FUNC(sd_resolve_query*, sd_resolve_query_unref); - -#define _cleanup_resolve_unref_ _cleanup_(sd_resolve_unrefp) -#define _cleanup_resolve_query_unref_ _cleanup_(sd_resolve_query_unrefp) diff --git a/src/libelogind/sd-resolve/sd-resolve.c b/src/libelogind/sd-resolve/sd-resolve.c deleted file mode 100644 index b0dc82259..000000000 --- a/src/libelogind/sd-resolve/sd-resolve.c +++ /dev/null @@ -1,1426 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2005-2008 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "util.h" -#include "list.h" -#include "socket-util.h" -#include "missing.h" -#include "resolve-util.h" -#include "sd-resolve.h" - -#define WORKERS_MIN 1U -#define WORKERS_MAX 16U -#define QUERIES_MAX 256U -#define BUFSIZE 10240U - -typedef enum { - REQUEST_ADDRINFO, - RESPONSE_ADDRINFO, - REQUEST_NAMEINFO, - RESPONSE_NAMEINFO, - REQUEST_RES_QUERY, - REQUEST_RES_SEARCH, - RESPONSE_RES, - REQUEST_TERMINATE, - RESPONSE_DIED -} QueryType; - -enum { - REQUEST_RECV_FD, - REQUEST_SEND_FD, - RESPONSE_RECV_FD, - RESPONSE_SEND_FD, - _FD_MAX -}; - -struct sd_resolve { - unsigned n_ref; - - bool dead:1; - pid_t original_pid; - - int fds[_FD_MAX]; - - pthread_t workers[WORKERS_MAX]; - unsigned n_valid_workers; - - unsigned current_id; - sd_resolve_query* query_array[QUERIES_MAX]; - unsigned n_queries, n_done, n_outstanding; - - sd_event_source *event_source; - sd_event *event; - - sd_resolve_query *current; - - sd_resolve **default_resolve_ptr; - pid_t tid; - - LIST_HEAD(sd_resolve_query, queries); -}; - -struct sd_resolve_query { - unsigned n_ref; - - sd_resolve *resolve; - - QueryType type:4; - bool done:1; - bool floating:1; - unsigned id; - - int ret; - int _errno; - int _h_errno; - struct addrinfo *addrinfo; - char *serv, *host; - unsigned char *answer; - - union { - sd_resolve_getaddrinfo_handler_t getaddrinfo_handler; - sd_resolve_getnameinfo_handler_t getnameinfo_handler; - sd_resolve_res_handler_t res_handler; - }; - - void *userdata; - - LIST_FIELDS(sd_resolve_query, queries); -}; - -typedef struct RHeader { - QueryType type; - unsigned id; - size_t length; -} RHeader; - -typedef struct AddrInfoRequest { - struct RHeader header; - bool hints_valid; - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - size_t node_len, service_len; -} AddrInfoRequest; - -typedef struct AddrInfoResponse { - struct RHeader header; - int ret; - int _errno; - int _h_errno; - /* followed by addrinfo_serialization[] */ -} AddrInfoResponse; - -typedef struct AddrInfoSerialization { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - size_t ai_addrlen; - size_t canonname_len; - /* Followed by ai_addr amd ai_canonname with variable lengths */ -} AddrInfoSerialization; - -typedef struct NameInfoRequest { - struct RHeader header; - int flags; - socklen_t sockaddr_len; - bool gethost:1, getserv:1; -} NameInfoRequest; - -typedef struct NameInfoResponse { - struct RHeader header; - size_t hostlen, servlen; - int ret; - int _errno; - int _h_errno; -} NameInfoResponse; - -typedef struct ResRequest { - struct RHeader header; - int class; - int type; - size_t dname_len; -} ResRequest; - -typedef struct ResResponse { - struct RHeader header; - int ret; - int _errno; - int _h_errno; -} ResResponse; - -typedef union Packet { - RHeader rheader; - AddrInfoRequest addrinfo_request; - AddrInfoResponse addrinfo_response; - NameInfoRequest nameinfo_request; - NameInfoResponse nameinfo_response; - ResRequest res_request; - ResResponse res_response; -} Packet; - -static int getaddrinfo_done(sd_resolve_query* q); -static int getnameinfo_done(sd_resolve_query *q); -static int res_query_done(sd_resolve_query* q); - -static void resolve_query_disconnect(sd_resolve_query *q); - -#define RESOLVE_DONT_DESTROY(resolve) \ - _cleanup_resolve_unref_ _unused_ sd_resolve *_dont_destroy_##resolve = sd_resolve_ref(resolve) - -static int send_died(int out_fd) { - - RHeader rh = { - .type = RESPONSE_DIED, - .length = sizeof(RHeader), - }; - - assert(out_fd >= 0); - - if (send(out_fd, &rh, rh.length, MSG_NOSIGNAL) < 0) - return -errno; - - return 0; -} - -static void *serialize_addrinfo(void *p, const struct addrinfo *ai, size_t *length, size_t maxlength) { - AddrInfoSerialization s; - size_t cnl, l; - - assert(p); - assert(ai); - assert(length); - assert(*length <= maxlength); - - cnl = ai->ai_canonname ? strlen(ai->ai_canonname)+1 : 0; - l = sizeof(AddrInfoSerialization) + ai->ai_addrlen + cnl; - - if (*length + l > maxlength) - return NULL; - - s.ai_flags = ai->ai_flags; - s.ai_family = ai->ai_family; - s.ai_socktype = ai->ai_socktype; - s.ai_protocol = ai->ai_protocol; - s.ai_addrlen = ai->ai_addrlen; - s.canonname_len = cnl; - - memcpy((uint8_t*) p, &s, sizeof(AddrInfoSerialization)); - memcpy((uint8_t*) p + sizeof(AddrInfoSerialization), ai->ai_addr, ai->ai_addrlen); - - if (ai->ai_canonname) - memcpy((char*) p + sizeof(AddrInfoSerialization) + ai->ai_addrlen, ai->ai_canonname, cnl); - - *length += l; - return (uint8_t*) p + l; -} - -static int send_addrinfo_reply( - int out_fd, - unsigned id, - int ret, - struct addrinfo *ai, - int _errno, - int _h_errno) { - - AddrInfoResponse resp = { - .header.type = RESPONSE_ADDRINFO, - .header.id = id, - .header.length = sizeof(AddrInfoResponse), - .ret = ret, - ._errno = _errno, - ._h_errno = _h_errno, - }; - - struct msghdr mh = {}; - struct iovec iov[2]; - union { - AddrInfoSerialization ais; - uint8_t space[BUFSIZE]; - } buffer; - - assert(out_fd >= 0); - - if (ret == 0 && ai) { - void *p = &buffer; - struct addrinfo *k; - - for (k = ai; k; k = k->ai_next) { - p = serialize_addrinfo(p, k, &resp.header.length, (uint8_t*) &buffer + BUFSIZE - (uint8_t*) p); - if (!p) { - freeaddrinfo(ai); - return -ENOBUFS; - } - } - } - - if (ai) - freeaddrinfo(ai); - - iov[0] = (struct iovec) { .iov_base = &resp, .iov_len = sizeof(AddrInfoResponse) }; - iov[1] = (struct iovec) { .iov_base = &buffer, .iov_len = resp.header.length - sizeof(AddrInfoResponse) }; - - mh.msg_iov = iov; - mh.msg_iovlen = ELEMENTSOF(iov); - - if (sendmsg(out_fd, &mh, MSG_NOSIGNAL) < 0) - return -errno; - - return 0; -} - -static int send_nameinfo_reply( - int out_fd, - unsigned id, - int ret, - const char *host, - const char *serv, - int _errno, - int _h_errno) { - - NameInfoResponse resp = { - .header.type = RESPONSE_NAMEINFO, - .header.id = id, - .ret = ret, - ._errno = _errno, - ._h_errno = _h_errno, - }; - - struct msghdr mh = {}; - struct iovec iov[3]; - size_t hl, sl; - - assert(out_fd >= 0); - - sl = serv ? strlen(serv)+1 : 0; - hl = host ? strlen(host)+1 : 0; - - resp.header.length = sizeof(NameInfoResponse) + hl + sl; - resp.hostlen = hl; - resp.servlen = sl; - - iov[0] = (struct iovec) { .iov_base = &resp, .iov_len = sizeof(NameInfoResponse) }; - iov[1] = (struct iovec) { .iov_base = (void*) host, .iov_len = hl }; - iov[2] = (struct iovec) { .iov_base = (void*) serv, .iov_len = sl }; - - mh.msg_iov = iov; - mh.msg_iovlen = ELEMENTSOF(iov); - - if (sendmsg(out_fd, &mh, MSG_NOSIGNAL) < 0) - return -errno; - - return 0; -} - -static int send_res_reply(int out_fd, unsigned id, const unsigned char *answer, int ret, int _errno, int _h_errno) { - - ResResponse resp = { - .header.type = RESPONSE_RES, - .header.id = id, - .ret = ret, - ._errno = _errno, - ._h_errno = _h_errno, - }; - - struct msghdr mh = {}; - struct iovec iov[2]; - size_t l; - - assert(out_fd >= 0); - - l = ret > 0 ? (size_t) ret : 0; - - resp.header.length = sizeof(ResResponse) + l; - - iov[0] = (struct iovec) { .iov_base = &resp, .iov_len = sizeof(ResResponse) }; - iov[1] = (struct iovec) { .iov_base = (void*) answer, .iov_len = l }; - - mh.msg_iov = iov; - mh.msg_iovlen = ELEMENTSOF(iov); - - if (sendmsg(out_fd, &mh, MSG_NOSIGNAL) < 0) - return -errno; - - return 0; -} - -static int handle_request(int out_fd, const Packet *packet, size_t length) { - const RHeader *req; - - assert(out_fd >= 0); - assert(packet); - - req = &packet->rheader; - - assert(length >= sizeof(RHeader)); - assert(length == req->length); - - switch (req->type) { - - case REQUEST_ADDRINFO: { - const AddrInfoRequest *ai_req = &packet->addrinfo_request; - struct addrinfo hints = {}, *result = NULL; - const char *node, *service; - int ret; - - assert(length >= sizeof(AddrInfoRequest)); - assert(length == sizeof(AddrInfoRequest) + ai_req->node_len + ai_req->service_len); - - hints.ai_flags = ai_req->ai_flags; - hints.ai_family = ai_req->ai_family; - hints.ai_socktype = ai_req->ai_socktype; - hints.ai_protocol = ai_req->ai_protocol; - - node = ai_req->node_len ? (const char*) ai_req + sizeof(AddrInfoRequest) : NULL; - service = ai_req->service_len ? (const char*) ai_req + sizeof(AddrInfoRequest) + ai_req->node_len : NULL; - - ret = getaddrinfo( - node, service, - ai_req->hints_valid ? &hints : NULL, - &result); - - /* send_addrinfo_reply() frees result */ - return send_addrinfo_reply(out_fd, req->id, ret, result, errno, h_errno); - } - - case REQUEST_NAMEINFO: { - const NameInfoRequest *ni_req = &packet->nameinfo_request; - char hostbuf[NI_MAXHOST], servbuf[NI_MAXSERV]; - union sockaddr_union sa; - int ret; - - assert(length >= sizeof(NameInfoRequest)); - assert(length == sizeof(NameInfoRequest) + ni_req->sockaddr_len); - assert(sizeof(sa) >= ni_req->sockaddr_len); - - memcpy(&sa, (const uint8_t *) ni_req + sizeof(NameInfoRequest), ni_req->sockaddr_len); - - ret = getnameinfo(&sa.sa, ni_req->sockaddr_len, - ni_req->gethost ? hostbuf : NULL, ni_req->gethost ? sizeof(hostbuf) : 0, - ni_req->getserv ? servbuf : NULL, ni_req->getserv ? sizeof(servbuf) : 0, - ni_req->flags); - - return send_nameinfo_reply(out_fd, req->id, ret, - ret == 0 && ni_req->gethost ? hostbuf : NULL, - ret == 0 && ni_req->getserv ? servbuf : NULL, - errno, h_errno); - } - - case REQUEST_RES_QUERY: - case REQUEST_RES_SEARCH: { - const ResRequest *res_req = &packet->res_request; - union { - HEADER header; - uint8_t space[BUFSIZE]; - } answer; - const char *dname; - int ret; - - assert(length >= sizeof(ResRequest)); - assert(length == sizeof(ResRequest) + res_req->dname_len); - - dname = (const char *) res_req + sizeof(ResRequest); - - if (req->type == REQUEST_RES_QUERY) - ret = res_query(dname, res_req->class, res_req->type, (unsigned char *) &answer, BUFSIZE); - else - ret = res_search(dname, res_req->class, res_req->type, (unsigned char *) &answer, BUFSIZE); - - return send_res_reply(out_fd, req->id, (unsigned char *) &answer, ret, errno, h_errno); - } - - case REQUEST_TERMINATE: - /* Quit */ - return -ECONNRESET; - - default: - assert_not_reached("Unknown request"); - } - - return 0; -} - -static void* thread_worker(void *p) { - sd_resolve *resolve = p; - sigset_t fullset; - - /* No signals in this thread please */ - assert_se(sigfillset(&fullset) == 0); - assert_se(pthread_sigmask(SIG_BLOCK, &fullset, NULL) == 0); - - /* Assign a pretty name to this thread */ - prctl(PR_SET_NAME, (unsigned long) "sd-resolve"); - - while (!resolve->dead) { - union { - Packet packet; - uint8_t space[BUFSIZE]; - } buf; - ssize_t length; - - length = recv(resolve->fds[REQUEST_RECV_FD], &buf, sizeof(buf), 0); - if (length < 0) { - if (errno == EINTR) - continue; - - break; - } - if (length == 0) - break; - - if (resolve->dead) - break; - - if (handle_request(resolve->fds[RESPONSE_SEND_FD], &buf.packet, (size_t) length) < 0) - break; - } - - send_died(resolve->fds[RESPONSE_SEND_FD]); - - return NULL; -} - -static int start_threads(sd_resolve *resolve, unsigned extra) { - unsigned n; - int r; - - n = resolve->n_outstanding + extra; - n = CLAMP(n, WORKERS_MIN, WORKERS_MAX); - - while (resolve->n_valid_workers < n) { - - r = pthread_create(&resolve->workers[resolve->n_valid_workers], NULL, thread_worker, resolve); - if (r != 0) - return -r; - - resolve->n_valid_workers ++; - } - - return 0; -} - -static bool resolve_pid_changed(sd_resolve *r) { - assert(r); - - /* We don't support people creating a resolver and keeping it - * around after fork(). Let's complain. */ - - return r->original_pid != getpid(); -} - -_public_ int sd_resolve_new(sd_resolve **ret) { - sd_resolve *resolve = NULL; - int i, r; - - assert_return(ret, -EINVAL); - - resolve = new0(sd_resolve, 1); - if (!resolve) - return -ENOMEM; - - resolve->n_ref = 1; - resolve->original_pid = getpid(); - - for (i = 0; i < _FD_MAX; i++) - resolve->fds[i] = -1; - - r = socketpair(PF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, resolve->fds + REQUEST_RECV_FD); - if (r < 0) { - r = -errno; - goto fail; - } - - r = socketpair(PF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, resolve->fds + RESPONSE_RECV_FD); - if (r < 0) { - r = -errno; - goto fail; - } - - fd_inc_sndbuf(resolve->fds[REQUEST_SEND_FD], QUERIES_MAX * BUFSIZE); - fd_inc_rcvbuf(resolve->fds[REQUEST_RECV_FD], QUERIES_MAX * BUFSIZE); - fd_inc_sndbuf(resolve->fds[RESPONSE_SEND_FD], QUERIES_MAX * BUFSIZE); - fd_inc_rcvbuf(resolve->fds[RESPONSE_RECV_FD], QUERIES_MAX * BUFSIZE); - - fd_nonblock(resolve->fds[RESPONSE_RECV_FD], true); - - *ret = resolve; - return 0; - -fail: - sd_resolve_unref(resolve); - return r; -} - -_public_ int sd_resolve_default(sd_resolve **ret) { - - static thread_local sd_resolve *default_resolve = NULL; - sd_resolve *e = NULL; - int r; - - if (!ret) - return !!default_resolve; - - if (default_resolve) { - *ret = sd_resolve_ref(default_resolve); - return 0; - } - - r = sd_resolve_new(&e); - if (r < 0) - return r; - - e->default_resolve_ptr = &default_resolve; - e->tid = gettid(); - default_resolve = e; - - *ret = e; - return 1; -} - -_public_ int sd_resolve_get_tid(sd_resolve *resolve, pid_t *tid) { - assert_return(resolve, -EINVAL); - assert_return(tid, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - if (resolve->tid != 0) { - *tid = resolve->tid; - return 0; - } - - if (resolve->event) - return sd_event_get_tid(resolve->event, tid); - - return -ENXIO; -} - -static void resolve_free(sd_resolve *resolve) { - PROTECT_ERRNO; - sd_resolve_query *q; - unsigned i; - - assert(resolve); - - while ((q = resolve->queries)) { - assert(q->floating); - resolve_query_disconnect(q); - sd_resolve_query_unref(q); - } - - if (resolve->default_resolve_ptr) - *(resolve->default_resolve_ptr) = NULL; - - resolve->dead = true; - - sd_resolve_detach_event(resolve); - - if (resolve->fds[REQUEST_SEND_FD] >= 0) { - - RHeader req = { - .type = REQUEST_TERMINATE, - .length = sizeof(req) - }; - - /* Send one termination packet for each worker */ - for (i = 0; i < resolve->n_valid_workers; i++) - (void) send(resolve->fds[REQUEST_SEND_FD], &req, req.length, MSG_NOSIGNAL); - } - - /* Now terminate them and wait until they are gone. */ - for (i = 0; i < resolve->n_valid_workers; i++) { - for (;;) { - if (pthread_join(resolve->workers[i], NULL) != EINTR) - break; - } - } - - /* Close all communication channels */ - for (i = 0; i < _FD_MAX; i++) - safe_close(resolve->fds[i]); - - free(resolve); -} - -_public_ sd_resolve* sd_resolve_ref(sd_resolve *resolve) { - assert_return(resolve, NULL); - - assert(resolve->n_ref >= 1); - resolve->n_ref++; - - return resolve; -} - -_public_ sd_resolve* sd_resolve_unref(sd_resolve *resolve) { - - if (!resolve) - return NULL; - - assert(resolve->n_ref >= 1); - resolve->n_ref--; - - if (resolve->n_ref <= 0) - resolve_free(resolve); - - return NULL; -} - -_public_ int sd_resolve_get_fd(sd_resolve *resolve) { - assert_return(resolve, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - return resolve->fds[RESPONSE_RECV_FD]; -} - -_public_ int sd_resolve_get_events(sd_resolve *resolve) { - assert_return(resolve, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - return resolve->n_queries > resolve->n_done ? POLLIN : 0; -} - -_public_ int sd_resolve_get_timeout(sd_resolve *resolve, uint64_t *usec) { - assert_return(resolve, -EINVAL); - assert_return(usec, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - *usec = (uint64_t) -1; - return 0; -} - -static sd_resolve_query *lookup_query(sd_resolve *resolve, unsigned id) { - sd_resolve_query *q; - - assert(resolve); - - q = resolve->query_array[id % QUERIES_MAX]; - if (q) - if (q->id == id) - return q; - - return NULL; -} - -static int complete_query(sd_resolve *resolve, sd_resolve_query *q) { - int r; - - assert(q); - assert(!q->done); - assert(q->resolve == resolve); - - q->done = true; - resolve->n_done ++; - - resolve->current = sd_resolve_query_ref(q); - - switch (q->type) { - - case REQUEST_ADDRINFO: - r = getaddrinfo_done(q); - break; - - case REQUEST_NAMEINFO: - r = getnameinfo_done(q); - break; - - case REQUEST_RES_QUERY: - case REQUEST_RES_SEARCH: - r = res_query_done(q); - break; - - default: - assert_not_reached("Cannot complete unknown query type"); - } - - resolve->current = NULL; - - if (q->floating) { - resolve_query_disconnect(q); - sd_resolve_query_unref(q); - } - - sd_resolve_query_unref(q); - - return r; -} - -static int unserialize_addrinfo(const void **p, size_t *length, struct addrinfo **ret_ai) { - AddrInfoSerialization s; - size_t l; - struct addrinfo *ai; - - assert(p); - assert(*p); - assert(ret_ai); - assert(length); - - if (*length < sizeof(AddrInfoSerialization)) - return -EBADMSG; - - memcpy(&s, *p, sizeof(s)); - - l = sizeof(AddrInfoSerialization) + s.ai_addrlen + s.canonname_len; - if (*length < l) - return -EBADMSG; - - ai = new0(struct addrinfo, 1); - if (!ai) - return -ENOMEM; - - ai->ai_flags = s.ai_flags; - ai->ai_family = s.ai_family; - ai->ai_socktype = s.ai_socktype; - ai->ai_protocol = s.ai_protocol; - ai->ai_addrlen = s.ai_addrlen; - - if (s.ai_addrlen > 0) { - ai->ai_addr = memdup((const uint8_t*) *p + sizeof(AddrInfoSerialization), s.ai_addrlen); - if (!ai->ai_addr) { - free(ai); - return -ENOMEM; - } - } - - if (s.canonname_len > 0) { - ai->ai_canonname = memdup((const uint8_t*) *p + sizeof(AddrInfoSerialization) + s.ai_addrlen, s.canonname_len); - if (!ai->ai_canonname) { - free(ai->ai_addr); - free(ai); - return -ENOMEM; - } - } - - *length -= l; - *ret_ai = ai; - *p = ((const uint8_t*) *p) + l; - - return 0; -} - -static int handle_response(sd_resolve *resolve, const Packet *packet, size_t length) { - const RHeader *resp; - sd_resolve_query *q; - int r; - - assert(resolve); - - resp = &packet->rheader; - assert(resp); - assert(length >= sizeof(RHeader)); - assert(length == resp->length); - - if (resp->type == RESPONSE_DIED) { - resolve->dead = true; - return 0; - } - - assert(resolve->n_outstanding > 0); - resolve->n_outstanding--; - - q = lookup_query(resolve, resp->id); - if (!q) - return 0; - - switch (resp->type) { - - case RESPONSE_ADDRINFO: { - const AddrInfoResponse *ai_resp = &packet->addrinfo_response; - const void *p; - size_t l; - struct addrinfo *prev = NULL; - - assert(length >= sizeof(AddrInfoResponse)); - assert(q->type == REQUEST_ADDRINFO); - - q->ret = ai_resp->ret; - q->_errno = ai_resp->_errno; - q->_h_errno = ai_resp->_h_errno; - - l = length - sizeof(AddrInfoResponse); - p = (const uint8_t*) resp + sizeof(AddrInfoResponse); - - while (l > 0 && p) { - struct addrinfo *ai = NULL; - - r = unserialize_addrinfo(&p, &l, &ai); - if (r < 0) { - q->ret = EAI_SYSTEM; - q->_errno = -r; - q->_h_errno = 0; - freeaddrinfo(q->addrinfo); - q->addrinfo = NULL; - break; - } - - if (prev) - prev->ai_next = ai; - else - q->addrinfo = ai; - - prev = ai; - } - - return complete_query(resolve, q); - } - - case RESPONSE_NAMEINFO: { - const NameInfoResponse *ni_resp = &packet->nameinfo_response; - - assert(length >= sizeof(NameInfoResponse)); - assert(q->type == REQUEST_NAMEINFO); - - q->ret = ni_resp->ret; - q->_errno = ni_resp->_errno; - q->_h_errno = ni_resp->_h_errno; - - if (ni_resp->hostlen > 0) { - q->host = strndup((const char*) ni_resp + sizeof(NameInfoResponse), ni_resp->hostlen-1); - if (!q->host) { - q->ret = EAI_MEMORY; - q->_errno = ENOMEM; - q->_h_errno = 0; - } - } - - if (ni_resp->servlen > 0) { - q->serv = strndup((const char*) ni_resp + sizeof(NameInfoResponse) + ni_resp->hostlen, ni_resp->servlen-1); - if (!q->serv) { - q->ret = EAI_MEMORY; - q->_errno = ENOMEM; - q->_h_errno = 0; - } - } - - return complete_query(resolve, q); - } - - case RESPONSE_RES: { - const ResResponse *res_resp = &packet->res_response; - - assert(length >= sizeof(ResResponse)); - assert(q->type == REQUEST_RES_QUERY || q->type == REQUEST_RES_SEARCH); - - q->ret = res_resp->ret; - q->_errno = res_resp->_errno; - q->_h_errno = res_resp->_h_errno; - - if (res_resp->ret >= 0) { - q->answer = memdup((const char *)resp + sizeof(ResResponse), res_resp->ret); - if (!q->answer) { - q->ret = -1; - q->_errno = ENOMEM; - q->_h_errno = 0; - } - } - - return complete_query(resolve, q); - } - - default: - return 0; - } -} - -_public_ int sd_resolve_process(sd_resolve *resolve) { - RESOLVE_DONT_DESTROY(resolve); - - union { - Packet packet; - uint8_t space[BUFSIZE]; - } buf; - ssize_t l; - int r; - - assert_return(resolve, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - /* We don't allow recursively invoking sd_resolve_process(). */ - assert_return(!resolve->current, -EBUSY); - - l = recv(resolve->fds[RESPONSE_RECV_FD], &buf, sizeof(buf), 0); - if (l < 0) { - if (errno == EAGAIN) - return 0; - - return -errno; - } - if (l == 0) - return -ECONNREFUSED; - - r = handle_response(resolve, &buf.packet, (size_t) l); - if (r < 0) - return r; - - return 1; -} - -_public_ int sd_resolve_wait(sd_resolve *resolve, uint64_t timeout_usec) { - int r; - - assert_return(resolve, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - if (resolve->n_done >= resolve->n_queries) - return 0; - - do { - r = fd_wait_for_event(resolve->fds[RESPONSE_RECV_FD], POLLIN, timeout_usec); - } while (r == -EINTR); - - if (r < 0) - return r; - - return sd_resolve_process(resolve); -} - -static int alloc_query(sd_resolve *resolve, bool floating, sd_resolve_query **_q) { - sd_resolve_query *q; - int r; - - assert(resolve); - assert(_q); - - if (resolve->n_queries >= QUERIES_MAX) - return -ENOBUFS; - - r = start_threads(resolve, 1); - if (r < 0) - return r; - - while (resolve->query_array[resolve->current_id % QUERIES_MAX]) - resolve->current_id++; - - q = resolve->query_array[resolve->current_id % QUERIES_MAX] = new0(sd_resolve_query, 1); - if (!q) - return -ENOMEM; - - q->n_ref = 1; - q->resolve = resolve; - q->floating = floating; - q->id = resolve->current_id++; - - if (!floating) - sd_resolve_ref(resolve); - - LIST_PREPEND(queries, resolve->queries, q); - resolve->n_queries++; - - *_q = q; - return 0; -} - -_public_ int sd_resolve_getaddrinfo( - sd_resolve *resolve, - sd_resolve_query **_q, - const char *node, const char *service, - const struct addrinfo *hints, - sd_resolve_getaddrinfo_handler_t callback, void *userdata) { - - AddrInfoRequest req = {}; - struct msghdr mh = {}; - struct iovec iov[3]; - sd_resolve_query *q; - int r; - - assert_return(resolve, -EINVAL); - assert_return(node || service, -EINVAL); - assert_return(callback, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - r = alloc_query(resolve, !_q, &q); - if (r < 0) - return r; - - q->type = REQUEST_ADDRINFO; - q->getaddrinfo_handler = callback; - q->userdata = userdata; - - req.node_len = node ? strlen(node)+1 : 0; - req.service_len = service ? strlen(service)+1 : 0; - - req.header.id = q->id; - req.header.type = REQUEST_ADDRINFO; - req.header.length = sizeof(AddrInfoRequest) + req.node_len + req.service_len; - - if (hints) { - req.hints_valid = true; - req.ai_flags = hints->ai_flags; - req.ai_family = hints->ai_family; - req.ai_socktype = hints->ai_socktype; - req.ai_protocol = hints->ai_protocol; - } - - iov[mh.msg_iovlen++] = (struct iovec) { .iov_base = &req, .iov_len = sizeof(AddrInfoRequest) }; - if (node) - iov[mh.msg_iovlen++] = (struct iovec) { .iov_base = (void*) node, .iov_len = req.node_len }; - if (service) - iov[mh.msg_iovlen++] = (struct iovec) { .iov_base = (void*) service, .iov_len = req.service_len }; - mh.msg_iov = iov; - - if (sendmsg(resolve->fds[REQUEST_SEND_FD], &mh, MSG_NOSIGNAL) < 0) { - sd_resolve_query_unref(q); - return -errno; - } - - resolve->n_outstanding++; - - if (_q) - *_q = q; - - return 0; -} - -static int getaddrinfo_done(sd_resolve_query* q) { - assert(q); - assert(q->done); - assert(q->getaddrinfo_handler); - - errno = q->_errno; - h_errno = q->_h_errno; - - return q->getaddrinfo_handler(q, q->ret, q->addrinfo, q->userdata); -} - -_public_ int sd_resolve_getnameinfo( - sd_resolve *resolve, - sd_resolve_query**_q, - const struct sockaddr *sa, socklen_t salen, - int flags, - uint64_t get, - sd_resolve_getnameinfo_handler_t callback, - void *userdata) { - - NameInfoRequest req = {}; - struct msghdr mh = {}; - struct iovec iov[2]; - sd_resolve_query *q; - int r; - - assert_return(resolve, -EINVAL); - assert_return(sa, -EINVAL); - assert_return(salen >= sizeof(struct sockaddr), -EINVAL); - assert_return(salen <= sizeof(union sockaddr_union), -EINVAL); - assert_return((get & ~SD_RESOLVE_GET_BOTH) == 0, -EINVAL); - assert_return(callback, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - r = alloc_query(resolve, !_q, &q); - if (r < 0) - return r; - - q->type = REQUEST_NAMEINFO; - q->getnameinfo_handler = callback; - q->userdata = userdata; - - req.header.id = q->id; - req.header.type = REQUEST_NAMEINFO; - req.header.length = sizeof(NameInfoRequest) + salen; - - req.flags = flags; - req.sockaddr_len = salen; - req.gethost = !!(get & SD_RESOLVE_GET_HOST); - req.getserv = !!(get & SD_RESOLVE_GET_SERVICE); - - iov[0] = (struct iovec) { .iov_base = &req, .iov_len = sizeof(NameInfoRequest) }; - iov[1] = (struct iovec) { .iov_base = (void*) sa, .iov_len = salen }; - - mh.msg_iov = iov; - mh.msg_iovlen = 2; - - if (sendmsg(resolve->fds[REQUEST_SEND_FD], &mh, MSG_NOSIGNAL) < 0) { - sd_resolve_query_unref(q); - return -errno; - } - - resolve->n_outstanding++; - - if (_q) - *_q = q; - - return 0; -} - -static int getnameinfo_done(sd_resolve_query *q) { - - assert(q); - assert(q->done); - assert(q->getnameinfo_handler); - - errno = q->_errno; - h_errno= q->_h_errno; - - return q->getnameinfo_handler(q, q->ret, q->host, q->serv, q->userdata); -} - -static int resolve_res( - sd_resolve *resolve, - sd_resolve_query **_q, - QueryType qtype, - const char *dname, - int class, int type, - sd_resolve_res_handler_t callback, void *userdata) { - - struct msghdr mh = {}; - struct iovec iov[2]; - ResRequest req = {}; - sd_resolve_query *q; - int r; - - assert_return(resolve, -EINVAL); - assert_return(dname, -EINVAL); - assert_return(callback, -EINVAL); - assert_return(!resolve_pid_changed(resolve), -ECHILD); - - r = alloc_query(resolve, !_q, &q); - if (r < 0) - return r; - - q->type = qtype; - q->res_handler = callback; - q->userdata = userdata; - - req.dname_len = strlen(dname) + 1; - req.class = class; - req.type = type; - - req.header.id = q->id; - req.header.type = qtype; - req.header.length = sizeof(ResRequest) + req.dname_len; - - iov[0] = (struct iovec) { .iov_base = &req, .iov_len = sizeof(ResRequest) }; - iov[1] = (struct iovec) { .iov_base = (void*) dname, .iov_len = req.dname_len }; - - mh.msg_iov = iov; - mh.msg_iovlen = 2; - - if (sendmsg(resolve->fds[REQUEST_SEND_FD], &mh, MSG_NOSIGNAL) < 0) { - sd_resolve_query_unref(q); - return -errno; - } - - resolve->n_outstanding++; - - if (_q) - *_q = q; - - return 0; -} - -_public_ int sd_resolve_res_query(sd_resolve *resolve, sd_resolve_query** q, const char *dname, int class, int type, sd_resolve_res_handler_t callback, void *userdata) { - return resolve_res(resolve, q, REQUEST_RES_QUERY, dname, class, type, callback, userdata); -} - -_public_ int sd_resolve_res_search(sd_resolve *resolve, sd_resolve_query** q, const char *dname, int class, int type, sd_resolve_res_handler_t callback, void *userdata) { - return resolve_res(resolve, q, REQUEST_RES_SEARCH, dname, class, type, callback, userdata); -} - -static int res_query_done(sd_resolve_query* q) { - assert(q); - assert(q->done); - assert(q->res_handler); - - errno = q->_errno; - h_errno = q->_h_errno; - - return q->res_handler(q, q->ret, q->answer, q->userdata); -} - -_public_ sd_resolve_query* sd_resolve_query_ref(sd_resolve_query *q) { - assert_return(q, NULL); - - assert(q->n_ref >= 1); - q->n_ref++; - - return q; -} - -static void resolve_freeaddrinfo(struct addrinfo *ai) { - while (ai) { - struct addrinfo *next = ai->ai_next; - - free(ai->ai_addr); - free(ai->ai_canonname); - free(ai); - ai = next; - } -} - -static void resolve_query_disconnect(sd_resolve_query *q) { - sd_resolve *resolve; - unsigned i; - - assert(q); - - if (!q->resolve) - return; - - resolve = q->resolve; - assert(resolve->n_queries > 0); - - if (q->done) { - assert(resolve->n_done > 0); - resolve->n_done--; - } - - i = q->id % QUERIES_MAX; - assert(resolve->query_array[i] == q); - resolve->query_array[i] = NULL; - LIST_REMOVE(queries, resolve->queries, q); - resolve->n_queries--; - - q->resolve = NULL; - if (!q->floating) - sd_resolve_unref(resolve); -} - -static void resolve_query_free(sd_resolve_query *q) { - assert(q); - - resolve_query_disconnect(q); - - resolve_freeaddrinfo(q->addrinfo); - free(q->host); - free(q->serv); - free(q->answer); - free(q); -} - -_public_ sd_resolve_query* sd_resolve_query_unref(sd_resolve_query* q) { - if (!q) - return NULL; - - assert(q->n_ref >= 1); - q->n_ref--; - - if (q->n_ref <= 0) - resolve_query_free(q); - - return NULL; -} - -_public_ int sd_resolve_query_is_done(sd_resolve_query *q) { - assert_return(q, -EINVAL); - assert_return(!resolve_pid_changed(q->resolve), -ECHILD); - - return q->done; -} - -_public_ void* sd_resolve_query_set_userdata(sd_resolve_query *q, void *userdata) { - void *ret; - - assert_return(q, NULL); - assert_return(!resolve_pid_changed(q->resolve), NULL); - - ret = q->userdata; - q->userdata = userdata; - - return ret; -} - -_public_ void* sd_resolve_query_get_userdata(sd_resolve_query *q) { - assert_return(q, NULL); - assert_return(!resolve_pid_changed(q->resolve), NULL); - - return q->userdata; -} - -_public_ sd_resolve *sd_resolve_query_get_resolve(sd_resolve_query *q) { - assert_return(q, NULL); - assert_return(!resolve_pid_changed(q->resolve), NULL); - - return q->resolve; -} - -static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) { - sd_resolve *resolve = userdata; - int r; - - assert(resolve); - - r = sd_resolve_process(resolve); - if (r < 0) - return r; - - return 1; -} - -_public_ int sd_resolve_attach_event(sd_resolve *resolve, sd_event *event, int priority) { - int r; - - assert_return(resolve, -EINVAL); - assert_return(!resolve->event, -EBUSY); - - assert(!resolve->event_source); - - if (event) - resolve->event = sd_event_ref(event); - else { - r = sd_event_default(&resolve->event); - if (r < 0) - return r; - } - - r = sd_event_add_io(resolve->event, &resolve->event_source, resolve->fds[RESPONSE_RECV_FD], POLLIN, io_callback, resolve); - if (r < 0) - goto fail; - - r = sd_event_source_set_priority(resolve->event_source, priority); - if (r < 0) - goto fail; - - return 0; - -fail: - sd_resolve_detach_event(resolve); - return r; -} - -_public_ int sd_resolve_detach_event(sd_resolve *resolve) { - assert_return(resolve, -EINVAL); - - if (!resolve->event) - return 0; - - if (resolve->event_source) { - sd_event_source_set_enabled(resolve->event_source, SD_EVENT_OFF); - resolve->event_source = sd_event_source_unref(resolve->event_source); - } - - resolve->event = sd_event_unref(resolve->event); - return 1; -} - -_public_ sd_event *sd_resolve_get_event(sd_resolve *resolve) { - assert_return(resolve, NULL); - - return resolve->event; -} diff --git a/src/libelogind/sd-resolve/test-resolve.c b/src/libelogind/sd-resolve/test-resolve.c deleted file mode 100644 index 354a4071b..000000000 --- a/src/libelogind/sd-resolve/test-resolve.c +++ /dev/null @@ -1,171 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2005-2008 Lennart Poettering - Copyright 2014 Daniel Buch - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include -#include - -#include "socket-util.h" -#include "sd-resolve.h" -#include "resolve-util.h" -#include "macro.h" - -static int getaddrinfo_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) { - const struct addrinfo *i; - - assert_se(q); - - if (ret != 0) { - log_error("getaddrinfo error: %s %i", gai_strerror(ret), ret); - return 0; - } - - for (i = ai; i; i = i->ai_next) { - _cleanup_free_ char *addr = NULL; - - assert_se(sockaddr_pretty(i->ai_addr, i->ai_addrlen, false, true, &addr) == 0); - puts(addr); - } - - printf("canonical name: %s\n", strna(ai->ai_canonname)); - - return 0; -} - -static int getnameinfo_handler(sd_resolve_query *q, int ret, const char *host, const char *serv, void *userdata) { - assert_se(q); - - if (ret != 0) { - log_error("getnameinfo error: %s %i", gai_strerror(ret), ret); - return 0; - } - - printf("Host: %s -- Serv: %s\n", strna(host), strna(serv)); - return 0; -} - -static int res_handler(sd_resolve_query *q, int ret, unsigned char *answer, void *userdata) { - int qdcount, ancount, len; - const unsigned char *pos = answer + sizeof(HEADER); - unsigned char *end = answer + ret; - HEADER *head = (HEADER *) answer; - char name[256]; - assert_se(q); - - if (ret < 0) { - log_error("res_query() error: %s %i", strerror(errno), errno); - return 0; - } - - if (ret == 0) { - log_error("No reply for SRV lookup"); - return 0; - } - - qdcount = ntohs(head->qdcount); - ancount = ntohs(head->ancount); - - printf("%d answers for srv lookup:\n", ancount); - - /* Ignore the questions */ - while (qdcount-- > 0 && (len = dn_expand(answer, end, pos, name, 255)) >= 0) { - assert_se(len >= 0); - pos += len + QFIXEDSZ; - } - - /* Parse the answers */ - while (ancount-- > 0 && (len = dn_expand(answer, end, pos, name, 255)) >= 0) { - /* Ignore the initial string */ - uint16_t pref, weight, port; - assert_se(len >= 0); - pos += len; - /* Ignore type, ttl, class and dlen */ - pos += 10; - - GETSHORT(pref, pos); - GETSHORT(weight, pos); - GETSHORT(port, pos); - len = dn_expand(answer, end, pos, name, 255); - printf("\tpreference: %2d weight: %2d port: %d host: %s\n", - pref, weight, port, name); - - pos += len; - } - - return 0; -} - -int main(int argc, char *argv[]) { - _cleanup_resolve_query_unref_ sd_resolve_query *q1 = NULL, *q2 = NULL, *q3 = NULL; - _cleanup_resolve_unref_ sd_resolve *resolve = NULL; - int r = 0; - - struct addrinfo hints = { - .ai_family = PF_UNSPEC, - .ai_socktype = SOCK_STREAM, - .ai_flags = AI_CANONNAME - }; - - struct sockaddr_in sa = { - .sin_family = AF_INET, - .sin_port = htons(80) - }; - - assert_se(sd_resolve_default(&resolve) >= 0); - - /* Test a floating resolver query */ - sd_resolve_getaddrinfo(resolve, NULL, "redhat.com", "http", NULL, getaddrinfo_handler, NULL); - - /* Make a name -> address query */ - r = sd_resolve_getaddrinfo(resolve, &q1, argc >= 2 ? argv[1] : "www.heise.de", NULL, &hints, getaddrinfo_handler, NULL); - if (r < 0) - log_error_errno(r, "sd_resolve_getaddrinfo(): %m"); - - /* Make an address -> name query */ - sa.sin_addr.s_addr = inet_addr(argc >= 3 ? argv[2] : "193.99.144.71"); - r = sd_resolve_getnameinfo(resolve, &q2, (struct sockaddr*) &sa, sizeof(sa), 0, SD_RESOLVE_GET_BOTH, getnameinfo_handler, NULL); - if (r < 0) - log_error_errno(r, "sd_resolve_getnameinfo(): %m"); - - /* Make a res_query() call */ - r = sd_resolve_res_query(resolve, &q3, "_xmpp-client._tcp.gmail.com", C_IN, T_SRV, res_handler, NULL); - if (r < 0) - log_error_errno(r, "sd_resolve_res_query(): %m"); - - /* Wait until the three queries are completed */ - while (sd_resolve_query_is_done(q1) == 0 || - sd_resolve_query_is_done(q2) == 0 || - sd_resolve_query_is_done(q3) == 0) { - - r = sd_resolve_wait(resolve, (uint64_t) -1); - if (r < 0) { - log_error_errno(r, "sd_resolve_wait(): %m"); - assert_not_reached("sd_resolve_wait() failed"); - } - } - - return 0; -} diff --git a/src/libelogind/sd-rtnl/test-local-addresses.c b/src/libelogind/sd-rtnl/test-local-addresses.c deleted file mode 100644 index 38cbcfbcc..000000000 --- a/src/libelogind/sd-rtnl/test-local-addresses.c +++ /dev/null @@ -1,58 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "in-addr-util.h" -#include "local-addresses.h" -#include "af-list.h" - -static void print_local_addresses(struct local_address *a, unsigned n) { - unsigned i; - - for (i = 0; i < n; i++) { - _cleanup_free_ char *b = NULL; - - assert_se(in_addr_to_string(a[i].family, &a[i].address, &b) >= 0); - printf("%s if%i scope=%i metric=%u address=%s\n", af_to_name(a[i].family), a[i].ifindex, a[i].scope, a[i].metric, b); - } -} - -int main(int argc, char *argv[]) { - struct local_address *a; - int n; - - a = NULL; - n = local_addresses(NULL, 0, AF_UNSPEC, &a); - assert_se(n >= 0); - - printf("Local Addresses:\n"); - print_local_addresses(a, (unsigned) n); - free(a); - - a = NULL; - n = local_gateways(NULL, 0, AF_UNSPEC, &a); - assert_se(n >= 0); - - printf("Local Gateways:\n"); - print_local_addresses(a, (unsigned) n); - free(a); - - return 0; -} diff --git a/src/shared/btrfs-ctree.h b/src/shared/btrfs-ctree.h deleted file mode 100644 index d3ae57331..000000000 --- a/src/shared/btrfs-ctree.h +++ /dev/null @@ -1,98 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -#include "macro.h" -#include "sparse-endian.h" - -/* Stolen from btrfs' ctree.h */ - -struct btrfs_timespec { - le64_t sec; - le32_t nsec; -} _packed_; - -struct btrfs_disk_key { - le64_t objectid; - uint8_t type; - le64_t offset; -} _packed_; - -struct btrfs_inode_item { - le64_t generation; - le64_t transid; - le64_t size; - le64_t nbytes; - le64_t block_group; - le32_t nlink; - le32_t uid; - le32_t gid; - le32_t mode; - le64_t rdev; - le64_t flags; - le64_t sequence; - le64_t reserved[4]; - struct btrfs_timespec atime; - struct btrfs_timespec ctime; - struct btrfs_timespec mtime; - struct btrfs_timespec otime; -} _packed_; - -struct btrfs_root_item { - struct btrfs_inode_item inode; - le64_t generation; - le64_t root_dirid; - le64_t bytenr; - le64_t byte_limit; - le64_t bytes_used; - le64_t last_snapshot; - le64_t flags; - le32_t refs; - struct btrfs_disk_key drop_progress; - uint8_t drop_level; - uint8_t level; - le64_t generation_v2; - uint8_t uuid[BTRFS_UUID_SIZE]; - uint8_t parent_uuid[BTRFS_UUID_SIZE]; - uint8_t received_uuid[BTRFS_UUID_SIZE]; - le64_t ctransid; - le64_t otransid; - le64_t stransid; - le64_t rtransid; - struct btrfs_timespec ctime; - struct btrfs_timespec otime; - struct btrfs_timespec stime; - struct btrfs_timespec rtime; - le64_t reserved[8]; -} _packed_; - -#define BTRFS_ROOT_SUBVOL_RDONLY (1ULL << 0) - -struct btrfs_qgroup_info_item { - le64_t generation; - le64_t rfer; - le64_t rfer_cmpr; - le64_t excl; - le64_t excl_cmpr; -} _packed_; - -#define BTRFS_QGROUP_LIMIT_MAX_RFER (1ULL << 0) -#define BTRFS_QGROUP_LIMIT_MAX_EXCL (1ULL << 1) -#define BTRFS_QGROUP_LIMIT_RSV_RFER (1ULL << 2) -#define BTRFS_QGROUP_LIMIT_RSV_EXCL (1ULL << 3) -#define BTRFS_QGROUP_LIMIT_RFER_CMPR (1ULL << 4) -#define BTRFS_QGROUP_LIMIT_EXCL_CMPR (1ULL << 5) - -struct btrfs_qgroup_limit_item { - le64_t flags; - le64_t max_rfer; - le64_t max_excl; - le64_t rsv_rfer; - le64_t rsv_excl; -} _packed_; - -struct btrfs_root_ref { - le64_t dirid; - le64_t sequence; - le16_t name_len; -} _packed_; diff --git a/src/shared/btrfs-util.c b/src/shared/btrfs-util.c deleted file mode 100644 index 49528dbf0..000000000 --- a/src/shared/btrfs-util.c +++ /dev/null @@ -1,1152 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -#ifdef HAVE_LINUX_BTRFS_H -#include -#endif - -#include "missing.h" -#include "util.h" -#include "path-util.h" -#include "macro.h" -#include "copy.h" -#include "selinux-util.h" -#include "smack-util.h" -#include "fileio.h" -#include "btrfs-ctree.h" -#include "btrfs-util.h" - -/* WARNING: Be careful with file system ioctls! When we get an fd, we - * need to make sure it either refers to only a regular file or - * directory, or that it is located on btrfs, before invoking any - * btrfs ioctls. The ioctl numbers are reused by some device drivers - * (such as DRM), and hence might have bad effects when invoked on - * device nodes (that reference drivers) rather than fds to normal - * files or directories. */ - -static int validate_subvolume_name(const char *name) { - - if (!filename_is_valid(name)) - return -EINVAL; - - if (strlen(name) > BTRFS_SUBVOL_NAME_MAX) - return -E2BIG; - - return 0; -} - -static int open_parent(const char *path, int flags) { - _cleanup_free_ char *parent = NULL; - int r, fd; - - assert(path); - - r = path_get_parent(path, &parent); - if (r < 0) - return r; - - fd = open(parent, flags); - if (fd < 0) - return -errno; - - return fd; -} - -static int extract_subvolume_name(const char *path, const char **subvolume) { - const char *fn; - int r; - - assert(path); - assert(subvolume); - - fn = basename(path); - - r = validate_subvolume_name(fn); - if (r < 0) - return r; - - *subvolume = fn; - return 0; -} - -int btrfs_is_filesystem(int fd) { - struct statfs sfs; - - assert(fd >= 0); - - if (fstatfs(fd, &sfs) < 0) - return -errno; - - return F_TYPE_EQUAL(sfs.f_type, BTRFS_SUPER_MAGIC); -} - -int btrfs_is_subvol(int fd) { - struct stat st; - - assert(fd >= 0); - - /* On btrfs subvolumes always have the inode 256 */ - - if (fstat(fd, &st) < 0) - return -errno; - - if (!S_ISDIR(st.st_mode) || st.st_ino != 256) - return 0; - - return btrfs_is_filesystem(fd); -} - -int btrfs_subvol_make(const char *path) { - struct btrfs_ioctl_vol_args args = {}; - _cleanup_close_ int fd = -1; - const char *subvolume; - int r; - - assert(path); - - r = extract_subvolume_name(path, &subvolume); - if (r < 0) - return r; - - fd = open_parent(path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (fd < 0) - return fd; - - strncpy(args.name, subvolume, sizeof(args.name)-1); - - if (ioctl(fd, BTRFS_IOC_SUBVOL_CREATE, &args) < 0) - return -errno; - - return 0; -} - -int btrfs_subvol_make_label(const char *path) { - int r; - - assert(path); - - r = mac_selinux_create_file_prepare(path, S_IFDIR); - if (r < 0) - return r; - - r = btrfs_subvol_make(path); - mac_selinux_create_file_clear(); - - if (r < 0) - return r; - - return mac_smack_fix(path, false, false); -} - -int btrfs_subvol_set_read_only_fd(int fd, bool b) { - uint64_t flags, nflags; - struct stat st; - - assert(fd >= 0); - - if (fstat(fd, &st) < 0) - return -errno; - - if (!S_ISDIR(st.st_mode) || st.st_ino != 256) - return -EINVAL; - - if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0) - return -errno; - - if (b) - nflags = flags | BTRFS_SUBVOL_RDONLY; - else - nflags = flags & ~BTRFS_SUBVOL_RDONLY; - - if (flags == nflags) - return 0; - - if (ioctl(fd, BTRFS_IOC_SUBVOL_SETFLAGS, &nflags) < 0) - return -errno; - - return 0; -} - -int btrfs_subvol_set_read_only(const char *path, bool b) { - _cleanup_close_ int fd = -1; - - fd = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (fd < 0) - return -errno; - - return btrfs_subvol_set_read_only_fd(fd, b); -} - -int btrfs_subvol_get_read_only_fd(int fd) { - uint64_t flags; - struct stat st; - - assert(fd >= 0); - - if (fstat(fd, &st) < 0) - return -errno; - - if (!S_ISDIR(st.st_mode) || st.st_ino != 256) - return -EINVAL; - - if (ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &flags) < 0) - return -errno; - - return !!(flags & BTRFS_SUBVOL_RDONLY); -} - -int btrfs_reflink(int infd, int outfd) { - struct stat st; - int r; - - assert(infd >= 0); - assert(outfd >= 0); - - /* Make sure we invoke the ioctl on a regular file, so that no - * device driver accidentally gets it. */ - - if (fstat(outfd, &st) < 0) - return -errno; - - if (!S_ISREG(st.st_mode)) - return -EINVAL; - - r = ioctl(outfd, BTRFS_IOC_CLONE, infd); - if (r < 0) - return -errno; - - return 0; -} - -int btrfs_clone_range(int infd, uint64_t in_offset, int outfd, uint64_t out_offset, uint64_t sz) { - struct btrfs_ioctl_clone_range_args args = { - .src_fd = infd, - .src_offset = in_offset, - .src_length = sz, - .dest_offset = out_offset, - }; - struct stat st; - int r; - - assert(infd >= 0); - assert(outfd >= 0); - assert(sz > 0); - - if (fstat(outfd, &st) < 0) - return -errno; - - if (!S_ISREG(st.st_mode)) - return -EINVAL; - - r = ioctl(outfd, BTRFS_IOC_CLONE_RANGE, &args); - if (r < 0) - return -errno; - - return 0; -} - -int btrfs_get_block_device_fd(int fd, dev_t *dev) { - struct btrfs_ioctl_fs_info_args fsi = {}; - uint64_t id; - int r; - - assert(fd >= 0); - assert(dev); - - r = btrfs_is_filesystem(fd); - if (r < 0) - return r; - if (!r) - return -ENOTTY; - - if (ioctl(fd, BTRFS_IOC_FS_INFO, &fsi) < 0) - return -errno; - - /* We won't do this for btrfs RAID */ - if (fsi.num_devices != 1) - return 0; - - for (id = 1; id <= fsi.max_id; id++) { - struct btrfs_ioctl_dev_info_args di = { - .devid = id, - }; - struct stat st; - - if (ioctl(fd, BTRFS_IOC_DEV_INFO, &di) < 0) { - if (errno == ENODEV) - continue; - - return -errno; - } - - if (stat((char*) di.path, &st) < 0) - return -errno; - - if (!S_ISBLK(st.st_mode)) - return -ENODEV; - - if (major(st.st_rdev) == 0) - return -ENODEV; - - *dev = st.st_rdev; - return 1; - } - - return -ENODEV; -} - -int btrfs_get_block_device(const char *path, dev_t *dev) { - _cleanup_close_ int fd = -1; - - assert(path); - assert(dev); - - fd = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC); - if (fd < 0) - return -errno; - - return btrfs_get_block_device_fd(fd, dev); -} - -int btrfs_subvol_get_id_fd(int fd, uint64_t *ret) { - struct btrfs_ioctl_ino_lookup_args args = { - .objectid = BTRFS_FIRST_FREE_OBJECTID - }; - int r; - - assert(fd >= 0); - assert(ret); - - r = btrfs_is_filesystem(fd); - if (r < 0) - return r; - if (!r) - return -ENOTTY; - - if (ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args) < 0) - return -errno; - - *ret = args.treeid; - return 0; -} - -static bool btrfs_ioctl_search_args_inc(struct btrfs_ioctl_search_args *args) { - assert(args); - - /* the objectid, type, offset together make up the btrfs key, - * which is considered a single 136byte integer when - * comparing. This call increases the counter by one, dealing - * with the overflow between the overflows */ - - if (args->key.min_offset < (uint64_t) -1) { - args->key.min_offset++; - return true; - } - - if (args->key.min_type < (uint8_t) -1) { - args->key.min_type++; - args->key.min_offset = 0; - return true; - } - - if (args->key.min_objectid < (uint64_t) -1) { - args->key.min_objectid++; - args->key.min_offset = 0; - args->key.min_type = 0; - return true; - } - - return 0; -} - -static void btrfs_ioctl_search_args_set(struct btrfs_ioctl_search_args *args, const struct btrfs_ioctl_search_header *h) { - assert(args); - assert(h); - - args->key.min_objectid = h->objectid; - args->key.min_type = h->type; - args->key.min_offset = h->offset; -} - -static int btrfs_ioctl_search_args_compare(const struct btrfs_ioctl_search_args *args) { - assert(args); - - /* Compare min and max */ - - if (args->key.min_objectid < args->key.max_objectid) - return -1; - if (args->key.min_objectid > args->key.max_objectid) - return 1; - - if (args->key.min_type < args->key.max_type) - return -1; - if (args->key.min_type > args->key.max_type) - return 1; - - if (args->key.min_offset < args->key.max_offset) - return -1; - if (args->key.min_offset > args->key.max_offset) - return 1; - - return 0; -} - -#define FOREACH_BTRFS_IOCTL_SEARCH_HEADER(i, sh, args) \ - for ((i) = 0, \ - (sh) = (const struct btrfs_ioctl_search_header*) (args).buf; \ - (i) < (args).key.nr_items; \ - (i)++, \ - (sh) = (const struct btrfs_ioctl_search_header*) ((uint8_t*) (sh) + sizeof(struct btrfs_ioctl_search_header) + (sh)->len)) - -#define BTRFS_IOCTL_SEARCH_HEADER_BODY(sh) \ - ((void*) ((uint8_t*) sh + sizeof(struct btrfs_ioctl_search_header))) - -int btrfs_subvol_get_info_fd(int fd, BtrfsSubvolInfo *ret) { - struct btrfs_ioctl_search_args args = { - /* Tree of tree roots */ - .key.tree_id = BTRFS_ROOT_TREE_OBJECTID, - - /* Look precisely for the subvolume items */ - .key.min_type = BTRFS_ROOT_ITEM_KEY, - .key.max_type = BTRFS_ROOT_ITEM_KEY, - - .key.min_offset = 0, - .key.max_offset = (uint64_t) -1, - - /* No restrictions on the other components */ - .key.min_transid = 0, - .key.max_transid = (uint64_t) -1, - }; - - uint64_t subvol_id; - bool found = false; - int r; - - assert(fd >= 0); - assert(ret); - - r = btrfs_subvol_get_id_fd(fd, &subvol_id); - if (r < 0) - return r; - - args.key.min_objectid = args.key.max_objectid = subvol_id; - - while (btrfs_ioctl_search_args_compare(&args) <= 0) { - const struct btrfs_ioctl_search_header *sh; - unsigned i; - - args.key.nr_items = 256; - if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) - return -errno; - - if (args.key.nr_items <= 0) - break; - - FOREACH_BTRFS_IOCTL_SEARCH_HEADER(i, sh, args) { - - const struct btrfs_root_item *ri; - - /* Make sure we start the next search at least from this entry */ - btrfs_ioctl_search_args_set(&args, sh); - - if (sh->objectid != subvol_id) - continue; - if (sh->type != BTRFS_ROOT_ITEM_KEY) - continue; - - /* Older versions of the struct lacked the otime setting */ - if (sh->len < offsetof(struct btrfs_root_item, otime) + sizeof(struct btrfs_timespec)) - continue; - - ri = BTRFS_IOCTL_SEARCH_HEADER_BODY(sh); - - ret->otime = (usec_t) le64toh(ri->otime.sec) * USEC_PER_SEC + - (usec_t) le32toh(ri->otime.nsec) / NSEC_PER_USEC; - - ret->subvol_id = subvol_id; - ret->read_only = !!(le64toh(ri->flags) & BTRFS_ROOT_SUBVOL_RDONLY); - - assert_cc(sizeof(ri->uuid) == sizeof(ret->uuid)); - memcpy(&ret->uuid, ri->uuid, sizeof(ret->uuid)); - memcpy(&ret->parent_uuid, ri->parent_uuid, sizeof(ret->parent_uuid)); - - found = true; - goto finish; - } - - /* Increase search key by one, to read the next item, if we can. */ - if (!btrfs_ioctl_search_args_inc(&args)) - break; - } - -finish: - if (!found) - return -ENODATA; - - return 0; -} - -int btrfs_subvol_get_quota_fd(int fd, BtrfsQuotaInfo *ret) { - - struct btrfs_ioctl_search_args args = { - /* Tree of quota items */ - .key.tree_id = BTRFS_QUOTA_TREE_OBJECTID, - - /* The object ID is always 0 */ - .key.min_objectid = 0, - .key.max_objectid = 0, - - /* Look precisely for the quota items */ - .key.min_type = BTRFS_QGROUP_STATUS_KEY, - .key.max_type = BTRFS_QGROUP_LIMIT_KEY, - - /* No restrictions on the other components */ - .key.min_transid = 0, - .key.max_transid = (uint64_t) -1, - }; - - uint64_t subvol_id; - bool found_info = false, found_limit = false; - int r; - - assert(fd >= 0); - assert(ret); - - r = btrfs_subvol_get_id_fd(fd, &subvol_id); - if (r < 0) - return r; - - args.key.min_offset = args.key.max_offset = subvol_id; - - while (btrfs_ioctl_search_args_compare(&args) <= 0) { - const struct btrfs_ioctl_search_header *sh; - unsigned i; - - args.key.nr_items = 256; - if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) - return -errno; - - if (args.key.nr_items <= 0) - break; - - FOREACH_BTRFS_IOCTL_SEARCH_HEADER(i, sh, args) { - - /* Make sure we start the next search at least from this entry */ - btrfs_ioctl_search_args_set(&args, sh); - - if (sh->objectid != 0) - continue; - if (sh->offset != subvol_id) - continue; - - if (sh->type == BTRFS_QGROUP_INFO_KEY) { - const struct btrfs_qgroup_info_item *qii = BTRFS_IOCTL_SEARCH_HEADER_BODY(sh); - - ret->referenced = le64toh(qii->rfer); - ret->exclusive = le64toh(qii->excl); - - found_info = true; - - } else if (sh->type == BTRFS_QGROUP_LIMIT_KEY) { - const struct btrfs_qgroup_limit_item *qli = BTRFS_IOCTL_SEARCH_HEADER_BODY(sh); - - ret->referenced_max = le64toh(qli->max_rfer); - ret->exclusive_max = le64toh(qli->max_excl); - - if (ret->referenced_max == 0) - ret->referenced_max = (uint64_t) -1; - if (ret->exclusive_max == 0) - ret->exclusive_max = (uint64_t) -1; - - found_limit = true; - } - - if (found_info && found_limit) - goto finish; - } - - /* Increase search key by one, to read the next item, if we can. */ - if (!btrfs_ioctl_search_args_inc(&args)) - break; - } - -finish: - if (!found_limit && !found_info) - return -ENODATA; - - if (!found_info) { - ret->referenced = (uint64_t) -1; - ret->exclusive = (uint64_t) -1; - } - - if (!found_limit) { - ret->referenced_max = (uint64_t) -1; - ret->exclusive_max = (uint64_t) -1; - } - - return 0; -} - -int btrfs_defrag_fd(int fd) { - struct stat st; - - assert(fd >= 0); - - if (fstat(fd, &st) < 0) - return -errno; - - if (!S_ISREG(st.st_mode)) - return -EINVAL; - - if (ioctl(fd, BTRFS_IOC_DEFRAG, NULL) < 0) - return -errno; - - return 0; -} - -int btrfs_defrag(const char *p) { - _cleanup_close_ int fd = -1; - - fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); - if (fd < 0) - return -errno; - - return btrfs_defrag_fd(fd); -} - -int btrfs_quota_enable_fd(int fd, bool b) { - struct btrfs_ioctl_quota_ctl_args args = { - .cmd = b ? BTRFS_QUOTA_CTL_ENABLE : BTRFS_QUOTA_CTL_DISABLE, - }; - int r; - - assert(fd >= 0); - - r = btrfs_is_filesystem(fd); - if (r < 0) - return r; - if (!r) - return -ENOTTY; - - if (ioctl(fd, BTRFS_IOC_QUOTA_CTL, &args) < 0) - return -errno; - - return 0; -} - -int btrfs_quota_enable(const char *path, bool b) { - _cleanup_close_ int fd = -1; - - fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); - if (fd < 0) - return -errno; - - return btrfs_quota_enable_fd(fd, b); -} - -int btrfs_quota_limit_fd(int fd, uint64_t referenced_max) { - struct btrfs_ioctl_qgroup_limit_args args = { - .lim.max_rfer = - referenced_max == (uint64_t) -1 ? 0 : - referenced_max == 0 ? 1 : referenced_max, - .lim.flags = BTRFS_QGROUP_LIMIT_MAX_RFER, - }; - int r; - - assert(fd >= 0); - - r = btrfs_is_filesystem(fd); - if (r < 0) - return r; - if (!r) - return -ENOTTY; - - if (ioctl(fd, BTRFS_IOC_QGROUP_LIMIT, &args) < 0) - return -errno; - - return 0; -} - -int btrfs_quota_limit(const char *path, uint64_t referenced_max) { - _cleanup_close_ int fd = -1; - - fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); - if (fd < 0) - return -errno; - - return btrfs_quota_limit_fd(fd, referenced_max); -} - -int btrfs_resize_loopback_fd(int fd, uint64_t new_size, bool grow_only) { - struct btrfs_ioctl_vol_args args = {}; - _cleanup_free_ char *p = NULL, *loop = NULL, *backing = NULL; - _cleanup_close_ int loop_fd = -1, backing_fd = -1; - struct stat st; - dev_t dev = 0; - int r; - - /* btrfs cannot handle file systems < 16M, hence use this as minimum */ - if (new_size < 16*1024*1024) - new_size = 16*1024*1024; - - r = btrfs_get_block_device_fd(fd, &dev); - if (r < 0) - return r; - if (r == 0) - return -ENODEV; - - if (asprintf(&p, "/sys/dev/block/%u:%u/loop/backing_file", major(dev), minor(dev)) < 0) - return -ENOMEM; - r = read_one_line_file(p, &backing); - if (r == -ENOENT) - return -ENODEV; - if (r < 0) - return r; - if (isempty(backing) || !path_is_absolute(backing)) - return -ENODEV; - - backing_fd = open(backing, O_RDWR|O_CLOEXEC|O_NOCTTY); - if (backing_fd < 0) - return -errno; - - if (fstat(backing_fd, &st) < 0) - return -errno; - if (!S_ISREG(st.st_mode)) - return -ENODEV; - - if (new_size == (uint64_t) st.st_size) - return 0; - - if (grow_only && new_size < (uint64_t) st.st_size) - return -EINVAL; - - if (asprintf(&loop, "/dev/block/%u:%u", major(dev), minor(dev)) < 0) - return -ENOMEM; - loop_fd = open(loop, O_RDWR|O_CLOEXEC|O_NOCTTY); - if (loop_fd < 0) - return -errno; - - if (snprintf(args.name, sizeof(args.name), "%" PRIu64, new_size) >= (int) sizeof(args.name)) - return -EINVAL; - - if (new_size < (uint64_t) st.st_size) { - /* Decrease size: first decrease btrfs size, then shorten loopback */ - if (ioctl(fd, BTRFS_IOC_RESIZE, &args) < 0) - return -errno; - } - - if (ftruncate(backing_fd, new_size) < 0) - return -errno; - - if (ioctl(loop_fd, LOOP_SET_CAPACITY, 0) < 0) - return -errno; - - if (new_size > (uint64_t) st.st_size) { - /* Increase size: first enlarge loopback, then increase btrfs size */ - if (ioctl(fd, BTRFS_IOC_RESIZE, &args) < 0) - return -errno; - } - - /* Make sure the free disk space is correctly updated for both file systems */ - (void) fsync(fd); - (void) fsync(backing_fd); - - return 1; -} - -int btrfs_resize_loopback(const char *p, uint64_t new_size, bool grow_only) { - _cleanup_close_ int fd = -1; - - fd = open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC); - if (fd < 0) - return -errno; - - return btrfs_resize_loopback_fd(fd, new_size, grow_only); -} - -static int subvol_remove_children(int fd, const char *subvolume, uint64_t subvol_id, bool recursive) { - struct btrfs_ioctl_search_args args = { - .key.tree_id = BTRFS_ROOT_TREE_OBJECTID, - - .key.min_objectid = BTRFS_FIRST_FREE_OBJECTID, - .key.max_objectid = BTRFS_LAST_FREE_OBJECTID, - - .key.min_type = BTRFS_ROOT_BACKREF_KEY, - .key.max_type = BTRFS_ROOT_BACKREF_KEY, - - .key.min_transid = 0, - .key.max_transid = (uint64_t) -1, - }; - - struct btrfs_ioctl_vol_args vol_args = {}; - _cleanup_close_ int subvol_fd = -1; - struct stat st; - bool made_writable = false; - int r; - - assert(fd >= 0); - assert(subvolume); - - if (fstat(fd, &st) < 0) - return -errno; - - if (!S_ISDIR(st.st_mode)) - return -EINVAL; - - /* First, try to remove the subvolume. If it happens to be - * already empty, this will just work. */ - strncpy(vol_args.name, subvolume, sizeof(vol_args.name)-1); - if (ioctl(fd, BTRFS_IOC_SNAP_DESTROY, &vol_args) >= 0) - return 0; - if (!recursive || errno != ENOTEMPTY) - return -errno; - - /* OK, the subvolume is not empty, let's look for child - * subvolumes, and remove them, first */ - subvol_fd = openat(fd, subvolume, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (subvol_fd < 0) - return -errno; - - if (subvol_id == 0) { - r = btrfs_subvol_get_id_fd(subvol_fd, &subvol_id); - if (r < 0) - return r; - } - - args.key.min_offset = args.key.max_offset = subvol_id; - - while (btrfs_ioctl_search_args_compare(&args) <= 0) { - const struct btrfs_ioctl_search_header *sh; - unsigned i; - - args.key.nr_items = 256; - if (ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) - return -errno; - - if (args.key.nr_items <= 0) - break; - - FOREACH_BTRFS_IOCTL_SEARCH_HEADER(i, sh, args) { - _cleanup_free_ char *p = NULL; - const struct btrfs_root_ref *ref; - struct btrfs_ioctl_ino_lookup_args ino_args; - - btrfs_ioctl_search_args_set(&args, sh); - - if (sh->type != BTRFS_ROOT_BACKREF_KEY) - continue; - if (sh->offset != subvol_id) - continue; - - ref = BTRFS_IOCTL_SEARCH_HEADER_BODY(sh); - - p = strndup((char*) ref + sizeof(struct btrfs_root_ref), le64toh(ref->name_len)); - if (!p) - return -ENOMEM; - - zero(ino_args); - ino_args.treeid = subvol_id; - ino_args.objectid = htole64(ref->dirid); - - if (ioctl(fd, BTRFS_IOC_INO_LOOKUP, &ino_args) < 0) - return -errno; - - if (!made_writable) { - r = btrfs_subvol_set_read_only_fd(subvol_fd, false); - if (r < 0) - return r; - - made_writable = true; - } - - if (isempty(ino_args.name)) - /* Subvolume is in the top-level - * directory of the subvolume. */ - r = subvol_remove_children(subvol_fd, p, sh->objectid, recursive); - else { - _cleanup_close_ int child_fd = -1; - - /* Subvolume is somewhere further down, - * hence we need to open the - * containing directory first */ - - child_fd = openat(subvol_fd, ino_args.name, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (child_fd < 0) - return -errno; - - r = subvol_remove_children(child_fd, p, sh->objectid, recursive); - } - if (r < 0) - return r; - } - - /* Increase search key by one, to read the next item, if we can. */ - if (!btrfs_ioctl_search_args_inc(&args)) - break; - } - - /* OK, the child subvolumes should all be gone now, let's try - * again to remove the subvolume */ - if (ioctl(fd, BTRFS_IOC_SNAP_DESTROY, &vol_args) < 0) - return -errno; - - return 0; -} - -int btrfs_subvol_remove(const char *path, bool recursive) { - _cleanup_close_ int fd = -1; - const char *subvolume; - int r; - - assert(path); - - r = extract_subvolume_name(path, &subvolume); - if (r < 0) - return r; - - fd = open_parent(path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (fd < 0) - return fd; - - return subvol_remove_children(fd, subvolume, 0, recursive); -} - -int btrfs_subvol_remove_fd(int fd, const char *subvolume, bool recursive) { - return subvol_remove_children(fd, subvolume, 0, recursive); -} - -static int subvol_snapshot_children(int old_fd, int new_fd, const char *subvolume, uint64_t subvol_id, BtrfsSnapshotFlags flags) { - - struct btrfs_ioctl_search_args args = { - .key.tree_id = BTRFS_ROOT_TREE_OBJECTID, - - .key.min_objectid = BTRFS_FIRST_FREE_OBJECTID, - .key.max_objectid = BTRFS_LAST_FREE_OBJECTID, - - .key.min_type = BTRFS_ROOT_BACKREF_KEY, - .key.max_type = BTRFS_ROOT_BACKREF_KEY, - - .key.min_transid = 0, - .key.max_transid = (uint64_t) -1, - }; - - struct btrfs_ioctl_vol_args_v2 vol_args = { - .flags = flags & BTRFS_SNAPSHOT_READ_ONLY ? BTRFS_SUBVOL_RDONLY : 0, - .fd = old_fd, - }; - int r; - _cleanup_close_ int subvolume_fd = -1; - - assert(old_fd >= 0); - assert(new_fd >= 0); - assert(subvolume); - - strncpy(vol_args.name, subvolume, sizeof(vol_args.name)-1); - vol_args.fd = old_fd; - - if (ioctl(new_fd, BTRFS_IOC_SNAP_CREATE_V2, &vol_args) < 0) - return -errno; - - if (!(flags & BTRFS_SNAPSHOT_RECURSIVE)) - return 0; - - if (subvol_id == 0) { - r = btrfs_subvol_get_id_fd(old_fd, &subvol_id); - if (r < 0) - return r; - } - - args.key.min_offset = args.key.max_offset = subvol_id; - - while (btrfs_ioctl_search_args_compare(&args) <= 0) { - const struct btrfs_ioctl_search_header *sh; - unsigned i; - - args.key.nr_items = 256; - if (ioctl(old_fd, BTRFS_IOC_TREE_SEARCH, &args) < 0) - return -errno; - - if (args.key.nr_items <= 0) - break; - - FOREACH_BTRFS_IOCTL_SEARCH_HEADER(i, sh, args) { - _cleanup_free_ char *p = NULL, *c = NULL, *np = NULL; - struct btrfs_ioctl_ino_lookup_args ino_args; - const struct btrfs_root_ref *ref; - _cleanup_close_ int old_child_fd = -1, new_child_fd = -1; - - btrfs_ioctl_search_args_set(&args, sh); - - if (sh->type != BTRFS_ROOT_BACKREF_KEY) - continue; - if (sh->offset != subvol_id) - continue; - - ref = BTRFS_IOCTL_SEARCH_HEADER_BODY(sh); - - p = strndup((char*) ref + sizeof(struct btrfs_root_ref), le64toh(ref->name_len)); - if (!p) - return -ENOMEM; - - zero(ino_args); - ino_args.treeid = subvol_id; - ino_args.objectid = htole64(ref->dirid); - - if (ioctl(old_fd, BTRFS_IOC_INO_LOOKUP, &ino_args) < 0) - return -errno; - - /* The kernel returns an empty name if the - * subvolume is in the top-level directory, - * and otherwise appends a slash, so that we - * can just concatenate easily here, without - * adding a slash. */ - c = strappend(ino_args.name, p); - if (!c) - return -ENOMEM; - - old_child_fd = openat(old_fd, c, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (old_child_fd < 0) - return -errno; - - np = strjoin(subvolume, "/", ino_args.name, NULL); - if (!np) - return -ENOMEM; - - new_child_fd = openat(new_fd, np, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (new_child_fd < 0) - return -errno; - - if (flags & BTRFS_SNAPSHOT_READ_ONLY) { - /* If the snapshot is read-only we - * need to mark it writable - * temporarily, to put the subsnapshot - * into place. */ - - if (subvolume_fd < 0) { - subvolume_fd = openat(new_fd, subvolume, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (subvolume_fd < 0) - return -errno; - } - - r = btrfs_subvol_set_read_only_fd(subvolume_fd, false); - if (r < 0) - return r; - } - - /* When btrfs clones the subvolumes, child - * subvolumes appear as directories. Remove - * them, so that we can create a new snapshot - * in their place */ - if (unlinkat(new_child_fd, p, AT_REMOVEDIR) < 0) { - int k = -errno; - - if (flags & BTRFS_SNAPSHOT_READ_ONLY) - (void) btrfs_subvol_set_read_only_fd(subvolume_fd, true); - - return k; - } - - r = subvol_snapshot_children(old_child_fd, new_child_fd, p, sh->objectid, flags & ~BTRFS_SNAPSHOT_FALLBACK_COPY); - - /* Restore the readonly flag */ - if (flags & BTRFS_SNAPSHOT_READ_ONLY) { - int k; - - k = btrfs_subvol_set_read_only_fd(subvolume_fd, true); - if (r >= 0 && k < 0) - return k; - } - - if (r < 0) - return r; - } - - /* Increase search key by one, to read the next item, if we can. */ - if (!btrfs_ioctl_search_args_inc(&args)) - break; - } - - return 0; -} - -int btrfs_subvol_snapshot_fd(int old_fd, const char *new_path, BtrfsSnapshotFlags flags) { - _cleanup_close_ int new_fd = -1; - const char *subvolume; - int r; - - assert(old_fd >= 0); - assert(new_path); - - r = btrfs_is_subvol(old_fd); - if (r < 0) - return r; - if (r == 0) { - if (!(flags & BTRFS_SNAPSHOT_FALLBACK_COPY)) - return -EISDIR; - - r = btrfs_subvol_make(new_path); - if (r < 0) - return r; - - r = copy_directory_fd(old_fd, new_path, true); - if (r < 0) { - btrfs_subvol_remove(new_path, false); - return r; - } - - if (flags & BTRFS_SNAPSHOT_READ_ONLY) { - r = btrfs_subvol_set_read_only(new_path, true); - if (r < 0) { - btrfs_subvol_remove(new_path, false); - return r; - } - } - - return 0; - } - - r = extract_subvolume_name(new_path, &subvolume); - if (r < 0) - return r; - - new_fd = open_parent(new_path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (new_fd < 0) - return new_fd; - - return subvol_snapshot_children(old_fd, new_fd, subvolume, 0, flags); -} - -int btrfs_subvol_snapshot(const char *old_path, const char *new_path, BtrfsSnapshotFlags flags) { - _cleanup_close_ int old_fd = -1; - - assert(old_path); - assert(new_path); - - old_fd = open(old_path, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY); - if (old_fd < 0) - return -errno; - - return btrfs_subvol_snapshot_fd(old_fd, new_path, flags); -} diff --git a/src/shared/btrfs-util.h b/src/shared/btrfs-util.h deleted file mode 100644 index a7eb895c9..000000000 --- a/src/shared/btrfs-util.h +++ /dev/null @@ -1,87 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include -#include - -#include "time-util.h" - -typedef struct BtrfsSubvolInfo { - uint64_t subvol_id; - usec_t otime; - - sd_id128_t uuid; - sd_id128_t parent_uuid; - - bool read_only; -} BtrfsSubvolInfo; - -typedef struct BtrfsQuotaInfo { - uint64_t referenced; - uint64_t exclusive; - uint64_t referenced_max; - uint64_t exclusive_max; -} BtrfsQuotaInfo; - -typedef enum BtrfsSnapshotFlags { - BTRFS_SNAPSHOT_FALLBACK_COPY = 1, - BTRFS_SNAPSHOT_READ_ONLY = 2, - BTRFS_SNAPSHOT_RECURSIVE = 4, -} BtrfsSnapshotFlags; - -int btrfs_is_filesystem(int fd); -int btrfs_is_subvol(int fd); - -int btrfs_subvol_make(const char *path); -int btrfs_subvol_make_label(const char *path); - -int btrfs_subvol_snapshot_fd(int old_fd, const char *new_path, BtrfsSnapshotFlags flags); -int btrfs_subvol_snapshot(const char *old_path, const char *new_path, BtrfsSnapshotFlags flags); - -int btrfs_subvol_set_read_only_fd(int fd, bool b); -int btrfs_subvol_set_read_only(const char *path, bool b); -int btrfs_subvol_get_read_only_fd(int fd); -int btrfs_subvol_get_id_fd(int fd, uint64_t *ret); -int btrfs_subvol_get_info_fd(int fd, BtrfsSubvolInfo *info); -int btrfs_subvol_get_quota_fd(int fd, BtrfsQuotaInfo *quota); - -int btrfs_reflink(int infd, int outfd); -int btrfs_clone_range(int infd, uint64_t in_offset, int ofd, uint64_t out_offset, uint64_t sz); - -int btrfs_get_block_device_fd(int fd, dev_t *dev); -int btrfs_get_block_device(const char *path, dev_t *dev); - -int btrfs_defrag_fd(int fd); -int btrfs_defrag(const char *p); - -int btrfs_quota_enable_fd(int fd, bool b); -int btrfs_quota_enable(const char *path, bool b); - -int btrfs_quota_limit_fd(int fd, uint64_t referenced_max); -int btrfs_quota_limit(const char *path, uint64_t referenced_max); - -int btrfs_resize_loopback_fd(int fd, uint64_t size, bool grow_only); -int btrfs_resize_loopback(const char *path, uint64_t size, bool grow_only); - -int btrfs_subvol_remove(const char *path, bool recursive); -int btrfs_subvol_remove_fd(int fd, const char *subvolume, bool recursive); diff --git a/src/shared/copy.h b/src/shared/copy.h deleted file mode 100644 index 8de0cfba3..000000000 --- a/src/shared/copy.h +++ /dev/null @@ -1,35 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -int copy_file_fd(const char *from, int to, bool try_reflink); -int copy_file(const char *from, const char *to, int flags, mode_t mode, unsigned chattr_flags); -int copy_file_atomic(const char *from, const char *to, mode_t mode, bool replace, unsigned chattr_flags); -int copy_tree(const char *from, const char *to, bool merge); -int copy_tree_at(int fdf, const char *from, int fdt, const char *to, bool merge); -int copy_directory_fd(int dirfd, const char *to, bool merge); -int copy_bytes(int fdf, int fdt, off_t max_bytes, bool try_reflink); -int copy_times(int fdf, int fdt); -int copy_xattr(int fdf, int fdt); diff --git a/src/shared/dev-setup.c b/src/shared/dev-setup.c deleted file mode 100644 index 25ad918b8..000000000 --- a/src/shared/dev-setup.c +++ /dev/null @@ -1,72 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2010-2012 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -#include "util.h" -#include "label.h" -#include "path-util.h" -#include "dev-setup.h" - -int dev_setup(const char *prefix, uid_t uid, gid_t gid) { - static const char symlinks[] = - "-/proc/kcore\0" "/dev/core\0" - "/proc/self/fd\0" "/dev/fd\0" - "/proc/self/fd/0\0" "/dev/stdin\0" - "/proc/self/fd/1\0" "/dev/stdout\0" - "/proc/self/fd/2\0" "/dev/stderr\0"; - - const char *j, *k; - int r; - - NULSTR_FOREACH_PAIR(j, k, symlinks) { - _cleanup_free_ char *link_name = NULL; - const char *n; - - if (j[0] == '-') { - j++; - - if (access(j, F_OK) < 0) - continue; - } - - if (prefix) { - link_name = prefix_root(prefix, k); - if (!link_name) - return -ENOMEM; - - n = link_name; - } else - n = k; - - r = symlink_label(j, n); - if (r < 0) - log_debug_errno(r, "Failed to symlink %s to %s: %m", j, n); - - if (uid != UID_INVALID || gid != GID_INVALID) - if (lchown(n, uid, gid) < 0) - log_debug_errno(errno, "Failed to chown %s: %m", n); - } - - return 0; -} diff --git a/src/shared/dev-setup.h b/src/shared/dev-setup.h deleted file mode 100644 index ab2748db7..000000000 --- a/src/shared/dev-setup.h +++ /dev/null @@ -1,26 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2010-2012 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -int dev_setup(const char *prefix, uid_t uid, gid_t gid); diff --git a/src/shared/dropin.c b/src/shared/dropin.c deleted file mode 100644 index 963d05d32..000000000 --- a/src/shared/dropin.c +++ /dev/null @@ -1,239 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "dropin.h" -#include "util.h" -#include "strv.h" -#include "mkdir.h" -#include "fileio-label.h" -#include "conf-files.h" - -int drop_in_file(const char *dir, const char *unit, unsigned level, - const char *name, char **_p, char **_q) { - - _cleanup_free_ char *b = NULL; - char *p, *q; - - char prefix[DECIMAL_STR_MAX(unsigned)]; - - assert(unit); - assert(name); - assert(_p); - assert(_q); - - sprintf(prefix, "%u", level); - - b = xescape(name, "/."); - if (!b) - return -ENOMEM; - - if (!filename_is_valid(b)) - return -EINVAL; - - p = strjoin(dir, "/", unit, ".d", NULL); - if (!p) - return -ENOMEM; - - q = strjoin(p, "/", prefix, "-", b, ".conf", NULL); - if (!q) { - free(p); - return -ENOMEM; - } - - *_p = p; - *_q = q; - return 0; -} - -int write_drop_in(const char *dir, const char *unit, unsigned level, - const char *name, const char *data) { - - _cleanup_free_ char *p = NULL, *q = NULL; - int r; - - assert(dir); - assert(unit); - assert(name); - assert(data); - - r = drop_in_file(dir, unit, level, name, &p, &q); - if (r < 0) - return r; - - mkdir_p(p, 0755); - return write_string_file_atomic_label(q, data); -} - -int write_drop_in_format(const char *dir, const char *unit, unsigned level, - const char *name, const char *format, ...) { - _cleanup_free_ char *p = NULL; - va_list ap; - int r; - - assert(dir); - assert(unit); - assert(name); - assert(format); - - va_start(ap, format); - r = vasprintf(&p, format, ap); - va_end(ap); - - if (r < 0) - return -ENOMEM; - - return write_drop_in(dir, unit, level, name, p); -} - -static int iterate_dir( - const char *path, - UnitDependency dependency, - dependency_consumer_t consumer, - void *arg, - char ***strv) { - - _cleanup_closedir_ DIR *d = NULL; - int r; - - assert(path); - - /* The config directories are special, since the order of the - * drop-ins matters */ - if (dependency < 0) { - r = strv_extend(strv, path); - if (r < 0) - return log_oom(); - - return 0; - } - - assert(consumer); - - d = opendir(path); - if (!d) { - if (errno == ENOENT) - return 0; - - log_error_errno(errno, "Failed to open directory %s: %m", path); - return -errno; - } - - for (;;) { - struct dirent *de; - _cleanup_free_ char *f = NULL; - - errno = 0; - de = readdir(d); - if (!de && errno != 0) - return log_error_errno(errno, "Failed to read directory %s: %m", path); - - if (!de) - break; - - if (hidden_file(de->d_name)) - continue; - - f = strjoin(path, "/", de->d_name, NULL); - if (!f) - return log_oom(); - - r = consumer(dependency, de->d_name, f, arg); - if (r < 0) - return r; - } - - return 0; -} - -int unit_file_process_dir( - Set *unit_path_cache, - const char *unit_path, - const char *name, - const char *suffix, - UnitDependency dependency, - dependency_consumer_t consumer, - void *arg, - char ***strv) { - - _cleanup_free_ char *path = NULL; - int r; - - assert(unit_path); - assert(name); - assert(suffix); - - path = strjoin(unit_path, "/", name, suffix, NULL); - if (!path) - return log_oom(); - - if (!unit_path_cache || set_get(unit_path_cache, path)) - (void) iterate_dir(path, dependency, consumer, arg, strv); - - if (unit_name_is_valid(name, UNIT_NAME_INSTANCE)) { - _cleanup_free_ char *template = NULL, *p = NULL; - /* Also try the template dir */ - - r = unit_name_template(name, &template); - if (r < 0) - return log_error_errno(r, "Failed to generate template from unit name: %m"); - - p = strjoin(unit_path, "/", template, suffix, NULL); - if (!p) - return log_oom(); - - if (!unit_path_cache || set_get(unit_path_cache, p)) - (void) iterate_dir(p, dependency, consumer, arg, strv); - } - - return 0; -} - -int unit_file_find_dropin_paths( - char **lookup_path, - Set *unit_path_cache, - Set *names, - char ***paths) { - - _cleanup_strv_free_ char **strv = NULL, **ans = NULL; - Iterator i; - char *t; - int r; - - assert(paths); - - SET_FOREACH(t, names, i) { - char **p; - - STRV_FOREACH(p, lookup_path) - unit_file_process_dir(unit_path_cache, *p, t, ".d", _UNIT_DEPENDENCY_INVALID, NULL, NULL, &strv); - } - - if (strv_isempty(strv)) - return 0; - - r = conf_files_list_strv(&ans, ".conf", NULL, (const char**) strv); - if (r < 0) - return log_warning_errno(r, "Failed to get list of configuration files: %m"); - - *paths = ans; - ans = NULL; - return 1; -} diff --git a/src/shared/dropin.h b/src/shared/dropin.h deleted file mode 100644 index d4531fca2..000000000 --- a/src/shared/dropin.h +++ /dev/null @@ -1,62 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "macro.h" -#include "set.h" -#include "unit-name.h" - -int drop_in_file(const char *dir, const char *unit, unsigned level, - const char *name, char **_p, char **_q); - -int write_drop_in(const char *dir, const char *unit, unsigned level, - const char *name, const char *data); - -int write_drop_in_format(const char *dir, const char *unit, unsigned level, - const char *name, const char *format, ...) _printf_(5, 6); - -/** - * This callback will be called for each directory entry @entry, - * with @filepath being the full path to the entry. - * - * If return value is negative, loop will be aborted. - */ -typedef int (*dependency_consumer_t)(UnitDependency dependency, - const char *entry, - const char* filepath, - void *arg); - -int unit_file_process_dir( - Set * unit_path_cache, - const char *unit_path, - const char *name, - const char *suffix, - UnitDependency dependency, - dependency_consumer_t consumer, - void *arg, - char ***strv); - -int unit_file_find_dropin_paths( - char **lookup_path, - Set *unit_path_cache, - Set *names, - char ***paths); diff --git a/src/shared/ether-addr-util.h b/src/shared/ether-addr-util.h deleted file mode 100644 index 703313878..000000000 --- a/src/shared/ether-addr-util.h +++ /dev/null @@ -1,27 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Tom Gundersen - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#define ETHER_ADDR_FORMAT_STR "%02X%02X%02X%02X%02X%02X" -#define ETHER_ADDR_FORMAT_VAL(x) (x).ether_addr_octet[0], (x).ether_addr_octet[1], (x).ether_addr_octet[2], (x).ether_addr_octet[3], (x).ether_addr_octet[4], (x).ether_addr_octet[5] diff --git a/src/shared/generator.h b/src/shared/generator.h deleted file mode 100644 index 6c3f38abb..000000000 --- a/src/shared/generator.h +++ /dev/null @@ -1,38 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -int generator_write_fsck_deps( - FILE *f, - const char *dir, - const char *what, - const char *where, - const char *type); - -int generator_write_timeouts( - const char *dir, - const char *what, - const char *where, - const char *opts, - char **filtered); diff --git a/src/shared/gpt.h b/src/shared/gpt.h deleted file mode 100644 index add1df420..000000000 --- a/src/shared/gpt.h +++ /dev/null @@ -1,63 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include - -#include "sd-id128.h" - -/* We only support root disk discovery for x86, x86-64 and ARM for - * now, since EFI for anything else doesn't really exist, and we only - * care for root partitions on the same disk as the EFI ESP. */ - -#define GPT_ROOT_X86 SD_ID128_MAKE(44,47,95,40,f2,97,41,b2,9a,f7,d1,31,d5,f0,45,8a) -#define GPT_ROOT_X86_64 SD_ID128_MAKE(4f,68,bc,e3,e8,cd,4d,b1,96,e7,fb,ca,f9,84,b7,09) -#define GPT_ROOT_ARM SD_ID128_MAKE(69,da,d7,10,2c,e4,4e,3c,b1,6c,21,a1,d4,9a,be,d3) -#define GPT_ROOT_ARM_64 SD_ID128_MAKE(b9,21,b0,45,1d,f0,41,c3,af,44,4c,6f,28,0d,3f,ae) - -#define GPT_ESP SD_ID128_MAKE(c1,2a,73,28,f8,1f,11,d2,ba,4b,00,a0,c9,3e,c9,3b) -#define GPT_SWAP SD_ID128_MAKE(06,57,fd,6d,a4,ab,43,c4,84,e5,09,33,c8,4b,4f,4f) -#define GPT_HOME SD_ID128_MAKE(93,3a,c7,e1,2e,b4,4f,13,b8,44,0e,14,e2,ae,f9,15) -#define GPT_SRV SD_ID128_MAKE(3b,8f,84,25,20,e0,4f,3b,90,7f,1a,25,a7,6f,98,e8) - -#if defined(__x86_64__) -# define GPT_ROOT_NATIVE GPT_ROOT_X86_64 -# define GPT_ROOT_SECONDARY GPT_ROOT_X86 -#elif defined(__i386__) -# define GPT_ROOT_NATIVE GPT_ROOT_X86 -#endif - -#if defined(__aarch64__) && (__BYTE_ORDER != __BIG_ENDIAN) -# define GPT_ROOT_NATIVE GPT_ROOT_ARM_64 -# define GPT_ROOT_SECONDARY GPT_ROOT_ARM -#elif defined(__arm__) && (__BYTE_ORDER != __BIG_ENDIAN) -# define GPT_ROOT_NATIVE GPT_ROOT_ARM -#endif - -/* Flags we recognize on the root, swap, home and srv partitions when - * doing auto-discovery. These happen to be identical to what - * Microsoft defines for its own Basic Data Partitions, but that's - * just because we saw no point in defining any other values here. */ -#define GPT_FLAG_READ_ONLY (1ULL << 60) -#define GPT_FLAG_NO_AUTO (1ULL << 63) - -#define GPT_LINUX_GENERIC SD_ID128_MAKE(0f,c6,3d,af,84,83,47,72,8e,79,3d,69,d8,47,7d,e4) diff --git a/src/shared/initreq.h b/src/shared/initreq.h deleted file mode 100644 index 710037d84..000000000 --- a/src/shared/initreq.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * initreq.h Interface to talk to init through /dev/initctl. - * - * Copyright (C) 1995-2004 Miquel van Smoorenburg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * Version: @(#)initreq.h 1.28 31-Mar-2004 MvS - * - */ -#ifndef _INITREQ_H -#define _INITREQ_H - -#include - -#if defined(__FreeBSD_kernel__) -# define INIT_FIFO "/etc/.initctl" -#else -# define INIT_FIFO "/dev/initctl" -#endif - -#define INIT_MAGIC 0x03091969 -#define INIT_CMD_START 0 -#define INIT_CMD_RUNLVL 1 -#define INIT_CMD_POWERFAIL 2 -#define INIT_CMD_POWERFAILNOW 3 -#define INIT_CMD_POWEROK 4 -#define INIT_CMD_BSD 5 -#define INIT_CMD_SETENV 6 -#define INIT_CMD_UNSETENV 7 - -#define INIT_CMD_CHANGECONS 12345 - -#ifdef MAXHOSTNAMELEN -# define INITRQ_HLEN MAXHOSTNAMELEN -#else -# define INITRQ_HLEN 64 -#endif - -/* - * This is what BSD 4.4 uses when talking to init. - * Linux doesn't use this right now. - */ -struct init_request_bsd { - char gen_id[8]; /* Beats me.. telnetd uses "fe" */ - char tty_id[16]; /* Tty name minus /dev/tty */ - char host[INITRQ_HLEN]; /* Hostname */ - char term_type[16]; /* Terminal type */ - int signal; /* Signal to send */ - int pid; /* Process to send to */ - char exec_name[128]; /* Program to execute */ - char reserved[128]; /* For future expansion. */ -}; - - -/* - * Because of legacy interfaces, "runlevel" and "sleeptime" - * aren't in a separate struct in the union. - * - * The weird sizes are because init expects the whole - * struct to be 384 bytes. - */ -struct init_request { - int magic; /* Magic number */ - int cmd; /* What kind of request */ - int runlevel; /* Runlevel to change to */ - int sleeptime; /* Time between TERM and KILL */ - union { - struct init_request_bsd bsd; - char data[368]; - } i; -}; - -#endif diff --git a/src/shared/install-printf.c b/src/shared/install-printf.c deleted file mode 100644 index cbe984d2f..000000000 --- a/src/shared/install-printf.c +++ /dev/null @@ -1,144 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#include "specifier.h" -#include "unit-name.h" -#include "util.h" -#include "install-printf.h" -#include "formats-util.h" - -static int specifier_prefix_and_instance(char specifier, void *data, void *userdata, char **ret) { - UnitFileInstallInfo *i = userdata; - - assert(i); - - return unit_name_to_prefix_and_instance(i->name, ret); -} - -static int specifier_prefix(char specifier, void *data, void *userdata, char **ret) { - UnitFileInstallInfo *i = userdata; - - assert(i); - - return unit_name_to_prefix(i->name, ret); -} - -static int specifier_instance(char specifier, void *data, void *userdata, char **ret) { - UnitFileInstallInfo *i = userdata; - char *instance; - int r; - - assert(i); - - r = unit_name_to_instance(i->name, &instance); - if (r < 0) - return r; - - if (!instance) { - instance = strdup(""); - if (!instance) - return -ENOMEM; - } - - *ret = instance; - return 0; -} - -static int specifier_user_name(char specifier, void *data, void *userdata, char **ret) { - UnitFileInstallInfo *i = userdata; - const char *username; - _cleanup_free_ char *tmp = NULL; - char *printed = NULL; - - assert(i); - - if (i->user) - username = i->user; - else - /* get USER env from env or our own uid */ - username = tmp = getusername_malloc(); - - switch (specifier) { - case 'u': - printed = strdup(username); - break; - case 'U': { - /* fish username from passwd */ - uid_t uid; - int r; - - r = get_user_creds(&username, &uid, NULL, NULL, NULL); - if (r < 0) - return r; - - if (asprintf(&printed, UID_FMT, uid) < 0) - return -ENOMEM; - break; - }} - - - *ret = printed; - return 0; -} - - -int install_full_printf(UnitFileInstallInfo *i, const char *format, char **ret) { - - /* This is similar to unit_full_printf() but does not support - * anything path-related. - * - * %n: the full id of the unit (foo@bar.waldo) - * %N: the id of the unit without the suffix (foo@bar) - * %p: the prefix (foo) - * %i: the instance (bar) - - * %U the UID of the configured user or running user - * %u the username of the configured user or running user - * %m the machine ID of the running system - * %H the host name of the running system - * %b the boot ID of the running system - * %v `uname -r` of the running system - */ - - const Specifier table[] = { - { 'n', specifier_string, i->name }, - { 'N', specifier_prefix_and_instance, NULL }, - { 'p', specifier_prefix, NULL }, - { 'i', specifier_instance, NULL }, - - { 'U', specifier_user_name, NULL }, - { 'u', specifier_user_name, NULL }, - - { 'm', specifier_machine_id, NULL }, - { 'H', specifier_host_name, NULL }, - { 'b', specifier_boot_id, NULL }, - { 'v', specifier_kernel_release, NULL }, - {} - }; - - assert(i); - assert(format); - assert(ret); - - return specifier_printf(format, table, i, ret); -} diff --git a/src/shared/install-printf.h b/src/shared/install-printf.h deleted file mode 100644 index 655033782..000000000 --- a/src/shared/install-printf.h +++ /dev/null @@ -1,26 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Zbigniew Jędrzejewski-Szmek - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#pragma once - -#include "install.h" - -int install_full_printf(UnitFileInstallInfo *i, const char *format, char **ret); diff --git a/src/shared/linux/auto_dev-ioctl.h b/src/shared/linux/auto_dev-ioctl.h deleted file mode 100644 index aeaeb3ea7..000000000 --- a/src/shared/linux/auto_dev-ioctl.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 2008 Red Hat, Inc. All rights reserved. - * Copyright 2008 Ian Kent - * - * 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 - -#ifdef __KERNEL__ -#include -#else -#include -#endif /* __KERNEL__ */ - -#define AUTOFS_DEVICE_NAME "autofs" - -#define AUTOFS_DEV_IOCTL_VERSION_MAJOR 1 -#define AUTOFS_DEV_IOCTL_VERSION_MINOR 0 - -#define AUTOFS_DEVID_LEN 16 - -#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 is 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[0]; -}; - -static inline void init_autofs_dev_ioctl(struct autofs_dev_ioctl *in) { - memset(in, 0, sizeof(struct autofs_dev_ioctl)); - in->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR; - in->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR; - in->size = sizeof(struct autofs_dev_ioctl); - in->ioctlfd = -1; - return; -} - -/* - * If you change this make sure you make the corresponding change - * to autofs-dev-ioctl.c:lookup_ioctl() - */ -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, -}; - -#define AUTOFS_IOCTL 0x93 - -#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 */ diff --git a/src/shared/lockfile-util.c b/src/shared/lockfile-util.c deleted file mode 100644 index 05e16d1ca..000000000 --- a/src/shared/lockfile-util.c +++ /dev/null @@ -1,154 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include -#include - -#include "util.h" -#include "lockfile-util.h" -#include "fileio.h" - -int make_lock_file(const char *p, int operation, LockFile *ret) { - _cleanup_close_ int fd = -1; - _cleanup_free_ char *t = NULL; - int r; - - /* - * We use UNPOSIX locks if they are available. They have nice - * semantics, and are mostly compatible with NFS. However, - * they are only available on new kernels. When we detect we - * are running on an older kernel, then we fall back to good - * old BSD locks. They also have nice semantics, but are - * slightly problematic on NFS, where they are upgraded to - * POSIX locks, even though locally they are orthogonal to - * POSIX locks. - */ - - t = strdup(p); - if (!t) - return -ENOMEM; - - for (;;) { - struct flock fl = { - .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK, - .l_whence = SEEK_SET, - }; - struct stat st; - - fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600); - if (fd < 0) - return -errno; - - r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl); - if (r < 0) { - - /* If the kernel is too old, use good old BSD locks */ - if (errno == EINVAL) - r = flock(fd, operation); - - if (r < 0) - return errno == EAGAIN ? -EBUSY : -errno; - } - - /* If we acquired the lock, let's check if the file - * still exists in the file system. If not, then the - * previous exclusive owner removed it and then closed - * it. In such a case our acquired lock is worthless, - * hence try again. */ - - r = fstat(fd, &st); - if (r < 0) - return -errno; - if (st.st_nlink > 0) - break; - - fd = safe_close(fd); - } - - ret->path = t; - ret->fd = fd; - ret->operation = operation; - - fd = -1; - t = NULL; - - return r; -} - -int make_lock_file_for(const char *p, int operation, LockFile *ret) { - const char *fn; - char *t; - - assert(p); - assert(ret); - - fn = basename(p); - if (!filename_is_valid(fn)) - return -EINVAL; - - t = newa(char, strlen(p) + 2 + 4 + 1); - stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck"); - - return make_lock_file(t, operation, ret); -} - -void release_lock_file(LockFile *f) { - int r; - - if (!f) - return; - - if (f->path) { - - /* If we are the exclusive owner we can safely delete - * the lock file itself. If we are not the exclusive - * owner, we can try becoming it. */ - - if (f->fd >= 0 && - (f->operation & ~LOCK_NB) == LOCK_SH) { - static const struct flock fl = { - .l_type = F_WRLCK, - .l_whence = SEEK_SET, - }; - - r = fcntl(f->fd, F_OFD_SETLK, &fl); - if (r < 0 && errno == EINVAL) - r = flock(f->fd, LOCK_EX|LOCK_NB); - - if (r >= 0) - f->operation = LOCK_EX|LOCK_NB; - } - - if ((f->operation & ~LOCK_NB) == LOCK_EX) - unlink_noerrno(f->path); - - free(f->path); - f->path = NULL; - } - - f->fd = safe_close(f->fd); - f->operation = 0; -} diff --git a/src/shared/lockfile-util.h b/src/shared/lockfile-util.h deleted file mode 100644 index 38d47094b..000000000 --- a/src/shared/lockfile-util.h +++ /dev/null @@ -1,39 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2011 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "macro.h" -#include "missing.h" - -typedef struct LockFile { - char *path; - int fd; - int operation; -} LockFile; - -int make_lock_file(const char *p, int operation, LockFile *ret); -int make_lock_file_for(const char *p, int operation, LockFile *ret); -void release_lock_file(LockFile *f); - -#define _cleanup_release_lock_file_ _cleanup_(release_lock_file) - -#define LOCK_FILE_INIT { .fd = -1, .path = NULL } diff --git a/src/shared/machine-image.c b/src/shared/machine-image.c deleted file mode 100644 index 273dacff1..000000000 --- a/src/shared/machine-image.c +++ /dev/null @@ -1,675 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2013 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -#include "utf8.h" -#include "btrfs-util.h" -#include "path-util.h" -#include "copy.h" -#include "mkdir.h" -#include "rm-rf.h" -#include "machine-image.h" - -static const char image_search_path[] = - "/var/lib/machines\0" - "/var/lib/container\0" - "/usr/local/lib/machines\0" - "/usr/lib/machines\0"; - -Image *image_unref(Image *i) { - if (!i) - return NULL; - - free(i->name); - free(i->path); - free(i); - return NULL; -} - -static int image_new( - ImageType t, - const char *pretty, - const char *path, - const char *filename, - bool read_only, - usec_t crtime, - usec_t mtime, - Image **ret) { - - _cleanup_(image_unrefp) Image *i = NULL; - - assert(t >= 0); - assert(t < _IMAGE_TYPE_MAX); - assert(pretty); - assert(filename); - assert(ret); - - i = new0(Image, 1); - if (!i) - return -ENOMEM; - - i->type = t; - i->read_only = read_only; - i->crtime = crtime; - i->mtime = mtime; - i->usage = i->usage_exclusive = (uint64_t) -1; - i->limit = i->limit_exclusive = (uint64_t) -1; - - i->name = strdup(pretty); - if (!i->name) - return -ENOMEM; - - if (path) - i->path = strjoin(path, "/", filename, NULL); - else - i->path = strdup(filename); - - if (!i->path) - return -ENOMEM; - - path_kill_slashes(i->path); - - *ret = i; - i = NULL; - - return 0; -} - -static int image_make( - const char *pretty, - int dfd, - const char *path, - const char *filename, - Image **ret) { - - struct stat st; - bool read_only; - int r; - - assert(filename); - - /* We explicitly *do* follow symlinks here, since we want to - * allow symlinking trees into /var/lib/machines/, and treat - * them normally. */ - - if (fstatat(dfd, filename, &st, 0) < 0) - return -errno; - - read_only = - (path && path_startswith(path, "/usr")) || - (faccessat(dfd, filename, W_OK, AT_EACCESS) < 0 && errno == EROFS); - - if (S_ISDIR(st.st_mode)) { - _cleanup_close_ int fd = -1; - unsigned file_attr = 0; - - if (!ret) - return 1; - - if (!pretty) - pretty = filename; - - fd = openat(dfd, filename, O_CLOEXEC|O_NOCTTY|O_DIRECTORY); - if (fd < 0) - return -errno; - - /* btrfs subvolumes have inode 256 */ - if (st.st_ino == 256) { - - r = btrfs_is_filesystem(fd); - if (r < 0) - return r; - if (r) { - BtrfsSubvolInfo info; - BtrfsQuotaInfo quota; - - /* It's a btrfs subvolume */ - - r = btrfs_subvol_get_info_fd(fd, &info); - if (r < 0) - return r; - - r = image_new(IMAGE_SUBVOLUME, - pretty, - path, - filename, - info.read_only || read_only, - info.otime, - 0, - ret); - if (r < 0) - return r; - - r = btrfs_subvol_get_quota_fd(fd, "a); - if (r >= 0) { - (*ret)->usage = quota.referenced; - (*ret)->usage_exclusive = quota.exclusive; - - (*ret)->limit = quota.referenced_max; - (*ret)->limit_exclusive = quota.exclusive_max; - } - - return 1; - } - } - - /* If the IMMUTABLE bit is set, we consider the - * directory read-only. Since the ioctl is not - * supported everywhere we ignore failures. */ - (void) read_attr_fd(fd, &file_attr); - - /* It's just a normal directory. */ - r = image_new(IMAGE_DIRECTORY, - pretty, - path, - filename, - read_only || (file_attr & FS_IMMUTABLE_FL), - 0, - 0, - ret); - if (r < 0) - return r; - - return 1; - - } else if (S_ISREG(st.st_mode) && endswith(filename, ".raw")) { - usec_t crtime = 0; - - /* It's a RAW disk image */ - - if (!ret) - return 1; - - fd_getcrtime_at(dfd, filename, &crtime, 0); - - if (!pretty) - pretty = strndupa(filename, strlen(filename) - 4); - - r = image_new(IMAGE_RAW, - pretty, - path, - filename, - !(st.st_mode & 0222) || read_only, - crtime, - timespec_load(&st.st_mtim), - ret); - if (r < 0) - return r; - - (*ret)->usage = (*ret)->usage_exclusive = st.st_blocks * 512; - (*ret)->limit = (*ret)->limit_exclusive = st.st_size; - - return 1; - } - - return 0; -} - -int image_find(const char *name, Image **ret) { - const char *path; - int r; - - assert(name); - - /* There are no images with invalid names */ - if (!image_name_is_valid(name)) - return 0; - - NULSTR_FOREACH(path, image_search_path) { - _cleanup_closedir_ DIR *d = NULL; - - d = opendir(path); - if (!d) { - if (errno == ENOENT) - continue; - - return -errno; - } - - r = image_make(NULL, dirfd(d), path, name, ret); - if (r == 0 || r == -ENOENT) { - _cleanup_free_ char *raw = NULL; - - raw = strappend(name, ".raw"); - if (!raw) - return -ENOMEM; - - r = image_make(NULL, dirfd(d), path, raw, ret); - if (r == 0 || r == -ENOENT) - continue; - } - if (r < 0) - return r; - - return 1; - } - - if (streq(name, ".host")) - return image_make(".host", AT_FDCWD, NULL, "/", ret); - - return 0; -}; - -int image_discover(Hashmap *h) { - const char *path; - int r; - - assert(h); - - NULSTR_FOREACH(path, image_search_path) { - _cleanup_closedir_ DIR *d = NULL; - struct dirent *de; - - d = opendir(path); - if (!d) { - if (errno == ENOENT) - continue; - - return -errno; - } - - FOREACH_DIRENT_ALL(de, d, return -errno) { - _cleanup_(image_unrefp) Image *image = NULL; - - if (!image_name_is_valid(de->d_name)) - continue; - - if (hashmap_contains(h, de->d_name)) - continue; - - r = image_make(NULL, dirfd(d), path, de->d_name, &image); - if (r == 0 || r == -ENOENT) - continue; - if (r < 0) - return r; - - r = hashmap_put(h, image->name, image); - if (r < 0) - return r; - - image = NULL; - } - } - - if (!hashmap_contains(h, ".host")) { - _cleanup_(image_unrefp) Image *image = NULL; - - r = image_make(".host", AT_FDCWD, NULL, "/", &image); - if (r < 0) - return r; - - r = hashmap_put(h, image->name, image); - if (r < 0) - return r; - - image = NULL; - - } - - return 0; -} - -void image_hashmap_free(Hashmap *map) { - Image *i; - - while ((i = hashmap_steal_first(map))) - image_unref(i); - - hashmap_free(map); -} - -int image_remove(Image *i) { - _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT; - int r; - - assert(i); - - if (path_equal(i->path, "/") || - path_startswith(i->path, "/usr")) - return -EROFS; - - /* Make sure we don't interfere with a running nspawn */ - r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock); - if (r < 0) - return r; - - switch (i->type) { - - case IMAGE_SUBVOLUME: - return btrfs_subvol_remove(i->path, true); - - case IMAGE_DIRECTORY: - /* Allow deletion of read-only directories */ - (void) chattr_path(i->path, false, FS_IMMUTABLE_FL); - return rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME); - - case IMAGE_RAW: - if (unlink(i->path) < 0) - return -errno; - - return 0; - - default: - return -EOPNOTSUPP; - } -} - -int image_rename(Image *i, const char *new_name) { - _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT; - _cleanup_free_ char *new_path = NULL, *nn = NULL; - unsigned file_attr = 0; - int r; - - assert(i); - - if (!image_name_is_valid(new_name)) - return -EINVAL; - - if (path_equal(i->path, "/") || - path_startswith(i->path, "/usr")) - return -EROFS; - - /* Make sure we don't interfere with a running nspawn */ - r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock); - if (r < 0) - return r; - - /* Make sure nobody takes the new name, between the time we - * checked it is currently unused in all search paths, and the - * time we take possesion of it */ - r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock); - if (r < 0) - return r; - - r = image_find(new_name, NULL); - if (r < 0) - return r; - if (r > 0) - return -EEXIST; - - switch (i->type) { - - case IMAGE_DIRECTORY: - /* Turn of the immutable bit while we rename the image, so that we can rename it */ - (void) read_attr_path(i->path, &file_attr); - - if (file_attr & FS_IMMUTABLE_FL) - (void) chattr_path(i->path, false, FS_IMMUTABLE_FL); - - /* fall through */ - - case IMAGE_SUBVOLUME: - new_path = file_in_same_dir(i->path, new_name); - break; - - case IMAGE_RAW: { - const char *fn; - - fn = strjoina(new_name, ".raw"); - new_path = file_in_same_dir(i->path, fn); - break; - } - - default: - return -EOPNOTSUPP; - } - - if (!new_path) - return -ENOMEM; - - nn = strdup(new_name); - if (!nn) - return -ENOMEM; - - r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path); - if (r < 0) - return r; - - /* Restore the immutable bit, if it was set before */ - if (file_attr & FS_IMMUTABLE_FL) - (void) chattr_path(new_path, true, FS_IMMUTABLE_FL); - - free(i->path); - i->path = new_path; - new_path = NULL; - - free(i->name); - i->name = nn; - nn = NULL; - - return 0; -} - -int image_clone(Image *i, const char *new_name, bool read_only) { - _cleanup_release_lock_file_ LockFile name_lock = LOCK_FILE_INIT; - const char *new_path; - int r; - - assert(i); - - if (!image_name_is_valid(new_name)) - return -EINVAL; - - /* Make sure nobody takes the new name, between the time we - * checked it is currently unused in all search paths, and the - * time we take possesion of it */ - r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock); - if (r < 0) - return r; - - r = image_find(new_name, NULL); - if (r < 0) - return r; - if (r > 0) - return -EEXIST; - - switch (i->type) { - - case IMAGE_SUBVOLUME: - case IMAGE_DIRECTORY: - new_path = strjoina("/var/lib/machines/", new_name); - - r = btrfs_subvol_snapshot(i->path, new_path, (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) | BTRFS_SNAPSHOT_FALLBACK_COPY | BTRFS_SNAPSHOT_RECURSIVE); - break; - - case IMAGE_RAW: - new_path = strjoina("/var/lib/machines/", new_name, ".raw"); - - r = copy_file_atomic(i->path, new_path, read_only ? 0444 : 0644, false, FS_NOCOW_FL); - break; - - default: - return -EOPNOTSUPP; - } - - if (r < 0) - return r; - - return 0; -} - -int image_read_only(Image *i, bool b) { - _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT; - int r; - assert(i); - - if (path_equal(i->path, "/") || - path_startswith(i->path, "/usr")) - return -EROFS; - - /* Make sure we don't interfere with a running nspawn */ - r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock); - if (r < 0) - return r; - - switch (i->type) { - - case IMAGE_SUBVOLUME: - r = btrfs_subvol_set_read_only(i->path, b); - if (r < 0) - return r; - - break; - - case IMAGE_DIRECTORY: - /* For simple directory trees we cannot use the access - mode of the top-level directory, since it has an - effect on the container itself. However, we can - use the "immutable" flag, to at least make the - top-level directory read-only. It's not as good as - a read-only subvolume, but at least something, and - we can read the value back.*/ - - r = chattr_path(i->path, b, FS_IMMUTABLE_FL); - if (r < 0) - return r; - - break; - - case IMAGE_RAW: { - struct stat st; - - if (stat(i->path, &st) < 0) - return -errno; - - if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0) - return -errno; - - /* If the images is now read-only, it's a good time to - * defrag it, given that no write patterns will - * fragment it again. */ - if (b) - (void) btrfs_defrag(i->path); - break; - } - - default: - return -EOPNOTSUPP; - } - - return 0; -} - -int image_path_lock(const char *path, int operation, LockFile *global, LockFile *local) { - _cleanup_free_ char *p = NULL; - LockFile t = LOCK_FILE_INIT; - struct stat st; - int r; - - assert(path); - assert(global); - assert(local); - - /* Locks an image path. This actually creates two locks: one - * "local" one, next to the image path itself, which might be - * shared via NFS. And another "global" one, in /run, that - * uses the device/inode number. This has the benefit that we - * can even lock a tree that is a mount point, correctly. */ - - if (path_equal(path, "/")) - return -EBUSY; - - if (!path_is_absolute(path)) - return -EINVAL; - - if (stat(path, &st) >= 0) { - if (asprintf(&p, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st.st_dev, (unsigned long) st.st_ino) < 0) - return -ENOMEM; - } - - r = make_lock_file_for(path, operation, &t); - if (r < 0) - return r; - - if (p) { - mkdir_p("/run/systemd/nspawn/locks", 0700); - - r = make_lock_file(p, operation, global); - if (r < 0) { - release_lock_file(&t); - return r; - } - } - - *local = t; - return 0; -} - -int image_set_limit(Image *i, uint64_t referenced_max) { - assert(i); - - if (path_equal(i->path, "/") || - path_startswith(i->path, "/usr")) - return -EROFS; - - if (i->type != IMAGE_SUBVOLUME) - return -EOPNOTSUPP; - - return btrfs_quota_limit(i->path, referenced_max); -} - -int image_name_lock(const char *name, int operation, LockFile *ret) { - const char *p; - - assert(name); - assert(ret); - - /* Locks an image name, regardless of the precise path used. */ - - if (!image_name_is_valid(name)) - return -EINVAL; - - if (streq(name, ".host")) - return -EBUSY; - - mkdir_p("/run/systemd/nspawn/locks", 0700); - p = strjoina("/run/systemd/nspawn/locks/name-", name); - - return make_lock_file(p, operation, ret); -} - -bool image_name_is_valid(const char *s) { - if (!filename_is_valid(s)) - return false; - - if (string_has_cc(s, NULL)) - return false; - - if (!utf8_is_valid(s)) - return false; - - /* Temporary files for atomically creating new files */ - if (startswith(s, ".#")) - return false; - - return true; -} - -static const char* const image_type_table[_IMAGE_TYPE_MAX] = { - [IMAGE_DIRECTORY] = "directory", - [IMAGE_SUBVOLUME] = "subvolume", - [IMAGE_RAW] = "raw", -}; - -DEFINE_STRING_TABLE_LOOKUP(image_type, ImageType); diff --git a/src/shared/machine-image.h b/src/shared/machine-image.h deleted file mode 100644 index f041600fb..000000000 --- a/src/shared/machine-image.h +++ /dev/null @@ -1,75 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "time-util.h" -#include "lockfile-util.h" -#include "hashmap.h" - -typedef enum ImageType { - IMAGE_DIRECTORY, - IMAGE_SUBVOLUME, - IMAGE_RAW, - _IMAGE_TYPE_MAX, - _IMAGE_TYPE_INVALID = -1 -} ImageType; - -typedef struct Image { - ImageType type; - char *name; - char *path; - bool read_only; - - usec_t crtime; - usec_t mtime; - - uint64_t usage; - uint64_t usage_exclusive; - uint64_t limit; - uint64_t limit_exclusive; - - void *userdata; -} Image; - -Image *image_unref(Image *i); -void image_hashmap_free(Hashmap *map); - -DEFINE_TRIVIAL_CLEANUP_FUNC(Image*, image_unref); -DEFINE_TRIVIAL_CLEANUP_FUNC(Hashmap*, image_hashmap_free); - -int image_find(const char *name, Image **ret); -int image_discover(Hashmap *map); - -int image_remove(Image *i); -int image_rename(Image *i, const char *new_name); -int image_clone(Image *i, const char *new_name, bool read_only); -int image_read_only(Image *i, bool b); - -const char* image_type_to_string(ImageType t) _const_; -ImageType image_type_from_string(const char *s) _pure_; - -bool image_name_is_valid(const char *s) _pure_; - -int image_path_lock(const char *path, int operation, LockFile *global, LockFile *local); -int image_name_lock(const char *name, int operation, LockFile *ret); - -int image_set_limit(Image *i, uint64_t referenced_max); diff --git a/src/shared/machine-pool.h b/src/shared/machine-pool.h deleted file mode 100644 index fe01d3d47..000000000 --- a/src/shared/machine-pool.h +++ /dev/null @@ -1,30 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2015 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include "sd-bus.h" - -/* Grow the /var/lib/machines directory after each 10MiB written */ -#define GROW_INTERVAL_BYTES (UINT64_C(10) * UINT64_C(1024) * UINT64_C(1024)) - -int setup_machine_directory(uint64_t size, sd_bus_error *error); -int grow_machine_directory(void); diff --git a/src/shared/path-lookup.c b/src/shared/path-lookup.c deleted file mode 100644 index 3d16e37d0..000000000 --- a/src/shared/path-lookup.c +++ /dev/null @@ -1,353 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include - -#include "util.h" -#include "strv.h" -#include "path-util.h" -#include "path-lookup.h" -#include "install.h" - -int user_config_home(char **config_home) { - const char *e; - char *r; - - e = getenv("XDG_CONFIG_HOME"); - if (e) { - r = strappend(e, "/systemd/user"); - if (!r) - return -ENOMEM; - - *config_home = r; - return 1; - } else { - const char *home; - - home = getenv("HOME"); - if (home) { - r = strappend(home, "/.config/systemd/user"); - if (!r) - return -ENOMEM; - - *config_home = r; - return 1; - } - } - - return 0; -} - -int user_runtime_dir(char **runtime_dir) { - const char *e; - char *r; - - e = getenv("XDG_RUNTIME_DIR"); - if (e) { - r = strappend(e, "/systemd/user"); - if (!r) - return -ENOMEM; - - *runtime_dir = r; - return 1; - } - - return 0; -} - -static int user_data_home_dir(char **dir, const char *suffix) { - const char *e; - char *res; - - /* We don't treat /etc/xdg/systemd here as the spec - * suggests because we assume that that is a link to - * /etc/systemd/ anyway. */ - - e = getenv("XDG_DATA_HOME"); - if (e) - res = strappend(e, suffix); - else { - const char *home; - - home = getenv("HOME"); - if (home) - res = strjoin(home, "/.local/share", suffix, NULL); - else - return 0; - } - if (!res) - return -ENOMEM; - - *dir = res; - return 0; -} - -static char** user_dirs( - const char *generator, - const char *generator_early, - const char *generator_late) { - - const char * const config_unit_paths[] = { - USER_CONFIG_UNIT_PATH, - "/etc/systemd/user", - NULL - }; - - const char * const runtime_unit_path = "/run/systemd/user"; - - const char * const data_unit_paths[] = { - "/usr/local/lib/systemd/user", - "/usr/local/share/systemd/user", - USER_DATA_UNIT_PATH, - "/usr/lib/systemd/user", - "/usr/share/systemd/user", - NULL - }; - - const char *e; - _cleanup_free_ char *config_home = NULL, *runtime_dir = NULL, *data_home = NULL; - _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL; - _cleanup_free_ char **res = NULL; - char **tmp; - int r; - - /* Implement the mechanisms defined in - * - * http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html - * - * We look in both the config and the data dirs because we - * want to encourage that distributors ship their unit files - * as data, and allow overriding as configuration. - */ - - if (user_config_home(&config_home) < 0) - return NULL; - - if (user_runtime_dir(&runtime_dir) < 0) - return NULL; - - e = getenv("XDG_CONFIG_DIRS"); - if (e) { - config_dirs = strv_split(e, ":"); - if (!config_dirs) - return NULL; - } - - r = user_data_home_dir(&data_home, "/systemd/user"); - if (r < 0) - return NULL; - - e = getenv("XDG_DATA_DIRS"); - if (e) - data_dirs = strv_split(e, ":"); - else - data_dirs = strv_new("/usr/local/share", - "/usr/share", - NULL); - if (!data_dirs) - return NULL; - - /* Now merge everything we found. */ - if (generator_early) - if (strv_extend(&res, generator_early) < 0) - return NULL; - - if (config_home) - if (strv_extend(&res, config_home) < 0) - return NULL; - - if (!strv_isempty(config_dirs)) - if (strv_extend_strv_concat(&res, config_dirs, "/systemd/user") < 0) - return NULL; - - if (strv_extend_strv(&res, (char**) config_unit_paths) < 0) - return NULL; - - if (runtime_dir) - if (strv_extend(&res, runtime_dir) < 0) - return NULL; - - if (strv_extend(&res, runtime_unit_path) < 0) - return NULL; - - if (generator) - if (strv_extend(&res, generator) < 0) - return NULL; - - if (data_home) - if (strv_extend(&res, data_home) < 0) - return NULL; - - if (!strv_isempty(data_dirs)) - if (strv_extend_strv_concat(&res, data_dirs, "/systemd/user") < 0) - return NULL; - - if (strv_extend_strv(&res, (char**) data_unit_paths) < 0) - return NULL; - - if (generator_late) - if (strv_extend(&res, generator_late) < 0) - return NULL; - - if (!path_strv_make_absolute_cwd(res)) - return NULL; - - tmp = res; - res = NULL; - return tmp; -} - -int lookup_paths_init( - LookupPaths *p, - SystemdRunningAs running_as, - bool personal, - const char *root_dir, - const char *generator, - const char *generator_early, - const char *generator_late) { - - const char *e; - bool append = false; /* Add items from SYSTEMD_UNIT_PATH before normal directories */ - - assert(p); - - /* First priority is whatever has been passed to us via env - * vars */ - e = getenv("SYSTEMD_UNIT_PATH"); - if (e) { - if (endswith(e, ":")) { - e = strndupa(e, strlen(e) - 1); - append = true; - } - - /* FIXME: empty components in other places should be - * rejected. */ - - p->unit_path = path_split_and_make_absolute(e); - if (!p->unit_path) - return -ENOMEM; - } else - p->unit_path = NULL; - - if (!p->unit_path || append) { - /* Let's figure something out. */ - - _cleanup_strv_free_ char **unit_path; - int r; - - /* For the user units we include share/ in the search - * path in order to comply with the XDG basedir spec. - * For the system stuff we avoid such nonsense. OTOH - * we include /lib in the search path for the system - * stuff but avoid it for user stuff. */ - - if (running_as == SYSTEMD_USER) { - if (personal) - unit_path = user_dirs(generator, generator_early, generator_late); - else - unit_path = strv_new( - /* If you modify this you also want to modify - * systemduserunitpath= in systemd.pc.in, and - * the arrays in user_dirs() above! */ - STRV_IFNOTNULL(generator_early), - USER_CONFIG_UNIT_PATH, - "/etc/systemd/user", - "/run/systemd/user", - STRV_IFNOTNULL(generator), - "/usr/local/lib/systemd/user", - "/usr/local/share/systemd/user", - USER_DATA_UNIT_PATH, - "/usr/lib/systemd/user", - "/usr/share/systemd/user", - STRV_IFNOTNULL(generator_late), - NULL); - } else - unit_path = strv_new( - /* If you modify this you also want to modify - * systemdsystemunitpath= in systemd.pc.in! */ - STRV_IFNOTNULL(generator_early), - SYSTEM_CONFIG_UNIT_PATH, - "/etc/systemd/system", - "/run/systemd/system", - STRV_IFNOTNULL(generator), - "/usr/local/lib/systemd/system", - SYSTEM_DATA_UNIT_PATH, - "/usr/lib/systemd/system", -#ifdef HAVE_SPLIT_USR - "/lib/systemd/system", -#endif - STRV_IFNOTNULL(generator_late), - NULL); - - if (!unit_path) - return -ENOMEM; - - r = strv_extend_strv(&p->unit_path, unit_path); - if (r < 0) - return r; - } - - if (!path_strv_resolve_uniq(p->unit_path, root_dir)) - return -ENOMEM; - - if (!strv_isempty(p->unit_path)) { - _cleanup_free_ char *t = strv_join(p->unit_path, "\n\t"); - if (!t) - return -ENOMEM; - log_debug("Looking for unit files in (higher priority first):\n\t%s", t); - } else { - log_debug("Ignoring unit files."); - strv_free(p->unit_path); - p->unit_path = NULL; - } - - if (running_as == SYSTEMD_SYSTEM) { - log_debug("SysV init scripts and rcN.d links support disabled"); - } - - return 0; -} - -void lookup_paths_free(LookupPaths *p) { - assert(p); - - strv_free(p->unit_path); - p->unit_path = NULL; -} - -int lookup_paths_init_from_scope(LookupPaths *paths, - UnitFileScope scope, - const char *root_dir) { - assert(paths); - assert(scope >= 0); - assert(scope < _UNIT_FILE_SCOPE_MAX); - - zero(*paths); - - return lookup_paths_init(paths, - scope == UNIT_FILE_SYSTEM ? SYSTEMD_SYSTEM : SYSTEMD_USER, - scope == UNIT_FILE_USER, - root_dir, - NULL, NULL, NULL); -} diff --git a/src/shared/seccomp-util.c b/src/shared/seccomp-util.c deleted file mode 100644 index d73a74912..000000000 --- a/src/shared/seccomp-util.c +++ /dev/null @@ -1,89 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -#include "util.h" -#include "seccomp-util.h" - -const char* seccomp_arch_to_string(uint32_t c) { - - if (c == SCMP_ARCH_NATIVE) - return "native"; - if (c == SCMP_ARCH_X86) - return "x86"; - if (c == SCMP_ARCH_X86_64) - return "x86-64"; - if (c == SCMP_ARCH_X32) - return "x32"; - if (c == SCMP_ARCH_ARM) - return "arm"; - - return NULL; -} - -int seccomp_arch_from_string(const char *n, uint32_t *ret) { - if (!n) - return -EINVAL; - - assert(ret); - - if (streq(n, "native")) - *ret = SCMP_ARCH_NATIVE; - else if (streq(n, "x86")) - *ret = SCMP_ARCH_X86; - else if (streq(n, "x86-64")) - *ret = SCMP_ARCH_X86_64; - else if (streq(n, "x32")) - *ret = SCMP_ARCH_X32; - else if (streq(n, "arm")) - *ret = SCMP_ARCH_ARM; - else - return -EINVAL; - - return 0; -} - -int seccomp_add_secondary_archs(scmp_filter_ctx *c) { - -#if defined(__i386__) || defined(__x86_64__) - int r; - - /* Add in all possible secondary archs we are aware of that - * this kernel might support. */ - - r = seccomp_arch_add(c, SCMP_ARCH_X86); - if (r < 0 && r != -EEXIST) - return r; - - r = seccomp_arch_add(c, SCMP_ARCH_X86_64); - if (r < 0 && r != -EEXIST) - return r; - - r = seccomp_arch_add(c, SCMP_ARCH_X32); - if (r < 0 && r != -EEXIST) - return r; - -#endif - - return 0; - -} diff --git a/src/shared/seccomp-util.h b/src/shared/seccomp-util.h deleted file mode 100644 index 60d97154e..000000000 --- a/src/shared/seccomp-util.h +++ /dev/null @@ -1,29 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -const char* seccomp_arch_to_string(uint32_t c); -int seccomp_arch_from_string(const char *n, uint32_t *ret); - -int seccomp_add_secondary_archs(scmp_filter_ctx *c); diff --git a/src/shared/securebits.h b/src/shared/securebits.h deleted file mode 100644 index 98fbe0d43..000000000 --- a/src/shared/securebits.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef _LINUX_SECUREBITS_H -#define _LINUX_SECUREBITS_H 1 - -/* This is minimal version of Linux' linux/securebits.h header file, - * which is licensed GPL2 */ - -#define SECUREBITS_DEFAULT 0x00000000 - -/* When set UID 0 has no special privileges. When unset, we support - inheritance of root-permissions and suid-root executable under - compatibility mode. We raise the effective and inheritable bitmasks - *of the executable file* if the effective uid of the new process is - 0. If the real uid is 0, we raise the effective (legacy) bit of the - executable file. */ -#define SECURE_NOROOT 0 -#define SECURE_NOROOT_LOCKED 1 /* make bit-0 immutable */ - -/* When set, setuid to/from uid 0 does not trigger capability-"fixup". - When unset, to provide compatibility with old programs relying on - set*uid to gain/lose privilege, transitions to/from uid 0 cause - capabilities to be gained/lost. */ -#define SECURE_NO_SETUID_FIXUP 2 -#define SECURE_NO_SETUID_FIXUP_LOCKED 3 /* make bit-2 immutable */ - -/* When set, a process can retain its capabilities even after - transitioning to a non-root user (the set-uid fixup suppressed by - bit 2). Bit-4 is cleared when a process calls exec(); setting both - bit 4 and 5 will create a barrier through exec that no exec()'d - child can use this feature again. */ -#define SECURE_KEEP_CAPS 4 -#define SECURE_KEEP_CAPS_LOCKED 5 /* make bit-4 immutable */ - -/* Each securesetting is implemented using two bits. One bit specifies - whether the setting is on or off. The other bit specify whether the - setting is locked or not. A setting which is locked cannot be - changed from user-level. */ -#define issecure_mask(X) (1 << (X)) -#define issecure(X) (issecure_mask(X) & current_cred_xxx(securebits)) - -#define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \ - issecure_mask(SECURE_NO_SETUID_FIXUP) | \ - issecure_mask(SECURE_KEEP_CAPS)) -#define SECURE_ALL_LOCKS (SECURE_ALL_BITS << 1) - -#endif /* !_LINUX_SECUREBITS_H */ diff --git a/src/shared/spawn-ask-password-agent.c b/src/shared/spawn-ask-password-agent.c deleted file mode 100644 index 70466d17e..000000000 --- a/src/shared/spawn-ask-password-agent.c +++ /dev/null @@ -1,64 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2011 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include - -#include "log.h" -#include "util.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; - - r = fork_agent(&agent_pid, - NULL, 0, - SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, - SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL); - if (r < 0) - log_error_errno(r, "Failed to fork TTY ask password agent: %m"); - - return r; -} - -void ask_password_agent_close(void) { - - if (agent_pid <= 0) - return; - - /* Inform agent that we are done */ - kill(agent_pid, SIGTERM); - kill(agent_pid, SIGCONT); - (void) wait_for_terminate(agent_pid, NULL); - agent_pid = 0; -} diff --git a/src/shared/spawn-ask-password-agent.h b/src/shared/spawn-ask-password-agent.h deleted file mode 100644 index 31b4beab5..000000000 --- a/src/shared/spawn-ask-password-agent.h +++ /dev/null @@ -1,25 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2011 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -int ask_password_agent_open(void); -void ask_password_agent_close(void); diff --git a/src/shared/specifier.c b/src/shared/specifier.c deleted file mode 100644 index 85bd477f2..000000000 --- a/src/shared/specifier.c +++ /dev/null @@ -1,183 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "macro.h" -#include "util.h" -#include "hostname-util.h" -#include "specifier.h" - -/* - * Generic infrastructure for replacing %x style specifiers in - * strings. Will call a callback for each replacement. - * - */ - -int specifier_printf(const char *text, const Specifier table[], void *userdata, char **_ret) { - char *ret, *t; - const char *f; - bool percent = false; - size_t l; - int r; - - assert(text); - assert(table); - - l = strlen(text); - ret = new(char, l+1); - if (!ret) - return -ENOMEM; - - t = ret; - - for (f = text; *f; f++, l--) { - - if (percent) { - if (*f == '%') - *(t++) = '%'; - else { - const Specifier *i; - - for (i = table; i->specifier; i++) - if (i->specifier == *f) - break; - - if (i->lookup) { - _cleanup_free_ char *w = NULL; - char *n; - size_t k, j; - - r = i->lookup(i->specifier, i->data, userdata, &w); - if (r < 0) { - free(ret); - return r; - } - - j = t - ret; - k = strlen(w); - - n = new(char, j + k + l + 1); - if (!n) { - free(ret); - return -ENOMEM; - } - - memcpy(n, ret, j); - memcpy(n + j, w, k); - - free(ret); - - ret = n; - t = n + j + k; - } else { - *(t++) = '%'; - *(t++) = *f; - } - } - - percent = false; - } else if (*f == '%') - percent = true; - else - *(t++) = *f; - } - - *t = 0; - *_ret = ret; - return 0; -} - -/* Generic handler for simple string replacements */ - -int specifier_string(char specifier, void *data, void *userdata, char **ret) { - char *n; - - n = strdup(strempty(data)); - if (!n) - return -ENOMEM; - - *ret = n; - return 0; -} - -int specifier_machine_id(char specifier, void *data, void *userdata, char **ret) { - sd_id128_t id; - char *n; - int r; - - r = sd_id128_get_machine(&id); - if (r < 0) - return r; - - n = new(char, 33); - if (!n) - return -ENOMEM; - - *ret = sd_id128_to_string(id, n); - return 0; -} - -int specifier_boot_id(char specifier, void *data, void *userdata, char **ret) { - sd_id128_t id; - char *n; - int r; - - r = sd_id128_get_boot(&id); - if (r < 0) - return r; - - n = new(char, 33); - if (!n) - return -ENOMEM; - - *ret = sd_id128_to_string(id, n); - return 0; -} - -int specifier_host_name(char specifier, void *data, void *userdata, char **ret) { - char *n; - - n = gethostname_malloc(); - if (!n) - return -ENOMEM; - - *ret = n; - return 0; -} - -int specifier_kernel_release(char specifier, void *data, void *userdata, char **ret) { - struct utsname uts; - char *n; - int r; - - r = uname(&uts); - if (r < 0) - return -errno; - - n = strdup(uts.release); - if (!n) - return -ENOMEM; - - *ret = n; - return 0; -} diff --git a/src/shared/specifier.h b/src/shared/specifier.h deleted file mode 100644 index fca206f66..000000000 --- a/src/shared/specifier.h +++ /dev/null @@ -1,39 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -typedef int (*SpecifierCallback)(char specifier, void *data, void *userdata, char **ret); - -typedef struct Specifier { - const char specifier; - const SpecifierCallback lookup; - void *data; -} Specifier; - -int specifier_printf(const char *text, const Specifier table[], void *userdata, char **ret); - -int specifier_string(char specifier, void *data, void *userdata, char **ret); - -int specifier_machine_id(char specifier, void *data, void *userdata, char **ret); -int specifier_boot_id(char specifier, void *data, void *userdata, char **ret); -int specifier_host_name(char specifier, void *data, void *userdata, char **ret); -int specifier_kernel_release(char specifier, void *data, void *userdata, char **ret); diff --git a/src/shared/switch-root.c b/src/shared/switch-root.c deleted file mode 100644 index b12189cd1..000000000 --- a/src/shared/switch-root.c +++ /dev/null @@ -1,152 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -/*** - This file is part of systemd. - - Copyright 2012 Harald Hoyer, Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include -#include -#include -#include - -#include "util.h" -#include "path-util.h" -#include "mkdir.h" -#include "rm-rf.h" -#include "base-filesystem.h" -#include "missing.h" -#include "switch-root.h" - -int switch_root(const char *new_root, const char *oldroot, bool detach_oldroot, unsigned long mountflags) { - - /* Don't try to unmount/move the old "/", there's no way to do it. */ - static const char move_mounts[] = - "/dev\0" - "/proc\0" - "/sys\0" - "/run\0"; - - _cleanup_close_ int old_root_fd = -1; - struct stat new_root_stat; - bool old_root_remove; - const char *i, *temporary_old_root; - - if (path_equal(new_root, "/")) - return 0; - - temporary_old_root = strjoina(new_root, oldroot); - mkdir_p_label(temporary_old_root, 0755); - - old_root_remove = in_initrd(); - - if (stat(new_root, &new_root_stat) < 0) - return log_error_errno(errno, "Failed to stat directory %s: %m", new_root); - - /* Work-around for kernel design: the kernel refuses switching - * root if any file systems are mounted MS_SHARED. Hence - * remount them MS_PRIVATE here as a work-around. - * - * https://bugzilla.redhat.com/show_bug.cgi?id=847418 */ - if (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL) < 0) - log_warning_errno(errno, "Failed to make \"/\" private mount: %m"); - - NULSTR_FOREACH(i, move_mounts) { - char new_mount[PATH_MAX]; - struct stat sb; - - snprintf(new_mount, sizeof(new_mount), "%s%s", new_root, i); - - mkdir_p_label(new_mount, 0755); - - if ((stat(new_mount, &sb) < 0) || - sb.st_dev != new_root_stat.st_dev) { - - /* Mount point seems to be mounted already or - * stat failed. Unmount the old mount - * point. */ - if (umount2(i, MNT_DETACH) < 0) - log_warning_errno(errno, "Failed to unmount %s: %m", i); - continue; - } - - if (mount(i, new_mount, NULL, mountflags, NULL) < 0) { - if (mountflags & MS_MOVE) { - log_error_errno(errno, "Failed to move mount %s to %s, forcing unmount: %m", i, new_mount); - - if (umount2(i, MNT_FORCE) < 0) - log_warning_errno(errno, "Failed to unmount %s: %m", i); - } - if (mountflags & MS_BIND) - log_error_errno(errno, "Failed to bind mount %s to %s: %m", i, new_mount); - - } - } - - /* Do not fail, if base_filesystem_create() fails. Not all - * switch roots are like base_filesystem_create() wants them - * to look like. They might even boot, if they are RO and - * don't have the FS layout. Just ignore the error and - * switch_root() nevertheless. */ - (void) base_filesystem_create(new_root, UID_INVALID, GID_INVALID); - - if (chdir(new_root) < 0) - return log_error_errno(errno, "Failed to change directory to %s: %m", new_root); - - if (old_root_remove) { - old_root_fd = open("/", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY|O_DIRECTORY); - if (old_root_fd < 0) - log_warning_errno(errno, "Failed to open root directory: %m"); - } - - /* We first try a pivot_root() so that we can umount the old - * root dir. In many cases (i.e. where rootfs is /), that's - * not possible however, and hence we simply overmount root */ - if (pivot_root(new_root, temporary_old_root) >= 0) { - - /* Immediately get rid of the old root, if detach_oldroot is set. - * Since we are running off it we need to do this lazily. */ - if (detach_oldroot && umount2(oldroot, MNT_DETACH) < 0) - log_error_errno(errno, "Failed to lazily umount old root dir %s, %s: %m", - oldroot, - errno == ENOENT ? "ignoring" : "leaving it around"); - - } else if (mount(new_root, "/", NULL, MS_MOVE, NULL) < 0) - return log_error_errno(errno, "Failed to mount moving %s to /: %m", new_root); - - if (chroot(".") < 0) - return log_error_errno(errno, "Failed to change root: %m"); - - if (chdir("/") < 0) - return log_error_errno(errno, "Failed to change directory: %m"); - - if (old_root_fd >= 0) { - struct stat rb; - - if (fstat(old_root_fd, &rb) < 0) - log_warning_errno(errno, "Failed to stat old root directory, leaving: %m"); - else { - (void) rm_rf_children(old_root_fd, 0, &rb); - old_root_fd = -1; - } - } - - return 0; -} diff --git a/src/shared/switch-root.h b/src/shared/switch-root.h deleted file mode 100644 index adf893a92..000000000 --- a/src/shared/switch-root.h +++ /dev/null @@ -1,24 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2012 Harald Hoyer, Lennart Poettering - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -int switch_root(const char *new_root, const char *oldroot, bool detach_oldroot, unsigned long mountflags); diff --git a/src/shared/unaligned.h b/src/shared/unaligned.h deleted file mode 100644 index d6181dd9a..000000000 --- a/src/shared/unaligned.h +++ /dev/null @@ -1,66 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#pragma once - -/*** - This file is part of systemd. - - Copyright 2014 Tom Gundersen - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include - -static inline uint16_t unaligned_read_be16(const void *_u) { - const uint8_t *u = _u; - - return (((uint16_t) u[0]) << 8) | - ((uint16_t) u[1]); -} - -static inline uint32_t unaligned_read_be32(const void *_u) { - const uint8_t *u = _u; - - return (((uint32_t) unaligned_read_be16(u)) << 16) | - ((uint32_t) unaligned_read_be16(u + 2)); -} - -static inline uint64_t unaligned_read_be64(const void *_u) { - const uint8_t *u = _u; - - return (((uint64_t) unaligned_read_be32(u)) << 32) | - ((uint64_t) unaligned_read_be32(u + 4)); -} - -static inline void unaligned_write_be16(void *_u, uint16_t a) { - uint8_t *u = _u; - - u[0] = (uint8_t) (a >> 8); - u[1] = (uint8_t) a; -} - -static inline void unaligned_write_be32(void *_u, uint32_t a) { - uint8_t *u = _u; - - unaligned_write_be16(u, (uint16_t) (a >> 16)); - unaligned_write_be16(u + 2, (uint16_t) a); -} - -static inline void unaligned_write_be64(void *_u, uint64_t a) { - uint8_t *u = _u; - - unaligned_write_be32(u, (uint32_t) (a >> 32)); - unaligned_write_be32(u + 4, (uint32_t) a); -} diff --git a/src/systemd/sd-pppoe.h b/src/systemd/sd-pppoe.h deleted file mode 100644 index 318d2f033..000000000 --- a/src/systemd/sd-pppoe.h +++ /dev/null @@ -1,53 +0,0 @@ -/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ - -#ifndef foosdpppoefoo -#define foosdpppoefoo - -/*** - This file is part of systemd. - - Copyright (C) 2014 Tom Gundersen - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "sd-event.h" - -#include "sparse-endian.h" - -enum { - PPPOE_EVENT_RUNNING = 0, - PPPOE_EVENT_STOPPED = 1, -}; - -typedef struct sd_pppoe sd_pppoe; -typedef void (*sd_pppoe_cb_t)(sd_pppoe *ppp, int event, void *userdata); - -int sd_pppoe_detach_event(sd_pppoe *ppp); -int sd_pppoe_attach_event(sd_pppoe *ppp, sd_event *event, int priority); -int sd_pppoe_get_channel(sd_pppoe *ppp, int *channel); -int sd_pppoe_set_callback(sd_pppoe *ppp, sd_pppoe_cb_t cb, void *userdata); -int sd_pppoe_set_ifindex(sd_pppoe *ppp, int ifindex); -int sd_pppoe_set_ifname(sd_pppoe *ppp, const char *ifname); -int sd_pppoe_set_service_name(sd_pppoe *ppp, const char *service_name); -int sd_pppoe_start(sd_pppoe *ppp); -int sd_pppoe_stop(sd_pppoe *ppp); -sd_pppoe *sd_pppoe_ref(sd_pppoe *ppp); -sd_pppoe *sd_pppoe_unref(sd_pppoe *ppp); -int sd_pppoe_new (sd_pppoe **ret); - -#endif diff --git a/src/test/test-process-util.c b/src/test/test-process-util.c deleted file mode 100644 index e4e2efecd..000000000 --- a/src/test/test-process-util.c +++ /dev/null @@ -1,138 +0,0 @@ -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - Copyright 2013 Thomas H.P. Andersen - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include -#include -#include - -#include "process-util.h" -#include "log.h" -#include "util.h" -#include "macro.h" -#include "virt.h" -#include "terminal-util.h" - -static void test_get_process_comm(void) { - struct stat st; - _cleanup_free_ char *a = NULL, *c = NULL, *d = NULL, *f = NULL, *i = NULL, *cwd = NULL, *root = NULL; - _cleanup_free_ char *env = NULL; - pid_t e; - uid_t u; - gid_t g; - dev_t h; - int r; - pid_t me; - - if (stat("/proc/1/comm", &st) == 0) { - assert_se(get_process_comm(1, &a) >= 0); - log_info("pid1 comm: '%s'", a); - } else - log_warning("/proc/1/comm does not exist."); - - assert_se(get_process_cmdline(1, 0, true, &c) >= 0); - log_info("pid1 cmdline: '%s'", c); - - assert_se(get_process_cmdline(1, 8, false, &d) >= 0); - log_info("pid1 cmdline truncated: '%s'", d); - - assert_se(get_parent_of_pid(1, &e) >= 0); - log_info("pid1 ppid: "PID_FMT, e); - assert_se(e == 0); - - assert_se(is_kernel_thread(1) == 0); - - r = get_process_exe(1, &f); - assert_se(r >= 0 || r == -EACCES); - log_info("pid1 exe: '%s'", strna(f)); - - assert_se(get_process_uid(1, &u) == 0); - log_info("pid1 uid: "UID_FMT, u); - assert_se(u == 0); - - assert_se(get_process_gid(1, &g) == 0); - log_info("pid1 gid: "GID_FMT, g); - assert_se(g == 0); - - me = getpid(); - - r = get_process_cwd(me, &cwd); - assert_se(r >= 0 || r == -EACCES); - log_info("pid1 cwd: '%s'", cwd); - - r = get_process_root(me, &root); - assert_se(r >= 0 || r == -EACCES); - log_info("pid1 root: '%s'", root); - - r = get_process_environ(me, &env); - assert_se(r >= 0 || r == -EACCES); - log_info("self strlen(environ): '%zu'", strlen(env)); - - if (!detect_container(NULL)) - assert_se(get_ctty_devnr(1, &h) == -ENXIO); - - getenv_for_pid(1, "PATH", &i); - log_info("pid1 $PATH: '%s'", strna(i)); -} - -static void test_pid_is_unwaited(void) { - pid_t pid; - - pid = fork(); - assert_se(pid >= 0); - if (pid == 0) { - _exit(EXIT_SUCCESS); - } else { - int status; - - waitpid(pid, &status, 0); - assert_se(!pid_is_unwaited(pid)); - } - assert_se(pid_is_unwaited(getpid())); - assert_se(!pid_is_unwaited(-1)); -} - -static void test_pid_is_alive(void) { - pid_t pid; - - pid = fork(); - assert_se(pid >= 0); - if (pid == 0) { - _exit(EXIT_SUCCESS); - } else { - int status; - - waitpid(pid, &status, 0); - assert_se(!pid_is_alive(pid)); - } - assert_se(pid_is_alive(getpid())); - assert_se(!pid_is_alive(-1)); -} - -int main(int argc, char *argv[]) { - log_parse_environment(); - log_open(); - - test_get_process_comm(); - test_pid_is_unwaited(); - test_pid_is_alive(); - - return 0; -} diff --git a/src/test/test-terminal-util.c b/src/test/test-terminal-util.c deleted file mode 100644 index d81fdb992..000000000 --- a/src/test/test-terminal-util.c +++ /dev/null @@ -1,84 +0,0 @@ -/*** - This file is part of systemd. - - Copyright 2010 Lennart Poettering - Copyright 2013 Thomas H.P. Andersen - - systemd is free software; you can redistribute it and/or modify it - under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 2.1 of the License, or - (at your option) any later version. - - systemd is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with systemd; If not, see . -***/ - -#include -#include - -#include "terminal-util.h" -#include "macro.h" -#include "util.h" -#include "log.h" - -static void test_default_term_for_tty(void) { - puts(default_term_for_tty("/dev/tty23")); - puts(default_term_for_tty("/dev/ttyS23")); - puts(default_term_for_tty("/dev/tty0")); - puts(default_term_for_tty("/dev/pty0")); - puts(default_term_for_tty("/dev/pts/0")); - puts(default_term_for_tty("/dev/console")); - puts(default_term_for_tty("tty23")); - puts(default_term_for_tty("ttyS23")); - puts(default_term_for_tty("tty0")); - puts(default_term_for_tty("pty0")); - puts(default_term_for_tty("pts/0")); - puts(default_term_for_tty("console")); -} - -static void test_read_one_char(void) { - _cleanup_fclose_ FILE *file = NULL; - char r; - bool need_nl; - char name[] = "/tmp/test-read_one_char.XXXXXX"; - int fd; - - fd = mkostemp_safe(name, O_RDWR|O_CLOEXEC); - assert_se(fd >= 0); - file = fdopen(fd, "r+"); - assert_se(file); - assert_se(fputs("c\n", file) >= 0); - rewind(file); - - assert_se(read_one_char(file, &r, 1000000, &need_nl) >= 0); - assert_se(!need_nl); - assert_se(r == 'c'); - assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); - - rewind(file); - assert_se(fputs("foobar\n", file) >= 0); - rewind(file); - assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); - - rewind(file); - assert_se(fputs("\n", file) >= 0); - rewind(file); - assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); - - unlink(name); -} - -int main(int argc, char *argv[]) { - log_parse_environment(); - log_open(); - - test_default_term_for_tty(); - test_read_one_char(); - - return 0; -} diff --git a/tmpfiles.d/home.conf b/tmpfiles.d/home.conf deleted file mode 100644 index aa652b197..000000000 --- a/tmpfiles.d/home.conf +++ /dev/null @@ -1,11 +0,0 @@ -# This file is part of systemd. -# -# systemd is free software; you can redistribute it and/or modify it -# under the terms of the GNU Lesser General Public License as published by -# the Free Software Foundation; either version 2.1 of the License, or -# (at your option) any later version. - -# See tmpfiles.d(5) for details - -v /home 0755 - - - -v /srv 0755 - - -