diff options
author | Luke Shumaker <lukeshu@sbcglobal.net> | 2016-10-26 22:01:39 -0400 |
---|---|---|
committer | Luke Shumaker <lukeshu@sbcglobal.net> | 2016-10-26 22:01:39 -0400 |
commit | f753633383c0a879b9dc42ee37b38e33730e3e44 (patch) | |
tree | d0a7022079649a7a56344cfed09356bf76bde8ab /src/libsystemd | |
parent | 042468f48fa4b7de28fd51c4416af31f6be2dfde (diff) |
./tools/notsd-move
Diffstat (limited to 'src/libsystemd')
250 files changed, 35043 insertions, 3996 deletions
diff --git a/src/libsystemd/Makefile b/src/libsystemd/Makefile index d0b0e8e008..599a872f58 120000..100644 --- a/src/libsystemd/Makefile +++ b/src/libsystemd/Makefile @@ -1 +1,103 @@ -../Makefile
\ No newline at end of file +# -*- Mode: makefile; indent-tabs-mode: t -*- +# +# This file is part of systemd. +# +# Copyright 2010-2012 Lennart Poettering +# Copyright 2010-2012 Kay Sievers +# Copyright 2013 Zbigniew Jędrzejewski-Szmek +# Copyright 2013 David Strauss +# Copyright 2016 Luke Shumaker +# +# 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 <http://www.gnu.org/licenses/>. +include $(dir $(lastword $(MAKEFILE_LIST)))/../../config.mk +include $(topsrcdir)/build-aux/Makefile.head.mk + +LIBSYSTEMD_CURRENT=16 +LIBSYSTEMD_REVISION=0 +LIBSYSTEMD_AGE=16 + +EXTRA_DIST += \ + src/libsystemd/libsystemd.pc.in \ + src/libsystemd/sd-bus/DIFFERENCES \ + src/libsystemd/sd-bus/GVARIANT-SERIALIZATION + +libsystemd_la_SOURCES = + +libsystemd_la_LDFLAGS = \ + -version-info $(LIBSYSTEMD_CURRENT):$(LIBSYSTEMD_REVISION):$(LIBSYSTEMD_AGE) \ + -Wl,--version-script=$(srcdir)/libsystemd.sym + +libsystemd_la_LIBADD = \ + libsystemd-internal.la \ + libsystemd-basic.la \ + libsystemd-journal-internal.la + +pkgconfiglib_DATA += \ + src/libsystemd/libsystemd.pc + +pkginclude_HEADERS += \ + src/systemd/sd-bus.h \ + src/systemd/sd-bus-protocol.h \ + src/systemd/sd-bus-vtable.h \ + src/systemd/sd-event.h \ + src/systemd/sd-login.h \ + src/systemd/sd-id128.h \ + src/systemd/sd-daemon.h + +lib_LTLIBRARIES += \ + libsystemd.la + +# ------------------------------------------------------------------------------ + +tests += \ + test-bus-marshal \ + test-bus-signature \ + test-bus-benchmark \ + test-bus-chat \ + test-bus-cleanup \ + test-bus-server \ + test-bus-match \ + test-bus-kernel \ + test-bus-kernel-bloom \ + test-bus-zero-copy \ + test-bus-introspect \ + test-bus-objects \ + test-bus-error \ + test-bus-creds \ + test-bus-gvariant \ + test-event \ + test-netlink \ + test-local-addresses \ + test-resolve + +test-libsystemd-sym.c: \ + $(top_builddir)/src/libsystemd/libsystemd.sym \ + src/systemd/sd-journal.h \ + src/systemd/sd-daemon.h \ + src/systemd/sd-login.h \ + src/systemd/sd-bus.h \ + src/systemd/sd-utf8.h \ + src/systemd/sd-resolve.h \ + src/systemd/sd-path.h \ + src/systemd/sd-event.h + $(generate-sym-test) + +nodist_test_libsystemd_sym_SOURCES = \ + test-libsystemd-sym.c +test_libsystemd_sym_LDADD = \ + libsystemd.la + +nested.subdirs += src + +include $(topsrcdir)/build-aux/Makefile.tail.mk diff --git a/src/libsystemd/include-staging/systemd-staging/sd-device.h b/src/libsystemd/include-staging/systemd-staging/sd-device.h new file mode 100644 index 0000000000..5e32fc6110 --- /dev/null +++ b/src/libsystemd/include-staging/systemd-staging/sd-device.h @@ -0,0 +1,101 @@ +#ifndef foosddevicehfoo +#define foosddevicehfoo + +/*** + This file is part of systemd. + + Copyright 2008-2012 Kay Sievers <kay@vrfy.org> + Copyright 2014-2015 Tom Gundersen <teg@jklm.no> + + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <sys/sysmacros.h> +#include <sys/types.h> + +#include <systemd/_sd-common.h> + +_SD_BEGIN_DECLARATIONS; + +typedef struct sd_device sd_device; +typedef struct sd_device_enumerator sd_device_enumerator; + +/* device */ + +sd_device *sd_device_ref(sd_device *device); +sd_device *sd_device_unref(sd_device *device); + +int sd_device_new_from_syspath(sd_device **ret, const char *syspath); +int sd_device_new_from_devnum(sd_device **ret, char type, dev_t devnum); +int sd_device_new_from_subsystem_sysname(sd_device **ret, const char *subsystem, const char *sysname); +int sd_device_new_from_device_id(sd_device **ret, const char *id); + +int sd_device_get_parent(sd_device *child, sd_device **ret); +int sd_device_get_parent_with_subsystem_devtype(sd_device *child, const char *subsystem, const char *devtype, sd_device **ret); + +int sd_device_get_syspath(sd_device *device, const char **ret); +int sd_device_get_subsystem(sd_device *device, const char **ret); +int sd_device_get_devtype(sd_device *device, const char **ret); +int sd_device_get_devnum(sd_device *device, dev_t *devnum); +int sd_device_get_ifindex(sd_device *device, int *ifindex); +int sd_device_get_driver(sd_device *device, const char **ret); +int sd_device_get_devpath(sd_device *device, const char **ret); +int sd_device_get_devname(sd_device *device, const char **ret); +int sd_device_get_sysname(sd_device *device, const char **ret); +int sd_device_get_sysnum(sd_device *device, const char **ret); + +int sd_device_get_is_initialized(sd_device *device, int *initialized); +int sd_device_get_usec_since_initialized(sd_device *device, uint64_t *usec); + +const char *sd_device_get_tag_first(sd_device *device); +const char *sd_device_get_tag_next(sd_device *device); +const char *sd_device_get_devlink_first(sd_device *device); +const char *sd_device_get_devlink_next(sd_device *device); +const char *sd_device_get_property_first(sd_device *device, const char **value); +const char *sd_device_get_property_next(sd_device *device, const char **value); +const char *sd_device_get_sysattr_first(sd_device *device); +const char *sd_device_get_sysattr_next(sd_device *device); + +int sd_device_has_tag(sd_device *device, const char *tag); +int sd_device_get_property_value(sd_device *device, const char *key, const char **value); +int sd_device_get_sysattr_value(sd_device *device, const char *sysattr, const char **_value); + +int sd_device_set_sysattr_value(sd_device *device, const char *sysattr, char *value); + +/* device enumerator */ + +int sd_device_enumerator_new(sd_device_enumerator **ret); +sd_device_enumerator *sd_device_enumerator_ref(sd_device_enumerator *enumerator); +sd_device_enumerator *sd_device_enumerator_unref(sd_device_enumerator *enumerator); + +sd_device *sd_device_enumerator_get_device_first(sd_device_enumerator *enumerator); +sd_device *sd_device_enumerator_get_device_next(sd_device_enumerator *enumerator); +sd_device *sd_device_enumerator_get_subsystem_first(sd_device_enumerator *enumerator); +sd_device *sd_device_enumerator_get_subsystem_next(sd_device_enumerator *enumerator); + +int sd_device_enumerator_add_match_subsystem(sd_device_enumerator *enumerator, const char *subsystem, int match); +int sd_device_enumerator_add_match_sysattr(sd_device_enumerator *enumerator, const char *sysattr, const char *value, int match); +int sd_device_enumerator_add_match_property(sd_device_enumerator *enumerator, const char *property, const char *value); +int sd_device_enumerator_add_match_sysname(sd_device_enumerator *enumerator, const char *sysname); +int sd_device_enumerator_add_match_tag(sd_device_enumerator *enumerator, const char *tag); +int sd_device_enumerator_add_match_parent(sd_device_enumerator *enumerator, sd_device *parent); +int sd_device_enumerator_allow_uninitialized(sd_device_enumerator *enumerator); + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_device, sd_device_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_device_enumerator, sd_device_enumerator_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include-staging/systemd-staging/sd-hwdb.h b/src/libsystemd/include-staging/systemd-staging/sd-hwdb.h new file mode 100644 index 0000000000..f46d7ad561 --- /dev/null +++ b/src/libsystemd/include-staging/systemd-staging/sd-hwdb.h @@ -0,0 +1,49 @@ +#ifndef foosdhwdbhfoo +#define foosdhwdbhfoo + +/*** + This file is part of systemd. + + Copyright 2008-2012 Kay Sievers <kay@vrfy.org> + Copyright 2014 Tom Gundersen <teg@jklm.no> + + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <systemd/_sd-common.h> + +_SD_BEGIN_DECLARATIONS; + +typedef struct sd_hwdb sd_hwdb; + +sd_hwdb *sd_hwdb_ref(sd_hwdb *hwdb); +sd_hwdb *sd_hwdb_unref(sd_hwdb *hwdb); + +int sd_hwdb_new(sd_hwdb **ret); + +int sd_hwdb_get(sd_hwdb *hwdb, const char *modalias, const char *key, const char **value); + +int sd_hwdb_seek(sd_hwdb *hwdb, const char *modalias); +int sd_hwdb_enumerate(sd_hwdb *hwdb, const char **key, const char **value); + +/* the inverse condition avoids ambiguity of dangling 'else' after the macro */ +#define SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value) \ + if (sd_hwdb_seek(hwdb, modalias) < 0) { } \ + else while (sd_hwdb_enumerate(hwdb, &(key), &(value)) > 0) + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_hwdb, sd_hwdb_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include-staging/systemd-staging/sd-netlink.h b/src/libsystemd/include-staging/systemd-staging/sd-netlink.h new file mode 100644 index 0000000000..8a8c85a004 --- /dev/null +++ b/src/libsystemd/include-staging/systemd-staging/sd-netlink.h @@ -0,0 +1,163 @@ +#ifndef foosdnetlinkhfoo +#define foosdnetlinkhfoo + +/*** + This file is part of systemd. + + Copyright 2013 Tom Gundersen <teg@jklm.no> + + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <netinet/ether.h> +#include <netinet/in.h> + +#include <linux/rtnetlink.h> +#include <linux/neighbour.h> + +#include <systemd/_sd-common.h> +#include <systemd/sd-event.h> + +_SD_BEGIN_DECLARATIONS; + +typedef struct sd_netlink sd_netlink; +typedef struct sd_netlink_message sd_netlink_message; + +/* callback */ + +typedef int (*sd_netlink_message_handler_t)(sd_netlink *nl, sd_netlink_message *m, void *userdata); + +/* bus */ +int sd_netlink_new_from_netlink(sd_netlink **nl, int fd); +int sd_netlink_open(sd_netlink **nl); +int sd_netlink_open_fd(sd_netlink **nl, int fd); +int sd_netlink_inc_rcvbuf(sd_netlink *nl, const size_t size); + +sd_netlink *sd_netlink_ref(sd_netlink *nl); +sd_netlink *sd_netlink_unref(sd_netlink *nl); + +int sd_netlink_send(sd_netlink *nl, sd_netlink_message *message, uint32_t *serial); +int sd_netlink_call_async(sd_netlink *nl, sd_netlink_message *message, + sd_netlink_message_handler_t callback, + void *userdata, uint64_t usec, uint32_t *serial); +int sd_netlink_call_async_cancel(sd_netlink *nl, uint32_t serial); +int sd_netlink_call(sd_netlink *nl, sd_netlink_message *message, uint64_t timeout, + sd_netlink_message **reply); + +int sd_netlink_get_events(sd_netlink *nl); +int sd_netlink_get_timeout(sd_netlink *nl, uint64_t *timeout); +int sd_netlink_process(sd_netlink *nl, sd_netlink_message **ret); +int sd_netlink_wait(sd_netlink *nl, uint64_t timeout); + +int sd_netlink_add_match(sd_netlink *nl, uint16_t match, sd_netlink_message_handler_t c, void *userdata); +int sd_netlink_remove_match(sd_netlink *nl, uint16_t match, sd_netlink_message_handler_t c, void *userdata); + +int sd_netlink_attach_event(sd_netlink *nl, sd_event *e, int64_t priority); +int sd_netlink_detach_event(sd_netlink *nl); + +int sd_netlink_message_append_string(sd_netlink_message *m, unsigned short type, const char *data); +int sd_netlink_message_append_flag(sd_netlink_message *m, unsigned short type); +int sd_netlink_message_append_u8(sd_netlink_message *m, unsigned short type, uint8_t data); +int sd_netlink_message_append_u16(sd_netlink_message *m, unsigned short type, uint16_t data); +int sd_netlink_message_append_u32(sd_netlink_message *m, unsigned short type, uint32_t data); +int sd_netlink_message_append_data(sd_netlink_message *m, unsigned short type, const void *data, size_t len); +int sd_netlink_message_append_in_addr(sd_netlink_message *m, unsigned short type, const struct in_addr *data); +int sd_netlink_message_append_in6_addr(sd_netlink_message *m, unsigned short type, const struct in6_addr *data); +int sd_netlink_message_append_ether_addr(sd_netlink_message *m, unsigned short type, const struct ether_addr *data); +int sd_netlink_message_append_cache_info(sd_netlink_message *m, unsigned short type, const struct ifa_cacheinfo *info); + +int sd_netlink_message_open_container(sd_netlink_message *m, unsigned short type); +int sd_netlink_message_open_container_union(sd_netlink_message *m, unsigned short type, const char *key); +int sd_netlink_message_close_container(sd_netlink_message *m); + +int sd_netlink_message_read_string(sd_netlink_message *m, unsigned short type, const char **data); +int sd_netlink_message_read_u8(sd_netlink_message *m, unsigned short type, uint8_t *data); +int sd_netlink_message_read_u16(sd_netlink_message *m, unsigned short type, uint16_t *data); +int sd_netlink_message_read_u32(sd_netlink_message *m, unsigned short type, uint32_t *data); +int sd_netlink_message_read_ether_addr(sd_netlink_message *m, unsigned short type, struct ether_addr *data); +int sd_netlink_message_read_cache_info(sd_netlink_message *m, unsigned short type, struct ifa_cacheinfo *info); +int sd_netlink_message_read_in_addr(sd_netlink_message *m, unsigned short type, struct in_addr *data); +int sd_netlink_message_read_in6_addr(sd_netlink_message *m, unsigned short type, struct in6_addr *data); +int sd_netlink_message_enter_container(sd_netlink_message *m, unsigned short type); +int sd_netlink_message_exit_container(sd_netlink_message *m); + +int sd_netlink_message_rewind(sd_netlink_message *m); + +sd_netlink_message *sd_netlink_message_next(sd_netlink_message *m); + +sd_netlink_message *sd_netlink_message_ref(sd_netlink_message *m); +sd_netlink_message *sd_netlink_message_unref(sd_netlink_message *m); + +int sd_netlink_message_request_dump(sd_netlink_message *m, int dump); +int sd_netlink_message_is_error(sd_netlink_message *m); +int sd_netlink_message_get_errno(sd_netlink_message *m); +int sd_netlink_message_get_type(sd_netlink_message *m, uint16_t *type); +int sd_netlink_message_set_flags(sd_netlink_message *m, uint16_t flags); +int sd_netlink_message_is_broadcast(sd_netlink_message *m); + +/* rtnl */ + +int sd_rtnl_message_new_link(sd_netlink *nl, sd_netlink_message **ret, uint16_t msg_type, int index); +int sd_rtnl_message_new_addr_update(sd_netlink *nl, sd_netlink_message **ret, int index, int family); +int sd_rtnl_message_new_addr(sd_netlink *nl, sd_netlink_message **ret, uint16_t msg_type, int index, int family); +int sd_rtnl_message_new_route(sd_netlink *nl, sd_netlink_message **ret, uint16_t nlmsg_type, int rtm_family, unsigned char rtm_protocol); +int sd_rtnl_message_new_neigh(sd_netlink *nl, sd_netlink_message **ret, uint16_t msg_type, int index, int nda_family); + +int sd_rtnl_message_get_family(sd_netlink_message *m, int *family); + +int sd_rtnl_message_addr_set_prefixlen(sd_netlink_message *m, unsigned char prefixlen); +int sd_rtnl_message_addr_set_scope(sd_netlink_message *m, unsigned char scope); +int sd_rtnl_message_addr_set_flags(sd_netlink_message *m, unsigned char flags); +int sd_rtnl_message_addr_get_family(sd_netlink_message *m, int *family); +int sd_rtnl_message_addr_get_prefixlen(sd_netlink_message *m, unsigned char *prefixlen); +int sd_rtnl_message_addr_get_scope(sd_netlink_message *m, unsigned char *scope); +int sd_rtnl_message_addr_get_flags(sd_netlink_message *m, unsigned char *flags); +int sd_rtnl_message_addr_get_ifindex(sd_netlink_message *m, int *ifindex); + +int sd_rtnl_message_link_set_flags(sd_netlink_message *m, unsigned flags, unsigned change); +int sd_rtnl_message_link_set_type(sd_netlink_message *m, unsigned type); +int sd_rtnl_message_link_set_family(sd_netlink_message *m, unsigned family); +int sd_rtnl_message_link_get_ifindex(sd_netlink_message *m, int *ifindex); +int sd_rtnl_message_link_get_flags(sd_netlink_message *m, unsigned *flags); +int sd_rtnl_message_link_get_type(sd_netlink_message *m, unsigned short *type); + +int sd_rtnl_message_route_set_dst_prefixlen(sd_netlink_message *m, unsigned char prefixlen); +int sd_rtnl_message_route_set_src_prefixlen(sd_netlink_message *m, unsigned char prefixlen); +int sd_rtnl_message_route_set_scope(sd_netlink_message *m, unsigned char scope); +int sd_rtnl_message_route_set_flags(sd_netlink_message *m, unsigned flags); +int sd_rtnl_message_route_set_table(sd_netlink_message *m, unsigned char table); +int sd_rtnl_message_route_get_flags(sd_netlink_message *m, unsigned *flags); +int sd_rtnl_message_route_get_family(sd_netlink_message *m, int *family); +int sd_rtnl_message_route_set_family(sd_netlink_message *m, int family); +int sd_rtnl_message_route_get_protocol(sd_netlink_message *m, unsigned char *protocol); +int sd_rtnl_message_route_get_scope(sd_netlink_message *m, unsigned char *scope); +int sd_rtnl_message_route_get_tos(sd_netlink_message *m, unsigned char *tos); +int sd_rtnl_message_route_get_table(sd_netlink_message *m, unsigned char *table); +int sd_rtnl_message_route_get_dst_prefixlen(sd_netlink_message *m, unsigned char *dst_len); +int sd_rtnl_message_route_get_src_prefixlen(sd_netlink_message *m, unsigned char *src_len); + +int sd_rtnl_message_neigh_set_flags(sd_netlink_message *m, uint8_t flags); +int sd_rtnl_message_neigh_set_state(sd_netlink_message *m, uint16_t state); +int sd_rtnl_message_neigh_get_family(sd_netlink_message *m, int *family); +int sd_rtnl_message_neigh_get_ifindex(sd_netlink_message *m, int *family); +int sd_rtnl_message_neigh_get_state(sd_netlink_message *m, uint16_t *state); +int sd_rtnl_message_neigh_get_flags(sd_netlink_message *m, uint8_t *flags); + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_netlink, sd_netlink_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_netlink_message, sd_netlink_message_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include-staging/systemd-staging/sd-network.h b/src/libsystemd/include-staging/systemd-staging/sd-network.h new file mode 100644 index 0000000000..ac2660de45 --- /dev/null +++ b/src/libsystemd/include-staging/systemd-staging/sd-network.h @@ -0,0 +1,176 @@ +#ifndef foosdnetworkhfoo +#define foosdnetworkhfoo + +/*** + This file is part of systemd. + + Copyright 2011 Lennart Poettering + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <sys/types.h> + +#include <systemd/_sd-common.h> + +/* + * A few points: + * + * Instead of returning an empty string array or empty integer array, we + * may return NULL. + * + * Free the data the library returns with libc free(). String arrays + * are NULL terminated, and you need to free the array itself in + * addition to the strings contained. + * + * We return error codes as negative errno, kernel-style. On success, we + * return 0 or positive. + * + * These functions access data in /run. This is a virtual file system; + * therefore, accesses are relatively cheap. + * + * See sd-network(3) for more information. + */ + +_SD_BEGIN_DECLARATIONS; + +/* Get overall operational state + * Possible states: down, up, dormant, carrier, degraded, routable + * Possible return codes: + * -ENODATA: networkd is not aware of any links + */ +int sd_network_get_operational_state(char **state); + +/* Get DNS entries for all links. These are string representations of + * IP addresses */ +int sd_network_get_dns(char ***dns); + +/* Get NTP entries for all links. These are domain names or string + * representations of IP addresses */ +int sd_network_get_ntp(char ***ntp); + +/* Get the search domains for all links. */ +int sd_network_get_search_domains(char ***domains); + +/* Get the search domains for all links. */ +int sd_network_get_route_domains(char ***domains); + +/* Get setup state from ifindex. + * Possible states: + * pending: udev is still processing the link, we don't yet know if we will manage it + * failed: networkd failed to manage the link + * configuring: in the process of retrieving configuration or configuring the link + * configured: link configured successfully + * unmanaged: networkd is not handling the link + * linger: the link is gone, but has not yet been dropped by networkd + * Possible return codes: + * -ENODATA: networkd is not aware of the link + */ +int sd_network_link_get_setup_state(int ifindex, char **state); + +/* Get operational state from ifindex. + * Possible states: + * off: the device is powered down + * no-carrier: the device is powered up, but it does not yet have a carrier + * dormant: the device has a carrier, but is not yet ready for normal traffic + * carrier: the link has a carrier + * degraded: the link has carrier and addresses valid on the local link configured + * routable: the link has carrier and routable address configured + * Possible return codes: + * -ENODATA: networkd is not aware of the link + */ +int sd_network_link_get_operational_state(int ifindex, char **state); + +/* Get path to .network file applied to link */ +int sd_network_link_get_network_file(int ifindex, char **filename); + +/* Get DNS entries for a given link. These are string representations of + * IP addresses */ +int sd_network_link_get_dns(int ifindex, char ***ret); + +/* Get NTP entries for a given link. These are domain names or string + * representations of IP addresses */ +int sd_network_link_get_ntp(int ifindex, char ***ret); + +/* Indicates whether or not LLMNR should be enabled for the link + * Possible levels of support: yes, no, resolve + * Possible return codes: + * -ENODATA: networkd is not aware of the link + */ +int sd_network_link_get_llmnr(int ifindex, char **llmnr); + +/* Indicates whether or not MulticastDNS should be enabled for the + * link. + * Possible levels of support: yes, no, resolve + * Possible return codes: + * -ENODATA: networkd is not aware of the link + */ +int sd_network_link_get_mdns(int ifindex, char **mdns); + +/* Indicates whether or not DNSSEC should be enabled for the link + * Possible levels of support: yes, no, allow-downgrade + * Possible return codes: + * -ENODATA: networkd is not aware of the link + */ +int sd_network_link_get_dnssec(int ifindex, char **dnssec); + +/* Returns the list of per-interface DNSSEC negative trust anchors + * Possible return codes: + * -ENODATA: networkd is not aware of the link, or has no such data + */ +int sd_network_link_get_dnssec_negative_trust_anchors(int ifindex, char ***nta); + +/* Get the search DNS domain names for a given link. */ +int sd_network_link_get_search_domains(int ifindex, char ***domains); + +/* Get the route DNS domain names for a given link. */ +int sd_network_link_get_route_domains(int ifindex, char ***domains); + +/* Get the carrier interface indexes to which current link is bound to. */ +int sd_network_link_get_carrier_bound_to(int ifindex, int **ifindexes); + +/* Get the CARRIERS that are bound to current link. */ +int sd_network_link_get_carrier_bound_by(int ifindex, int **ifindexes); + +/* Get the timezone that was learnt on a specific link. */ +int sd_network_link_get_timezone(int ifindex, char **timezone); + +/* Monitor object */ +typedef struct sd_network_monitor sd_network_monitor; + +/* Create a new monitor. Category must be NULL, "links" or "leases". */ +int sd_network_monitor_new(sd_network_monitor **ret, const char *category); + +/* Destroys the passed monitor. Returns NULL. */ +sd_network_monitor* sd_network_monitor_unref(sd_network_monitor *m); + +/* Flushes the monitor */ +int sd_network_monitor_flush(sd_network_monitor *m); + +/* Get FD from monitor */ +int sd_network_monitor_get_fd(sd_network_monitor *m); + +/* Get poll() mask to monitor */ +int sd_network_monitor_get_events(sd_network_monitor *m); + +/* Get timeout for poll(), as usec value relative to CLOCK_MONOTONIC's epoch */ +int sd_network_monitor_get_timeout(sd_network_monitor *m, uint64_t *timeout_usec); + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_network_monitor, sd_network_monitor_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include-staging/systemd-staging/sd-resolve.h b/src/libsystemd/include-staging/systemd-staging/sd-resolve.h new file mode 100644 index 0000000000..1996ae401a --- /dev/null +++ b/src/libsystemd/include-staging/systemd-staging/sd-resolve.h @@ -0,0 +1,116 @@ +#ifndef foosdresolvehfoo +#define foosdresolvehfoo + +/*** + This file is part of systemd. + + Copyright 2005-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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <netdb.h> +#include <sys/socket.h> +#include <sys/types.h> + +#include <systemd/_sd-common.h> +#include <systemd/sd-event.h> + +_SD_BEGIN_DECLARATIONS; + +/* An opaque sd-resolve session structure */ +typedef struct sd_resolve sd_resolve; + +/* An opaque sd-resolve query structure */ +typedef struct sd_resolve_query sd_resolve_query; + +/* A callback on completion */ +typedef int (*sd_resolve_getaddrinfo_handler_t)(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata); +typedef int (*sd_resolve_getnameinfo_handler_t)(sd_resolve_query *q, int ret, const char *host, const char *serv, void *userdata); + +enum { + SD_RESOLVE_GET_HOST = UINT64_C(1), + SD_RESOLVE_GET_SERVICE = UINT64_C(2), + SD_RESOLVE_GET_BOTH = UINT64_C(3), +}; + +int sd_resolve_default(sd_resolve **ret); + +/* Allocate a new sd-resolve session. */ +int sd_resolve_new(sd_resolve **ret); + +/* Free a sd-resolve session. This destroys all attached + * sd_resolve_query objects automatically. */ +sd_resolve* sd_resolve_unref(sd_resolve *resolve); +sd_resolve* sd_resolve_ref(sd_resolve *resolve); + +/* Return the UNIX file descriptor to poll() for events on. Use this + * function to integrate sd-resolve with your custom main loop. */ +int sd_resolve_get_fd(sd_resolve *resolve); + +/* Return the poll() events (a combination of flags like POLLIN, + * POLLOUT, ...) to check for. */ +int sd_resolve_get_events(sd_resolve *resolve); + +/* Return the poll() timeout to pass. Returns (uint64_t) -1 as + * timeout if no timeout is needed. */ +int sd_resolve_get_timeout(sd_resolve *resolve, uint64_t *timeout_usec); + +/* Process pending responses. After this function is called, you can + * get the next completed query object(s) using + * sd_resolve_get_next(). */ +int sd_resolve_process(sd_resolve *resolve); + +/* Wait for a resolve event to complete. */ +int sd_resolve_wait(sd_resolve *resolve, uint64_t timeout_usec); + +int sd_resolve_get_tid(sd_resolve *resolve, pid_t *tid); + +int sd_resolve_attach_event(sd_resolve *resolve, sd_event *e, int64_t priority); +int sd_resolve_detach_event(sd_resolve *resolve); +sd_event *sd_resolve_get_event(sd_resolve *resolve); + +/* Issue a name-to-address query on the specified session. The + * arguments are compatible with those of libc's + * getaddrinfo(3). The function returns a new query object. When the + * query is completed, you may retrieve the results using + * sd_resolve_getaddrinfo_done(). */ +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); + +/* Issue an address-to-name query on the specified session. The + * arguments are compatible with those of libc's + * getnameinfo(3). The function returns a new query object. When the + * query is completed, you may retrieve the results using + * sd_resolve_getnameinfo_done(). Set gethost (resp. getserv) to non-zero + * if you want to query the hostname (resp. the service name). */ +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); + +sd_resolve_query *sd_resolve_query_ref(sd_resolve_query* q); +sd_resolve_query *sd_resolve_query_unref(sd_resolve_query* q); + +/* Returns non-zero when the query operation specified by q has been completed. */ +int sd_resolve_query_is_done(sd_resolve_query*q); + +void *sd_resolve_query_get_userdata(sd_resolve_query *q); +void *sd_resolve_query_set_userdata(sd_resolve_query *q, void *userdata); + +sd_resolve *sd_resolve_query_get_resolve(sd_resolve_query *q); + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_resolve, sd_resolve_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_resolve_query, sd_resolve_query_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/_sd-common.h b/src/libsystemd/include/systemd/_sd-common.h new file mode 100644 index 0000000000..3bb886be75 --- /dev/null +++ b/src/libsystemd/include/systemd/_sd-common.h @@ -0,0 +1,83 @@ +#ifndef foosdcommonhfoo +#define foosdcommonhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +/* This is a private header; never even think of including this directly! */ + +#if __INCLUDE_LEVEL__ <= 1 +#error "Do not include _sd-common.h directly; it is a private header." +#endif + +#ifndef _sd_printf_ +# if __GNUC__ >= 4 +# define _sd_printf_(a,b) __attribute__ ((format (printf, a, b))) +# else +# define _sd_printf_(a,b) +# endif +#endif + +#ifndef _sd_sentinel_ +# define _sd_sentinel_ __attribute__((sentinel)) +#endif + +#ifndef _sd_packed_ +# define _sd_packed_ __attribute__((packed)) +#endif + +#ifndef _sd_pure_ +# define _sd_pure_ __attribute__((pure)) +#endif + +#ifndef _SD_STRINGIFY +# define _SD_XSTRINGIFY(x) #x +# define _SD_STRINGIFY(x) _SD_XSTRINGIFY(x) +#endif + +#ifndef _SD_BEGIN_DECLARATIONS +# ifdef __cplusplus +# define _SD_BEGIN_DECLARATIONS \ + extern "C" { \ + struct _sd_useless_struct_to_allow_trailing_semicolon_ +# else +# define _SD_BEGIN_DECLARATIONS \ + struct _sd_useless_struct_to_allow_trailing_semicolon_ +# endif +#endif + +#ifndef _SD_END_DECLARATIONS +# ifdef __cplusplus +# define _SD_END_DECLARATIONS \ + } \ + struct _sd_useless_cpp_struct_to_allow_trailing_semicolon_ +# else +# define _SD_END_DECLARATIONS \ + struct _sd_useless_struct_to_allow_trailing_semicolon_ +# endif +#endif + +#define _SD_DEFINE_POINTER_CLEANUP_FUNC(type, func) \ + static __inline__ void func##p(type **p) { \ + if (*p) \ + func(*p); \ + } \ + struct _sd_useless_struct_to_allow_trailing_semicolon_ + +#endif diff --git a/src/libsystemd/include/systemd/sd-bus-protocol.h b/src/libsystemd/include/systemd/sd-bus-protocol.h new file mode 100644 index 0000000000..623cee0c50 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-bus-protocol.h @@ -0,0 +1,102 @@ +#ifndef foosdbusprotocolhfoo +#define foosdbusprotocolhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include "_sd-common.h" + +_SD_BEGIN_DECLARATIONS; + +/* Types of message */ + +enum { + _SD_BUS_MESSAGE_TYPE_INVALID = 0, + SD_BUS_MESSAGE_METHOD_CALL, + SD_BUS_MESSAGE_METHOD_RETURN, + SD_BUS_MESSAGE_METHOD_ERROR, + SD_BUS_MESSAGE_SIGNAL, + _SD_BUS_MESSAGE_TYPE_MAX +}; + +/* Primitive types */ + +enum { + _SD_BUS_TYPE_INVALID = 0, + SD_BUS_TYPE_BYTE = 'y', + SD_BUS_TYPE_BOOLEAN = 'b', + SD_BUS_TYPE_INT16 = 'n', + SD_BUS_TYPE_UINT16 = 'q', + SD_BUS_TYPE_INT32 = 'i', + SD_BUS_TYPE_UINT32 = 'u', + SD_BUS_TYPE_INT64 = 'x', + SD_BUS_TYPE_UINT64 = 't', + SD_BUS_TYPE_DOUBLE = 'd', + SD_BUS_TYPE_STRING = 's', + SD_BUS_TYPE_OBJECT_PATH = 'o', + SD_BUS_TYPE_SIGNATURE = 'g', + SD_BUS_TYPE_UNIX_FD = 'h', + SD_BUS_TYPE_ARRAY = 'a', + SD_BUS_TYPE_VARIANT = 'v', + SD_BUS_TYPE_STRUCT = 'r', /* not actually used in signatures */ + SD_BUS_TYPE_STRUCT_BEGIN = '(', + SD_BUS_TYPE_STRUCT_END = ')', + SD_BUS_TYPE_DICT_ENTRY = 'e', /* not actually used in signatures */ + SD_BUS_TYPE_DICT_ENTRY_BEGIN = '{', + SD_BUS_TYPE_DICT_ENTRY_END = '}' +}; + +/* Well-known errors. Note that this is only a sanitized subset of the + * errors that the reference implementation generates. */ + +#define SD_BUS_ERROR_FAILED "org.freedesktop.DBus.Error.Failed" +#define SD_BUS_ERROR_NO_MEMORY "org.freedesktop.DBus.Error.NoMemory" +#define SD_BUS_ERROR_SERVICE_UNKNOWN "org.freedesktop.DBus.Error.ServiceUnknown" +#define SD_BUS_ERROR_NAME_HAS_NO_OWNER "org.freedesktop.DBus.Error.NameHasNoOwner" +#define SD_BUS_ERROR_NO_REPLY "org.freedesktop.DBus.Error.NoReply" +#define SD_BUS_ERROR_IO_ERROR "org.freedesktop.DBus.Error.IOError" +#define SD_BUS_ERROR_BAD_ADDRESS "org.freedesktop.DBus.Error.BadAddress" +#define SD_BUS_ERROR_NOT_SUPPORTED "org.freedesktop.DBus.Error.NotSupported" +#define SD_BUS_ERROR_LIMITS_EXCEEDED "org.freedesktop.DBus.Error.LimitsExceeded" +#define SD_BUS_ERROR_ACCESS_DENIED "org.freedesktop.DBus.Error.AccessDenied" +#define SD_BUS_ERROR_AUTH_FAILED "org.freedesktop.DBus.Error.AuthFailed" +#define SD_BUS_ERROR_NO_SERVER "org.freedesktop.DBus.Error.NoServer" +#define SD_BUS_ERROR_TIMEOUT "org.freedesktop.DBus.Error.Timeout" +#define SD_BUS_ERROR_NO_NETWORK "org.freedesktop.DBus.Error.NoNetwork" +#define SD_BUS_ERROR_ADDRESS_IN_USE "org.freedesktop.DBus.Error.AddressInUse" +#define SD_BUS_ERROR_DISCONNECTED "org.freedesktop.DBus.Error.Disconnected" +#define SD_BUS_ERROR_INVALID_ARGS "org.freedesktop.DBus.Error.InvalidArgs" +#define SD_BUS_ERROR_FILE_NOT_FOUND "org.freedesktop.DBus.Error.FileNotFound" +#define SD_BUS_ERROR_FILE_EXISTS "org.freedesktop.DBus.Error.FileExists" +#define SD_BUS_ERROR_UNKNOWN_METHOD "org.freedesktop.DBus.Error.UnknownMethod" +#define SD_BUS_ERROR_UNKNOWN_OBJECT "org.freedesktop.DBus.Error.UnknownObject" +#define SD_BUS_ERROR_UNKNOWN_INTERFACE "org.freedesktop.DBus.Error.UnknownInterface" +#define SD_BUS_ERROR_UNKNOWN_PROPERTY "org.freedesktop.DBus.Error.UnknownProperty" +#define SD_BUS_ERROR_PROPERTY_READ_ONLY "org.freedesktop.DBus.Error.PropertyReadOnly" +#define SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN "org.freedesktop.DBus.Error.UnixProcessIdUnknown" +#define SD_BUS_ERROR_INVALID_SIGNATURE "org.freedesktop.DBus.Error.InvalidSignature" +#define SD_BUS_ERROR_INCONSISTENT_MESSAGE "org.freedesktop.DBus.Error.InconsistentMessage" +#define SD_BUS_ERROR_MATCH_RULE_NOT_FOUND "org.freedesktop.DBus.Error.MatchRuleNotFound" +#define SD_BUS_ERROR_MATCH_RULE_INVALID "org.freedesktop.DBus.Error.MatchRuleInvalid" +#define SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED \ + "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired" + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-bus-vtable.h b/src/libsystemd/include/systemd/sd-bus-vtable.h new file mode 100644 index 0000000000..e8f84eb545 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-bus-vtable.h @@ -0,0 +1,141 @@ +#ifndef foosdbusvtablehfoo +#define foosdbusvtablehfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include "_sd-common.h" + +_SD_BEGIN_DECLARATIONS; + +typedef struct sd_bus_vtable sd_bus_vtable; + +#include "sd-bus.h" + +enum { + _SD_BUS_VTABLE_START = '<', + _SD_BUS_VTABLE_END = '>', + _SD_BUS_VTABLE_METHOD = 'M', + _SD_BUS_VTABLE_SIGNAL = 'S', + _SD_BUS_VTABLE_PROPERTY = 'P', + _SD_BUS_VTABLE_WRITABLE_PROPERTY = 'W' +}; + +enum { + SD_BUS_VTABLE_DEPRECATED = 1ULL << 0, + SD_BUS_VTABLE_HIDDEN = 1ULL << 1, + SD_BUS_VTABLE_UNPRIVILEGED = 1ULL << 2, + SD_BUS_VTABLE_METHOD_NO_REPLY = 1ULL << 3, + SD_BUS_VTABLE_PROPERTY_CONST = 1ULL << 4, + SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE = 1ULL << 5, + SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION = 1ULL << 6, + SD_BUS_VTABLE_PROPERTY_EXPLICIT = 1ULL << 7, + _SD_BUS_VTABLE_CAPABILITY_MASK = 0xFFFFULL << 40 +}; + +#define SD_BUS_VTABLE_CAPABILITY(x) ((uint64_t) (((x)+1) & 0xFFFF) << 40) + +struct sd_bus_vtable { + /* Please do not initialize this structure directly, use the + * macros below instead */ + + uint8_t type:8; + uint64_t flags:56; + union { + struct { + size_t element_size; + } start; + struct { + const char *member; + const char *signature; + const char *result; + sd_bus_message_handler_t handler; + size_t offset; + } method; + struct { + const char *member; + const char *signature; + } signal; + struct { + const char *member; + const char *signature; + sd_bus_property_get_t get; + sd_bus_property_set_t set; + size_t offset; + } property; + } x; +}; + +#define SD_BUS_VTABLE_START(_flags) \ + { \ + .type = _SD_BUS_VTABLE_START, \ + .flags = _flags, \ + .x.start.element_size = sizeof(sd_bus_vtable), \ + } + +#define SD_BUS_METHOD_WITH_OFFSET(_member, _signature, _result, _handler, _offset, _flags) \ + { \ + .type = _SD_BUS_VTABLE_METHOD, \ + .flags = _flags, \ + .x.method.member = _member, \ + .x.method.signature = _signature, \ + .x.method.result = _result, \ + .x.method.handler = _handler, \ + .x.method.offset = _offset, \ + } +#define SD_BUS_METHOD(_member, _signature, _result, _handler, _flags) \ + SD_BUS_METHOD_WITH_OFFSET(_member, _signature, _result, _handler, 0, _flags) + +#define SD_BUS_SIGNAL(_member, _signature, _flags) \ + { \ + .type = _SD_BUS_VTABLE_SIGNAL, \ + .flags = _flags, \ + .x.signal.member = _member, \ + .x.signal.signature = _signature, \ + } + +#define SD_BUS_PROPERTY(_member, _signature, _get, _offset, _flags) \ + { \ + .type = _SD_BUS_VTABLE_PROPERTY, \ + .flags = _flags, \ + .x.property.member = _member, \ + .x.property.signature = _signature, \ + .x.property.get = _get, \ + .x.property.offset = _offset, \ + } + +#define SD_BUS_WRITABLE_PROPERTY(_member, _signature, _get, _set, _offset, _flags) \ + { \ + .type = _SD_BUS_VTABLE_WRITABLE_PROPERTY, \ + .flags = _flags, \ + .x.property.member = _member, \ + .x.property.signature = _signature, \ + .x.property.get = _get, \ + .x.property.set = _set, \ + .x.property.offset = _offset, \ + } + +#define SD_BUS_VTABLE_END \ + { \ + .type = _SD_BUS_VTABLE_END, \ + } + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-bus.h b/src/libsystemd/include/systemd/sd-bus.h new file mode 100644 index 0000000000..4e338a3270 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-bus.h @@ -0,0 +1,455 @@ +#ifndef foosdbushfoo +#define foosdbushfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <stdarg.h> +#include <sys/types.h> +#include <sys/uio.h> + +#include "_sd-common.h" +#include "sd-event.h" +#include "sd-id128.h" + +_SD_BEGIN_DECLARATIONS; + +/* Types */ + +typedef struct sd_bus sd_bus; +typedef struct sd_bus_message sd_bus_message; +typedef struct sd_bus_slot sd_bus_slot; +typedef struct sd_bus_creds sd_bus_creds; +typedef struct sd_bus_track sd_bus_track; + +typedef struct { + const char *name; + const char *message; + int _need_free; +} sd_bus_error; + +typedef struct { + const char* name; + int code; +} sd_bus_error_map; + +/* Flags */ + +enum { + SD_BUS_CREDS_PID = 1ULL << 0, + SD_BUS_CREDS_TID = 1ULL << 1, + SD_BUS_CREDS_PPID = 1ULL << 2, + SD_BUS_CREDS_UID = 1ULL << 3, + SD_BUS_CREDS_EUID = 1ULL << 4, + SD_BUS_CREDS_SUID = 1ULL << 5, + SD_BUS_CREDS_FSUID = 1ULL << 6, + SD_BUS_CREDS_GID = 1ULL << 7, + SD_BUS_CREDS_EGID = 1ULL << 8, + SD_BUS_CREDS_SGID = 1ULL << 9, + SD_BUS_CREDS_FSGID = 1ULL << 10, + SD_BUS_CREDS_SUPPLEMENTARY_GIDS = 1ULL << 11, + SD_BUS_CREDS_COMM = 1ULL << 12, + SD_BUS_CREDS_TID_COMM = 1ULL << 13, + SD_BUS_CREDS_EXE = 1ULL << 14, + SD_BUS_CREDS_CMDLINE = 1ULL << 15, + SD_BUS_CREDS_CGROUP = 1ULL << 16, + SD_BUS_CREDS_UNIT = 1ULL << 17, + SD_BUS_CREDS_SLICE = 1ULL << 18, + SD_BUS_CREDS_USER_UNIT = 1ULL << 19, + SD_BUS_CREDS_USER_SLICE = 1ULL << 20, + SD_BUS_CREDS_SESSION = 1ULL << 21, + SD_BUS_CREDS_OWNER_UID = 1ULL << 22, + SD_BUS_CREDS_EFFECTIVE_CAPS = 1ULL << 23, + SD_BUS_CREDS_PERMITTED_CAPS = 1ULL << 24, + SD_BUS_CREDS_INHERITABLE_CAPS = 1ULL << 25, + SD_BUS_CREDS_BOUNDING_CAPS = 1ULL << 26, + SD_BUS_CREDS_SELINUX_CONTEXT = 1ULL << 27, + SD_BUS_CREDS_AUDIT_SESSION_ID = 1ULL << 28, + SD_BUS_CREDS_AUDIT_LOGIN_UID = 1ULL << 29, + SD_BUS_CREDS_TTY = 1ULL << 30, + SD_BUS_CREDS_UNIQUE_NAME = 1ULL << 31, + SD_BUS_CREDS_WELL_KNOWN_NAMES = 1ULL << 32, + SD_BUS_CREDS_DESCRIPTION = 1ULL << 33, + SD_BUS_CREDS_AUGMENT = 1ULL << 63, /* special flag, if on sd-bus will augment creds struct, in a potentially race-full way. */ + _SD_BUS_CREDS_ALL = (1ULL << 34) -1 +}; + +enum { + SD_BUS_NAME_REPLACE_EXISTING = 1ULL << 0, + SD_BUS_NAME_ALLOW_REPLACEMENT = 1ULL << 1, + SD_BUS_NAME_QUEUE = 1ULL << 2 +}; + +/* Callbacks */ + +typedef int (*sd_bus_message_handler_t)(sd_bus_message *m, void *userdata, sd_bus_error *ret_error); +typedef int (*sd_bus_node_enumerator_t) (sd_bus *bus, const char *prefix, void *userdata, char ***ret_nodes, sd_bus_error *ret_error); +typedef int (*sd_bus_object_find_t) (sd_bus *bus, const char *path, const char *interface, void *userdata, void **ret_found, sd_bus_error *ret_error); +typedef int (*sd_bus_property_get_t) (sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *ret_error); +typedef int (*sd_bus_property_set_t) (sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *value, void *userdata, sd_bus_error *ret_error); +typedef int (*sd_bus_track_handler_t) (sd_bus_track *track, void *userdata); + +#include "sd-bus-protocol.h" +#include "sd-bus-vtable.h" + +/* Connections */ + +int sd_bus_default(sd_bus **ret); +int sd_bus_default_user(sd_bus **ret); +int sd_bus_default_system(sd_bus **ret); + +int sd_bus_open(sd_bus **ret); +int sd_bus_open_user(sd_bus **ret); +int sd_bus_open_system(sd_bus **ret); +int sd_bus_open_system_remote(sd_bus **ret, const char *host); +int sd_bus_open_system_machine(sd_bus **ret, const char *machine); + +int sd_bus_new(sd_bus **ret); + +int sd_bus_set_address(sd_bus *bus, const char *address); +int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd); +int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]); +int sd_bus_get_address(sd_bus *bus, const char **address); +int sd_bus_set_bus_client(sd_bus *bus, int b); +int sd_bus_is_bus_client(sd_bus *bus); +int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t bus_id); +int sd_bus_is_server(sd_bus *bus); +int sd_bus_set_anonymous(sd_bus *bus, int b); +int sd_bus_is_anonymous(sd_bus *bus); +int sd_bus_set_trusted(sd_bus *bus, int b); +int sd_bus_is_trusted(sd_bus *bus); +int sd_bus_set_monitor(sd_bus *bus, int b); +int sd_bus_is_monitor(sd_bus *bus); +int sd_bus_set_description(sd_bus *bus, const char *description); +int sd_bus_get_description(sd_bus *bus, const char **description); +int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t creds_mask); +int sd_bus_negotiate_timestamp(sd_bus *bus, int b); +int sd_bus_negotiate_fds(sd_bus *bus, int b); +int sd_bus_can_send(sd_bus *bus, char type); +int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *creds_mask); +int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b); +int sd_bus_get_allow_interactive_authorization(sd_bus *bus); + +int sd_bus_start(sd_bus *ret); + +int sd_bus_try_close(sd_bus *bus); +void sd_bus_close(sd_bus *bus); + +sd_bus *sd_bus_ref(sd_bus *bus); +sd_bus *sd_bus_unref(sd_bus *bus); +sd_bus *sd_bus_flush_close_unref(sd_bus *bus); + +void sd_bus_default_flush_close(void); + +int sd_bus_is_open(sd_bus *bus); + +int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id); +int sd_bus_get_scope(sd_bus *bus, const char **scope); +int sd_bus_get_tid(sd_bus *bus, pid_t *tid); +int sd_bus_get_owner_creds(sd_bus *bus, uint64_t creds_mask, sd_bus_creds **ret); + +int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie); +int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie); +int sd_bus_call(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply); +int sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec); + +int sd_bus_get_fd(sd_bus *bus); +int sd_bus_get_events(sd_bus *bus); +int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec); +int sd_bus_process(sd_bus *bus, sd_bus_message **r); +int sd_bus_process_priority(sd_bus *bus, int64_t max_priority, sd_bus_message **r); +int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec); +int sd_bus_flush(sd_bus *bus); + +sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus); +sd_bus_message* sd_bus_get_current_message(sd_bus *bus); +sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus); +void* sd_bus_get_current_userdata(sd_bus *bus); + +int sd_bus_attach_event(sd_bus *bus, sd_event *e, int priority); +int sd_bus_detach_event(sd_bus *bus); +sd_event *sd_bus_get_event(sd_bus *bus); + +int sd_bus_add_filter(sd_bus *bus, sd_bus_slot **slot, sd_bus_message_handler_t callback, void *userdata); +int sd_bus_add_match(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, void *userdata); +int sd_bus_add_object(sd_bus *bus, sd_bus_slot **slot, const char *path, sd_bus_message_handler_t callback, void *userdata); +int sd_bus_add_fallback(sd_bus *bus, sd_bus_slot **slot, const char *prefix, sd_bus_message_handler_t callback, void *userdata); +int sd_bus_add_object_vtable(sd_bus *bus, sd_bus_slot **slot, const char *path, const char *interface, const sd_bus_vtable *vtable, void *userdata); +int sd_bus_add_fallback_vtable(sd_bus *bus, sd_bus_slot **slot, const char *prefix, const char *interface, const sd_bus_vtable *vtable, sd_bus_object_find_t find, void *userdata); +int sd_bus_add_node_enumerator(sd_bus *bus, sd_bus_slot **slot, const char *path, sd_bus_node_enumerator_t callback, void *userdata); +int sd_bus_add_object_manager(sd_bus *bus, sd_bus_slot **slot, const char *path); + +/* Slot object */ + +sd_bus_slot* sd_bus_slot_ref(sd_bus_slot *slot); +sd_bus_slot* sd_bus_slot_unref(sd_bus_slot *slot); + +sd_bus* sd_bus_slot_get_bus(sd_bus_slot *slot); +void *sd_bus_slot_get_userdata(sd_bus_slot *slot); +void *sd_bus_slot_set_userdata(sd_bus_slot *slot, void *userdata); +int sd_bus_slot_set_description(sd_bus_slot *slot, const char *description); +int sd_bus_slot_get_description(sd_bus_slot *slot, const char **description); + +sd_bus_message* sd_bus_slot_get_current_message(sd_bus_slot *slot); +sd_bus_message_handler_t sd_bus_slot_get_current_handler(sd_bus_slot *bus); +void *sd_bus_slot_get_current_userdata(sd_bus_slot *slot); + +/* Message object */ + +int sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **m, const char *path, const char *interface, const char *member); +int sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **m, const char *destination, const char *path, const char *interface, const char *member); +int sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **m); +int sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **m, const sd_bus_error *e); +int sd_bus_message_new_method_errorf(sd_bus_message *call, sd_bus_message **m, const char *name, const char *format, ...) _sd_printf_(4, 5); +int sd_bus_message_new_method_errno(sd_bus_message *call, sd_bus_message **m, int error, const sd_bus_error *e); +int sd_bus_message_new_method_errnof(sd_bus_message *call, sd_bus_message **m, int error, const char *format, ...) _sd_printf_(4, 5); + +sd_bus_message* sd_bus_message_ref(sd_bus_message *m); +sd_bus_message* sd_bus_message_unref(sd_bus_message *m); + +int sd_bus_message_get_type(sd_bus_message *m, uint8_t *type); +int sd_bus_message_get_cookie(sd_bus_message *m, uint64_t *cookie); +int sd_bus_message_get_reply_cookie(sd_bus_message *m, uint64_t *cookie); +int sd_bus_message_get_priority(sd_bus_message *m, int64_t *priority); + +int sd_bus_message_get_expect_reply(sd_bus_message *m); +int sd_bus_message_get_auto_start(sd_bus_message *m); +int sd_bus_message_get_allow_interactive_authorization(sd_bus_message *m); + +const char *sd_bus_message_get_signature(sd_bus_message *m, int complete); +const char *sd_bus_message_get_path(sd_bus_message *m); +const char *sd_bus_message_get_interface(sd_bus_message *m); +const char *sd_bus_message_get_member(sd_bus_message *m); +const char *sd_bus_message_get_destination(sd_bus_message *m); +const char *sd_bus_message_get_sender(sd_bus_message *m); +const sd_bus_error *sd_bus_message_get_error(sd_bus_message *m); +int sd_bus_message_get_errno(sd_bus_message *m); + +int sd_bus_message_get_monotonic_usec(sd_bus_message *m, uint64_t *usec); +int sd_bus_message_get_realtime_usec(sd_bus_message *m, uint64_t *usec); +int sd_bus_message_get_seqnum(sd_bus_message *m, uint64_t* seqnum); + +sd_bus* sd_bus_message_get_bus(sd_bus_message *m); +sd_bus_creds *sd_bus_message_get_creds(sd_bus_message *m); /* do not unref the result */ + +int sd_bus_message_is_signal(sd_bus_message *m, const char *interface, const char *member); +int sd_bus_message_is_method_call(sd_bus_message *m, const char *interface, const char *member); +int sd_bus_message_is_method_error(sd_bus_message *m, const char *name); +int sd_bus_message_is_empty(sd_bus_message *m); +int sd_bus_message_has_signature(sd_bus_message *m, const char *signature); + +int sd_bus_message_set_expect_reply(sd_bus_message *m, int b); +int sd_bus_message_set_auto_start(sd_bus_message *m, int b); +int sd_bus_message_set_allow_interactive_authorization(sd_bus_message *m, int b); + +int sd_bus_message_set_destination(sd_bus_message *m, const char *destination); +int sd_bus_message_set_priority(sd_bus_message *m, int64_t priority); + +int sd_bus_message_append(sd_bus_message *m, const char *types, ...); +int sd_bus_message_append_basic(sd_bus_message *m, char type, const void *p); +int sd_bus_message_append_array(sd_bus_message *m, char type, const void *ptr, size_t size); +int sd_bus_message_append_array_space(sd_bus_message *m, char type, size_t size, void **ptr); +int sd_bus_message_append_array_iovec(sd_bus_message *m, char type, const struct iovec *iov, unsigned n); +int sd_bus_message_append_array_memfd(sd_bus_message *m, char type, int memfd, uint64_t offset, uint64_t size); +int sd_bus_message_append_string_space(sd_bus_message *m, size_t size, char **s); +int sd_bus_message_append_string_iovec(sd_bus_message *m, const struct iovec *iov, unsigned n); +int sd_bus_message_append_string_memfd(sd_bus_message *m, int memfd, uint64_t offset, uint64_t size); +int sd_bus_message_append_strv(sd_bus_message *m, char **l); +int sd_bus_message_open_container(sd_bus_message *m, char type, const char *contents); +int sd_bus_message_close_container(sd_bus_message *m); +int sd_bus_message_copy(sd_bus_message *m, sd_bus_message *source, int all); + +int sd_bus_message_read(sd_bus_message *m, const char *types, ...); +int sd_bus_message_read_basic(sd_bus_message *m, char type, void *p); +int sd_bus_message_read_array(sd_bus_message *m, char type, const void **ptr, size_t *size); +int sd_bus_message_read_strv(sd_bus_message *m, char ***l); /* free the result! */ +int sd_bus_message_skip(sd_bus_message *m, const char *types); +int sd_bus_message_enter_container(sd_bus_message *m, char type, const char *contents); +int sd_bus_message_exit_container(sd_bus_message *m); +int sd_bus_message_peek_type(sd_bus_message *m, char *type, const char **contents); +int sd_bus_message_verify_type(sd_bus_message *m, char type, const char *contents); +int sd_bus_message_at_end(sd_bus_message *m, int complete); +int sd_bus_message_rewind(sd_bus_message *m, int complete); + +/* Bus management */ + +int sd_bus_get_unique_name(sd_bus *bus, const char **unique); +int sd_bus_request_name(sd_bus *bus, const char *name, uint64_t flags); +int sd_bus_release_name(sd_bus *bus, const char *name); +int sd_bus_list_names(sd_bus *bus, char ***acquired, char ***activatable); /* free the results */ +int sd_bus_get_name_creds(sd_bus *bus, const char *name, uint64_t mask, sd_bus_creds **creds); /* unref the result! */ +int sd_bus_get_name_machine_id(sd_bus *bus, const char *name, sd_id128_t *machine); + +/* Convenience calls */ + +int sd_bus_call_method(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, sd_bus_message **reply, const char *types, ...); +int sd_bus_call_method_async(sd_bus *bus, sd_bus_slot **slot, const char *destination, const char *path, const char *interface, const char *member, sd_bus_message_handler_t callback, void *userdata, const char *types, ...); +int sd_bus_get_property(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, sd_bus_message **reply, const char *type); +int sd_bus_get_property_trivial(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, char type, void *ret_ptr); +int sd_bus_get_property_string(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, char **ret); /* free the result! */ +int sd_bus_get_property_strv(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, char ***ret); /* free the result! */ +int sd_bus_set_property(sd_bus *bus, const char *destination, const char *path, const char *interface, const char *member, sd_bus_error *ret_error, const char *type, ...); + +int sd_bus_reply_method_return(sd_bus_message *call, const char *types, ...); +int sd_bus_reply_method_error(sd_bus_message *call, const sd_bus_error *e); +int sd_bus_reply_method_errorf(sd_bus_message *call, const char *name, const char *format, ...) _sd_printf_(3, 4); +int sd_bus_reply_method_errno(sd_bus_message *call, int error, const sd_bus_error *e); +int sd_bus_reply_method_errnof(sd_bus_message *call, int error, const char *format, ...) _sd_printf_(3, 4); + +int sd_bus_emit_signal(sd_bus *bus, const char *path, const char *interface, const char *member, const char *types, ...); + +int sd_bus_emit_properties_changed_strv(sd_bus *bus, const char *path, const char *interface, char **names); +int sd_bus_emit_properties_changed(sd_bus *bus, const char *path, const char *interface, const char *name, ...) _sd_sentinel_; + +int sd_bus_emit_object_added(sd_bus *bus, const char *path); +int sd_bus_emit_object_removed(sd_bus *bus, const char *path); +int sd_bus_emit_interfaces_added_strv(sd_bus *bus, const char *path, char **interfaces); +int sd_bus_emit_interfaces_added(sd_bus *bus, const char *path, const char *interface, ...) _sd_sentinel_; +int sd_bus_emit_interfaces_removed_strv(sd_bus *bus, const char *path, char **interfaces); +int sd_bus_emit_interfaces_removed(sd_bus *bus, const char *path, const char *interface, ...) _sd_sentinel_; + +int sd_bus_query_sender_creds(sd_bus_message *call, uint64_t mask, sd_bus_creds **creds); +int sd_bus_query_sender_privilege(sd_bus_message *call, int capability); + +/* Credential handling */ + +int sd_bus_creds_new_from_pid(sd_bus_creds **ret, pid_t pid, uint64_t creds_mask); +sd_bus_creds *sd_bus_creds_ref(sd_bus_creds *c); +sd_bus_creds *sd_bus_creds_unref(sd_bus_creds *c); +uint64_t sd_bus_creds_get_mask(const sd_bus_creds *c); +uint64_t sd_bus_creds_get_augmented_mask(const sd_bus_creds *c); + +int sd_bus_creds_get_pid(sd_bus_creds *c, pid_t *pid); +int sd_bus_creds_get_ppid(sd_bus_creds *c, pid_t *ppid); +int sd_bus_creds_get_tid(sd_bus_creds *c, pid_t *tid); +int sd_bus_creds_get_uid(sd_bus_creds *c, uid_t *uid); +int sd_bus_creds_get_euid(sd_bus_creds *c, uid_t *euid); +int sd_bus_creds_get_suid(sd_bus_creds *c, uid_t *suid); +int sd_bus_creds_get_fsuid(sd_bus_creds *c, uid_t *fsuid); +int sd_bus_creds_get_gid(sd_bus_creds *c, gid_t *gid); +int sd_bus_creds_get_egid(sd_bus_creds *c, gid_t *egid); +int sd_bus_creds_get_sgid(sd_bus_creds *c, gid_t *sgid); +int sd_bus_creds_get_fsgid(sd_bus_creds *c, gid_t *fsgid); +int sd_bus_creds_get_supplementary_gids(sd_bus_creds *c, const gid_t **gids); +int sd_bus_creds_get_comm(sd_bus_creds *c, const char **comm); +int sd_bus_creds_get_tid_comm(sd_bus_creds *c, const char **comm); +int sd_bus_creds_get_exe(sd_bus_creds *c, const char **exe); +int sd_bus_creds_get_cmdline(sd_bus_creds *c, char ***cmdline); +int sd_bus_creds_get_cgroup(sd_bus_creds *c, const char **cgroup); +int sd_bus_creds_get_unit(sd_bus_creds *c, const char **unit); +int sd_bus_creds_get_slice(sd_bus_creds *c, const char **slice); +int sd_bus_creds_get_user_unit(sd_bus_creds *c, const char **unit); +int sd_bus_creds_get_user_slice(sd_bus_creds *c, const char **slice); +int sd_bus_creds_get_session(sd_bus_creds *c, const char **session); +int sd_bus_creds_get_owner_uid(sd_bus_creds *c, uid_t *uid); +int sd_bus_creds_has_effective_cap(sd_bus_creds *c, int capability); +int sd_bus_creds_has_permitted_cap(sd_bus_creds *c, int capability); +int sd_bus_creds_has_inheritable_cap(sd_bus_creds *c, int capability); +int sd_bus_creds_has_bounding_cap(sd_bus_creds *c, int capability); +int sd_bus_creds_get_selinux_context(sd_bus_creds *c, const char **context); +int sd_bus_creds_get_audit_session_id(sd_bus_creds *c, uint32_t *sessionid); +int sd_bus_creds_get_audit_login_uid(sd_bus_creds *c, uid_t *loginuid); +int sd_bus_creds_get_tty(sd_bus_creds *c, const char **tty); +int sd_bus_creds_get_unique_name(sd_bus_creds *c, const char **name); +int sd_bus_creds_get_well_known_names(sd_bus_creds *c, char ***names); +int sd_bus_creds_get_description(sd_bus_creds *c, const char **name); + +/* Error structures */ + +#define SD_BUS_ERROR_MAKE_CONST(name, message) ((const sd_bus_error) {(name), (message), 0}) +#define SD_BUS_ERROR_NULL SD_BUS_ERROR_MAKE_CONST(NULL, NULL) + +void sd_bus_error_free(sd_bus_error *e); +int sd_bus_error_set(sd_bus_error *e, const char *name, const char *message); +int sd_bus_error_setf(sd_bus_error *e, const char *name, const char *format, ...) _sd_printf_(3, 4); +int sd_bus_error_set_const(sd_bus_error *e, const char *name, const char *message); +int sd_bus_error_set_errno(sd_bus_error *e, int error); +int sd_bus_error_set_errnof(sd_bus_error *e, int error, const char *format, ...) _sd_printf_(3, 4); +int sd_bus_error_set_errnofv(sd_bus_error *e, int error, const char *format, va_list ap) _sd_printf_(3,0); +int sd_bus_error_get_errno(const sd_bus_error *e); +int sd_bus_error_copy(sd_bus_error *dest, const sd_bus_error *e); +int sd_bus_error_is_set(const sd_bus_error *e); +int sd_bus_error_has_name(const sd_bus_error *e, const char *name); + +#define SD_BUS_ERROR_MAP(_name, _code) \ + { \ + .name = _name, \ + .code = _code, \ + } +#define SD_BUS_ERROR_MAP_END \ + { \ + .name = NULL, \ + .code = - 'x', \ + } + +int sd_bus_error_add_map(const sd_bus_error_map *map); + +/* Auxiliary macros */ + +#define SD_BUS_MESSAGE_APPEND_ID128(x) 16, \ + (x).bytes[0], (x).bytes[1], (x).bytes[2], (x).bytes[3], \ + (x).bytes[4], (x).bytes[5], (x).bytes[6], (x).bytes[7], \ + (x).bytes[8], (x).bytes[9], (x).bytes[10], (x).bytes[11], \ + (x).bytes[12], (x).bytes[13], (x).bytes[14], (x).bytes[15] + +#define SD_BUS_MESSAGE_READ_ID128(x) 16, \ + &(x).bytes[0], &(x).bytes[1], &(x).bytes[2], &(x).bytes[3], \ + &(x).bytes[4], &(x).bytes[5], &(x).bytes[6], &(x).bytes[7], \ + &(x).bytes[8], &(x).bytes[9], &(x).bytes[10], &(x).bytes[11], \ + &(x).bytes[12], &(x).bytes[13], &(x).bytes[14], &(x).bytes[15] + +/* Label escaping */ + +int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path); +int sd_bus_path_encode_many(char **out, const char *path_template, ...); +int sd_bus_path_decode(const char *path, const char *prefix, char **ret_external_id); +int sd_bus_path_decode_many(const char *path, const char *path_template, ...); + +/* Tracking peers */ + +int sd_bus_track_new(sd_bus *bus, sd_bus_track **track, sd_bus_track_handler_t handler, void *userdata); +sd_bus_track* sd_bus_track_ref(sd_bus_track *track); +sd_bus_track* sd_bus_track_unref(sd_bus_track *track); + +sd_bus* sd_bus_track_get_bus(sd_bus_track *track); +void *sd_bus_track_get_userdata(sd_bus_track *track); +void *sd_bus_track_set_userdata(sd_bus_track *track, void *userdata); + +int sd_bus_track_add_sender(sd_bus_track *track, sd_bus_message *m); +int sd_bus_track_remove_sender(sd_bus_track *track, sd_bus_message *m); +int sd_bus_track_add_name(sd_bus_track *track, const char *name); +int sd_bus_track_remove_name(sd_bus_track *track, const char *name); + +unsigned sd_bus_track_count(sd_bus_track *track); +const char* sd_bus_track_contains(sd_bus_track *track, const char *names); +const char* sd_bus_track_first(sd_bus_track *track); +const char* sd_bus_track_next(sd_bus_track *track); + +/* Define helpers so that __attribute__((cleanup(sd_bus_unrefp))) and similar may be used. */ +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus, sd_bus_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus, sd_bus_flush_close_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus_slot, sd_bus_slot_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus_message, sd_bus_message_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus_creds, sd_bus_creds_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_bus_track, sd_bus_track_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-daemon.h b/src/libsystemd/include/systemd/sd-daemon.h new file mode 100644 index 0000000000..740b176903 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-daemon.h @@ -0,0 +1,294 @@ +#ifndef foosddaemonhfoo +#define foosddaemonhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <sys/types.h> + +#include "_sd-common.h" + +_SD_BEGIN_DECLARATIONS; + +/* + The following functionality is provided: + + - Support for logging with log levels on stderr + - File descriptor passing for socket-based activation + - Daemon startup and status notification + - Detection of systemd boots + + See sd-daemon(3) for more information. +*/ + +/* + Log levels for usage on stderr: + + fprintf(stderr, SD_NOTICE "Hello World!\n"); + + This is similar to printk() usage in the kernel. +*/ +#define SD_EMERG "<0>" /* system is unusable */ +#define SD_ALERT "<1>" /* action must be taken immediately */ +#define SD_CRIT "<2>" /* critical conditions */ +#define SD_ERR "<3>" /* error conditions */ +#define SD_WARNING "<4>" /* warning conditions */ +#define SD_NOTICE "<5>" /* normal but significant condition */ +#define SD_INFO "<6>" /* informational */ +#define SD_DEBUG "<7>" /* debug-level messages */ + +/* The first passed file descriptor is fd 3 */ +#define SD_LISTEN_FDS_START 3 + +/* + Returns how many file descriptors have been passed, or a negative + errno code on failure. Optionally, removes the $LISTEN_FDS and + $LISTEN_PID file descriptors from the environment (recommended, but + problematic in threaded environments). If r is the return value of + this function you'll find the file descriptors passed as fds + SD_LISTEN_FDS_START to SD_LISTEN_FDS_START+r-1. Returns a negative + errno style error code on failure. This function call ensures that + the FD_CLOEXEC flag is set for the passed file descriptors, to make + sure they are not passed on to child processes. If FD_CLOEXEC shall + not be set, the caller needs to unset it after this call for all file + descriptors that are used. + + See sd_listen_fds(3) for more information. +*/ +int sd_listen_fds(int unset_environment); + +int sd_listen_fds_with_names(int unset_environment, char ***names); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is a FIFO in the file system stored under the + specified path, 0 otherwise. If path is NULL a path name check will + not be done and the call only verifies if the file descriptor + refers to a FIFO. Returns a negative errno style error code on + failure. + + See sd_is_fifo(3) for more information. +*/ +int sd_is_fifo(int fd, const char *path); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is a special character device on the file + system stored under the specified path, 0 otherwise. + If path is NULL a path name check will not be done and the call + only verifies if the file descriptor refers to a special character. + Returns a negative errno style error code on failure. + + See sd_is_special(3) for more information. +*/ +int sd_is_special(int fd, const char *path); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is a socket of the specified family (AF_INET, + ...) and type (SOCK_DGRAM, SOCK_STREAM, ...), 0 otherwise. If + family is 0 a socket family check will not be done. If type is 0 a + socket type check will not be done and the call only verifies if + the file descriptor refers to a socket. If listening is > 0 it is + verified that the socket is in listening mode. (i.e. listen() has + been called) If listening is == 0 it is verified that the socket is + not in listening mode. If listening is < 0 no listening mode check + is done. Returns a negative errno style error code on failure. + + See sd_is_socket(3) for more information. +*/ +int sd_is_socket(int fd, int family, int type, int listening); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is an Internet socket, of the specified family + (either AF_INET or AF_INET6) and the specified type (SOCK_DGRAM, + SOCK_STREAM, ...), 0 otherwise. If version is 0 a protocol version + check is not done. If type is 0 a socket type check will not be + done. If port is 0 a socket port check will not be done. The + listening flag is used the same way as in sd_is_socket(). Returns a + negative errno style error code on failure. + + See sd_is_socket_inet(3) for more information. +*/ +int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is an AF_UNIX socket of the specified type + (SOCK_DGRAM, SOCK_STREAM, ...) and path, 0 otherwise. If type is 0 + a socket type check will not be done. If path is NULL a socket path + check will not be done. For normal AF_UNIX sockets set length to + 0. For abstract namespace sockets set length to the length of the + socket name (including the initial 0 byte), and pass the full + socket path in path (including the initial 0 byte). The listening + flag is used the same way as in sd_is_socket(). Returns a negative + errno style error code on failure. + + See sd_is_socket_unix(3) for more information. +*/ +int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length); + +/* + Helper call for identifying a passed file descriptor. Returns 1 if + the file descriptor is a POSIX Message Queue of the specified name, + 0 otherwise. If path is NULL a message queue name check is not + done. Returns a negative errno style error code on failure. + + See sd_is_mq(3) for more information. +*/ +int sd_is_mq(int fd, const char *path); + +/* + Informs systemd about changed daemon state. This takes a number of + newline separated environment-style variable assignments in a + string. The following variables are known: + + READY=1 Tells systemd that daemon startup is finished (only + relevant for services of Type=notify). The passed + argument is a boolean "1" or "0". Since there is + little value in signaling non-readiness the only + value daemons should send is "READY=1". + + STATUS=... Passes a single-line status string back to systemd + that describes the daemon state. This is free-form + and can be used for various purposes: general state + feedback, fsck-like programs could pass completion + percentages and failing programs could pass a human + readable error message. Example: "STATUS=Completed + 66% of file system check..." + + ERRNO=... If a daemon fails, the errno-style error code, + formatted as string. Example: "ERRNO=2" for ENOENT. + + BUSERROR=... If a daemon fails, the D-Bus error-style error + code. Example: "BUSERROR=org.freedesktop.DBus.Error.TimedOut" + + MAINPID=... The main pid of a daemon, in case systemd did not + fork off the process itself. Example: "MAINPID=4711" + + WATCHDOG=1 Tells systemd to update the watchdog timestamp. + Services using this feature should do this in + regular intervals. A watchdog framework can use the + timestamps to detect failed services. Also see + sd_watchdog_enabled() below. + + FDSTORE=1 Store the file descriptors passed along with the + message in the per-service file descriptor store, + and pass them to the main process again on next + invocation. This variable is only supported with + sd_pid_notify_with_fds(). + + WATCHDOG_USEC=... + Reset watchdog_usec value during runtime. + To reset watchdog_usec value, start the service again. + Example: "WATCHDOG_USEC=20000000" + + Daemons can choose to send additional variables. However, it is + recommended to prefix variable names not listed above with X_. + + Returns a negative errno-style error code on failure. Returns > 0 + if systemd could be notified, 0 if it couldn't possibly because + systemd is not running. + + Example: When a daemon finished starting up, it could issue this + call to notify systemd about it: + + sd_notify(0, "READY=1"); + + See sd_notifyf() for more complete examples. + + See sd_notify(3) for more information. +*/ +int sd_notify(int unset_environment, const char *state); + +/* + Similar to sd_notify() but takes a format string. + + Example 1: A daemon could send the following after initialization: + + sd_notifyf(0, "READY=1\n" + "STATUS=Processing requests...\n" + "MAINPID=%lu", + (unsigned long) getpid()); + + Example 2: A daemon could send the following shortly before + exiting, on failure: + + sd_notifyf(0, "STATUS=Failed to start up: %s\n" + "ERRNO=%i", + strerror(errno), + errno); + + See sd_notifyf(3) for more information. +*/ +int sd_notifyf(int unset_environment, const char *format, ...) _sd_printf_(2,3); + +/* + Similar to sd_notify(), but send the message on behalf of another + process, if the appropriate permissions are available. +*/ +int sd_pid_notify(pid_t pid, int unset_environment, const char *state); + +/* + Similar to sd_notifyf(), but send the message on behalf of another + process, if the appropriate permissions are available. +*/ +int sd_pid_notifyf(pid_t pid, int unset_environment, const char *format, ...) _sd_printf_(3,4); + +/* + Similar to sd_pid_notify(), but also passes the specified fd array + to the service manager for storage. This is particularly useful for + FDSTORE=1 messages. +*/ +int sd_pid_notify_with_fds(pid_t pid, int unset_environment, const char *state, const int *fds, unsigned n_fds); + +/* + Returns > 0 if the system was booted with systemd. Returns < 0 on + error. Returns 0 if the system was not booted with systemd. Note + that all of the functions above handle non-systemd boots just + fine. You should NOT protect them with a call to this function. Also + note that this function checks whether the system, not the user + session is controlled by systemd. However the functions above work + for both user and system services. + + See sd_booted(3) for more information. +*/ +int sd_booted(void); + +/* + Returns > 0 if the service manager expects watchdog keep-alive + events to be sent regularly via sd_notify(0, "WATCHDOG=1"). Returns + 0 if it does not expect this. If the usec argument is non-NULL + returns the watchdog timeout in µs after which the service manager + will act on a process that has not sent a watchdog keep alive + message. This function is useful to implement services that + recognize automatically if they are being run under supervision of + systemd with WatchdogSec= set. It is recommended for clients to + generate keep-alive pings via sd_notify(0, "WATCHDOG=1") every half + of the returned time. + + See sd_watchdog_enabled(3) for more information. +*/ +int sd_watchdog_enabled(int unset_environment, uint64_t *usec); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-event.h b/src/libsystemd/include/systemd/sd-event.h new file mode 100644 index 0000000000..cc26b7df55 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-event.h @@ -0,0 +1,143 @@ +#ifndef foosdeventhfoo +#define foosdeventhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <signal.h> +#include <sys/epoll.h> +#include <sys/signalfd.h> +#include <sys/types.h> + +#include "_sd-common.h" + +/* + Why is this better than pure epoll? + + - Supports event source prioritization + - Scales better with a large number of time events because it does not require one timerfd each + - Automatically tries to coalesce timer events system-wide + - Handles signals and child PIDs +*/ + +_SD_BEGIN_DECLARATIONS; + +typedef struct sd_event sd_event; +typedef struct sd_event_source sd_event_source; + +enum { + SD_EVENT_OFF = 0, + SD_EVENT_ON = 1, + SD_EVENT_ONESHOT = -1 +}; + +enum { + SD_EVENT_INITIAL, + SD_EVENT_ARMED, + SD_EVENT_PENDING, + SD_EVENT_RUNNING, + SD_EVENT_EXITING, + SD_EVENT_FINISHED, + SD_EVENT_PREPARING +}; + +enum { + /* And everything in-between and outside is good too */ + SD_EVENT_PRIORITY_IMPORTANT = -100, + SD_EVENT_PRIORITY_NORMAL = 0, + SD_EVENT_PRIORITY_IDLE = 100 +}; + +typedef int (*sd_event_handler_t)(sd_event_source *s, void *userdata); +typedef int (*sd_event_io_handler_t)(sd_event_source *s, int fd, uint32_t revents, void *userdata); +typedef int (*sd_event_time_handler_t)(sd_event_source *s, uint64_t usec, void *userdata); +typedef int (*sd_event_signal_handler_t)(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata); +#if defined __USE_POSIX199309 || defined __USE_XOPEN_EXTENDED +typedef int (*sd_event_child_handler_t)(sd_event_source *s, const siginfo_t *si, void *userdata); +#else +typedef void* sd_event_child_handler_t; +#endif + +int sd_event_default(sd_event **e); + +int sd_event_new(sd_event **e); +sd_event* sd_event_ref(sd_event *e); +sd_event* sd_event_unref(sd_event *e); + +int sd_event_add_io(sd_event *e, sd_event_source **s, int fd, uint32_t events, sd_event_io_handler_t callback, void *userdata); +int sd_event_add_time(sd_event *e, sd_event_source **s, clockid_t clock, uint64_t usec, uint64_t accuracy, sd_event_time_handler_t callback, void *userdata); +int sd_event_add_signal(sd_event *e, sd_event_source **s, int sig, sd_event_signal_handler_t callback, void *userdata); +int sd_event_add_child(sd_event *e, sd_event_source **s, pid_t pid, int options, sd_event_child_handler_t callback, void *userdata); +int sd_event_add_defer(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata); +int sd_event_add_post(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata); +int sd_event_add_exit(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata); + +int sd_event_prepare(sd_event *e); +int sd_event_wait(sd_event *e, uint64_t usec); +int sd_event_dispatch(sd_event *e); +int sd_event_run(sd_event *e, uint64_t usec); +int sd_event_loop(sd_event *e); +int sd_event_exit(sd_event *e, int code); + +int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec); + +int sd_event_get_fd(sd_event *e); +int sd_event_get_state(sd_event *e); +int sd_event_get_tid(sd_event *e, pid_t *tid); +int sd_event_get_exit_code(sd_event *e, int *code); +int sd_event_set_watchdog(sd_event *e, int b); +int sd_event_get_watchdog(sd_event *e); +int sd_event_get_iteration(sd_event *e, uint64_t *ret); + +sd_event_source* sd_event_source_ref(sd_event_source *s); +sd_event_source* sd_event_source_unref(sd_event_source *s); + +sd_event *sd_event_source_get_event(sd_event_source *s); +void* sd_event_source_get_userdata(sd_event_source *s); +void* sd_event_source_set_userdata(sd_event_source *s, void *userdata); + +int sd_event_source_set_description(sd_event_source *s, const char *description); +int sd_event_source_get_description(sd_event_source *s, const char **description); +int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback); +int sd_event_source_get_pending(sd_event_source *s); +int sd_event_source_get_priority(sd_event_source *s, int64_t *priority); +int sd_event_source_set_priority(sd_event_source *s, int64_t priority); +int sd_event_source_get_enabled(sd_event_source *s, int *enabled); +int sd_event_source_set_enabled(sd_event_source *s, int enabled); +int sd_event_source_get_io_fd(sd_event_source *s); +int sd_event_source_set_io_fd(sd_event_source *s, int fd); +int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events); +int sd_event_source_set_io_events(sd_event_source *s, uint32_t events); +int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents); +int sd_event_source_get_time(sd_event_source *s, uint64_t *usec); +int sd_event_source_set_time(sd_event_source *s, uint64_t usec); +int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec); +int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec); +int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock); +int sd_event_source_get_signal(sd_event_source *s); +int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid); + +/* Define helpers so that __attribute__((cleanup(sd_event_unrefp))) and similar may be used. */ +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_event, sd_event_unref); +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_event_source, sd_event_source_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-id128.h b/src/libsystemd/include/systemd/sd-id128.h new file mode 100644 index 0000000000..4dff0b9b81 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-id128.h @@ -0,0 +1,115 @@ +#ifndef foosdid128hfoo +#define foosdid128hfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <string.h> + +#include "_sd-common.h" + +_SD_BEGIN_DECLARATIONS; + +/* 128-bit ID APIs. See sd-id128(3) for more information. */ + +typedef union sd_id128 sd_id128_t; + +union sd_id128 { + uint8_t bytes[16]; + uint64_t qwords[2]; +}; + +#define SD_ID128_STRING_MAX 33 + +char *sd_id128_to_string(sd_id128_t id, char s[SD_ID128_STRING_MAX]); + +int sd_id128_from_string(const char *s, sd_id128_t *ret); + +int sd_id128_randomize(sd_id128_t *ret); + +int sd_id128_get_machine(sd_id128_t *ret); + +int sd_id128_get_boot(sd_id128_t *ret); + +#define SD_ID128_MAKE(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) \ + ((const sd_id128_t) { .bytes = { 0x##v0, 0x##v1, 0x##v2, 0x##v3, 0x##v4, 0x##v5, 0x##v6, 0x##v7, \ + 0x##v8, 0x##v9, 0x##v10, 0x##v11, 0x##v12, 0x##v13, 0x##v14, 0x##v15 }}) + +#define SD_ID128_ARRAY(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) \ + { .bytes = { 0x##v0, 0x##v1, 0x##v2, 0x##v3, 0x##v4, 0x##v5, 0x##v6, 0x##v7, \ + 0x##v8, 0x##v9, 0x##v10, 0x##v11, 0x##v12, 0x##v13, 0x##v14, 0x##v15 }} + +/* Note that SD_ID128_FORMAT_VAL will evaluate the passed argument 16 + * times. It is hence not a good idea to call this macro with an + * expensive function as parameter or an expression with side + * effects */ + +#define SD_ID128_FORMAT_STR "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x" +#define SD_ID128_FORMAT_VAL(x) (x).bytes[0], (x).bytes[1], (x).bytes[2], (x).bytes[3], (x).bytes[4], (x).bytes[5], (x).bytes[6], (x).bytes[7], (x).bytes[8], (x).bytes[9], (x).bytes[10], (x).bytes[11], (x).bytes[12], (x).bytes[13], (x).bytes[14], (x).bytes[15] + +#define SD_ID128_CONST_STR(x) \ + ((const char[SD_ID128_STRING_MAX]) { \ + ((x).bytes[0] >> 4) >= 10 ? 'a' + ((x).bytes[0] >> 4) - 10 : '0' + ((x).bytes[0] >> 4), \ + ((x).bytes[0] & 15) >= 10 ? 'a' + ((x).bytes[0] & 15) - 10 : '0' + ((x).bytes[0] & 15), \ + ((x).bytes[1] >> 4) >= 10 ? 'a' + ((x).bytes[1] >> 4) - 10 : '0' + ((x).bytes[1] >> 4), \ + ((x).bytes[1] & 15) >= 10 ? 'a' + ((x).bytes[1] & 15) - 10 : '0' + ((x).bytes[1] & 15), \ + ((x).bytes[2] >> 4) >= 10 ? 'a' + ((x).bytes[2] >> 4) - 10 : '0' + ((x).bytes[2] >> 4), \ + ((x).bytes[2] & 15) >= 10 ? 'a' + ((x).bytes[2] & 15) - 10 : '0' + ((x).bytes[2] & 15), \ + ((x).bytes[3] >> 4) >= 10 ? 'a' + ((x).bytes[3] >> 4) - 10 : '0' + ((x).bytes[3] >> 4), \ + ((x).bytes[3] & 15) >= 10 ? 'a' + ((x).bytes[3] & 15) - 10 : '0' + ((x).bytes[3] & 15), \ + ((x).bytes[4] >> 4) >= 10 ? 'a' + ((x).bytes[4] >> 4) - 10 : '0' + ((x).bytes[4] >> 4), \ + ((x).bytes[4] & 15) >= 10 ? 'a' + ((x).bytes[4] & 15) - 10 : '0' + ((x).bytes[4] & 15), \ + ((x).bytes[5] >> 4) >= 10 ? 'a' + ((x).bytes[5] >> 4) - 10 : '0' + ((x).bytes[5] >> 4), \ + ((x).bytes[5] & 15) >= 10 ? 'a' + ((x).bytes[5] & 15) - 10 : '0' + ((x).bytes[5] & 15), \ + ((x).bytes[6] >> 4) >= 10 ? 'a' + ((x).bytes[6] >> 4) - 10 : '0' + ((x).bytes[6] >> 4), \ + ((x).bytes[6] & 15) >= 10 ? 'a' + ((x).bytes[6] & 15) - 10 : '0' + ((x).bytes[6] & 15), \ + ((x).bytes[7] >> 4) >= 10 ? 'a' + ((x).bytes[7] >> 4) - 10 : '0' + ((x).bytes[7] >> 4), \ + ((x).bytes[7] & 15) >= 10 ? 'a' + ((x).bytes[7] & 15) - 10 : '0' + ((x).bytes[7] & 15), \ + ((x).bytes[8] >> 4) >= 10 ? 'a' + ((x).bytes[8] >> 4) - 10 : '0' + ((x).bytes[8] >> 4), \ + ((x).bytes[8] & 15) >= 10 ? 'a' + ((x).bytes[8] & 15) - 10 : '0' + ((x).bytes[8] & 15), \ + ((x).bytes[9] >> 4) >= 10 ? 'a' + ((x).bytes[9] >> 4) - 10 : '0' + ((x).bytes[9] >> 4), \ + ((x).bytes[9] & 15) >= 10 ? 'a' + ((x).bytes[9] & 15) - 10 : '0' + ((x).bytes[9] & 15), \ + ((x).bytes[10] >> 4) >= 10 ? 'a' + ((x).bytes[10] >> 4) - 10 : '0' + ((x).bytes[10] >> 4), \ + ((x).bytes[10] & 15) >= 10 ? 'a' + ((x).bytes[10] & 15) - 10 : '0' + ((x).bytes[10] & 15), \ + ((x).bytes[11] >> 4) >= 10 ? 'a' + ((x).bytes[11] >> 4) - 10 : '0' + ((x).bytes[11] >> 4), \ + ((x).bytes[11] & 15) >= 10 ? 'a' + ((x).bytes[11] & 15) - 10 : '0' + ((x).bytes[11] & 15), \ + ((x).bytes[12] >> 4) >= 10 ? 'a' + ((x).bytes[12] >> 4) - 10 : '0' + ((x).bytes[12] >> 4), \ + ((x).bytes[12] & 15) >= 10 ? 'a' + ((x).bytes[12] & 15) - 10 : '0' + ((x).bytes[12] & 15), \ + ((x).bytes[13] >> 4) >= 10 ? 'a' + ((x).bytes[13] >> 4) - 10 : '0' + ((x).bytes[13] >> 4), \ + ((x).bytes[13] & 15) >= 10 ? 'a' + ((x).bytes[13] & 15) - 10 : '0' + ((x).bytes[13] & 15), \ + ((x).bytes[14] >> 4) >= 10 ? 'a' + ((x).bytes[14] >> 4) - 10 : '0' + ((x).bytes[14] >> 4), \ + ((x).bytes[14] & 15) >= 10 ? 'a' + ((x).bytes[14] & 15) - 10 : '0' + ((x).bytes[14] & 15), \ + ((x).bytes[15] >> 4) >= 10 ? 'a' + ((x).bytes[15] >> 4) - 10 : '0' + ((x).bytes[15] >> 4), \ + ((x).bytes[15] & 15) >= 10 ? 'a' + ((x).bytes[15] & 15) - 10 : '0' + ((x).bytes[15] & 15), \ + 0 }) + +_sd_pure_ static __inline__ int sd_id128_equal(sd_id128_t a, sd_id128_t b) { + return memcmp(&a, &b, 16) == 0; +} + +_sd_pure_ static __inline__ int sd_id128_is_null(sd_id128_t a) { + return a.qwords[0] == 0 && a.qwords[1] == 0; +} + +#define SD_ID128_NULL ((const sd_id128_t) { .qwords = { 0, 0 }}) + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-journal.h b/src/libsystemd/include/systemd/sd-journal.h new file mode 100644 index 0000000000..b684cf073c --- /dev/null +++ b/src/libsystemd/include/systemd/sd-journal.h @@ -0,0 +1,174 @@ +#ifndef foosdjournalhfoo +#define foosdjournalhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <stdarg.h> +#include <sys/types.h> +#include <sys/uio.h> +#include <syslog.h> + +#include "_sd-common.h" +#include "sd-id128.h" + +/* Journal APIs. See sd-journal(3) for more information. */ + +_SD_BEGIN_DECLARATIONS; + +/* Write to daemon */ +int sd_journal_print(int priority, const char *format, ...) _sd_printf_(2, 3); +int sd_journal_printv(int priority, const char *format, va_list ap) _sd_printf_(2, 0); +int sd_journal_send(const char *format, ...) _sd_printf_(1, 0) _sd_sentinel_; +int sd_journal_sendv(const struct iovec *iov, int n); +int sd_journal_perror(const char *message); + +/* Used by the macros below. You probably don't want to call this directly. */ +int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) _sd_printf_(5, 6); +int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) _sd_printf_(5, 0); +int sd_journal_send_with_location(const char *file, const char *line, const char *func, const char *format, ...) _sd_printf_(4, 0) _sd_sentinel_; +int sd_journal_sendv_with_location(const char *file, const char *line, const char *func, const struct iovec *iov, int n); +int sd_journal_perror_with_location(const char *file, const char *line, const char *func, const char *message); + +/* implicitly add code location to messages sent, if this is enabled */ +#ifndef SD_JOURNAL_SUPPRESS_LOCATION + +#define sd_journal_print(priority, ...) sd_journal_print_with_location(priority, "CODE_FILE=" __FILE__, "CODE_LINE=" _SD_STRINGIFY(__LINE__), __func__, __VA_ARGS__) +#define sd_journal_printv(priority, format, ap) sd_journal_printv_with_location(priority, "CODE_FILE=" __FILE__, "CODE_LINE=" _SD_STRINGIFY(__LINE__), __func__, format, ap) +#define sd_journal_send(...) sd_journal_send_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _SD_STRINGIFY(__LINE__), __func__, __VA_ARGS__) +#define sd_journal_sendv(iovec, n) sd_journal_sendv_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _SD_STRINGIFY(__LINE__), __func__, iovec, n) +#define sd_journal_perror(message) sd_journal_perror_with_location("CODE_FILE=" __FILE__, "CODE_LINE=" _SD_STRINGIFY(__LINE__), __func__, message) + +#endif + +int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix); + +/* Browse journal stream */ + +typedef struct sd_journal sd_journal; + +/* Open flags */ +enum { + SD_JOURNAL_LOCAL_ONLY = 1 << 0, + SD_JOURNAL_RUNTIME_ONLY = 1 << 1, + SD_JOURNAL_SYSTEM = 1 << 2, + SD_JOURNAL_CURRENT_USER = 1 << 3, + SD_JOURNAL_OS_ROOT = 1 << 4, + + SD_JOURNAL_SYSTEM_ONLY = SD_JOURNAL_SYSTEM /* deprecated name */ +}; + +/* Wakeup event types */ +enum { + SD_JOURNAL_NOP, + SD_JOURNAL_APPEND, + SD_JOURNAL_INVALIDATE +}; + +int sd_journal_open(sd_journal **ret, int flags); +int sd_journal_open_directory(sd_journal **ret, const char *path, int flags); +int sd_journal_open_directory_fd(sd_journal **ret, int fd, int flags); +int sd_journal_open_files(sd_journal **ret, const char **paths, int flags); +int sd_journal_open_files_fd(sd_journal **ret, int fds[], unsigned n_fds, int flags); +int sd_journal_open_container(sd_journal **ret, const char *machine, int flags); /* deprecated */ +void sd_journal_close(sd_journal *j); + +int sd_journal_previous(sd_journal *j); +int sd_journal_next(sd_journal *j); + +int sd_journal_previous_skip(sd_journal *j, uint64_t skip); +int sd_journal_next_skip(sd_journal *j, uint64_t skip); + +int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret); +int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id); + +int sd_journal_set_data_threshold(sd_journal *j, size_t sz); +int sd_journal_get_data_threshold(sd_journal *j, size_t *sz); + +int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *l); +int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *l); +void sd_journal_restart_data(sd_journal *j); + +int sd_journal_add_match(sd_journal *j, const void *data, size_t size); +int sd_journal_add_disjunction(sd_journal *j); +int sd_journal_add_conjunction(sd_journal *j); +void sd_journal_flush_matches(sd_journal *j); + +int sd_journal_seek_head(sd_journal *j); +int sd_journal_seek_tail(sd_journal *j); +int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec); +int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec); +int sd_journal_seek_cursor(sd_journal *j, const char *cursor); + +int sd_journal_get_cursor(sd_journal *j, char **cursor); +int sd_journal_test_cursor(sd_journal *j, const char *cursor); + +int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to); +int sd_journal_get_cutoff_monotonic_usec(sd_journal *j, const sd_id128_t boot_id, uint64_t *from, uint64_t *to); + +int sd_journal_get_usage(sd_journal *j, uint64_t *bytes); + +int sd_journal_query_unique(sd_journal *j, const char *field); +int sd_journal_enumerate_unique(sd_journal *j, const void **data, size_t *l); +void sd_journal_restart_unique(sd_journal *j); + +int sd_journal_enumerate_fields(sd_journal *j, const char **field); +void sd_journal_restart_fields(sd_journal *j); + +int sd_journal_get_fd(sd_journal *j); +int sd_journal_get_events(sd_journal *j); +int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec); +int sd_journal_process(sd_journal *j); +int sd_journal_wait(sd_journal *j, uint64_t timeout_usec); +int sd_journal_reliable_fd(sd_journal *j); + +int sd_journal_get_catalog(sd_journal *j, char **text); +int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **text); + +int sd_journal_has_runtime_files(sd_journal *j); +int sd_journal_has_persistent_files(sd_journal *j); + +/* The inverse condition avoids ambiguity of dangling 'else' after the macro */ +#define SD_JOURNAL_FOREACH(j) \ + if (sd_journal_seek_head(j) < 0) { } \ + else while (sd_journal_next(j) > 0) + +/* The inverse condition avoids ambiguity of dangling 'else' after the macro */ +#define SD_JOURNAL_FOREACH_BACKWARDS(j) \ + if (sd_journal_seek_tail(j) < 0) { } \ + else while (sd_journal_previous(j) > 0) + +/* Iterate through the data fields of the current journal entry */ +#define SD_JOURNAL_FOREACH_DATA(j, data, l) \ + for (sd_journal_restart_data(j); sd_journal_enumerate_data((j), &(data), &(l)) > 0; ) + +/* Iterate through the all known values of a specific field */ +#define SD_JOURNAL_FOREACH_UNIQUE(j, data, l) \ + for (sd_journal_restart_unique(j); sd_journal_enumerate_unique((j), &(data), &(l)) > 0; ) + +/* Iterate through all known field names */ +#define SD_JOURNAL_FOREACH_FIELD(j, field) \ + for (sd_journal_restart_fields(j); sd_journal_enumerate_fields((j), &(field)) > 0; ) + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_journal, sd_journal_close); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-login.h b/src/libsystemd/include/systemd/sd-login.h new file mode 100644 index 0000000000..e3ecbd8378 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-login.h @@ -0,0 +1,245 @@ +#ifndef foosdloginhfoo +#define foosdloginhfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <sys/types.h> + +#include "_sd-common.h" + +/* + * A few points: + * + * Instead of returning an empty string array or empty uid array, we + * may return NULL. + * + * Free the data the library returns with libc free(). String arrays + * are NULL terminated, and you need to free the array itself, in + * addition to the strings contained. + * + * We return error codes as negative errno, kernel-style. On success, we + * return 0 or positive. + * + * These functions access data in /proc, /sys/fs/cgroup, and /run. All + * of these are virtual file systems; therefore, accesses are + * relatively cheap. + * + * See sd-login(3) for more information. + */ + +_SD_BEGIN_DECLARATIONS; + +/* Get session from PID. Note that 'shared' processes of a user are + * not attached to a session, but only attached to a user. This will + * return an error for system processes and 'shared' processes of a + * user. */ +int sd_pid_get_session(pid_t pid, char **session); + +/* Get UID of the owner of the session of the PID (or in case the + * process is a 'shared' user process, the UID of that user is + * returned). This will not return the UID of the process, but rather + * the UID of the owner of the cgroup that the process is in. This will + * return an error for system processes. */ +int sd_pid_get_owner_uid(pid_t pid, uid_t *uid); + +/* Get systemd non-slice unit (i.e. service) name from PID, for system + * services. This will return an error for non-service processes. */ +int sd_pid_get_unit(pid_t pid, char **unit); + +/* Get systemd non-slice unit (i.e. service) name from PID, for user + * services. This will return an error for non-user-service + * processes. */ +int sd_pid_get_user_unit(pid_t pid, char **unit); + +/* Get slice name from PID. */ +int sd_pid_get_slice(pid_t pid, char **slice); + +/* Get user slice name from PID. */ +int sd_pid_get_user_slice(pid_t pid, char **slice); + +/* Get machine name from PID, for processes assigned to a VM or + * container. This will return an error for non-machine processes. */ +int sd_pid_get_machine_name(pid_t pid, char **machine); + +/* Get the control group from a PID, relative to the root of the + * hierarchy. */ +int sd_pid_get_cgroup(pid_t pid, char **cgroup); + +/* Similar to sd_pid_get_session(), but retrieves data about the peer + * of a connected AF_UNIX socket */ +int sd_peer_get_session(int fd, char **session); + +/* Similar to sd_pid_get_owner_uid(), but retrieves data about the peer of + * a connected AF_UNIX socket */ +int sd_peer_get_owner_uid(int fd, uid_t *uid); + +/* Similar to sd_pid_get_unit(), but retrieves data about the peer of + * a connected AF_UNIX socket */ +int sd_peer_get_unit(int fd, char **unit); + +/* Similar to sd_pid_get_user_unit(), but retrieves data about the peer of + * a connected AF_UNIX socket */ +int sd_peer_get_user_unit(int fd, char **unit); + +/* Similar to sd_pid_get_slice(), but retrieves data about the peer of + * a connected AF_UNIX socket */ +int sd_peer_get_slice(int fd, char **slice); + +/* Similar to sd_pid_get_user_slice(), but retrieves data about the peer of + * a connected AF_UNIX socket */ +int sd_peer_get_user_slice(int fd, char **slice); + +/* Similar to sd_pid_get_machine_name(), but retrieves data about the + * peer of a connected AF_UNIX socket */ +int sd_peer_get_machine_name(int fd, char **machine); + +/* Similar to sd_pid_get_cgroup(), but retrieves data about the peer + * of a connected AF_UNIX socket. */ +int sd_peer_get_cgroup(pid_t pid, char **cgroup); + +/* Get state from UID. Possible states: offline, lingering, online, active, closing */ +int sd_uid_get_state(uid_t uid, char **state); + +/* Return primary session of user, if there is any */ +int sd_uid_get_display(uid_t uid, char **session); + +/* Return 1 if UID has session on seat. If require_active is true, this will + * look for active sessions only. */ +int sd_uid_is_on_seat(uid_t uid, int require_active, const char *seat); + +/* Return sessions of user. If require_active is true, this will look for + * active sessions only. Returns the number of sessions. + * If sessions is NULL, this will just return the number of sessions. */ +int sd_uid_get_sessions(uid_t uid, int require_active, char ***sessions); + +/* Return seats of user is on. If require_active is true, this will look for + * active seats only. Returns the number of seats. + * If seats is NULL, this will just return the number of seats. */ +int sd_uid_get_seats(uid_t uid, int require_active, char ***seats); + +/* Return 1 if the session is active. */ +int sd_session_is_active(const char *session); + +/* Return 1 if the session is remote. */ +int sd_session_is_remote(const char *session); + +/* Get state from session. Possible states: online, active, closing. + * This function is a more generic version of sd_session_is_active(). */ +int sd_session_get_state(const char *session, char **state); + +/* Determine user ID of session */ +int sd_session_get_uid(const char *session, uid_t *uid); + +/* Determine seat of session */ +int sd_session_get_seat(const char *session, char **seat); + +/* Determine the (PAM) service name this session was registered by. */ +int sd_session_get_service(const char *session, char **service); + +/* Determine the type of this session, i.e. one of "tty", "x11", "wayland", "mir" or "unspecified". */ +int sd_session_get_type(const char *session, char **type); + +/* Determine the class of this session, i.e. one of "user", "greeter" or "lock-screen". */ +int sd_session_get_class(const char *session, char **clazz); + +/* Determine the desktop brand of this session, i.e. something like "GNOME", "KDE" or "systemd-console". */ +int sd_session_get_desktop(const char *session, char **desktop); + +/* Determine the X11 display of this session. */ +int sd_session_get_display(const char *session, char **display); + +/* Determine the remote host of this session. */ +int sd_session_get_remote_host(const char *session, char **remote_host); + +/* Determine the remote user of this session (if provided by PAM). */ +int sd_session_get_remote_user(const char *session, char **remote_user); + +/* Determine the TTY of this session. */ +int sd_session_get_tty(const char *session, char **display); + +/* Determine the VT number of this session. */ +int sd_session_get_vt(const char *session, unsigned *vtnr); + +/* Return active session and user of seat */ +int sd_seat_get_active(const char *seat, char **session, uid_t *uid); + +/* Return sessions and users on seat. Returns number of sessions. + * If sessions is NULL, this returns only the number of sessions. */ +int sd_seat_get_sessions(const char *seat, char ***sessions, uid_t **uid, unsigned *n_uids); + +/* Return whether the seat is multi-session capable */ +int sd_seat_can_multi_session(const char *seat); + +/* Return whether the seat is TTY capable, i.e. suitable for showing console UIs */ +int sd_seat_can_tty(const char *seat); + +/* Return whether the seat is graphics capable, i.e. suitable for showing graphical UIs */ +int sd_seat_can_graphical(const char *seat); + +/* Return the class of machine */ +int sd_machine_get_class(const char *machine, char **clazz); + +/* Return the list if host-side network interface indices of a machine */ +int sd_machine_get_ifindices(const char *machine, int **ifindices); + +/* Get all seats, store in *seats. Returns the number of seats. If + * seats is NULL, this only returns the number of seats. */ +int sd_get_seats(char ***seats); + +/* Get all sessions, store in *sessions. Returns the number of + * sessions. If sessions is NULL, this only returns the number of sessions. */ +int sd_get_sessions(char ***sessions); + +/* Get all logged in users, store in *users. Returns the number of + * users. If users is NULL, this only returns the number of users. */ +int sd_get_uids(uid_t **users); + +/* Get all running virtual machines/containers */ +int sd_get_machine_names(char ***machines); + +/* Monitor object */ +typedef struct sd_login_monitor sd_login_monitor; + +/* Create a new monitor. Category must be NULL, "seat", "session", + * "uid", or "machine" to get monitor events for the specific category + * (or all). */ +int sd_login_monitor_new(const char *category, sd_login_monitor** ret); + +/* Destroys the passed monitor. Returns NULL. */ +sd_login_monitor* sd_login_monitor_unref(sd_login_monitor *m); + +/* Flushes the monitor */ +int sd_login_monitor_flush(sd_login_monitor *m); + +/* Get FD from monitor */ +int sd_login_monitor_get_fd(sd_login_monitor *m); + +/* Get poll() mask to monitor */ +int sd_login_monitor_get_events(sd_login_monitor *m); + +/* Get timeout for poll(), as usec value relative to CLOCK_MONOTONIC's epoch */ +int sd_login_monitor_get_timeout(sd_login_monitor *m, uint64_t *timeout_usec); + +_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_login_monitor, sd_login_monitor_unref); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-messages.h b/src/libsystemd/include/systemd/sd-messages.h new file mode 100644 index 0000000000..c8599c596d --- /dev/null +++ b/src/libsystemd/include/systemd/sd-messages.h @@ -0,0 +1,90 @@ +#ifndef foosdmessageshfoo +#define foosdmessageshfoo + +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include "_sd-common.h" +#include "sd-id128.h" + +_SD_BEGIN_DECLARATIONS; + +/* Hey! If you add a new message here, you *must* also update the + * message catalog with an appropriate explanation */ + +/* And if you add a new ID here, make sure to generate a random one + * with journalctl --new-id128. Do not use any other IDs, and do not + * count them up manually. */ + +#define SD_MESSAGE_JOURNAL_START SD_ID128_MAKE(f7,73,79,a8,49,0b,40,8b,be,5f,69,40,50,5a,77,7b) +#define SD_MESSAGE_JOURNAL_STOP SD_ID128_MAKE(d9,3f,b3,c9,c2,4d,45,1a,97,ce,a6,15,ce,59,c0,0b) +#define SD_MESSAGE_JOURNAL_DROPPED SD_ID128_MAKE(a5,96,d6,fe,7b,fa,49,94,82,8e,72,30,9e,95,d6,1e) +#define SD_MESSAGE_JOURNAL_MISSED SD_ID128_MAKE(e9,bf,28,e6,e8,34,48,1b,b6,f4,8f,54,8a,d1,36,06) +#define SD_MESSAGE_JOURNAL_USAGE SD_ID128_MAKE(ec,38,7f,57,7b,84,4b,8f,a9,48,f3,3c,ad,9a,75,e6) + +#define SD_MESSAGE_COREDUMP SD_ID128_MAKE(fc,2e,22,bc,6e,e6,47,b6,b9,07,29,ab,34,a2,50,b1) + +#define SD_MESSAGE_SESSION_START SD_ID128_MAKE(8d,45,62,0c,1a,43,48,db,b1,74,10,da,57,c6,0c,66) +#define SD_MESSAGE_SESSION_STOP SD_ID128_MAKE(33,54,93,94,24,b4,45,6d,98,02,ca,83,33,ed,42,4a) +#define SD_MESSAGE_SEAT_START SD_ID128_MAKE(fc,be,fc,5d,a2,3d,42,80,93,f9,7c,82,a9,29,0f,7b) +#define SD_MESSAGE_SEAT_STOP SD_ID128_MAKE(e7,85,2b,fe,46,78,4e,d0,ac,cd,e0,4b,c8,64,c2,d5) +#define SD_MESSAGE_MACHINE_START SD_ID128_MAKE(24,d8,d4,45,25,73,40,24,96,06,83,81,a6,31,2d,f2) +#define SD_MESSAGE_MACHINE_STOP SD_ID128_MAKE(58,43,2b,d3,ba,ce,47,7c,b5,14,b5,63,81,b8,a7,58) + +#define SD_MESSAGE_TIME_CHANGE SD_ID128_MAKE(c7,a7,87,07,9b,35,4e,aa,a9,e7,7b,37,18,93,cd,27) +#define SD_MESSAGE_TIMEZONE_CHANGE SD_ID128_MAKE(45,f8,2f,4a,ef,7a,4b,bf,94,2c,e8,61,d1,f2,09,90) + +#define SD_MESSAGE_STARTUP_FINISHED SD_ID128_MAKE(b0,7a,24,9c,d0,24,41,4a,82,dd,00,cd,18,13,78,ff) + +#define SD_MESSAGE_SLEEP_START SD_ID128_MAKE(6b,bd,95,ee,97,79,41,e4,97,c4,8b,e2,7c,25,41,28) +#define SD_MESSAGE_SLEEP_STOP SD_ID128_MAKE(88,11,e6,df,2a,8e,40,f5,8a,94,ce,a2,6f,8e,bf,14) + +#define SD_MESSAGE_SHUTDOWN SD_ID128_MAKE(98,26,88,66,d1,d5,4a,49,9c,4e,98,92,1d,93,bc,40) + +#define SD_MESSAGE_UNIT_STARTING SD_ID128_MAKE(7d,49,58,e8,42,da,4a,75,8f,6c,1c,dc,7b,36,dc,c5) +#define SD_MESSAGE_UNIT_STARTED SD_ID128_MAKE(39,f5,34,79,d3,a0,45,ac,8e,11,78,62,48,23,1f,bf) +#define SD_MESSAGE_UNIT_STOPPING SD_ID128_MAKE(de,5b,42,6a,63,be,47,a7,b6,ac,3e,aa,c8,2e,2f,6f) +#define SD_MESSAGE_UNIT_STOPPED SD_ID128_MAKE(9d,1a,aa,27,d6,01,40,bd,96,36,54,38,aa,d2,02,86) +#define SD_MESSAGE_UNIT_FAILED SD_ID128_MAKE(be,02,cf,68,55,d2,42,8b,a4,0d,f7,e9,d0,22,f0,3d) +#define SD_MESSAGE_UNIT_RELOADING SD_ID128_MAKE(d3,4d,03,7f,ff,18,47,e6,ae,66,9a,37,0e,69,47,25) +#define SD_MESSAGE_UNIT_RELOADED SD_ID128_MAKE(7b,05,eb,c6,68,38,42,22,ba,a8,88,11,79,cf,da,54) + +#define SD_MESSAGE_SPAWN_FAILED SD_ID128_MAKE(64,12,57,65,1c,1b,4e,c9,a8,62,4d,7a,40,a9,e1,e7) + +#define SD_MESSAGE_FORWARD_SYSLOG_MISSED SD_ID128_MAKE(00,27,22,9c,a0,64,41,81,a7,6c,4e,92,45,8a,fa,2e) + +#define SD_MESSAGE_OVERMOUNTING SD_ID128_MAKE(1d,ee,03,69,c7,fc,47,36,b7,09,9b,38,ec,b4,6e,e7) + +#define SD_MESSAGE_LID_OPENED SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,6f) +#define SD_MESSAGE_LID_CLOSED SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,70) +#define SD_MESSAGE_SYSTEM_DOCKED SD_ID128_MAKE(f5,f4,16,b8,62,07,4b,28,92,7a,48,c3,ba,7d,51,ff) +#define SD_MESSAGE_SYSTEM_UNDOCKED SD_ID128_MAKE(51,e1,71,bd,58,52,48,56,81,10,14,4c,51,7c,ca,53) +#define SD_MESSAGE_POWER_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,71) +#define SD_MESSAGE_SUSPEND_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,72) +#define SD_MESSAGE_HIBERNATE_KEY SD_ID128_MAKE(b7,2e,a4,a2,88,15,45,a0,b5,0e,20,0e,55,b9,b0,73) + +#define SD_MESSAGE_INVALID_CONFIGURATION SD_ID128_MAKE(c7,72,d2,4e,9a,88,4c,be,b9,ea,12,62,5c,30,6c,01) + +#define SD_MESSAGE_DNSSEC_FAILURE SD_ID128_MAKE(16,75,d7,f1,72,17,40,98,b1,10,8b,f8,c7,dc,8f,5d) +#define SD_MESSAGE_DNSSEC_TRUST_ANCHOR_REVOKED SD_ID128_MAKE(4d,44,08,cf,d0,d1,44,85,91,84,d1,e6,5d,7c,8a,65) +#define SD_MESSAGE_DNSSEC_DOWNGRADE SD_ID128_MAKE(36,db,2d,fa,5a,90,45,e1,bd,4a,f5,f9,3e,1c,f0,57) + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/include/systemd/sd-utf8.h b/src/libsystemd/include/systemd/sd-utf8.h new file mode 100644 index 0000000000..6781983878 --- /dev/null +++ b/src/libsystemd/include/systemd/sd-utf8.h @@ -0,0 +1,32 @@ +#ifndef foosdutf8hfoo +#define foosdutf8hfoo + +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include "_sd-common.h" + +_SD_BEGIN_DECLARATIONS; + +_sd_pure_ const char *sd_utf8_is_valid(const char *s); +_sd_pure_ const char *sd_ascii_is_valid(const char *s); + +_SD_END_DECLARATIONS; + +#endif diff --git a/src/libsystemd/libsystemd-pkgconfig.xml b/src/libsystemd/libsystemd-pkgconfig.xml new file mode 100644 index 0000000000..272da64cd7 --- /dev/null +++ b/src/libsystemd/libsystemd-pkgconfig.xml @@ -0,0 +1,12 @@ +<?xml version="1.0"?> +<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" + "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"> + +<refsect1> + <title>Notes</title> + + <para id='pkgconfig-text'>These APIs are implemented as a shared + library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> +</refsect1> diff --git a/src/libsystemd/sd-bus-errors.xml b/src/libsystemd/sd-bus-errors.xml new file mode 100644 index 0000000000..d2b81f4e4a --- /dev/null +++ b/src/libsystemd/sd-bus-errors.xml @@ -0,0 +1,309 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-bus-errors"> + + <refentryinfo> + <title>sd-bus-errors</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-bus-errors</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-bus-errors</refname> + <refname>SD_BUS_ERROR_FAILED</refname> + <refname>SD_BUS_ERROR_NO_MEMORY</refname> + <refname>SD_BUS_ERROR_SERVICE_UNKNOWN</refname> + <refname>SD_BUS_ERROR_NAME_HAS_NO_OWNER</refname> + <refname>SD_BUS_ERROR_NO_REPLY</refname> + <refname>SD_BUS_ERROR_IO_ERROR</refname> + <refname>SD_BUS_ERROR_BAD_ADDRESS</refname> + <refname>SD_BUS_ERROR_NOT_SUPPORTED</refname> + <refname>SD_BUS_ERROR_LIMITS_EXCEEDED</refname> + <refname>SD_BUS_ERROR_ACCESS_DENIED</refname> + <refname>SD_BUS_ERROR_AUTH_FAILED</refname> + <refname>SD_BUS_ERROR_NO_SERVER</refname> + <refname>SD_BUS_ERROR_TIMEOUT</refname> + <refname>SD_BUS_ERROR_NO_NETWORK</refname> + <refname>SD_BUS_ERROR_ADDRESS_IN_USE</refname> + <refname>SD_BUS_ERROR_DISCONNECTED</refname> + <refname>SD_BUS_ERROR_INVALID_ARGS</refname> + <refname>SD_BUS_ERROR_FILE_NOT_FOUND</refname> + <refname>SD_BUS_ERROR_FILE_EXISTS</refname> + <refname>SD_BUS_ERROR_UNKNOWN_METHOD</refname> + <refname>SD_BUS_ERROR_UNKNOWN_OBJECT</refname> + <refname>SD_BUS_ERROR_UNKNOWN_INTERFACE</refname> + <refname>SD_BUS_ERROR_UNKNOWN_PROPERTY</refname> + <refname>SD_BUS_ERROR_PROPERTY_READ_ONLY</refname> + <refname>SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN</refname> + <refname>SD_BUS_ERROR_INVALID_SIGNATURE</refname> + <refname>SD_BUS_ERROR_INCONSISTENT_MESSAGE</refname> + <refname>SD_BUS_ERROR_MATCH_RULE_NOT_FOUND</refname> + <refname>SD_BUS_ERROR_MATCH_RULE_INVALID</refname> + <refname>SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED</refname> + + <refpurpose>Standard D-Bus error names</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + +<funcsynopsisinfo>#define SD_BUS_ERROR_FAILED "org.freedesktop.DBus.Error.Failed" +#define SD_BUS_ERROR_NO_MEMORY "org.freedesktop.DBus.Error.NoMemory" +#define SD_BUS_ERROR_SERVICE_UNKNOWN "org.freedesktop.DBus.Error.ServiceUnknown" +#define SD_BUS_ERROR_NAME_HAS_NO_OWNER "org.freedesktop.DBus.Error.NameHasNoOwner" +#define SD_BUS_ERROR_NO_REPLY "org.freedesktop.DBus.Error.NoReply" +#define SD_BUS_ERROR_IO_ERROR "org.freedesktop.DBus.Error.IOError" +#define SD_BUS_ERROR_BAD_ADDRESS "org.freedesktop.DBus.Error.BadAddress" +#define SD_BUS_ERROR_NOT_SUPPORTED "org.freedesktop.DBus.Error.NotSupported" +#define SD_BUS_ERROR_LIMITS_EXCEEDED "org.freedesktop.DBus.Error.LimitsExceeded" +#define SD_BUS_ERROR_ACCESS_DENIED "org.freedesktop.DBus.Error.AccessDenied" +#define SD_BUS_ERROR_AUTH_FAILED "org.freedesktop.DBus.Error.AuthFailed" +#define SD_BUS_ERROR_NO_SERVER "org.freedesktop.DBus.Error.NoServer" +#define SD_BUS_ERROR_TIMEOUT "org.freedesktop.DBus.Error.Timeout" +#define SD_BUS_ERROR_NO_NETWORK "org.freedesktop.DBus.Error.NoNetwork" +#define SD_BUS_ERROR_ADDRESS_IN_USE "org.freedesktop.DBus.Error.AddressInUse" +#define SD_BUS_ERROR_DISCONNECTED "org.freedesktop.DBus.Error.Disconnected" +#define SD_BUS_ERROR_INVALID_ARGS "org.freedesktop.DBus.Error.InvalidArgs" +#define SD_BUS_ERROR_FILE_NOT_FOUND "org.freedesktop.DBus.Error.FileNotFound" +#define SD_BUS_ERROR_FILE_EXISTS "org.freedesktop.DBus.Error.FileExists" +#define SD_BUS_ERROR_UNKNOWN_METHOD "org.freedesktop.DBus.Error.UnknownMethod" +#define SD_BUS_ERROR_UNKNOWN_OBJECT "org.freedesktop.DBus.Error.UnknownObject" +#define SD_BUS_ERROR_UNKNOWN_INTERFACE "org.freedesktop.DBus.Error.UnknownInterface" +#define SD_BUS_ERROR_UNKNOWN_PROPERTY "org.freedesktop.DBus.Error.UnknownProperty" +#define SD_BUS_ERROR_PROPERTY_READ_ONLY "org.freedesktop.DBus.Error.PropertyReadOnly" +#define SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN "org.freedesktop.DBus.Error.UnixProcessIdUnknown" +#define SD_BUS_ERROR_INVALID_SIGNATURE "org.freedesktop.DBus.Error.InvalidSignature" +#define SD_BUS_ERROR_INCONSISTENT_MESSAGE "org.freedesktop.DBus.Error.InconsistentMessage" +#define SD_BUS_ERROR_MATCH_RULE_NOT_FOUND "org.freedesktop.DBus.Error.MatchRuleNotFound" +#define SD_BUS_ERROR_MATCH_RULE_INVALID "org.freedesktop.DBus.Error.MatchRuleInvalid" +#define SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED \ + "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"</funcsynopsisinfo> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>In addition to the error names user programs define, D-Bus + knows a number of generic, standardized error names that are + listed below.</para> + + <para>In addition to this list, in sd-bus, the special error + namespace <literal>System.Error.</literal> is used to map + arbitrary GNU/Linux system errors (as defined by <citerefentry + project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>) + to D-Bus errors and back. For example, the error + <constant>EUCLEAN</constant> is mapped to + <literal>System.Error.EUCLEAN</literal> and back.</para> + + <variablelist> + + <varlistentry> + <term><varname>SD_BUS_ERROR_FAILED</varname></term> + <listitem><para>A generic error indication. See the error + message for further details. This error name should be + avoided, in favor of a more expressive error + name.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>SD_BUS_ERROR_NO_MEMORY</varname></term> + <listitem><para>A memory allocation failed, and the requested + operation could not be completed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>SD_BUS_ERROR_SERVICE_UNKNOWN</varname></term> + <listitem><para>The contacted bus service is unknown and + cannot be activated.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>SD_BUS_ERROR_NAME_HAS_NO_OWNER</varname></term> + <listitem><para>The specified bus service name currently has + no owner.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_NO_REPLY</varname></term> + <listitem><para>A message did not receive a reply. This error + is usually generated after a timeout.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_IO_ERROR</varname></term> + <listitem><para>Generic input/output error, for example when + accessing a socket or other I/O context.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_BAD_ADDRESS</varname></term> + <listitem><para>The specified D-Bus bus address string is + malformed.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_NOT_SUPPORTED</varname></term> + <listitem><para>The requested operation is not supported on + the local system.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_LIMITS_EXCEEDED</varname></term> + <listitem><para>Some limited resource has been + exhausted.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_ACCESS_DENIED</varname></term> + <listitem><para>Access to a resource has been denied due to security restrictions.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_AUTH_FAILED</varname></term> + <listitem><para>Authentication did not complete successfully.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_NO_SERVER</varname></term> + <listitem><para>Unable to connect to the specified server.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_TIMEOUT</varname></term> + <listitem><para>An operation timed out. Note that method calls + which timeout generate a + <varname>SD_BUS_ERROR_NO_REPLY</varname>.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_NO_NETWORK</varname></term> + <listitem><para>No network available to execute requested network operation on.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_ADDRESS_IN_USE</varname></term> + <listitem><para>The specified network address is already being listened on.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_DISCONNECTED</varname></term> + <listitem><para>The connection has been terminated.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_INVALID_ARGS</varname></term> + <listitem><para>One or more invalid arguments have been passed.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_FILE_NOT_FOUND</varname></term> + <listitem><para>The requested file could not be found.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_FILE_EXISTS</varname></term> + <listitem><para>The requested file already exists.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_UNKNOWN_METHOD</varname></term> + <listitem><para>The requested method does not exist in the selected interface.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_UNKNOWN_OBJECT</varname></term> + <listitem><para>The requested object does not exist in the selected service.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_UNKNOWN_INTERFACE</varname></term> + <listitem><para>The requested interface does not exist on the selected object.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_UNKNOWN_PROPERTY</varname></term> + <listitem><para>The requested property does not exist in the selected interface.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_PROPERTY_READ_ONLY</varname></term> + <listitem><para>A write operation was requested on a read-only property.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN</varname></term> + <listitem><para>The requested PID is not known.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_INVALID_SIGNATURE</varname></term> + <listitem><para>The specified message signature is not + valid.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_INCONSISTENT_MESSAGE</varname></term> + <listitem><para>The passed message does not validate + correctly.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_MATCH_RULE_NOT_FOUND</varname></term> + <listitem><para>The specified match rule does not exist.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_MATCH_RULE_INVALID</varname></term> + <listitem><para>The specified match rule is invalid.</para></listitem> + </varlistentry> + <varlistentry> + <term><varname>SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED</varname></term> + <listitem><para>Access to the requested operation is not + permitted. However, it might be available after interactive + authentication. This is usually returned by method calls + supporting a framework for additional interactive + authorization, when interactive authorization was not enabled + with the + <citerefentry><refentrytitle>sd_bus_message_set_allow_interactive_authorization</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for the method call message.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The various error definitions described here are available + as a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_error</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_set_allow_interactive_authorization</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>strerror</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-bus.xml b/src/libsystemd/sd-bus.xml new file mode 100644 index 0000000000..336dd33ea0 --- /dev/null +++ b/src/libsystemd/sd-bus.xml @@ -0,0 +1,123 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-bus" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-bus</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Documentation</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-bus</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-bus</refname> + <refpurpose>A lightweight D-Bus and kdbus client library</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-bus.h</filename> provides an implementation + of a D-Bus client. It can interoperate both with the traditional + <citerefentry project='man-pages'><refentrytitle>dbus-daemon</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + and with kdbus. See + <ulink url="http://www.freedesktop.org/software/dbus/" /> + for more information about the big picture. + </para> + + <important> + <para>Interfaces described here have not been declared stable yet, + and are not accessible from <filename>libsystemd.so</filename>. + This documentation is provided in hope it might be useful for + developers, without any guarantees of availability or stability. + </para> + </important> + + <para>See + <citerefentry><refentrytitle>sd_bus_default</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_request_name</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_start</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_array</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_string_memfd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_strv</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_can_send</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_cookie</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_monotonic_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_send</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_set_address</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_set_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_creds_get_pid</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_creds_new_from_pid</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_get_name_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_get_owner_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_negotiate_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_path_encode</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_error</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_error_add_map</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_set_allow_interactive_authorization</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the functions available.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>dbus-daemon</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>dbus-send</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <ulink url="https://developer.gnome.org/gio/stable/gdbus.html">gdbus</ulink> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-bus/Makefile b/src/libsystemd/sd-bus/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-bus/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-bus/busctl-introspect.c b/src/libsystemd/sd-bus/busctl-introspect.c deleted file mode 100644 index b09509f8e1..0000000000 --- a/src/libsystemd/sd-bus/busctl-introspect.c +++ /dev/null @@ -1,790 +0,0 @@ -/*** - 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 <http://www.gnu.org/licenses/>. -***/ - -#include "sd-bus.h" - -#include "alloc-util.h" -#include "busctl-introspect.h" -#include "string-util.h" -#include "util.h" -#include "xml.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) { - c->interface_name = mfree(c->interface_name); - 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 <annotation> 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 <annotation>. (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 <annotation>. (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 <annotation>. (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("<node> 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 <node> 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 <node> 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 <node>. (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 <node>. (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 <interface> 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 <interface> 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 <interface>. (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 <interface>. (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 <method> 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 <method> 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 <method> (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 <method> (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 <arg> 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 <arg> 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(); - } - } - - argument_type = mfree(argument_type); - argument_direction = mfree(argument_direction); - } - - state = STATE_METHOD; - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in method <arg>. (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 <arg>. (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 <arg>. (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 <arg>. (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 <signal> 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 <signal> 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 <signal>. (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 <signal>. (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 <arg> 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 <arg> 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(); - - argument_type = mfree(argument_type); - } - - state = STATE_SIGNAL; - } else if (t != XML_TEXT || !in_charset(name, WHITESPACE)) { - log_error("Unexpected token in signal <arg> (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 <arg> (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 <arg> (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 <property> 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 <property> 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 <property>. (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 <property>. (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 <property>. (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 <property>. (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/libsystemd/sd-bus/busctl-introspect.h b/src/libsystemd/sd-bus/busctl-introspect.h deleted file mode 100644 index d922e352db..0000000000 --- a/src/libsystemd/sd-bus/busctl-introspect.h +++ /dev/null @@ -1,32 +0,0 @@ -#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 <http://www.gnu.org/licenses/>. -***/ - -#include <stdbool.h> - -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/libsystemd/sd-bus/busctl.c b/src/libsystemd/sd-bus/busctl.c deleted file mode 100644 index eb042e9c81..0000000000 --- a/src/libsystemd/sd-bus/busctl.c +++ /dev/null @@ -1,2087 +0,0 @@ -/*** - 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 <http://www.gnu.org/licenses/>. -***/ - -#include <getopt.h> - -#include "sd-bus.h" - -#include "alloc-util.h" -#include "bus-dump.h" -#include "bus-internal.h" -#include "bus-signature.h" -#include "bus-type.h" -#include "bus-util.h" -#include "busctl-introspect.h" -#include "escape.h" -#include "fd-util.h" -#include "locale-util.h" -#include "log.h" -#include "pager.h" -#include "parse-util.h" -#include "path-util.h" -#include "set.h" -#include "strv.h" -#include "terminal-util.h" -#include "user-util.h" -#include "util.h" - -static bool arg_no_pager = false; -static bool arg_legend = true; -static char *arg_address = NULL; -static bool arg_unique = false; -static bool arg_acquired = false; -static bool arg_activatable = false; -static bool arg_show_machine = false; -static char **arg_matches = NULL; -static BusTransport arg_transport = BUS_TRANSPORT_LOCAL; -static char *arg_host = NULL; -static bool arg_user = false; -static size_t arg_snaplen = 4096; -static bool arg_list = false; -static bool arg_quiet = false; -static bool arg_verbose = false; -static bool arg_expect_reply = true; -static bool arg_auto_start = true; -static bool arg_allow_interactive_authorization = true; -static bool arg_augment_creds = true; -static usec_t arg_timeout = 0; - -#define NAME_IS_ACQUIRED INT_TO_PTR(1) -#define NAME_IS_ACTIVATABLE INT_TO_PTR(2) - -static int list_bus_names(sd_bus *bus, char **argv) { - _cleanup_strv_free_ char **acquired = NULL, **activatable = NULL; - _cleanup_free_ char **merged = NULL; - _cleanup_hashmap_free_ Hashmap *names = NULL; - char **i; - int r; - size_t max_i = 0; - unsigned n = 0; - void *v; - char *k; - Iterator iterator; - - assert(bus); - - if (!arg_unique && !arg_acquired && !arg_activatable) - arg_unique = arg_acquired = arg_activatable = true; - - r = sd_bus_list_names(bus, (arg_acquired || arg_unique) ? &acquired : NULL, arg_activatable ? &activatable : NULL); - if (r < 0) - return log_error_errno(r, "Failed to list names: %m"); - - pager_open(arg_no_pager, false); - - names = hashmap_new(&string_hash_ops); - if (!names) - return log_oom(); - - STRV_FOREACH(i, acquired) { - max_i = MAX(max_i, strlen(*i)); - - r = hashmap_put(names, *i, NAME_IS_ACQUIRED); - if (r < 0) - return log_error_errno(r, "Failed to add to hashmap: %m"); - } - - STRV_FOREACH(i, activatable) { - max_i = MAX(max_i, strlen(*i)); - - r = hashmap_put(names, *i, NAME_IS_ACTIVATABLE); - if (r < 0 && r != -EEXIST) - return log_error_errno(r, "Failed to add to hashmap: %m"); - } - - merged = new(char*, hashmap_size(names) + 1); - HASHMAP_FOREACH_KEY(v, k, names, iterator) - merged[n++] = k; - - merged[n] = NULL; - strv_sort(merged); - - if (arg_legend) { - printf("%-*s %*s %-*s %-*s %-*s %-*s %-*s %-*s", - (int) max_i, "NAME", 10, "PID", 15, "PROCESS", 16, "USER", 13, "CONNECTION", 25, "UNIT", 10, "SESSION", 19, "DESCRIPTION"); - - if (arg_show_machine) - puts(" MACHINE"); - else - putchar('\n'); - } - - STRV_FOREACH(i, merged) { - _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL; - sd_id128_t mid; - - if (hashmap_get(names, *i) == NAME_IS_ACTIVATABLE) { - /* Activatable */ - - printf("%-*s", (int) max_i, *i); - printf(" - - - (activatable) - - "); - if (arg_show_machine) - puts(" -"); - else - putchar('\n'); - continue; - - } - - if (!arg_unique && (*i)[0] == ':') - continue; - - if (!arg_acquired && (*i)[0] != ':') - continue; - - printf("%-*s", (int) max_i, *i); - - r = sd_bus_get_name_creds( - bus, *i, - (arg_augment_creds ? SD_BUS_CREDS_AUGMENT : 0) | - SD_BUS_CREDS_EUID|SD_BUS_CREDS_PID|SD_BUS_CREDS_COMM| - SD_BUS_CREDS_UNIQUE_NAME|SD_BUS_CREDS_UNIT|SD_BUS_CREDS_SESSION| - SD_BUS_CREDS_DESCRIPTION, &creds); - if (r >= 0) { - const char *unique, *session, *unit, *cn; - pid_t pid; - uid_t uid; - - r = sd_bus_creds_get_pid(creds, &pid); - if (r >= 0) { - const char *comm = NULL; - - sd_bus_creds_get_comm(creds, &comm); - - printf(" %10lu %-15s", (unsigned long) pid, strna(comm)); - } else - fputs(" - - ", stdout); - - r = sd_bus_creds_get_euid(creds, &uid); - if (r >= 0) { - _cleanup_free_ char *u = NULL; - - u = uid_to_name(uid); - if (!u) - return log_oom(); - - if (strlen(u) > 16) - u[16] = 0; - - printf(" %-16s", u); - } else - fputs(" - ", stdout); - - r = sd_bus_creds_get_unique_name(creds, &unique); - if (r >= 0) - printf(" %-13s", unique); - else - fputs(" - ", stdout); - - r = sd_bus_creds_get_unit(creds, &unit); - if (r >= 0) { - _cleanup_free_ char *e; - - e = ellipsize(unit, 25, 100); - if (!e) - return log_oom(); - - printf(" %-25s", e); - } else - fputs(" - ", stdout); - - r = sd_bus_creds_get_session(creds, &session); - if (r >= 0) - printf(" %-10s", session); - else - fputs(" - ", stdout); - - r = sd_bus_creds_get_description(creds, &cn); - if (r >= 0) - printf(" %-19s", cn); - else - fputs(" - ", stdout); - - } else - printf(" - - - - - - - "); - - if (arg_show_machine) { - r = sd_bus_get_name_machine_id(bus, *i, &mid); - if (r >= 0) { - char m[SD_ID128_STRING_MAX]; - printf(" %s\n", sd_id128_to_string(mid, m)); - } else - puts(" -"); - } else - putchar('\n'); - } - - return 0; -} - -static void print_subtree(const char *prefix, const char *path, char **l) { - const char *vertical, *space; - char **n; - - /* We assume the list is sorted. Let's first skip over the - * entry we are looking at. */ - for (;;) { - if (!*l) - return; - - if (!streq(*l, path)) - break; - - l++; - } - - vertical = strjoina(prefix, special_glyph(TREE_VERTICAL)); - space = strjoina(prefix, special_glyph(TREE_SPACE)); - - for (;;) { - bool has_more = false; - - if (!*l || !path_startswith(*l, path)) - break; - - n = l + 1; - for (;;) { - if (!*n || !path_startswith(*n, path)) - break; - - if (!path_startswith(*n, *l)) { - has_more = true; - break; - } - - n++; - } - - printf("%s%s%s\n", prefix, special_glyph(has_more ? TREE_BRANCH : TREE_RIGHT), *l); - - print_subtree(has_more ? vertical : space, *l, l); - l = n; - } -} - -static void print_tree(const char *prefix, char **l) { - - pager_open(arg_no_pager, false); - - prefix = strempty(prefix); - - if (arg_list) { - char **i; - - STRV_FOREACH(i, l) - printf("%s%s\n", prefix, *i); - return; - } - - if (strv_isempty(l)) { - printf("No objects discovered.\n"); - return; - } - - if (streq(l[0], "/") && !l[1]) { - printf("Only root object discovered.\n"); - return; - } - - print_subtree(prefix, "/", l); -} - -static int on_path(const char *path, void *userdata) { - Set *paths = userdata; - int r; - - assert(paths); - - r = set_put_strdup(paths, path); - if (r < 0) - return log_oom(); - - return 0; -} - -static int find_nodes(sd_bus *bus, const char *service, const char *path, Set *paths, bool many) { - static const XMLIntrospectOps ops = { - .on_path = on_path, - }; - - _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - const char *xml; - int r; - - r = sd_bus_call_method(bus, service, path, "org.freedesktop.DBus.Introspectable", "Introspect", &error, &reply, ""); - if (r < 0) { - if (many) - printf("Failed to introspect object %s of service %s: %s\n", path, service, bus_error_message(&error, r)); - else - log_error("Failed to introspect object %s of service %s: %s", path, service, bus_error_message(&error, r)); - return r; - } - - r = sd_bus_message_read(reply, "s", &xml); - if (r < 0) - return bus_log_parse_error(r); - - return parse_xml_introspect(path, xml, &ops, paths); -} - -static int tree_one(sd_bus *bus, const char *service, const char *prefix, bool many) { - _cleanup_set_free_free_ Set *paths = NULL, *done = NULL, *failed = NULL; - _cleanup_free_ char **l = NULL; - char *m; - int r; - - paths = set_new(&string_hash_ops); - if (!paths) - return log_oom(); - - done = set_new(&string_hash_ops); - if (!done) - return log_oom(); - - failed = set_new(&string_hash_ops); - if (!failed) - return log_oom(); - - m = strdup("/"); - if (!m) - return log_oom(); - - r = set_put(paths, m); - if (r < 0) { - free(m); - return log_oom(); - } - - for (;;) { - _cleanup_free_ char *p = NULL; - int q; - - p = set_steal_first(paths); - if (!p) - break; - - if (set_contains(done, p) || - set_contains(failed, p)) - continue; - - q = find_nodes(bus, service, p, paths, many); - if (q < 0) { - if (r >= 0) - r = q; - - q = set_put(failed, p); - } else - q = set_put(done, p); - - if (q < 0) - return log_oom(); - - assert(q != 0); - p = NULL; - } - - pager_open(arg_no_pager, false); - - l = set_get_strv(done); - if (!l) - return log_oom(); - - strv_sort(l); - print_tree(prefix, l); - - fflush(stdout); - - return r; -} - -static int tree(sd_bus *bus, char **argv) { - char **i; - int r = 0; - - if (!arg_unique && !arg_acquired) - arg_acquired = true; - - if (strv_length(argv) <= 1) { - _cleanup_strv_free_ char **names = NULL; - bool not_first = false; - - r = sd_bus_list_names(bus, &names, NULL); - if (r < 0) - return log_error_errno(r, "Failed to get name list: %m"); - - pager_open(arg_no_pager, false); - - STRV_FOREACH(i, names) { - int q; - - if (!arg_unique && (*i)[0] == ':') - continue; - - if (!arg_acquired && (*i)[0] == ':') - continue; - - if (not_first) - printf("\n"); - - printf("Service %s%s%s:\n", ansi_highlight(), *i, ansi_normal()); - - q = tree_one(bus, *i, NULL, true); - if (q < 0 && r >= 0) - r = q; - - not_first = true; - } - } else { - STRV_FOREACH(i, argv+1) { - int q; - - if (i > argv+1) - printf("\n"); - - if (argv[2]) { - pager_open(arg_no_pager, false); - printf("Service %s%s%s:\n", ansi_highlight(), *i, ansi_normal()); - } - - q = tree_one(bus, *i, NULL, !!argv[2]); - if (q < 0 && r >= 0) - r = q; - } - } - - return r; -} - -static int format_cmdline(sd_bus_message *m, FILE *f, bool needs_space) { - int r; - - for (;;) { - 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 r; - if (r == 0) - return needs_space; - - if (bus_type_is_container(type) > 0) { - - r = sd_bus_message_enter_container(m, type, contents); - if (r < 0) - return r; - - if (type == SD_BUS_TYPE_ARRAY) { - unsigned n = 0; - - /* count array entries */ - for (;;) { - - r = sd_bus_message_skip(m, contents); - if (r < 0) - return r; - if (r == 0) - break; - - n++; - } - - r = sd_bus_message_rewind(m, false); - if (r < 0) - return r; - - if (needs_space) - fputc(' ', f); - - fprintf(f, "%u", n); - needs_space = true; - - } else if (type == SD_BUS_TYPE_VARIANT) { - - if (needs_space) - fputc(' ', f); - - fprintf(f, "%s", contents); - needs_space = true; - } - - r = format_cmdline(m, f, needs_space); - if (r < 0) - return r; - - needs_space = r > 0; - - r = sd_bus_message_exit_container(m); - if (r < 0) - return r; - - continue; - } - - r = sd_bus_message_read_basic(m, type, &basic); - if (r < 0) - return r; - - if (needs_space) - fputc(' ', f); - - switch (type) { - case SD_BUS_TYPE_BYTE: - fprintf(f, "%u", basic.u8); - break; - - case SD_BUS_TYPE_BOOLEAN: - fputs(true_false(basic.i), f); - break; - - case SD_BUS_TYPE_INT16: - fprintf(f, "%i", basic.s16); - break; - - case SD_BUS_TYPE_UINT16: - fprintf(f, "%u", basic.u16); - break; - - case SD_BUS_TYPE_INT32: - fprintf(f, "%i", basic.s32); - break; - - case SD_BUS_TYPE_UINT32: - fprintf(f, "%u", basic.u32); - break; - - case SD_BUS_TYPE_INT64: - fprintf(f, "%" PRIi64, basic.s64); - break; - - case SD_BUS_TYPE_UINT64: - fprintf(f, "%" PRIu64, basic.u64); - break; - - case SD_BUS_TYPE_DOUBLE: - fprintf(f, "%g", basic.d64); - break; - - case SD_BUS_TYPE_STRING: - case SD_BUS_TYPE_OBJECT_PATH: - case SD_BUS_TYPE_SIGNATURE: { - _cleanup_free_ char *b = NULL; - - b = cescape(basic.string); - if (!b) - return -ENOMEM; - - fprintf(f, "\"%s\"", b); - break; - } - - case SD_BUS_TYPE_UNIX_FD: - fprintf(f, "%i", basic.i); - break; - - default: - assert_not_reached("Unknown basic type."); - } - - needs_space = true; - } -} - -typedef struct Member { - const char *type; - char *interface; - char *name; - char *signature; - char *result; - char *value; - bool writable; - uint64_t flags; -} Member; - -static void member_hash_func(const void *p, struct siphash *state) { - const Member *m = p; - uint64_t arity = 1; - - assert(m); - assert(m->type); - - string_hash_func(m->type, state); - - arity += !!m->name + !!m->interface; - - uint64_hash_func(&arity, state); - - if (m->name) - string_hash_func(m->name, state); - - if (m->interface) - string_hash_func(m->interface, state); -} - -static int member_compare_func(const void *a, const void *b) { - const Member *x = a, *y = b; - int d; - - assert(x); - assert(y); - assert(x->type); - assert(y->type); - - d = strcmp_ptr(x->interface, y->interface); - if (d != 0) - return d; - - d = strcmp(x->type, y->type); - if (d != 0) - return d; - - return strcmp_ptr(x->name, y->name); -} - -static int member_compare_funcp(const void *a, const void *b) { - const Member *const * x = (const Member *const *) a, * const *y = (const Member *const *) b; - - return member_compare_func(*x, *y); -} - -static void member_free(Member *m) { - if (!m) - return; - - free(m->interface); - free(m->name); - free(m->signature); - free(m->result); - free(m->value); - free(m); -} - -DEFINE_TRIVIAL_CLEANUP_FUNC(Member*, member_free); - -static void member_set_free(Set *s) { - Member *m; - - while ((m = set_steal_first(s))) - member_free(m); - - set_free(s); -} - -DEFINE_TRIVIAL_CLEANUP_FUNC(Set*, member_set_free); - -static int on_interface(const char *interface, uint64_t flags, void *userdata) { - _cleanup_(member_freep) Member *m; - Set *members = userdata; - int r; - - assert(interface); - assert(members); - - m = new0(Member, 1); - if (!m) - return log_oom(); - - m->type = "interface"; - m->flags = flags; - - r = free_and_strdup(&m->interface, interface); - if (r < 0) - return log_oom(); - - r = set_put(members, m); - if (r <= 0) { - log_error("Duplicate interface"); - return -EINVAL; - } - - m = NULL; - return 0; -} - -static int on_method(const char *interface, const char *name, const char *signature, const char *result, uint64_t flags, void *userdata) { - _cleanup_(member_freep) Member *m; - Set *members = userdata; - int r; - - assert(interface); - assert(name); - - m = new0(Member, 1); - if (!m) - return log_oom(); - - m->type = "method"; - m->flags = flags; - - r = free_and_strdup(&m->interface, interface); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->name, name); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->signature, signature); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->result, result); - if (r < 0) - return log_oom(); - - r = set_put(members, m); - if (r <= 0) { - log_error("Duplicate method"); - return -EINVAL; - } - - m = NULL; - return 0; -} - -static int on_signal(const char *interface, const char *name, const char *signature, uint64_t flags, void *userdata) { - _cleanup_(member_freep) Member *m; - Set *members = userdata; - int r; - - assert(interface); - assert(name); - - m = new0(Member, 1); - if (!m) - return log_oom(); - - m->type = "signal"; - m->flags = flags; - - r = free_and_strdup(&m->interface, interface); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->name, name); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->signature, signature); - if (r < 0) - return log_oom(); - - r = set_put(members, m); - if (r <= 0) { - log_error("Duplicate signal"); - return -EINVAL; - } - - m = NULL; - return 0; -} - -static int on_property(const char *interface, const char *name, const char *signature, bool writable, uint64_t flags, void *userdata) { - _cleanup_(member_freep) Member *m; - Set *members = userdata; - int r; - - assert(interface); - assert(name); - - m = new0(Member, 1); - if (!m) - return log_oom(); - - m->type = "property"; - m->flags = flags; - m->writable = writable; - - r = free_and_strdup(&m->interface, interface); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->name, name); - if (r < 0) - return log_oom(); - - r = free_and_strdup(&m->signature, signature); - if (r < 0) - return log_oom(); - - r = set_put(members, m); - if (r <= 0) { - log_error("Duplicate property"); - return -EINVAL; - } - - m = NULL; - return 0; -} - -static const char *strdash(const char *x) { - return isempty(x) ? "-" : x; -} - -static int introspect(sd_bus *bus, char **argv) { - static const struct hash_ops member_hash_ops = { - .hash = member_hash_func, - .compare = member_compare_func, - }; - - static const XMLIntrospectOps ops = { - .on_interface = on_interface, - .on_method = on_method, - .on_signal = on_signal, - .on_property = on_property, - }; - - _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - _cleanup_(member_set_freep) Set *members = NULL; - Iterator i; - Member *m; - const char *xml; - int r; - unsigned name_width, type_width, signature_width, result_width; - Member **sorted = NULL; - unsigned k = 0, j, n_args; - - n_args = strv_length(argv); - if (n_args < 3) { - log_error("Requires service and object path argument."); - return -EINVAL; - } - - if (n_args > 4) { - log_error("Too many arguments."); - return -EINVAL; - } - - members = set_new(&member_hash_ops); - if (!members) - return log_oom(); - - r = sd_bus_call_method(bus, argv[1], argv[2], "org.freedesktop.DBus.Introspectable", "Introspect", &error, &reply, ""); - if (r < 0) { - log_error("Failed to introspect object %s of service %s: %s", argv[2], argv[1], bus_error_message(&error, r)); - return r; - } - - r = sd_bus_message_read(reply, "s", &xml); - if (r < 0) - return bus_log_parse_error(r); - - /* First, get list of all properties */ - r = parse_xml_introspect(argv[2], xml, &ops, members); - if (r < 0) - return r; - - /* Second, find the current values for them */ - SET_FOREACH(m, members, i) { - - if (!streq(m->type, "property")) - continue; - - if (m->value) - continue; - - if (argv[3] && !streq(argv[3], m->interface)) - continue; - - r = sd_bus_call_method(bus, argv[1], argv[2], "org.freedesktop.DBus.Properties", "GetAll", &error, &reply, "s", m->interface); - if (r < 0) { - log_error("%s", bus_error_message(&error, r)); - return r; - } - - r = sd_bus_message_enter_container(reply, 'a', "{sv}"); - if (r < 0) - return bus_log_parse_error(r); - - for (;;) { - Member *z; - _cleanup_free_ char *buf = NULL; - _cleanup_fclose_ FILE *mf = NULL; - size_t sz = 0; - const char *name; - - r = sd_bus_message_enter_container(reply, 'e', "sv"); - if (r < 0) - return bus_log_parse_error(r); - - if (r == 0) - break; - - r = sd_bus_message_read(reply, "s", &name); - if (r < 0) - return bus_log_parse_error(r); - - r = sd_bus_message_enter_container(reply, 'v', NULL); - if (r < 0) - return bus_log_parse_error(r); - - mf = open_memstream(&buf, &sz); - if (!mf) - return log_oom(); - - r = format_cmdline(reply, mf, false); - if (r < 0) - return bus_log_parse_error(r); - - fclose(mf); - mf = NULL; - - z = set_get(members, &((Member) { - .type = "property", - .interface = m->interface, - .name = (char*) name })); - if (z) { - free(z->value); - z->value = buf; - buf = NULL; - } - - r = sd_bus_message_exit_container(reply); - if (r < 0) - return bus_log_parse_error(r); - - r = sd_bus_message_exit_container(reply); - if (r < 0) - return bus_log_parse_error(r); - } - - r = sd_bus_message_exit_container(reply); - if (r < 0) - return bus_log_parse_error(r); - } - - pager_open(arg_no_pager, false); - - name_width = strlen("NAME"); - type_width = strlen("TYPE"); - signature_width = strlen("SIGNATURE"); - result_width = strlen("RESULT/VALUE"); - - sorted = newa(Member*, set_size(members)); - - SET_FOREACH(m, members, i) { - - if (argv[3] && !streq(argv[3], m->interface)) - continue; - - if (m->interface) - name_width = MAX(name_width, strlen(m->interface)); - if (m->name) - name_width = MAX(name_width, strlen(m->name) + 1); - if (m->type) - type_width = MAX(type_width, strlen(m->type)); - if (m->signature) - signature_width = MAX(signature_width, strlen(m->signature)); - if (m->result) - result_width = MAX(result_width, strlen(m->result)); - if (m->value) - result_width = MAX(result_width, strlen(m->value)); - - sorted[k++] = m; - } - - if (result_width > 40) - result_width = 40; - - qsort(sorted, k, sizeof(Member*), member_compare_funcp); - - if (arg_legend) { - printf("%-*s %-*s %-*s %-*s %s\n", - (int) name_width, "NAME", - (int) type_width, "TYPE", - (int) signature_width, "SIGNATURE", - (int) result_width, "RESULT/VALUE", - "FLAGS"); - } - - for (j = 0; j < k; j++) { - _cleanup_free_ char *ellipsized = NULL; - const char *rv; - bool is_interface; - - m = sorted[j]; - - if (argv[3] && !streq(argv[3], m->interface)) - continue; - - is_interface = streq(m->type, "interface"); - - if (argv[3] && is_interface) - continue; - - if (m->value) { - ellipsized = ellipsize(m->value, result_width, 100); - if (!ellipsized) - return log_oom(); - - rv = ellipsized; - } else - rv = strdash(m->result); - - printf("%s%s%-*s%s %-*s %-*s %-*s%s%s%s%s%s%s\n", - is_interface ? ansi_highlight() : "", - is_interface ? "" : ".", - - !is_interface + (int) name_width, strdash(streq_ptr(m->type, "interface") ? m->interface : m->name), - is_interface ? ansi_normal() : "", - (int) type_width, strdash(m->type), - (int) signature_width, strdash(m->signature), - (int) result_width, rv, - (m->flags & SD_BUS_VTABLE_DEPRECATED) ? " deprecated" : (m->flags || m->writable ? "" : " -"), - (m->flags & SD_BUS_VTABLE_METHOD_NO_REPLY) ? " no-reply" : "", - (m->flags & SD_BUS_VTABLE_PROPERTY_CONST) ? " const" : "", - (m->flags & SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE) ? " emits-change" : "", - (m->flags & SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION) ? " emits-invalidation" : "", - m->writable ? " writable" : ""); - } - - return 0; -} - -static int message_dump(sd_bus_message *m, FILE *f) { - return bus_message_dump(m, f, BUS_MESSAGE_DUMP_WITH_HEADER); -} - -static int message_pcap(sd_bus_message *m, FILE *f) { - return bus_message_pcap_frame(m, arg_snaplen, f); -} - -static int monitor(sd_bus *bus, char *argv[], int (*dump)(sd_bus_message *m, FILE *f)) { - _cleanup_(sd_bus_message_unrefp) sd_bus_message *message = NULL; - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - char **i; - uint32_t flags = 0; - int r; - - /* upgrade connection; it's not used for anything else after this call */ - r = sd_bus_message_new_method_call(bus, &message, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus.Monitoring", "BecomeMonitor"); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_open_container(message, 'a', "s"); - if (r < 0) - return bus_log_create_error(r); - - STRV_FOREACH(i, argv+1) { - _cleanup_free_ char *m = NULL; - - if (!service_name_is_valid(*i)) { - log_error("Invalid service name '%s'", *i); - return -EINVAL; - } - - m = strjoin("sender='", *i, "'", NULL); - if (!m) - return log_oom(); - - r = sd_bus_message_append_basic(message, 's', m); - if (r < 0) - return bus_log_create_error(r); - - free(m); - m = strjoin("destination='", *i, "'", NULL); - if (!m) - return log_oom(); - - r = sd_bus_message_append_basic(message, 's', m); - if (r < 0) - return bus_log_create_error(r); - } - - STRV_FOREACH(i, arg_matches) { - r = sd_bus_message_append_basic(message, 's', *i); - if (r < 0) - return bus_log_create_error(r); - } - - r = sd_bus_message_close_container(message); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_append_basic(message, 'u', &flags); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_call(bus, message, arg_timeout, &error, NULL); - if (r < 0) { - log_error("%s", bus_error_message(&error, r)); - return r; - } - - log_info("Monitoring bus message stream."); - - for (;;) { - _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; - - r = sd_bus_process(bus, &m); - if (r < 0) - return log_error_errno(r, "Failed to process bus: %m"); - - if (m) { - dump(m, stdout); - fflush(stdout); - - if (sd_bus_message_is_signal(m, "org.freedesktop.DBus.Local", "Disconnected") > 0) { - log_info("Connection terminated, exiting."); - return 0; - } - - continue; - } - - if (r > 0) - continue; - - r = sd_bus_wait(bus, (uint64_t) -1); - if (r < 0) - return log_error_errno(r, "Failed to wait for bus: %m"); - } -} - -static int capture(sd_bus *bus, char *argv[]) { - int r; - - if (isatty(fileno(stdout)) > 0) { - log_error("Refusing to write message data to console, please redirect output to a file."); - return -EINVAL; - } - - bus_pcap_header(arg_snaplen, stdout); - - r = monitor(bus, argv, message_pcap); - if (r < 0) - return r; - - if (ferror(stdout)) { - log_error("Couldn't write capture file."); - return -EIO; - } - - return r; -} - -static int status(sd_bus *bus, char *argv[]) { - _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL; - pid_t pid; - int r; - - assert(bus); - - if (strv_length(argv) > 2) { - log_error("Expects no or one argument."); - return -EINVAL; - } - - if (argv[1]) { - r = parse_pid(argv[1], &pid); - if (r < 0) - r = sd_bus_get_name_creds( - bus, - argv[1], - (arg_augment_creds ? SD_BUS_CREDS_AUGMENT : 0) | _SD_BUS_CREDS_ALL, - &creds); - else - r = sd_bus_creds_new_from_pid( - &creds, - pid, - _SD_BUS_CREDS_ALL); - } else { - const char *scope, *address; - sd_id128_t bus_id; - - r = sd_bus_get_address(bus, &address); - if (r >= 0) - printf("BusAddress=%s%s%s\n", ansi_highlight(), address, ansi_normal()); - - r = sd_bus_get_scope(bus, &scope); - if (r >= 0) - printf("BusScope=%s%s%s\n", ansi_highlight(), scope, ansi_normal()); - - r = sd_bus_get_bus_id(bus, &bus_id); - if (r >= 0) - printf("BusID=%s" SD_ID128_FORMAT_STR "%s\n", ansi_highlight(), SD_ID128_FORMAT_VAL(bus_id), ansi_normal()); - - r = sd_bus_get_owner_creds( - bus, - (arg_augment_creds ? SD_BUS_CREDS_AUGMENT : 0) | _SD_BUS_CREDS_ALL, - &creds); - } - - if (r < 0) - return log_error_errno(r, "Failed to get credentials: %m"); - - bus_creds_dump(creds, NULL, false); - return 0; -} - -static int message_append_cmdline(sd_bus_message *m, const char *signature, char ***x) { - char **p; - int r; - - assert(m); - assert(signature); - assert(x); - - p = *x; - - for (;;) { - const char *v; - char t; - - t = *signature; - v = *p; - - if (t == 0) - break; - if (!v) { - log_error("Too few parameters for signature."); - return -EINVAL; - } - - signature++; - p++; - - switch (t) { - - case SD_BUS_TYPE_BOOLEAN: - - r = parse_boolean(v); - if (r < 0) { - log_error("Failed to parse as boolean: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &r); - break; - - case SD_BUS_TYPE_BYTE: { - uint8_t z; - - r = safe_atou8(v, &z); - if (r < 0) { - log_error("Failed to parse as byte (unsigned 8bit integer): %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_INT16: { - int16_t z; - - r = safe_atoi16(v, &z); - if (r < 0) { - log_error("Failed to parse as signed 16bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_UINT16: { - uint16_t z; - - r = safe_atou16(v, &z); - if (r < 0) { - log_error("Failed to parse as unsigned 16bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_INT32: { - int32_t z; - - r = safe_atoi32(v, &z); - if (r < 0) { - log_error("Failed to parse as signed 32bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_UINT32: { - uint32_t z; - - r = safe_atou32(v, &z); - if (r < 0) { - log_error("Failed to parse as unsigned 32bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_INT64: { - int64_t z; - - r = safe_atoi64(v, &z); - if (r < 0) { - log_error("Failed to parse as signed 64bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_UINT64: { - uint64_t z; - - r = safe_atou64(v, &z); - if (r < 0) { - log_error("Failed to parse as unsigned 64bit integer: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - - case SD_BUS_TYPE_DOUBLE: { - double z; - - r = safe_atod(v, &z); - if (r < 0) { - log_error("Failed to parse as double precision floating point: %s", v); - return r; - } - - r = sd_bus_message_append_basic(m, t, &z); - break; - } - - case SD_BUS_TYPE_STRING: - case SD_BUS_TYPE_OBJECT_PATH: - case SD_BUS_TYPE_SIGNATURE: - - r = sd_bus_message_append_basic(m, t, v); - break; - - case SD_BUS_TYPE_ARRAY: { - uint32_t n; - size_t k; - - r = safe_atou32(v, &n); - if (r < 0) { - log_error("Failed to parse number of array entries: %s", v); - return r; - } - - r = signature_element_length(signature, &k); - if (r < 0) { - log_error("Invalid array signature."); - return r; - } - - { - unsigned i; - char s[k + 1]; - memcpy(s, signature, k); - s[k] = 0; - - r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, s); - if (r < 0) - return bus_log_create_error(r); - - for (i = 0; i < n; i++) { - r = message_append_cmdline(m, s, &p); - if (r < 0) - return r; - } - } - - signature += k; - - r = sd_bus_message_close_container(m); - break; - } - - case SD_BUS_TYPE_VARIANT: - r = sd_bus_message_open_container(m, SD_BUS_TYPE_VARIANT, v); - if (r < 0) - return bus_log_create_error(r); - - r = message_append_cmdline(m, v, &p); - if (r < 0) - return r; - - r = sd_bus_message_close_container(m); - break; - - case SD_BUS_TYPE_STRUCT_BEGIN: - case SD_BUS_TYPE_DICT_ENTRY_BEGIN: { - size_t k; - - signature--; - p--; - - r = signature_element_length(signature, &k); - if (r < 0) { - log_error("Invalid struct/dict entry signature."); - return r; - } - - { - char s[k-1]; - memcpy(s, signature + 1, k - 2); - s[k - 2] = 0; - - r = sd_bus_message_open_container(m, t == SD_BUS_TYPE_STRUCT_BEGIN ? SD_BUS_TYPE_STRUCT : SD_BUS_TYPE_DICT_ENTRY, s); - if (r < 0) - return bus_log_create_error(r); - - r = message_append_cmdline(m, s, &p); - if (r < 0) - return r; - } - - signature += k; - - r = sd_bus_message_close_container(m); - break; - } - - case SD_BUS_TYPE_UNIX_FD: - log_error("UNIX file descriptor not supported as type."); - return -EINVAL; - - default: - log_error("Unknown signature type %c.", t); - return -EINVAL; - } - - if (r < 0) - return bus_log_create_error(r); - } - - *x = p; - return 0; -} - -static int call(sd_bus *bus, char *argv[]) { - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL; - int r; - - assert(bus); - - if (strv_length(argv) < 5) { - log_error("Expects at least four arguments."); - return -EINVAL; - } - - r = sd_bus_message_new_method_call(bus, &m, argv[1], argv[2], argv[3], argv[4]); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_set_expect_reply(m, arg_expect_reply); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_set_auto_start(m, arg_auto_start); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_set_allow_interactive_authorization(m, arg_allow_interactive_authorization); - if (r < 0) - return bus_log_create_error(r); - - if (!isempty(argv[5])) { - char **p; - - p = argv+6; - - r = message_append_cmdline(m, argv[5], &p); - if (r < 0) - return r; - - if (*p) { - log_error("Too many parameters for signature."); - return -EINVAL; - } - } - - if (!arg_expect_reply) { - r = sd_bus_send(bus, m, NULL); - if (r < 0) { - log_error("Failed to send message."); - return r; - } - - return 0; - } - - r = sd_bus_call(bus, m, arg_timeout, &error, &reply); - if (r < 0) { - log_error("%s", bus_error_message(&error, r)); - return r; - } - - r = sd_bus_message_is_empty(reply); - if (r < 0) - return bus_log_parse_error(r); - - if (r == 0 && !arg_quiet) { - - if (arg_verbose) { - pager_open(arg_no_pager, false); - - r = bus_message_dump(reply, stdout, 0); - if (r < 0) - return r; - } else { - - fputs(sd_bus_message_get_signature(reply, true), stdout); - fputc(' ', stdout); - - r = format_cmdline(reply, stdout, false); - if (r < 0) - return bus_log_parse_error(r); - - fputc('\n', stdout); - } - } - - return 0; -} - -static int get_property(sd_bus *bus, char *argv[]) { - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - unsigned n; - char **i; - int r; - - assert(bus); - - n = strv_length(argv); - if (n < 5) { - log_error("Expects at least four arguments."); - return -EINVAL; - } - - STRV_FOREACH(i, argv + 4) { - _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; - const char *contents = NULL; - char type; - - r = sd_bus_call_method(bus, argv[1], argv[2], "org.freedesktop.DBus.Properties", "Get", &error, &reply, "ss", argv[3], *i); - if (r < 0) { - log_error("%s", bus_error_message(&error, r)); - return r; - } - - r = sd_bus_message_peek_type(reply, &type, &contents); - if (r < 0) - return bus_log_parse_error(r); - - r = sd_bus_message_enter_container(reply, 'v', contents); - if (r < 0) - return bus_log_parse_error(r); - - if (arg_verbose) { - pager_open(arg_no_pager, false); - - r = bus_message_dump(reply, stdout, BUS_MESSAGE_DUMP_SUBTREE_ONLY); - if (r < 0) - return r; - } else { - fputs(contents, stdout); - fputc(' ', stdout); - - r = format_cmdline(reply, stdout, false); - if (r < 0) - return bus_log_parse_error(r); - - fputc('\n', stdout); - } - - r = sd_bus_message_exit_container(reply); - if (r < 0) - return bus_log_parse_error(r); - } - - return 0; -} - -static int set_property(sd_bus *bus, char *argv[]) { - _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; - _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; - unsigned n; - char **p; - int r; - - assert(bus); - - n = strv_length(argv); - if (n < 6) { - log_error("Expects at least five arguments."); - return -EINVAL; - } - - r = sd_bus_message_new_method_call(bus, &m, argv[1], argv[2], "org.freedesktop.DBus.Properties", "Set"); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_append(m, "ss", argv[3], argv[4]); - if (r < 0) - return bus_log_create_error(r); - - r = sd_bus_message_open_container(m, 'v', argv[5]); - if (r < 0) - return bus_log_create_error(r); - - p = argv+6; - r = message_append_cmdline(m, argv[5], &p); - if (r < 0) - return r; - - r = sd_bus_message_close_container(m); - if (r < 0) - return bus_log_create_error(r); - - if (*p) { - log_error("Too many parameters for signature."); - return -EINVAL; - } - - r = sd_bus_call(bus, m, arg_timeout, &error, NULL); - if (r < 0) { - log_error("%s", bus_error_message(&error, r)); - return r; - } - - return 0; -} - -static int help(void) { - printf("%s [OPTIONS...] {COMMAND} ...\n\n" - "Introspect the bus.\n\n" - " -h --help Show this help\n" - " --version Show package version\n" - " --no-pager Do not pipe output into a pager\n" - " --no-legend Do not show the headers and footers\n" - " --system Connect to system bus\n" - " --user Connect to user bus\n" - " -H --host=[USER@]HOST Operate on remote host\n" - " -M --machine=CONTAINER Operate on local container\n" - " --address=ADDRESS Connect to bus specified by address\n" - " --show-machine Show machine ID column in list\n" - " --unique Only show unique names\n" - " --acquired Only show acquired names\n" - " --activatable Only show activatable names\n" - " --match=MATCH Only show matching messages\n" - " --size=SIZE Maximum length of captured packet\n" - " --list Don't show tree, but simple object path list\n" - " --quiet Don't show method call reply\n" - " --verbose Show result values in long format\n" - " --expect-reply=BOOL Expect a method call reply\n" - " --auto-start=BOOL Auto-start destination service\n" - " --allow-interactive-authorization=BOOL\n" - " Allow interactive authorization for operation\n" - " --timeout=SECS Maximum time to wait for method call completion\n" - " --augment-creds=BOOL Extend credential data with data read from /proc/$PID\n\n" - "Commands:\n" - " list List bus names\n" - " status [SERVICE] Show bus service, process or bus owner credentials\n" - " monitor [SERVICE...] Show bus traffic\n" - " capture [SERVICE...] Capture bus traffic as pcap\n" - " tree [SERVICE...] Show object tree of service\n" - " introspect SERVICE OBJECT [INTERFACE]\n" - " call SERVICE OBJECT INTERFACE METHOD [SIGNATURE [ARGUMENT...]]\n" - " Call a method\n" - " get-property SERVICE OBJECT INTERFACE PROPERTY...\n" - " Get property value\n" - " set-property SERVICE OBJECT INTERFACE PROPERTY SIGNATURE ARGUMENT...\n" - " Set property value\n" - " help Show this help\n" - , program_invocation_short_name); - - return 0; -} - -static int parse_argv(int argc, char *argv[]) { - - enum { - ARG_VERSION = 0x100, - ARG_NO_PAGER, - ARG_NO_LEGEND, - ARG_SYSTEM, - ARG_USER, - ARG_ADDRESS, - ARG_MATCH, - ARG_SHOW_MACHINE, - ARG_UNIQUE, - ARG_ACQUIRED, - ARG_ACTIVATABLE, - ARG_SIZE, - ARG_LIST, - ARG_VERBOSE, - ARG_EXPECT_REPLY, - ARG_AUTO_START, - ARG_ALLOW_INTERACTIVE_AUTHORIZATION, - ARG_TIMEOUT, - ARG_AUGMENT_CREDS, - }; - - static const struct option options[] = { - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, ARG_VERSION }, - { "no-pager", no_argument, NULL, ARG_NO_PAGER }, - { "no-legend", no_argument, NULL, ARG_NO_LEGEND }, - { "system", no_argument, NULL, ARG_SYSTEM }, - { "user", no_argument, NULL, ARG_USER }, - { "address", required_argument, NULL, ARG_ADDRESS }, - { "show-machine", no_argument, NULL, ARG_SHOW_MACHINE }, - { "unique", no_argument, NULL, ARG_UNIQUE }, - { "acquired", no_argument, NULL, ARG_ACQUIRED }, - { "activatable", no_argument, NULL, ARG_ACTIVATABLE }, - { "match", required_argument, NULL, ARG_MATCH }, - { "host", required_argument, NULL, 'H' }, - { "machine", required_argument, NULL, 'M' }, - { "size", required_argument, NULL, ARG_SIZE }, - { "list", no_argument, NULL, ARG_LIST }, - { "quiet", no_argument, NULL, 'q' }, - { "verbose", no_argument, NULL, ARG_VERBOSE }, - { "expect-reply", required_argument, NULL, ARG_EXPECT_REPLY }, - { "auto-start", required_argument, NULL, ARG_AUTO_START }, - { "allow-interactive-authorization", required_argument, NULL, ARG_ALLOW_INTERACTIVE_AUTHORIZATION }, - { "timeout", required_argument, NULL, ARG_TIMEOUT }, - { "augment-creds",required_argument, NULL, ARG_AUGMENT_CREDS}, - {}, - }; - - int c, r; - - assert(argc >= 0); - assert(argv); - - while ((c = getopt_long(argc, argv, "hH:M:q", options, NULL)) >= 0) - - switch (c) { - - case 'h': - return help(); - - case ARG_VERSION: - return version(); - - case ARG_NO_PAGER: - arg_no_pager = true; - break; - - case ARG_NO_LEGEND: - arg_legend = false; - break; - - case ARG_USER: - arg_user = true; - break; - - case ARG_SYSTEM: - arg_user = false; - break; - - case ARG_ADDRESS: - arg_address = optarg; - break; - - case ARG_SHOW_MACHINE: - arg_show_machine = true; - break; - - case ARG_UNIQUE: - arg_unique = true; - break; - - case ARG_ACQUIRED: - arg_acquired = true; - break; - - case ARG_ACTIVATABLE: - arg_activatable = true; - break; - - case ARG_MATCH: - if (strv_extend(&arg_matches, optarg) < 0) - return log_oom(); - break; - - case ARG_SIZE: { - uint64_t sz; - - r = parse_size(optarg, 1024, &sz); - if (r < 0) { - log_error("Failed to parse size: %s", optarg); - return r; - } - - if ((uint64_t) (size_t) sz != sz) { - log_error("Size out of range."); - return -E2BIG; - } - - arg_snaplen = (size_t) sz; - break; - } - - case ARG_LIST: - arg_list = true; - break; - - case 'H': - arg_transport = BUS_TRANSPORT_REMOTE; - arg_host = optarg; - break; - - case 'M': - arg_transport = BUS_TRANSPORT_MACHINE; - arg_host = optarg; - break; - - case 'q': - arg_quiet = true; - break; - - case ARG_VERBOSE: - arg_verbose = true; - break; - - case ARG_EXPECT_REPLY: - r = parse_boolean(optarg); - if (r < 0) { - log_error("Failed to parse --expect-reply= parameter."); - return r; - } - - arg_expect_reply = !!r; - break; - - - case ARG_AUTO_START: - r = parse_boolean(optarg); - if (r < 0) { - log_error("Failed to parse --auto-start= parameter."); - return r; - } - - arg_auto_start = !!r; - break; - - - case ARG_ALLOW_INTERACTIVE_AUTHORIZATION: - r = parse_boolean(optarg); - if (r < 0) { - log_error("Failed to parse --allow-interactive-authorization= parameter."); - return r; - } - - arg_allow_interactive_authorization = !!r; - break; - - case ARG_TIMEOUT: - r = parse_sec(optarg, &arg_timeout); - if (r < 0) { - log_error("Failed to parse --timeout= parameter."); - return r; - } - - break; - - case ARG_AUGMENT_CREDS: - r = parse_boolean(optarg); - if (r < 0) { - log_error("Failed to parse --augment-creds= parameter."); - return r; - } - - arg_augment_creds = !!r; - break; - - case '?': - return -EINVAL; - - default: - assert_not_reached("Unhandled option"); - } - - return 1; -} - -static int busctl_main(sd_bus *bus, int argc, char *argv[]) { - assert(bus); - - if (optind >= argc || - streq(argv[optind], "list")) - return list_bus_names(bus, argv + optind); - - if (streq(argv[optind], "monitor")) - return monitor(bus, argv + optind, message_dump); - - if (streq(argv[optind], "capture")) - return capture(bus, argv + optind); - - if (streq(argv[optind], "status")) - return status(bus, argv + optind); - - if (streq(argv[optind], "tree")) - return tree(bus, argv + optind); - - if (streq(argv[optind], "introspect")) - return introspect(bus, argv + optind); - - if (streq(argv[optind], "call")) - return call(bus, argv + optind); - - if (streq(argv[optind], "get-property")) - return get_property(bus, argv + optind); - - if (streq(argv[optind], "set-property")) - return set_property(bus, argv + optind); - - if (streq(argv[optind], "help")) - return help(); - - log_error("Unknown command '%s'", argv[optind]); - return -EINVAL; -} - -int main(int argc, char *argv[]) { - sd_bus *bus = NULL; - int r; - - log_parse_environment(); - log_open(); - - r = parse_argv(argc, argv); - if (r <= 0) - goto finish; - - r = sd_bus_new(&bus); - if (r < 0) { - log_error_errno(r, "Failed to allocate bus: %m"); - goto finish; - } - - if (streq_ptr(argv[optind], "monitor") || - streq_ptr(argv[optind], "capture")) { - - r = sd_bus_set_monitor(bus, true); - if (r < 0) { - log_error_errno(r, "Failed to set monitor mode: %m"); - goto finish; - } - - r = sd_bus_negotiate_creds(bus, true, _SD_BUS_CREDS_ALL); - if (r < 0) { - log_error_errno(r, "Failed to enable credentials: %m"); - goto finish; - } - - r = sd_bus_negotiate_timestamp(bus, true); - if (r < 0) { - log_error_errno(r, "Failed to enable timestamps: %m"); - goto finish; - } - - r = sd_bus_negotiate_fds(bus, true); - if (r < 0) { - log_error_errno(r, "Failed to enable fds: %m"); - goto finish; - } - } - - r = sd_bus_set_bus_client(bus, true); - if (r < 0) { - log_error_errno(r, "Failed to set bus client: %m"); - goto finish; - } - - if (arg_address) - r = sd_bus_set_address(bus, arg_address); - else { - switch (arg_transport) { - - case BUS_TRANSPORT_LOCAL: - if (arg_user) { - bus->is_user = true; - r = bus_set_address_user(bus); - } else { - bus->is_system = true; - r = bus_set_address_system(bus); - } - break; - - case BUS_TRANSPORT_REMOTE: - r = bus_set_address_system_remote(bus, arg_host); - break; - - case BUS_TRANSPORT_MACHINE: - r = bus_set_address_system_machine(bus, arg_host); - break; - - default: - assert_not_reached("Hmm, unknown transport type."); - } - } - if (r < 0) { - log_error_errno(r, "Failed to set address: %m"); - goto finish; - } - - r = sd_bus_start(bus); - if (r < 0) { - log_error_errno(r, "Failed to connect to bus: %m"); - goto finish; - } - - r = busctl_main(bus, argc, argv); - -finish: - sd_bus_flush_close_unref(bus); - pager_close(); - - strv_free(arg_matches); - - return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; -} diff --git a/src/libsystemd/sd-daemon.xml b/src/libsystemd/sd-daemon.xml new file mode 100644 index 0000000000..b06d99f346 --- /dev/null +++ b/src/libsystemd/sd-daemon.xml @@ -0,0 +1,144 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-daemon" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-daemon</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-daemon</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-daemon</refname> + <refname>SD_EMERG</refname> + <refname>SD_ALERT</refname> + <refname>SD_CRIT</refname> + <refname>SD_ERR</refname> + <refname>SD_WARNING</refname> + <refname>SD_NOTICE</refname> + <refname>SD_INFO</refname> + <refname>SD_DEBUG</refname> + <refpurpose>APIs for + new-style daemons</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-daemon.h</filename> provides APIs for new-style + daemons, as implemented by the + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry> + service manager.</para> + + <para>See + <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_booted</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_fifo</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the functions implemented. In addition + to these functions, a couple of logging prefixes are defined as + macros:</para> + + <programlisting>#define SD_EMERG "<0>" /* system is unusable */ +#define SD_ALERT "<1>" /* action must be taken immediately */ +#define SD_CRIT "<2>" /* critical conditions */ +#define SD_ERR "<3>" /* error conditions */ +#define SD_WARNING "<4>" /* warning conditions */ +#define SD_NOTICE "<5>" /* normal but significant condition */ +#define SD_INFO "<6>" /* informational */ +#define SD_DEBUG "<7>" /* debug-level messages */</programlisting> + + <para>These prefixes are intended to be used in conjunction with + stderr-based logging as implemented by systemd. If a systemd + service definition file is configured with + <varname>StandardError=journal</varname>, + <varname>StandardError=syslog</varname> or + <varname>StandardError=kmsg</varname>, these prefixes can be used + to encode a log level in lines printed. This is similar to the + kernel <function>printk()</function>-style logging. See + <citerefentry><refentrytitle>klogctl</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for more information.</para> + + <para>The log levels are identical to + <citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry>'s + log level system. To use these prefixes simply prefix every line + with one of these strings. A line that is not prefixed will be + logged at the default log level SD_INFO.</para> + + <example> + <title>Hello World</title> + + <para>A daemon may log with the log level NOTICE by issuing this + call:</para> + + <programlisting>fprintf(stderr, SD_NOTICE "Hello World!\n");</programlisting> + </example> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_booted</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_fifo</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>fprintf</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-daemon/Makefile b/src/libsystemd/sd-daemon/Makefile deleted file mode 120000 index d0b0e8e008..0000000000 --- a/src/libsystemd/sd-daemon/Makefile +++ /dev/null @@ -1 +0,0 @@ -../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-device/Makefile b/src/libsystemd/sd-device/Makefile deleted file mode 120000 index d0b0e8e008..0000000000 --- a/src/libsystemd/sd-device/Makefile +++ /dev/null @@ -1 +0,0 @@ -../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-event.xml b/src/libsystemd/sd-event.xml new file mode 100644 index 0000000000..fc615f0906 --- /dev/null +++ b/src/libsystemd/sd-event.xml @@ -0,0 +1,187 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-event" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-event</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-event</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-event</refname> + <refpurpose>A generic event loop implementation</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-event.h</filename> provides a generic event + loop implementation, based on Linux <citerefentry + project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry>. + </para> + + <para>See + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_get_event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_get_pending</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_set_watchdog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the functions available.</para> + + <para>The event loop design is targeted on running a separate + instance of the event loop in each thread; it has no concept of + distributing events from a single event loop instance onto + multiple worker threads. Dispatching events is strictly ordered + and subject to configurable priorities. In each event loop + iteration a single event source is dispatched. Each time an event + source is dispatched the kernel is polled for new events, before + the next event source is dispatched. The event loop is designed to + honour priorities and provide fairness within each priority. It is + not designed to provide optimal throughput, as this contradicts + these goals due the limitations of the underlying <citerefentry + project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry> + primitives.</para> + + <para>The event loop implementation provides the following features:</para> + + <orderedlist> + <listitem><para>I/O event sources, based on <citerefentry + project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry>'s + file descriptor watching, including edge triggered events (<constant>EPOLLET</constant>). See <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>Timer event sources, based on <citerefentry + project='man-pages'><refentrytitle>timerfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + supporting the <constant>CLOCK_MONOTONIC</constant>, + <constant>CLOCK_REALTIME</constant>, + <constant>CLOCK_BOOTIME</constant> clocks, as well as the + <constant>CLOCK_REALTIME_ALARM</constant> and + <constant>CLOCK_BOOTTIME_ALARM</constant> clocks that can resume + the system from suspend. When creating timer events a required + accuracy parameter may be specified which allows coalescing of + timer events to minimize power consumption. See <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>UNIX process signal events, based on + <citerefentry + project='man-pages'><refentrytitle>signalfd</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + including full support for real-time signals, and queued parameters. See <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>Child process state change events, based on + <citerefentry project='man-pages'><refentrytitle>waitid</refentrytitle><manvolnum>2</manvolnum></citerefentry>. See <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>Static event sources, of three types: defer, + post and exit, for invoking calls in each event loop, after + other event sources or at event loop termination. See + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>Event sources may be assigned a 64bit priority + value, that controls the order in which event sources are + dispatched if multiple are pending simultaneously. See + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>The event loop may automatically send watchdog + notification messages to the service manager. See + <citerefentry><refentrytitle>sd_event_set_watchdog</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + <listitem><para>The event loop may be integrated into foreign + event loops, such as the GLib one. See + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for an example.</para></listitem> + </orderedlist> + + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_get_event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_get_pending</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_set_watchdog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>timerfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>signalfd</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>waitid</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-event/Makefile b/src/libsystemd/sd-event/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-event/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-hwdb/Makefile b/src/libsystemd/sd-hwdb/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-hwdb/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-id128.xml b/src/libsystemd/sd-id128.xml new file mode 100644 index 0000000000..ea7972055d --- /dev/null +++ b/src/libsystemd/sd-id128.xml @@ -0,0 +1,166 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-id128" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-id128</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-id128</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-id128</refname> + <refname>sd_id128_t</refname> + <refname>SD_ID128_MAKE</refname> + <refname>SD_ID128_CONST_STR</refname> + <refname>SD_ID128_FORMAT_STR</refname> + <refname>SD_ID128_FORMAT_VAL</refname> + <refname>sd_id128_equal</refname> + <refpurpose>APIs for processing 128-bit IDs</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-id128.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-id128.h</filename> provides APIs to process and + generate 128-bit ID values. The 128-bit ID values processed and + generated by these APIs are a generalization of OSF UUIDs as + defined by <ulink url="https://tools.ietf.org/html/rfc4122">RFC + 4122</ulink> but use a simpler string format. These functions + impose no structure on the used IDs, much unlike OSF UUIDs or + Microsoft GUIDs, but are fully compatible with those types of IDs. + </para> + + <para>See + <citerefentry><refentrytitle>sd_id128_to_string</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_randomize</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_id128_get_machine</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the implemented functions.</para> + + <para>A 128-bit ID is implemented as the following + union type:</para> + + <programlisting>typedef union sd_id128 { + uint8_t bytes[16]; + uint64_t qwords[2]; +} sd_id128_t;</programlisting> + + <para>This union type allows accessing the 128-bit ID as 16 + separate bytes or two 64-bit words. It is generally safer to + access the ID components by their 8-bit array to avoid endianness + issues. This union is intended to be passed call-by-value (as + opposed to call-by-reference) and may be directly manipulated by + clients.</para> + + <para>A couple of macros are defined to denote and decode 128-bit + IDs:</para> + + <para><function>SD_ID128_MAKE()</function> may be used to denote a + constant 128-bit ID in source code. A commonly used idiom is to + assign a name to a 128-bit ID using this macro:</para> + + <programlisting>#define SD_MESSAGE_COREDUMP SD_ID128_MAKE(fc,2e,22,bc,6e,e6,47,b6,b9,07,29,ab,34,a2,50,b1)</programlisting> + + <para><function>SD_ID128_CONST_STR()</function> may be used to + convert constant 128-bit IDs into constant strings for output. The + following example code will output the string + "fc2e22bc6ee647b6b90729ab34a250b1":</para> + <programlisting>int main(int argc, char *argv[]) { + puts(SD_ID128_CONST_STR(SD_MESSAGE_COREDUMP)); +}</programlisting> + + <para><function>SD_ID128_FORMAT_STR</function> and + <function>SD_ID128_FORMAT_VAL()</function> may be used to format a + 128-bit ID in a + <citerefentry project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry> + format string, as shown in the following example:</para> + + <programlisting>int main(int argc, char *argv[]) { + sd_id128_t id; + id = SD_ID128_MAKE(ee,89,be,71,bd,6e,43,d6,91,e6,c5,5d,eb,03,02,07); + printf("The ID encoded in this C file is " SD_ID128_FORMAT_STR ".\n", SD_ID128_FORMAT_VAL(id)); + return 0; +}</programlisting> + + <para>Use <function>sd_id128_equal()</function> to compare two 128-bit IDs:</para> + + <programlisting>int main(int argc, char *argv[]) { + sd_id128_t a, b, c; + a = SD_ID128_MAKE(ee,89,be,71,bd,6e,43,d6,91,e6,c5,5d,eb,03,02,07); + b = SD_ID128_MAKE(f2,28,88,9c,5f,09,44,15,9d,d7,04,77,58,cb,e7,3e); + c = a; + assert(sd_id128_equal(a, c)); + assert(!sd_id128_equal(a, b)); + return 0; +}</programlisting> + + <para>Note that new, randomized IDs may be generated with + <citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>'s + <option>--new-id</option> option.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_to_string</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_randomize</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_get_machine</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>machine-id</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-id128/Makefile b/src/libsystemd/sd-id128/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-id128/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-journal.xml b/src/libsystemd/sd-journal.xml new file mode 100644 index 0000000000..09747a480c --- /dev/null +++ b/src/libsystemd/sd-journal.xml @@ -0,0 +1,133 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-journal" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-journal</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-journal</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-journal</refname> + <refpurpose>APIs for submitting and querying log entries to and + from the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-journal.h</filename> provides APIs to submit + and query log entries. The APIs exposed act both as client for the + <citerefentry><refentrytitle>systemd-journald.service</refentrytitle><manvolnum>8</manvolnum></citerefentry> + journal service and as parser for the journal files on disk. + </para> + + <para>See + <citerefentry><refentrytitle>sd_journal_print</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_stream_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_add_match</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_seek_head</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_query_enumerate</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_enumerate_fields</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cutoff_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cutoff_monotonic_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_usage</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_catalog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_has_runtime_files</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_journal_has_persistent_files</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the functions implemented.</para> + + <para>Command line access for submitting entries to the journal is + available with the + <citerefentry><refentrytitle>systemd-cat</refentrytitle><manvolnum>1</manvolnum></citerefentry> + tool. Command line access for querying entries from the journal is + available with the + <citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry> + tool.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_print</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_stream_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_add_match</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_seek_head</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_query_enumerate</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_enumerate_fields</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cutoff_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cutoff_monotonic_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_usage</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_query_unique</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_catalog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_has_runtime_files</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_has_persistent_files</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-login.xml b/src/libsystemd/sd-login.xml new file mode 100644 index 0000000000..328f71164d --- /dev/null +++ b/src/libsystemd/sd-login.xml @@ -0,0 +1,135 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd-login" conditional='HAVE_PAM' + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd-login</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd-login</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd-login</refname> + <refpurpose>APIs for + tracking logins</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + </funcsynopsis> + + <cmdsynopsis> + <command>pkg-config --cflags --libs libsystemd</command> + </cmdsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><filename>sd-login.h</filename> provides APIs to introspect + and monitor seat, login session and user status information on the + local system. </para> + + <para>See <ulink + url="http://www.freedesktop.org/wiki/Software/systemd/multiseat">Multi-Seat + on Linux</ulink> for an introduction into multi-seat support on + Linux, the background for this set of APIs.</para> + + <para>Note that these APIs only allow purely passive access and + monitoring of seats, sessions and users. To actively make changes + to the seat configuration, terminate login sessions, or switch + session on a seat you need to utilize the D-Bus API of + systemd-logind, instead.</para> + + <para>These functions synchronously access data in + <filename>/proc</filename>, <filename>/sys/fs/cgroup</filename> + and <filename>/run</filename>. All of these are virtual file + systems, hence the runtime cost of the accesses is relatively + cheap.</para> + + <para>It is possible (and often a very good choice) to mix calls + to the synchronous interface of <filename>sd-login.h</filename> + with the asynchronous D-Bus interface of systemd-logind. However, + if this is done you need to think a bit about possible races since + the stream of events from D-Bus and from + <filename>sd-login.h</filename> interfaces such as the login + monitor are asynchronous and not ordered against each + other.</para> + + <para>If the functions return string arrays, these are generally + <constant>NULL</constant> terminated and need to be freed by the + caller with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use, including the strings referenced therein. + Similarly, individual strings returned need to be freed, as + well.</para> + + <para>As a special exception, instead of an empty string array + <constant>NULL</constant> may be returned, which should be treated + equivalent to an empty string array.</para> + + <para>See + <citerefentry><refentrytitle>sd_pid_get_session</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_uid_get_state</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_session_is_active</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_seat_get_active</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_get_seats</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_login_monitor_new</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information about the functions + implemented.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_pid_get_session</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_uid_get_state</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_session_is_active</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_seat_get_active</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_get_seats</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_login_monitor_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd-login/Makefile b/src/libsystemd/sd-login/Makefile deleted file mode 120000 index d0b0e8e008..0000000000 --- a/src/libsystemd/sd-login/Makefile +++ /dev/null @@ -1 +0,0 @@ -../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-netlink/Makefile b/src/libsystemd/sd-netlink/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-netlink/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-network/Makefile b/src/libsystemd/sd-network/Makefile deleted file mode 120000 index d0b0e8e008..0000000000 --- a/src/libsystemd/sd-network/Makefile +++ /dev/null @@ -1 +0,0 @@ -../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-path/Makefile b/src/libsystemd/sd-path/Makefile deleted file mode 120000 index d0b0e8e008..0000000000 --- a/src/libsystemd/sd-path/Makefile +++ /dev/null @@ -1 +0,0 @@ -../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-path/sd-path.c b/src/libsystemd/sd-path/sd-path.c deleted file mode 100644 index b7aec1f20a..0000000000 --- a/src/libsystemd/sd-path/sd-path.c +++ /dev/null @@ -1,638 +0,0 @@ -/*** - 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 <http://www.gnu.org/licenses/>. -***/ - -#include "sd-path.h" - -#include "alloc-util.h" -#include "architecture.h" -#include "fd-util.h" -#include "fileio.h" -#include "missing.h" -#include "path-util.h" -#include "string-util.h" -#include "strv.h" -#include "user-util.h" -#include "util.h" - -static int from_environment(const char *envname, const char *fallback, const char **ret) { - assert(ret); - - if (envname) { - const char *e; - - e = secure_getenv(envname); - if (e && path_is_absolute(e)) { - *ret = e; - return 0; - } - } - - if (fallback) { - *ret = fallback; - return 0; - } - - return -ENXIO; -} - -static int from_home_dir(const char *envname, const char *suffix, char **buffer, const char **ret) { - _cleanup_free_ char *h = NULL; - char *cc = NULL; - int r; - - assert(suffix); - assert(buffer); - assert(ret); - - if (envname) { - const char *e = NULL; - - e = secure_getenv(envname); - if (e && path_is_absolute(e)) { - *ret = e; - return 0; - } - } - - r = get_home_dir(&h); - if (r < 0) - return r; - - if (endswith(h, "/")) - cc = strappend(h, suffix); - else - cc = strjoin(h, "/", suffix, NULL); - if (!cc) - return -ENOMEM; - - *buffer = cc; - *ret = cc; - return 0; -} - -static int from_user_dir(const char *field, char **buffer, const char **ret) { - _cleanup_fclose_ FILE *f = NULL; - _cleanup_free_ char *b = NULL; - _cleanup_free_ const char *fn = NULL; - const char *c = NULL; - char line[LINE_MAX]; - size_t n; - int r; - - assert(field); - assert(buffer); - assert(ret); - - r = from_home_dir("XDG_CONFIG_HOME", ".config", &b, &c); - if (r < 0) - return r; - - fn = strappend(c, "/user-dirs.dirs"); - if (!fn) - return -ENOMEM; - - f = fopen(fn, "re"); - if (!f) { - if (errno == ENOENT) - goto fallback; - - return -errno; - } - - /* This is an awful parse, but it follows closely what - * xdg-user-dirs does upstream */ - - n = strlen(field); - FOREACH_LINE(line, f, return -errno) { - char *l, *p, *e; - - l = strstrip(line); - - if (!strneq(l, field, n)) - continue; - - p = l + n; - p += strspn(p, WHITESPACE); - - if (*p != '=') - continue; - p++; - - p += strspn(p, WHITESPACE); - - if (*p != '"') - continue; - p++; - - e = strrchr(p, '"'); - if (!e) - continue; - *e = 0; - - /* Three syntaxes permitted: relative to $HOME, $HOME itself, and absolute path */ - if (startswith(p, "$HOME/")) { - _cleanup_free_ char *h = NULL; - char *cc; - - r = get_home_dir(&h); - if (r < 0) - return r; - - cc = strappend(h, p+5); - if (!cc) - return -ENOMEM; - - *buffer = cc; - *ret = cc; - return 0; - } else if (streq(p, "$HOME")) { - - r = get_home_dir(buffer); - if (r < 0) - return r; - - *ret = *buffer; - return 0; - } else if (path_is_absolute(p)) { - char *copy; - - copy = strdup(p); - if (!copy) - return -ENOMEM; - - *buffer = copy; - *ret = copy; - return 0; - } - } - -fallback: - /* The desktop directory defaults to $HOME/Desktop, the others to $HOME */ - if (streq(field, "XDG_DESKTOP_DIR")) { - _cleanup_free_ char *h = NULL; - char *cc; - - r = get_home_dir(&h); - if (r < 0) - return r; - - cc = strappend(h, "/Desktop"); - if (!cc) - return -ENOMEM; - - *buffer = cc; - *ret = cc; - } else { - - r = get_home_dir(buffer); - if (r < 0) - return r; - - *ret = *buffer; - } - - return 0; -} - -static int get_path(uint64_t type, char **buffer, const char **ret) { - int r; - - assert(buffer); - assert(ret); - - switch (type) { - - case SD_PATH_TEMPORARY: - return from_environment("TMPDIR", "/tmp", ret); - - case SD_PATH_TEMPORARY_LARGE: - return from_environment("TMPDIR", "/var/tmp", ret); - - case SD_PATH_SYSTEM_BINARIES: - *ret = "/usr/bin"; - return 0; - - case SD_PATH_SYSTEM_INCLUDE: - *ret = "/usr/include"; - return 0; - - case SD_PATH_SYSTEM_LIBRARY_PRIVATE: - *ret = "/usr/lib"; - return 0; - - case SD_PATH_SYSTEM_LIBRARY_ARCH: - *ret = LIBDIR; - return 0; - - case SD_PATH_SYSTEM_SHARED: - *ret = "/usr/share"; - return 0; - - case SD_PATH_SYSTEM_CONFIGURATION_FACTORY: - *ret = "/usr/share/factory/etc"; - return 0; - - case SD_PATH_SYSTEM_STATE_FACTORY: - *ret = "/usr/share/factory/var"; - return 0; - - case SD_PATH_SYSTEM_CONFIGURATION: - *ret = "/etc"; - return 0; - - case SD_PATH_SYSTEM_RUNTIME: - *ret = "/run"; - return 0; - - case SD_PATH_SYSTEM_RUNTIME_LOGS: - *ret = "/run/log"; - return 0; - - case SD_PATH_SYSTEM_STATE_PRIVATE: - *ret = "/var/lib"; - return 0; - - case SD_PATH_SYSTEM_STATE_LOGS: - *ret = "/var/log"; - return 0; - - case SD_PATH_SYSTEM_STATE_CACHE: - *ret = "/var/cache"; - return 0; - - case SD_PATH_SYSTEM_STATE_SPOOL: - *ret = "/var/spool"; - return 0; - - case SD_PATH_USER_BINARIES: - return from_home_dir(NULL, ".local/bin", buffer, ret); - - case SD_PATH_USER_LIBRARY_PRIVATE: - return from_home_dir(NULL, ".local/lib", buffer, ret); - - case SD_PATH_USER_LIBRARY_ARCH: - return from_home_dir(NULL, ".local/lib/" LIB_ARCH_TUPLE, buffer, ret); - - case SD_PATH_USER_SHARED: - return from_home_dir("XDG_DATA_HOME", ".local/share", buffer, ret); - - case SD_PATH_USER_CONFIGURATION: - return from_home_dir("XDG_CONFIG_HOME", ".config", buffer, ret); - - case SD_PATH_USER_RUNTIME: - return from_environment("XDG_RUNTIME_DIR", NULL, ret); - - case SD_PATH_USER_STATE_CACHE: - return from_home_dir("XDG_CACHE_HOME", ".cache", buffer, ret); - - case SD_PATH_USER: - r = get_home_dir(buffer); - if (r < 0) - return r; - - *ret = *buffer; - return 0; - - case SD_PATH_USER_DOCUMENTS: - return from_user_dir("XDG_DOCUMENTS_DIR", buffer, ret); - - case SD_PATH_USER_MUSIC: - return from_user_dir("XDG_MUSIC_DIR", buffer, ret); - - case SD_PATH_USER_PICTURES: - return from_user_dir("XDG_PICTURES_DIR", buffer, ret); - - case SD_PATH_USER_VIDEOS: - return from_user_dir("XDG_VIDEOS_DIR", buffer, ret); - - case SD_PATH_USER_DOWNLOAD: - return from_user_dir("XDG_DOWNLOAD_DIR", buffer, ret); - - case SD_PATH_USER_PUBLIC: - return from_user_dir("XDG_PUBLICSHARE_DIR", buffer, ret); - - case SD_PATH_USER_TEMPLATES: - return from_user_dir("XDG_TEMPLATES_DIR", buffer, ret); - - case SD_PATH_USER_DESKTOP: - return from_user_dir("XDG_DESKTOP_DIR", buffer, ret); - } - - return -EOPNOTSUPP; -} - -_public_ int sd_path_home(uint64_t type, const char *suffix, char **path) { - char *buffer = NULL, *cc; - const char *ret; - int r; - - assert_return(path, -EINVAL); - - if (IN_SET(type, - SD_PATH_SEARCH_BINARIES, - SD_PATH_SEARCH_LIBRARY_PRIVATE, - SD_PATH_SEARCH_LIBRARY_ARCH, - SD_PATH_SEARCH_SHARED, - SD_PATH_SEARCH_CONFIGURATION_FACTORY, - SD_PATH_SEARCH_STATE_FACTORY, - SD_PATH_SEARCH_CONFIGURATION)) { - - _cleanup_strv_free_ char **l = NULL; - - r = sd_path_search(type, suffix, &l); - if (r < 0) - return r; - - buffer = strv_join(l, ":"); - if (!buffer) - return -ENOMEM; - - *path = buffer; - return 0; - } - - r = get_path(type, &buffer, &ret); - if (r < 0) - return r; - - if (!suffix) { - if (!buffer) { - buffer = strdup(ret); - if (!buffer) - return -ENOMEM; - } - - *path = buffer; - return 0; - } - - suffix += strspn(suffix, "/"); - - if (endswith(ret, "/")) - cc = strappend(ret, suffix); - else - cc = strjoin(ret, "/", suffix, NULL); - - free(buffer); - - if (!cc) - return -ENOMEM; - - *path = cc; - return 0; -} - -static int search_from_environment( - char ***list, - const char *env_home, - const char *home_suffix, - const char *env_search, - bool env_search_sufficient, - const char *first, ...) { - - const char *e; - char *h = NULL; - char **l = NULL; - int r; - - assert(list); - - if (env_search) { - e = secure_getenv(env_search); - if (e) { - l = strv_split(e, ":"); - if (!l) - return -ENOMEM; - - if (env_search_sufficient) { - *list = l; - return 0; - } - } - } - - if (!l && first) { - va_list ap; - - va_start(ap, first); - l = strv_new_ap(first, ap); - va_end(ap); - - if (!l) - return -ENOMEM; - } - - if (env_home) { - e = secure_getenv(env_home); - if (e && path_is_absolute(e)) { - h = strdup(e); - if (!h) { - strv_free(l); - return -ENOMEM; - } - } - } - - if (!h && home_suffix) { - e = secure_getenv("HOME"); - if (e && path_is_absolute(e)) { - if (endswith(e, "/")) - h = strappend(e, home_suffix); - else - h = strjoin(e, "/", home_suffix, NULL); - - if (!h) { - strv_free(l); - return -ENOMEM; - } - } - } - - if (h) { - r = strv_consume_prepend(&l, h); - if (r < 0) { - strv_free(l); - return -ENOMEM; - } - } - - *list = l; - return 0; -} - -static int get_search(uint64_t type, char ***list) { - - assert(list); - - switch(type) { - - case SD_PATH_SEARCH_BINARIES: - return search_from_environment(list, - NULL, - ".local/bin", - "PATH", - true, - "/usr/local/sbin", - "/usr/local/bin", - "/usr/sbin", - "/usr/bin", -#ifdef HAVE_SPLIT_USR - "/sbin", - "/bin", -#endif - NULL); - - case SD_PATH_SEARCH_LIBRARY_PRIVATE: - return search_from_environment(list, - NULL, - ".local/lib", - NULL, - false, - "/usr/local/lib", - "/usr/lib", -#ifdef HAVE_SPLIT_USR - "/lib", -#endif - NULL); - - case SD_PATH_SEARCH_LIBRARY_ARCH: - return search_from_environment(list, - NULL, - ".local/lib/" LIB_ARCH_TUPLE, - "LD_LIBRARY_PATH", - true, - LIBDIR, -#ifdef HAVE_SPLIT_USR - ROOTLIBDIR, -#endif - NULL); - - case SD_PATH_SEARCH_SHARED: - return search_from_environment(list, - "XDG_DATA_HOME", - ".local/share", - "XDG_DATA_DIRS", - false, - "/usr/local/share", - "/usr/share", - NULL); - - case SD_PATH_SEARCH_CONFIGURATION_FACTORY: - return search_from_environment(list, - NULL, - NULL, - NULL, - false, - "/usr/local/share/factory/etc", - "/usr/share/factory/etc", - NULL); - - case SD_PATH_SEARCH_STATE_FACTORY: - return search_from_environment(list, - NULL, - NULL, - NULL, - false, - "/usr/local/share/factory/var", - "/usr/share/factory/var", - NULL); - - case SD_PATH_SEARCH_CONFIGURATION: - return search_from_environment(list, - "XDG_CONFIG_HOME", - ".config", - "XDG_CONFIG_DIRS", - false, - "/etc", - NULL); - } - - return -EOPNOTSUPP; -} - -_public_ int sd_path_search(uint64_t type, const char *suffix, char ***paths) { - char **l, **i, **j, **n; - int r; - - assert_return(paths, -EINVAL); - - if (!IN_SET(type, - SD_PATH_SEARCH_BINARIES, - SD_PATH_SEARCH_LIBRARY_PRIVATE, - SD_PATH_SEARCH_LIBRARY_ARCH, - SD_PATH_SEARCH_SHARED, - SD_PATH_SEARCH_CONFIGURATION_FACTORY, - SD_PATH_SEARCH_STATE_FACTORY, - SD_PATH_SEARCH_CONFIGURATION)) { - - char *p; - - r = sd_path_home(type, suffix, &p); - if (r < 0) - return r; - - l = new(char*, 2); - if (!l) { - free(p); - return -ENOMEM; - } - - l[0] = p; - l[1] = NULL; - - *paths = l; - return 0; - } - - r = get_search(type, &l); - if (r < 0) - return r; - - if (!suffix) { - *paths = l; - return 0; - } - - n = new(char*, strv_length(l)+1); - if (!n) { - strv_free(l); - return -ENOMEM; - } - - j = n; - STRV_FOREACH(i, l) { - - if (endswith(*i, "/")) - *j = strappend(*i, suffix); - else - *j = strjoin(*i, "/", suffix, NULL); - - if (!*j) { - strv_free(l); - strv_free(n); - return -ENOMEM; - } - - j++; - } - - *j = NULL; - *paths = n; - return 0; -} diff --git a/src/libsystemd/sd-resolve/Makefile b/src/libsystemd/sd-resolve/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-resolve/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd-utf8/Makefile b/src/libsystemd/sd-utf8/Makefile deleted file mode 120000 index 94aaae2c4d..0000000000 --- a/src/libsystemd/sd-utf8/Makefile +++ /dev/null @@ -1 +0,0 @@ -../../Makefile
\ No newline at end of file diff --git a/src/libsystemd/sd_booted.xml b/src/libsystemd/sd_booted.xml new file mode 100644 index 0000000000..4dd674b8ea --- /dev/null +++ b/src/libsystemd/sd_booted.xml @@ -0,0 +1,95 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_booted" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_booted</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_booted</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_booted</refname> + <refpurpose>Test whether the system is running the systemd init system</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_booted</function></funcdef> + <paramdef>void</paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para><function>sd_booted()</function> checks whether the system + was booted up using the systemd init system.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, this call returns a negative errno-style error + code. If the system was booted up with systemd as init system, + this call returns a positive return value, zero otherwise.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <xi:include href="libsystemd-pkgconfig.xml" xpointer="pkgconfig-text"/> + + <para>Internally, this function checks whether the directory + <filename>/run/systemd/system/</filename> exists. A simple check + like this can also be implemented trivially in shell or any other + language.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_add_match.xml b/src/libsystemd/sd_bus_add_match.xml new file mode 100644 index 0000000000..8bcf7164a0 --- /dev/null +++ b/src/libsystemd/sd_bus_add_match.xml @@ -0,0 +1,119 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 Julian Orth + + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_add_match"> + + <refentryinfo> + <title>sd_bus_add_match</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <firstname>Julian</firstname> + <surname>Orth</surname> + <email>ju.orth@gmail.com</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_add_match</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_add_match</refname> + + <refpurpose>Add a match rule for message dispatching</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_add_match</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>sd_bus_slot **<parameter>slot</parameter></paramdef> + <paramdef>const char *<parameter>match</parameter></paramdef> + <paramdef>sd_bus_message_handler_t <parameter>callback</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>typedef int (*<function>sd_bus_message_handler_t</function>)</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + <paramdef>sd_bus_error *<parameter>ret_error</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <function>sd_bus_add_match()</function> adds a match rule used to dispatch + incoming messages. The syntax of the rule passed in + <parameter>match</parameter> is described in the + <ulink url="https://dbus.freedesktop.org/doc/dbus-specification.html">D-Bus Specification</ulink>. + </para> + + <para> + The message <parameter>m</parameter> passed to the callback is only + borrowed, that is, the callback should not call + <citerefentry><refentrytitle>sd_bus_message_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + on it. If the callback wants to hold on to the message beyond the lifetime + of the callback, it needs to call + <citerefentry><refentrytitle>sd_bus_message_ref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + to create a new reference. + </para> + + <para> + If an error occurs during the callback invocation, the callback should + return a negative error number. If it wants other callbacks that match the + same rule to be called, it should return 0. Otherwise it should return a + positive integer. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para> + On success, <function>sd_bus_add_match()</function> returns 0 or a + positive integer. On failure, it returns a negative errno-style error + code. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_creds_get_pid.xml b/src/libsystemd/sd_bus_creds_get_pid.xml new file mode 100644 index 0000000000..4c05835568 --- /dev/null +++ b/src/libsystemd/sd_bus_creds_get_pid.xml @@ -0,0 +1,566 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_creds_get_pid"> + + <refentryinfo> + <title>sd_bus_creds_get_pid</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_creds_get_pid</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_creds_get_pid</refname> + <refname>sd_bus_creds_get_ppid</refname> + <refname>sd_bus_creds_get_tid</refname> + <refname>sd_bus_creds_get_uid</refname> + <refname>sd_bus_creds_get_euid</refname> + <refname>sd_bus_creds_get_suid</refname> + <refname>sd_bus_creds_get_fsuid</refname> + <refname>sd_bus_creds_get_gid</refname> + <refname>sd_bus_creds_get_egid</refname> + <refname>sd_bus_creds_get_sgid</refname> + <refname>sd_bus_creds_get_fsgid</refname> + <refname>sd_bus_creds_get_supplementary_gids</refname> + <refname>sd_bus_creds_get_comm</refname> + <refname>sd_bus_creds_get_tid_comm</refname> + <refname>sd_bus_creds_get_exe</refname> + <refname>sd_bus_creds_get_cmdline</refname> + <refname>sd_bus_creds_get_cgroup</refname> + <refname>sd_bus_creds_get_unit</refname> + <refname>sd_bus_creds_get_slice</refname> + <refname>sd_bus_creds_get_user_unit</refname> + <refname>sd_bus_creds_get_user_slice</refname> + <refname>sd_bus_creds_get_session</refname> + <refname>sd_bus_creds_get_owner_uid</refname> + <refname>sd_bus_creds_has_effective_cap</refname> + <refname>sd_bus_creds_has_permitted_cap</refname> + <refname>sd_bus_creds_has_inheritable_cap</refname> + <refname>sd_bus_creds_has_bounding_cap</refname> + <refname>sd_bus_creds_get_selinux_context</refname> + <refname>sd_bus_creds_get_audit_session_id</refname> + <refname>sd_bus_creds_get_audit_login_uid</refname> + <refname>sd_bus_creds_get_tty</refname> + <refname>sd_bus_creds_get_unique_name</refname> + <refname>sd_bus_creds_get_well_known_names</refname> + <refname>sd_bus_creds_get_description</refname> + + <refpurpose>Retrieve fields from a credentials object</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_pid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>pid_t *<parameter>pid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_ppid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>pid_t *<parameter>ppid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_tid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>pid_t *<parameter>tid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_uid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_euid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_suid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_fsuid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_gid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>gid_t *<parameter>gid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_egid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>gid_t *<parameter>gid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_sgid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>gid_t *<parameter>gid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_fsgid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>gid_t *<parameter>gid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_supplementary_gids</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const gid_t **<parameter>gids</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_comm</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>comm</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_tid_comm</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>comm</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_exe</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>exe</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_cmdline</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>char ***<parameter>cmdline</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_cgroup</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>cgroup</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_unit</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_slice</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_user_unit</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_user_slice</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_session</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_owner_uid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_has_effective_cap</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>int <parameter>capability</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_has_permitted_cap</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>int <parameter>capability</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_has_inheritable_cap</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>int <parameter>capability</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_has_bounding_cap</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>int <parameter>capability</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_selinux_context</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>context</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_audit_session_id</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uint32_t *<parameter>sessionid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_audit_login_uid</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>uid_t *<parameter>loginuid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_tty</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>tty</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_unique_name</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>name</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_well_known_names</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>char ***<parameter>name</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_get_description</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + <paramdef>const char **<parameter>name</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>These functions return credential information from an + <parameter>sd_bus_creds</parameter> object. Credential objects may + be created with + <citerefentry><refentrytitle>sd_bus_creds_new_from_pid</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + in which case they describe the credentials of the process + identified by the specified PID, with + <citerefentry><refentrytitle>sd_bus_get_name_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + in which case they describe the credentials of a bus peer + identified by the specified bus name, with + <citerefentry><refentrytitle>sd_bus_get_owner_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + in which case they describe the credentials of the creator of a + bus, or with + <citerefentry><refentrytitle>sd_bus_message_get_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + in which case they describe the credentials of the sender of the + message.</para> + + <para>Not all credential fields are part of every + <literal>sd_bus_creds</literal> object. Use + <citerefentry><refentrytitle>sd_bus_creds_get_mask</refentrytitle><manvolnum>3</manvolnum></citerefentry> + to determine the mask of fields available.</para> + + <para><function>sd_bus_creds_get_pid()</function> will retrieve + the PID (process identifier). Similarly, + <function>sd_bus_creds_get_ppid()</function> will retrieve the + parent PID. Note that PID 1 has no parent process, in which case + -ENXIO is returned.</para> + + <para><function>sd_bus_creds_get_tid()</function> will retrieve the + TID (thread identifier).</para> + + <para><function>sd_bus_creds_get_uid()</function> will retrieve + the numeric UID (user identifier). Similarly, + <function>sd_bus_creds_get_euid()</function> returns the effective + UID, <function>sd_bus_creds_get_suid()</function> the saved UID + and <function>sd_bus_creds_get_fsuid()</function> the file system + UID.</para> + + <para><function>sd_bus_creds_get_gid()</function> will retrieve the + numeric GID (group identifier). Similarly, + <function>sd_bus_creds_get_egid()</function> returns the effective + GID, <function>sd_bus_creds_get_sgid()</function> the saved GID + and <function>sd_bus_creds_get_fsgid()</function> the file system + GID.</para> + + <para><function>sd_bus_creds_get_supplementary_gids()</function> + will retrieve the supplementary GIDs list.</para> + + <para><function>sd_bus_creds_get_comm()</function> will retrieve the + comm field (truncated name of the executable, as stored in + <filename>/proc/<replaceable>pid</replaceable>/comm</filename>). + </para> + + <para><function>sd_bus_creds_get_tid_comm()</function> will retrieve + the comm field of the thread (as stored in + <filename>/proc/<replaceable>pid</replaceable>/task/<replaceable>tid</replaceable>/comm</filename>). + </para> + + <para><function>sd_bus_creds_get_exe()</function> will retrieve + the path to the program executable (as stored in the + <filename>/proc/<replaceable>pid</replaceable>/exe</filename> + link, but with the <literal> (deleted)</literal> suffix removed). Note + that kernel threads do not have an executable path, in which case + -ENXIO is returned.</para> + + <para><function>sd_bus_creds_get_cmdline()</function> will + retrieve an array of command line arguments (as stored in + <filename>/proc/<replaceable>pid</replaceable>/cmdline</filename>). Note + that kernel threads do not have a command line, in which case + -ENXIO is returned.</para> + + <para><function>sd_bus_creds_get_cgroup()</function> will retrieve + the cgroup path. See <ulink + url="https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt">cgroups.txt</ulink>. + </para> + + <para><function>sd_bus_creds_get_unit()</function> will retrieve + the systemd unit name (in the system instance of systemd) that the + process is a part of. See + <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>. For + processes that are not part of a unit, returns -ENXIO. + </para> + + <para><function>sd_bus_creds_get_user_unit()</function> will + retrieve the systemd unit name (in the user instance of systemd) + that the process is a part of. See + <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>. For + processes that are not part of a user unit, returns -ENXIO. + </para> + + <para><function>sd_bus_creds_get_slice()</function> will retrieve + the systemd slice (a unit in the system instance of systemd) that + the process is a part of. See + <citerefentry><refentrytitle>systemd.slice</refentrytitle><manvolnum>5</manvolnum></citerefentry>. Similarly, + <function>sd_bus_creds_get_user_slice()</function> retrieves the + systemd slice of the process, in the user instance of systemd. + </para> + + <para><function>sd_bus_creds_get_session()</function> will + retrieve the identifier of the login session that the process is + a part of. See + <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>. For + processes that are not part of a session, returns -ENXIO. + </para> + + <para><function>sd_bus_creds_get_owner_uid()</function> will + retrieve the numeric UID (user identifier) of the user who owns + the login session that the process is a part of. See + <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>. + For processes that are not part of a session, returns -ENXIO. + </para> + + <para><function>sd_bus_creds_has_effective_cap()</function> will check whether the capability specified by + <parameter>capability</parameter> was set in the effective capabilities mask. A positive return value means that it + was set, zero means that it was not set, and a negative return value indicates an error. See <citerefentry + project='man-pages'><refentrytitle>capabilities</refentrytitle><manvolnum>7</manvolnum></citerefentry> and the + <varname>AmbientCapabilities=</varname> and <varname>CapabilityBoundingSet=</varname> settings in + <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>. + </para> + + <para><function>sd_bus_creds_has_permitted_cap()</function> is + similar to <function>sd_bus_creds_has_effective_cap()</function>, + but will check the permitted capabilities mask.</para> + + <para><function>sd_bus_creds_has_inheritable_cap()</function> is + similar to <function>sd_bus_creds_has_effective_cap()</function>, + but will check the inheritable capabilities mask.</para> + + <para><function>sd_bus_creds_has_bounding_cap()</function> is + similar to <function>sd_bus_creds_has_effective_cap()</function>, + but will check the bounding capabilities mask.</para> + + <para><function>sd_bus_creds_get_selinux_context()</function> will + retrieve the SELinux security context (label) of the process.</para> + + <para><function>sd_bus_creds_get_audit_session_id()</function> + will retrieve the audit session identifier of the process. Returns + -ENXIO for processes that are not part of an audit session.</para> + + <para><function>sd_bus_creds_get_audit_login_uid()</function> will + retrieve the audit user login identifier (the identifier of the + user who is "responsible" for the session). Returns -ENXIO for + processes that are not part of an audit session.</para> + + <para><function>sd_bus_creds_get_tty()</function> will retrieve + the controlling TTY, without the prefixing "/dev/". Returns -ENXIO + for processes that have no controlling TTY.</para> + + <para><function>sd_bus_creds_get_unique_name()</function> will + retrieve the D-Bus unique name. See <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus">The + D-Bus specification</ulink>.</para> + + <para><function>sd_bus_creds_get_well_known_names()</function> will + retrieve the set of D-Bus well-known names. See <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus">The + D-Bus specification</ulink>.</para> + + <para><function>sd_bus_creds_get_description()</function> will + retrieve a descriptive name of the bus connection of the + peer. This name is useful to discern multiple bus connections by + the same peer, and may be altered by the peer with the + <citerefentry><refentrytitle>sd_bus_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call.</para> + + <para>All functions that take a <parameter>const + char**</parameter> parameter will store the answer there as an + address of a NUL-terminated string. It will be valid as long as + <parameter>c</parameter> remains valid, and should not be freed or + modified by the caller.</para> + + <para>All functions that take a <parameter>char***</parameter> + parameter will store the answer there as an address of an array + of strings. Each individual string is NUL-terminated, and the + array is NULL-terminated as a whole. It will be valid as long as + <parameter>c</parameter> remains valid, and should not be freed or + modified by the caller.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error code. + </para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The given field is not available in the + credentials object <parameter>c</parameter>.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>The given field is not specified for the described + process or peer. This will be returned by + <function>sd_bus_get_unit()</function>, + <function>sd_bus_get_slice()</function>, + <function>sd_bus_get_user_unit()</function>, + <function>sd_bus_get_user_slice()</function>, + <function>sd_bus_get_session()</function>, and + <function>sd_bus_get_owner_uid()</function> if the process is + not part of a systemd system unit, systemd user unit, systemd + slice, or logind session. It will also be returned by + <function>sd_bus_creds_get_exe()</function> and + <function>sd_bus_creds_get_cmdline()</function> for kernel + threads (since these are not started from an executable binary, + nor have a command line), and by + <function>sd_bus_creds_get_audit_session_id()</function> and + <function>sd_bus_creds_get_audit_login_uid()</function> when + the process is not part of an audit session, and + <function>sd_bus_creds_get_tty()</function> if the process has + no controlling TTY. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>Specified pointer parameter is <constant>NULL</constant>. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_creds_get_pid()</function> and the other + functions described here are available as a shared library, which + can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_creds_new_from_pid</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>fork</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>execve</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>credentials</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>proc</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_creds_new_from_pid.xml b/src/libsystemd/sd_bus_creds_new_from_pid.xml new file mode 100644 index 0000000000..082f7b67db --- /dev/null +++ b/src/libsystemd/sd_bus_creds_new_from_pid.xml @@ -0,0 +1,353 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_creds_new_from_pid"> + + <refentryinfo> + <title>sd_bus_creds_new_from_pid</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_creds_new_from_pid</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_creds_new_from_pid</refname> + <refname>sd_bus_creds_get_mask</refname> + <refname>sd_bus_creds_get_augmented_mask</refname> + <refname>sd_bus_creds_ref</refname> + <refname>sd_bus_creds_unref</refname> + <refname>sd_bus_creds_unrefp</refname> + + <refpurpose>Retrieve credentials object for the specified PID</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_creds_new_from_pid</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>uint64_t <parameter>creds_mask</parameter></paramdef> + <paramdef>sd_bus_creds **<parameter>ret</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>uint64_t <function>sd_bus_creds_get_mask</function></funcdef> + <paramdef>const sd_bus_creds *<parameter>c</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>uint64_t <function>sd_bus_creds_get_augmented_mask</function></funcdef> + <paramdef>const sd_bus_creds *<parameter>c</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_bus_creds *<function>sd_bus_creds_ref</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_bus_creds *<function>sd_bus_creds_unref</function></funcdef> + <paramdef>sd_bus_creds *<parameter>c</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_bus_creds_unrefp</function></funcdef> + <paramdef>sd_bus_creds **<parameter>c</parameter></paramdef> + </funcprototype> + </funcsynopsis> + + <para> + <constant>SD_BUS_CREDS_PID</constant>, + <constant>SD_BUS_CREDS_PPID</constant>, + <constant>SD_BUS_CREDS_TID</constant>, + <constant>SD_BUS_CREDS_UID</constant>, + <constant>SD_BUS_CREDS_EUID</constant>, + <constant>SD_BUS_CREDS_SUID</constant>, + <constant>SD_BUS_CREDS_FSUID</constant>, + <constant>SD_BUS_CREDS_GID</constant>, + <constant>SD_BUS_CREDS_EGID</constant>, + <constant>SD_BUS_CREDS_SGID</constant>, + <constant>SD_BUS_CREDS_FSGID</constant>, + <constant>SD_BUS_CREDS_SUPPLEMENTARY_GIDS</constant>, + <constant>SD_BUS_CREDS_COMM</constant>, + <constant>SD_BUS_CREDS_TID_COMM</constant>, + <constant>SD_BUS_CREDS_EXE</constant>, + <constant>SD_BUS_CREDS_CMDLINE</constant>, + <constant>SD_BUS_CREDS_CGROUP</constant>, + <constant>SD_BUS_CREDS_UNIT</constant>, + <constant>SD_BUS_CREDS_SLICE</constant>, + <constant>SD_BUS_CREDS_USER_UNIT</constant>, + <constant>SD_BUS_CREDS_USER_SLICE</constant>, + <constant>SD_BUS_CREDS_SESSION</constant>, + <constant>SD_BUS_CREDS_OWNER_UID</constant>, + <constant>SD_BUS_CREDS_EFFECTIVE_CAPS</constant>, + <constant>SD_BUS_CREDS_PERMITTED_CAPS</constant>, + <constant>SD_BUS_CREDS_INHERITABLE_CAPS</constant>, + <constant>SD_BUS_CREDS_BOUNDING_CAPS</constant>, + <constant>SD_BUS_CREDS_SELINUX_CONTEXT</constant>, + <constant>SD_BUS_CREDS_AUDIT_SESSION_ID</constant>, + <constant>SD_BUS_CREDS_AUDIT_LOGIN_UID</constant>, + <constant>SD_BUS_CREDS_TTY</constant>, + <constant>SD_BUS_CREDS_UNIQUE_NAME</constant>, + <constant>SD_BUS_CREDS_WELL_KNOWN_NAMES</constant>, + <constant>SD_BUS_CREDS_DESCRIPTION</constant>, + <constant>SD_BUS_CREDS_AUGMENT</constant>, + <constant>_SD_BUS_CREDS_ALL</constant> + </para> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_creds_new_from_pid()</function> creates a + new credentials object and fills it with information about the + process <parameter>pid</parameter>. The pointer to this object + will be stored in the <parameter>ret</parameter> pointer. Note that + credential objects may also be created and retrieved via + <citerefentry><refentrytitle>sd_bus_get_name_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_get_owner_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_bus_message_get_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>The information that will be stored is determined by + <parameter>creds_mask</parameter>. It may contain a subset of ORed + constants <constant>SD_BUS_CREDS_PID</constant>, + <constant>SD_BUS_CREDS_PPID</constant>, + <constant>SD_BUS_CREDS_TID</constant>, + <constant>SD_BUS_CREDS_UID</constant>, + <constant>SD_BUS_CREDS_EUID</constant>, + <constant>SD_BUS_CREDS_SUID</constant>, + <constant>SD_BUS_CREDS_FSUID</constant>, + <constant>SD_BUS_CREDS_GID</constant>, + <constant>SD_BUS_CREDS_EGID</constant>, + <constant>SD_BUS_CREDS_SGID</constant>, + <constant>SD_BUS_CREDS_FSGID</constant>, + <constant>SD_BUS_CREDS_SUPPLEMENTARY_GIDS</constant>, + <constant>SD_BUS_CREDS_COMM</constant>, + <constant>SD_BUS_CREDS_TID_COMM</constant>, + <constant>SD_BUS_CREDS_EXE</constant>, + <constant>SD_BUS_CREDS_CMDLINE</constant>, + <constant>SD_BUS_CREDS_CGROUP</constant>, + <constant>SD_BUS_CREDS_UNIT</constant>, + <constant>SD_BUS_CREDS_SLICE</constant>, + <constant>SD_BUS_CREDS_USER_UNIT</constant>, + <constant>SD_BUS_CREDS_USER_SLICE</constant>, + <constant>SD_BUS_CREDS_SESSION</constant>, + <constant>SD_BUS_CREDS_OWNER_UID</constant>, + <constant>SD_BUS_CREDS_EFFECTIVE_CAPS</constant>, + <constant>SD_BUS_CREDS_PERMITTED_CAPS</constant>, + <constant>SD_BUS_CREDS_INHERITABLE_CAPS</constant>, + <constant>SD_BUS_CREDS_BOUNDING_CAPS</constant>, + <constant>SD_BUS_CREDS_SELINUX_CONTEXT</constant>, + <constant>SD_BUS_CREDS_AUDIT_SESSION_ID</constant>, + <constant>SD_BUS_CREDS_AUDIT_LOGIN_UID</constant>, + <constant>SD_BUS_CREDS_TTY</constant>, + <constant>SD_BUS_CREDS_UNIQUE_NAME</constant>, + <constant>SD_BUS_CREDS_WELL_KNOWN_NAMES</constant>, and + <constant>SD_BUS_CREDS_DESCRIPTION</constant>. Use the special + value <constant>_SD_BUS_CREDS_ALL</constant> to request all + supported fields. The <constant>SD_BUS_CREDS_AUGMENT</constant> + constant may not be ORed into the mask for invocations of + <function>sd_bus_creds_new_from_pid()</function>.</para> + + <para>Fields can be retrieved from the credentials object using + <citerefentry><refentrytitle>sd_bus_creds_get_pid</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and other functions which correspond directly to the constants + listed above.</para> + + <para>A mask of fields which were actually successfully retrieved + can be retrieved with + <function>sd_bus_creds_get_mask()</function>. If the credentials + object was created with + <function>sd_bus_creds_new_from_pid()</function>, this will be a + subset of fields requested in <parameter>creds_mask</parameter>. + </para> + + <para>Similar to <function>sd_bus_creds_get_mask()</function>, the + function <function>sd_bus_creds_get_augmented_mask()</function> + returns a bitmask of field constants. The mask indicates which + credential fields have been retrieved in a non-atomic fashion. For + credential objects created via + <function>sd_bus_creds_new_from_pid()</function>, this mask will be + identical to the mask returned by + <function>sd_bus_creds_get_mask()</function>. However, for + credential objects retrieved via + <function>sd_bus_get_name_creds()</function>, this mask will be set + for the credential fields that could not be determined atomically + at peer connection time, and which were later added by reading + augmenting credential data from + <filename>/proc</filename>. Similarly, for credential objects + retrieved via <function>sd_bus_get_owner_creds()</function>, the + mask is set for the fields that could not be determined atomically + at bus creation time, but have been augmented. Similarly, for + credential objects retrieved via + <function>sd_bus_message_get_creds()</function>, the mask is set + for the fields that could not be determined atomically at message + sending time, but have been augmented. The mask returned by + <function>sd_bus_creds_get_augmented_mask()</function> is always a + subset of (or identical to) the mask returned by + <function>sd_bus_creds_get_mask()</function> for the same + object. The latter call hence returns all credential fields + available in the credential object, the former then marks the + subset of those that have been augmented. Note that augmented + fields are unsuitable for authorization decisions, as they may be + retrieved at different times, thus being subject to races. Hence, + augmented fields should be used exclusively for informational + purposes. + </para> + + <para><function>sd_bus_creds_ref()</function> creates a new + reference to the credentials object <parameter>c</parameter>. This + object will not be destroyed until + <function>sd_bus_creds_unref()</function> has been called as many + times plus once more. Once the reference count has dropped to zero, + <parameter>c</parameter> cannot be used anymore, so further + calls to <function>sd_bus_creds_ref(c)</function> or + <function>sd_bus_creds_unref(c)</function> are illegal.</para> + + <para><function>sd_bus_creds_unref()</function> destroys a reference + to <parameter>c</parameter>.</para> + + <para><function>sd_bus_creds_unrefp()</function> is similar to + <function>sd_bus_creds_unref()</function> but takes a pointer to a + pointer to an <type>sd_bus_creds</type> object. This call is useful in + conjunction with GCC's and LLVM's <ulink + url="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html">Clean-up + Variable Attribute</ulink>. Note that this function is defined as + inline function.</para> + + <para><function>sd_bus_creds_ref()</function>, + <function>sd_bus_creds_unref()</function> and + <function>sd_bus_creds_unrefp()</function> execute no operation if + the passed in bus credentials object is + <constant>NULL</constant>.</para> + + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_bus_creds_new_from_pid()</function> + returns 0 or a positive integer. On failure, it returns a negative + errno-style error code.</para> + + <para><function>sd_bus_creds_get_mask()</function> returns the + mask of successfully acquired fields.</para> + + <para><function>sd_bus_creds_get_augmented_mask()</function> + returns the mask of fields that have been augmented from data in + <filename>/proc</filename>, and are thus not suitable for + authorization decisions.</para> + + <para><function>sd_bus_creds_ref()</function> always returns the + argument.</para> + + <para><function>sd_bus_creds_unref()</function> always returns + <constant>NULL</constant>.</para> + </refsect1> + + <refsect1> + <title>Reference ownership</title> + + <para>Function <function>sd_bus_creds_new_from_pid()</function> + creates a new object and the caller owns the sole reference. When + not needed anymore, this reference should be destroyed with + <citerefentry><refentrytitle>sd_bus_creds_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ESRCH</constant></term> + + <listitem><para>Specified <parameter>pid</parameter> could not + be found.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>Specified parameter is invalid + (<constant>NULL</constant> in case of output + parameters).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EOPNOTSUPP</constant></term> + + <listitem><para>One of the requested fields is unknown to the local system.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_creds_new_from_pid()</function> and the + other calls described here are available as a shared library, + which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_creds_get_pid</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_get_name_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_get_owner_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_default.xml b/src/libsystemd/sd_bus_default.xml new file mode 100644 index 0000000000..6d5a90de72 --- /dev/null +++ b/src/libsystemd/sd_bus_default.xml @@ -0,0 +1,312 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_default"> + + <refentryinfo> + <title>sd_bus_default</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_default</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_default</refname> + <refname>sd_bus_default_user</refname> + <refname>sd_bus_default_system</refname> + + <refname>sd_bus_open</refname> + <refname>sd_bus_open_user</refname> + <refname>sd_bus_open_system</refname> + <refname>sd_bus_open_system_remote</refname> + <refname>sd_bus_open_system_machine</refname> + + <refpurpose>Acquire a connection to a system or user bus</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_default</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_default_user</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_default_system</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_open</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_open_user</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_open_system</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_open_system_remote</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + <paramdef>const char *<parameter>host</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_open_system_machine</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + <paramdef>const char *<parameter>machine</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_default()</function> acquires a bus + connection object to the user bus when invoked in user context, or + to the system bus otherwise. The connection object is associated + with the calling thread. Each time the function is invoked from + the same thread, the same object is returned, but its reference + count is increased by one, as long as at least one reference is + kept. When the last reference to the connection is dropped (using + the + <citerefentry><refentrytitle>sd_bus_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call), the connection is terminated. Note that the connection is + not automatically terminated when the associated thread ends. It + is important to drop the last reference to the bus connection + explicitly before the thread ends, as otherwise, the connection will + leak. Also, queued but unread or unwritten messages keep the + bus referenced, see below.</para> + + <para><function>sd_bus_default_user()</function> returns a user + bus connection object associated with the calling thread. + <function>sd_bus_default_system()</function> is similar, but + connects to the system bus. Note that + <function>sd_bus_default()</function> is identical to these two + calls, depending on the execution context.</para> + + <para><function>sd_bus_open()</function> creates a new, + independent bus connection to the user bus when invoked in user + context, or the system bus + otherwise. <function>sd_bus_open_user()</function> is similar, but + connects only to the user bus. + <function>sd_bus_open_system()</function> does the same, but + connects to the system bus. In contrast to + <function>sd_bus_default()</function>, + <function>sd_bus_default_user()</function>, and + <function>sd_bus_default_system()</function>, these calls return + new, independent connection objects that are not associated with + the invoking thread and are not shared between multiple + invocations. It is recommended to share connections per thread to + efficiently make use the available resources. Thus, it is + recommended to use <function>sd_bus_default()</function>, + <function>sd_bus_default_user()</function> and + <function>sd_bus_default_system()</function> to connect to the + user or system buses.</para> + + <para>If the <varname>$DBUS_SESSION_BUS_ADDRESS</varname> environment + variable is set + (cf. <citerefentry project='man-pages'><refentrytitle>environ</refentrytitle><manvolnum>7</manvolnum></citerefentry>), + it will be used as the address of the user bus. This variable can + contain multiple addresses separated by <literal>;</literal>. If + this variable is not set, a suitable default for the default user + D-Bus instance will be used.</para> + + <para>If the <varname>$DBUS_SYSTEM_BUS_ADDRESS</varname> + environment variable is set, it will be used as the address of the + system bus. This variable uses the same syntax as + <varname>$DBUS_SESSION_BUS_ADDRESS</varname>. If this variable is + not set, a suitable default for the default system D-Bus instance + will be used.</para> + + <para><function>sd_bus_open_system_remote()</function> connects to + the system bus on the specified <parameter>host</parameter> using + <citerefentry + project='die-net'><refentrytitle>ssh</refentrytitle><manvolnum>1</manvolnum></citerefentry>. <parameter>host</parameter> + consists of an optional user name followed by the + <literal>@</literal> symbol, and the hostname. + </para> + + <para><function>sd_bus_open_system_machine()</function> connects + to the system bus in the specified <parameter>machine</parameter>, + where <parameter>machine</parameter> is the name of a local + container. See + <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry> + for more information about the "machine" concept. Note that + connections into local containers are only available to privileged + processes at this time.</para> + + <para>These calls allocate a bus connection object and initiate + the connection to a well-known bus of some form. An alternative to + using these high-level calls is to create an unconnected bus + object with + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and to connect it with + <citerefentry><refentrytitle>sd_bus_start</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + + </refsect1> + + <refsect1> + <title>Reference ownership</title> + <para>The functions <function>sd_bus_open()</function>, + <function>sd_bus_open_user()</function>, + <function>sd_bus_open_system()</function>, + <function>sd_bus_open_system_remote()</function>, and + <function>sd_bus_open_system_machine()</function> return a new + connection object and the caller owns the sole reference. When not + needed anymore, this reference should be destroyed with + <citerefentry><refentrytitle>sd_bus_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + + <para>The functions <function>sd_bus_default()</function>, + <function>sd_bus_default_user()</function> and + <function>sd_bus_default_system()</function> do not necessarily + create a new object, but increase the connection reference of an + existing connection object by one. Use + <citerefentry><refentrytitle>sd_bus_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + to drop the reference.</para> + + <para>Queued but unwritten/unread messages also keep a reference + to their bus connection object. For this reason, even if an + application dropped all references to a bus connection, it might + not get destroyed right away. Until all incoming queued + messages are read, and until all outgoing unwritten messages are + written, the bus object will stay + alive. <function>sd_bus_flush()</function> may be used to write + all outgoing queued messages so they drop their references. To + flush the unread incoming messages, use + <function>sd_bus_close()</function>, which will also close the bus + connection. When using the default bus logic, it is a good idea to + first invoke <function>sd_bus_flush()</function> followed by + <function>sd_bus_close()</function> when a thread or process + terminates, and thus its bus connection object should be + freed.</para> + + <para>The life cycle of the default bus connection should be the + responsibility of the code that creates/owns the thread the + default bus connection object is associated with. Library code + should neither call <function>sd_bus_flush()</function> nor + <function>sd_bus_close()</function> on default bus objects unless + it does so in its own private, self-allocated thread. Library code + should not use the default bus object in other threads unless it + is clear that the program using it will life cycle the bus + connection object and flush and close it before exiting from the + thread. In libraries where it is not clear that the calling + program will life cycle the bus connection object, it is hence + recommended to use <function>sd_bus_open_system()</function> + instead of <function>sd_bus_default_system()</function> and + related calls.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive + integer. On failure, these calls return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The specified parameters are invalid.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESOCKTNOSUPPORT</constant></term> + + <listitem><para>The protocol version required to connect to the selected bus is not supported.</para></listitem> + </varlistentry> + </variablelist> + + <para>In addition, any further connection-related errors may be + by returned. See <citerefentry><refentrytitle>sd_bus_send</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_open_user()</function> and the other + functions described here are available as a shared library, which + can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_ref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>ssh</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd-machined.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>, + <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_error.xml b/src/libsystemd/sd_bus_error.xml new file mode 100644 index 0000000000..c2d7ee389b --- /dev/null +++ b/src/libsystemd/sd_bus_error.xml @@ -0,0 +1,389 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_error"> + + <refentryinfo> + <title>sd_bus_error</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_error</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_error</refname> + <refname>SD_BUS_ERROR_MAKE_CONST</refname> + <refname>SD_BUS_ERROR_NULL</refname> + <refname>sd_bus_error_free</refname> + <refname>sd_bus_error_set</refname> + <refname>sd_bus_error_setf</refname> + <refname>sd_bus_error_set_const</refname> + <refname>sd_bus_error_set_errno</refname> + <refname>sd_bus_error_set_errnof</refname> + <refname>sd_bus_error_set_errnofv</refname> + <refname>sd_bus_error_get_errno</refname> + <refname>sd_bus_error_copy</refname> + <refname>sd_bus_error_is_set</refname> + <refname>sd_bus_error_has_name</refname> + + <refpurpose>sd-bus error handling</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcsynopsisinfo>typedef struct { + const char *name; + const char *message; + ... +} sd_bus_error;</funcsynopsisinfo> + + <para> + <constant>SD_BUS_ERROR_MAKE_CONST(<replaceable>name</replaceable>, <replaceable>message</replaceable>)</constant> + </para> + <para> + <constant>SD_BUS_ERROR_NULL</constant> + </para> + + <funcprototype> + <funcdef>void <function>sd_bus_error_free</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_set</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + <paramdef>const char *<parameter>message</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_setf</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_set_const</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + <paramdef>const char *<parameter>message</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_set_errno</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>int <parameter>error</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_set_errnof</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>int <parameter>error</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_set_errnofv</function></funcdef> + <paramdef>sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>int <parameter>error</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>va_list ap</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_get_errno</function></funcdef> + <paramdef>const sd_bus_error *<parameter>e</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_copy</function></funcdef> + <paramdef>sd_bus_error *<parameter>dst</parameter></paramdef> + <paramdef>const sd_bus_error *<parameter>e</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_is_set</function></funcdef> + <paramdef>const sd_bus_error *<parameter>e</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_error_has_name</function></funcdef> + <paramdef>const sd_bus_error *<parameter>e</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + </funcprototype> + </funcsynopsis> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The <structname>sd_bus_error</structname> structure carries + information about a D-Bus error condition. The functions described + below may be used to set and query fields in this structure. The + <structfield>name</structfield> field contains a short identifier + of an error. It should follow the rules for error names described + in the D-Bus specification, subsection <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names">Valid + Names</ulink>. A number of common, standardized error names are + described in + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but additional domain-specific errors may be defined by + applications. The <structfield>message</structfield> field usually + contains a human-readable string describing the details, but might + be NULL. An unset <structname>sd_bus_error</structname> structure + should have both fields initialized to NULL. Set an error + structure to <constant>SD_BUS_ERROR_NULL</constant> in order to + reset both fields to NULL. When no longer necessary, resources + held by the <structname>sd_bus_error</structname>structure should + be destroyed with <function>sd_bus_error_free()</function>.</para> + + <para><function>sd_bus_error_set()</function> sets an error + structure to the specified name and message strings. The strings + will be copied into internal, newly allocated memory. It is + essential to free the error structure again when it is not + required anymore (see above). The function will return an + <varname>errno</varname>-like negative value (see <citerefentry + project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>) + determined from the specified error name. Various well-known + D-Bus errors are converted to well-known <varname>errno</varname> + counterparts, and the other ones to <constant>-EIO</constant>. See + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for a list of well-known error names. Additional error mappings + may be defined with + <citerefentry><refentrytitle>sd_bus_error_add_map</refentrytitle><manvolnum>3</manvolnum></citerefentry>. If + <parameter>e</parameter> is NULL, no error structure is initialized, + but the error is still converted into an + <varname>errno</varname>-style error. If + <parameter>name</parameter> is <constant>NULL</constant>, it is + assumed that no error occurred, and 0 is returned. This means that + this function may be conveniently used in a + <function>return</function> statement. If + <parameter>message</parameter> is NULL, no message is set. This + call can fail if no memory may be allocated for the name and + message strings, in which case an + <constant>SD_BUS_ERROR_NO_MEMORY</constant> error might be set + instead and -ENOMEM be returned. Do not use this call on error + structures that are already initialized. If you intend to reuse an + error structure, free the old data stored in it with + <function>sd_bus_error_free()</function> first.</para> + + <para><function>sd_bus_error_setf()</function> is similar to + <function>sd_bus_error_set()</function>, but takes a <citerefentry + project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry> + format string and corresponding arguments to generate the + <structfield>message</structfield> field.</para> + + <para><function>sd_bus_error_set_const()</function> is similar to + <function>sd_bus_error_set()</function>, but the string parameters + are not copied internally, and must hence remain constant and + valid for the lifetime of <parameter>e</parameter>. Use this call + to avoid memory allocations when setting error structures. Since + this call does not allocate memory, it will not fail with an + out-of-memory condition as + <function>sd_bus_error_set()</function> can, as described + above. Alternatively, the + <constant>SD_BUS_ERROR_MAKE_CONST()</constant> macro may be used + to generate a literal, constant bus error structure + on-the-fly.</para> + + <para><function>sd_bus_error_set_errno()</function> will set + <structfield>name</structfield> from an + <varname>errno</varname>-like value that is converted to a D-Bus + error. <citerefentry + project='die-net'><refentrytitle>strerror_r</refentrytitle><manvolnum>3</manvolnum></citerefentry> + will be used to set <structfield>message</structfield>. Well-known + D-Bus error names will be used for <structfield>name</structfield> + if applicable, otherwise a name in the + <literal>System.Error.</literal> namespace will be generated. The + sign of the specified error number is ignored. The absolute value + is used implicitly. The call always returns a negative value, for + convenient usage in <function>return</function> statements. This + call might fail due to lack of memory, in which case an + <constant>SD_BUS_ERROR_NO_MEMORY</constant> error is set instead, + and -ENOMEM is returned.</para> + + <para><function>sd_bus_error_set_errnof()</function> is similar to + <function>sd_bus_error_set_errno()</function>, but in addition to + <parameter>error</parameter>, takes a <citerefentry + project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry> + format string and corresponding arguments. The + <structfield>message</structfield> field will be generated from + <parameter>format</parameter> and the arguments.</para> + + <para><function>sd_bus_error_set_errnofv()</function> is similar to + <function>sd_bus_error_set_errnof()</function>, but takes the + format string parameters as <citerefentry + project='man-pages'><refentrytitle>va_arg</refentrytitle><manvolnum>3</manvolnum></citerefentry> + parameter list.</para> + + <para><function>sd_bus_error_get_errno()</function> converts the + <structfield>name</structfield> field of an error structure to an + <varname>errno</varname>-like (positive) value using the same + rules as <function>sd_bus_error_set()</function>. If + <parameter>e</parameter> is <constant>NULL</constant>, 0 will be + returned.</para> + + <para><function>sd_bus_error_copy()</function> will initialize + <parameter>dst</parameter> using the values in + <parameter>e</parameter>. If the strings in + <parameter>e</parameter> were set using + <function>sd_bus_set_error_const()</function>, they will be shared. + Otherwise, they will be copied. Returns a converted + <varname>errno</varname>-like, negative error code.</para> + + <para><function>sd_bus_error_is_set()</function> will return a + non-zero value if <parameter>e</parameter> is + non-<constant>NULL</constant> and an error has been set, + <constant>false</constant> otherwise.</para> + + <para><function>sd_bus_error_has_name()</function> will return a + non-zero value if <parameter>e</parameter> is + non-<constant>NULL</constant> and an error with the same + <parameter>name</parameter> has been set, + <constant>false</constant> otherwise.</para> + + <para><function>sd_bus_error_free()</function> will destroy + resources held by <parameter>e</parameter>. The parameter itself + will not be deallocated, and must be <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry>d + by the caller if necessary. The function may also be called safely + on unset errors (error structures with both fields set to NULL), + in which case it performs no operation. This call will reset the + error structure after freeing the data, so that all fields are set + to NULL. The structure may be reused afterwards.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The functions <function>sd_bus_error_set()</function>, + <function>sd_bus_error_setf()</function>, and + <function>sd_bus_error_set_const()</function>, when successful, + return the negative errno value corresponding to the + <parameter>name</parameter> parameter. The functions + <function>sd_bus_error_set_errno()</function>, + <function>sd_bus_error_set_errnof()</function> and + <function>sd_bus_error_set_errnofv()</function>, when successful, + return the negative value of the <parameter>error</parameter> + parameter. If an error occurs, one of the negative error values + listed below will be returned.</para> + + <para><function>sd_bus_error_get_errno()</function> returns + <constant>false</constant> when <parameter>e</parameter> is + <constant>NULL</constant>, and a positive errno value mapped from + <parameter>e->name</parameter> otherwise.</para> + + <para><function>sd_bus_error_copy()</function> returns 0 or a + positive integer on success, and a negative error value converted + from the error name otherwise.</para> + + <para><function>sd_bus_error_is_set()</function> returns a + non-zero value when <parameter>e</parameter> and the + <structfield>name</structfield> field are + non-<constant>NULL</constant>, zero otherwise.</para> + + <para><function>sd_bus_error_has_name()</function> returns a + non-zero value when <parameter>e</parameter> is + non-<constant>NULL</constant> and the + <structfield>name</structfield> field is equal to + <parameter>name</parameter>, zero otherwise.</para> + </refsect1> + + <refsect1> + <title>Reference ownership</title> + <para><structname>sd_bus_error</structname> is not reference + counted. Users should destroy resources held by it by calling + <function>sd_bus_error_free()</function>. Usually, error structures + are allocated on the stack or passed in as function parameters, + but they may also be allocated dynamically, in which case it is + the duty of the caller to <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + the memory held by the structure itself after freeing its contents + with <function>sd_bus_error_free()</function>.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>Error was already set in + <structname>sd_bus_error</structname> structure when one the + error-setting functions was called.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_set_error()</function> and other functions + described here are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_error_add_map</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>strerror_r</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_error_add_map.xml b/src/libsystemd/sd_bus_error_add_map.xml new file mode 100644 index 0000000000..7dc1ef6c90 --- /dev/null +++ b/src/libsystemd/sd_bus_error_add_map.xml @@ -0,0 +1,173 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_error_add_map"> + + <refentryinfo> + <title>sd_bus_error_add_map</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_error_add_map</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_error_add_map</refname> + <refname>sd_bus_error_map</refname> + <refname>SD_BUS_ERROR_MAP</refname> + <refname>SD_BUS_ERROR_END</refname> + + <refpurpose>Additional sd-dbus error mappings</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcsynopsisinfo>typedef struct { + const char *name; + int code; + ... +} sd_bus_error_map;</funcsynopsisinfo> + + </funcsynopsis> + + <para> + <constant>SD_BUS_ERROR_MAP(<replaceable>name</replaceable>, <replaceable>code</replaceable>)</constant> + </para> + <para> + <constant>SD_BUS_ERROR_MAP_END</constant> + </para> + + <funcprototype> + <funcdef>int <function>sd_bus_error_add_map</function></funcdef> + <paramdef>const sd_bus_map *<parameter>map</parameter></paramdef> + </funcprototype> + + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The <function>sd_bus_error_add_map()</function> call may be + used to register additional mappings for converting D-Bus errors + to GNU/Linux <varname>errno</varname>-style errors. The mappings + defined with this call are consulted by calls such as + <citerefentry><refentrytitle>sd_bus_error_set</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_bus_error_get_errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>. By + default, a number of generic, standardized mappings are known, as + documented in + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry>. Use + this call to add further, application-specific mappings.</para> + + <para>The function takes a pointer to an array of + <structname>sd_bus_error_map</structname> structures. A reference + to the specified array is added to the lookup tables for error + mappings. Note that the structure is not copied, and that it is hence + essential that the array stays available and constant during the + entire remaining runtime of the process.</para> + + <para>The mapping array should be put together with a series of + <constant>SD_BUS_ERROR_MAP()</constant> macro invocations that + take a literal name string and a (positive) + <varname>errno</varname>-style error number. The last entry of the + array should be an invocation of the + <constant>SD_BUS_ERROR_MAP_END</constant> macro. The array should not be + put together without use of these two macros.</para> + + <para>Note that the call is idempotent: it is safe to invoke it + multiple times with the parameter, which will only add the passed + mapping array once.</para> + + <para>Note that the memory allocated by this call is not intended + to be freed during the lifetime of the process. It should not be + freed explicitly.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_bus_error_add_map()</function> returns a + positive value when the new array was added to the lookup + tables. It returns zero when the same array was already added + before. On error, a negative <varname>errno</varname>-style error + code is returned. See below for known error codes.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The specified mapping array is invalid.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The various error definitions described here are available + as a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_error</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus-errors</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>strerror_r</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_get_fd.xml b/src/libsystemd/sd_bus_get_fd.xml new file mode 100644 index 0000000000..9f7019069f --- /dev/null +++ b/src/libsystemd/sd_bus_get_fd.xml @@ -0,0 +1,101 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 Julian Orth + + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_get_fd"> + + <refentryinfo> + <title>sd_bus_get_fd</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <firstname>Julian</firstname> + <surname>Orth</surname> + <email>ju.orth@gmail.com</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_get_fd</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_get_fd</refname> + + <refpurpose>Get the file descriptor connected to the message bus</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_get_fd</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <function>sd_bus_get_fd()</function> returns the file descriptor used to + communicate with the message bus. This descriptor can be used with + <citerefentry + project='die-net'><refentrytitle>select</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry + project='die-net'><refentrytitle>poll</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + or similar functions to wait for incoming messages. + </para> + + <para> + If the bus was created with the + <citerefentry><refentrytitle>sd_bus_set_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry> + function, then the <parameter>input_fd</parameter> used in that call is + returned. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para> + Returns the file descriptor used for incoming messages from the message + bus. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_set_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_append.xml b/src/libsystemd/sd_bus_message_append.xml new file mode 100644 index 0000000000..77fce02eae --- /dev/null +++ b/src/libsystemd/sd_bus_message_append.xml @@ -0,0 +1,264 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_append" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_bus_message_append</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_append</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_append</refname> + + <refpurpose>Attach fields to a D-Bus message based on a type + string</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int sd_bus_message_append</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>const char *<parameter>types</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The <function>sd_bus_message_append()</function> function + appends a sequence of fields to the D-Bus message object + <parameter>m</parameter>. The type string + <parameter>types</parameter> describes the types of the field + arguments that follow. For each type specified in the type string, + one or more arguments need to be specified, in the same order as + declared in the type string.</para> + + <para>The type string is composed of the elements shown in the + table below. It contains zero or more single "complete types". + Each complete type may be one of the basic types or a fully + described container type. A container type may be a structure with + the contained types, a variant, an array with its element type, or + a dictionary entry with the contained types. The type string is + <constant>NUL</constant>-terminated.</para> + + <para>In case of a basic type, one argument of the corresponding + type is expected.</para> + + <para>A structure is denoted by a sequence of complete types + between <literal>(</literal> and <literal>)</literal>. This + sequence cannot be empty — it must contain at least one type. + Arguments corresponding to this nested sequence follow the same + rules as if they were not nested.</para> + + <para>A variant is denoted by <literal>v</literal>. Corresponding + arguments must begin with a type string denoting a complete type, + and following that, arguments corresponding to the specified type. + </para> + + <para>An array is denoted by <literal>a</literal> followed by a + complete type. Corresponding arguments must begin with the number of + entries in the array, followed by the entries themselves, + matching the element type of the array.</para> + + <para>A dictionary is an array of dictionary entries, denoted by + <literal>a</literal> followed by a pair of complete types between + <literal>{</literal> and <literal>}</literal>. The first of those + types must be a basic type. Corresponding arguments must begin + with the number of dictionary entries, followed by a pair of + values for each entry matching the element type of + the dictionary entries.</para> + + <para>For further details on the D-Bus type system, please consult + the <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#type-system">D-Bus + Specification</ulink>.</para> + + <table> + <title>Item type specifiers</title> + + <tgroup cols='5'> + <xi:include href="sd_bus_message_append_basic.xml" xpointer="xpointer(//table[@id='format-specifiers'])//colspec" /> + <xi:include href="sd_bus_message_append_basic.xml" xpointer="xpointer(//table[@id='format-specifiers']//thead)" /> + + <tbody> + <xi:include href="sd_bus_message_append_basic.xml" xpointer="xpointer(//table[@id='format-specifiers']//tbody/*)" /> + + <row> + <entry><literal>a</literal></entry> + <entry><constant>SD_BUS_TYPE_ARRAY</constant></entry> + <entry>array</entry> + <entry>determined by array type and size</entry> + <entry>int, followed by array contents</entry> + </row> + + <row> + <entry><literal>v</literal></entry> + <entry><constant>SD_BUS_TYPE_VARIANT</constant></entry> + <entry>variant</entry> + <entry>determined by the type argument</entry> + <entry>signature string, followed by variant contents</entry> + </row> + + <row> + <entry><literal>(</literal></entry> + <entry><constant>SD_BUS_TYPE_STRUCT_BEGIN</constant></entry> + <entry>array start</entry> + <entry morerows="1">determined by the nested types</entry> + <entry morerows="1">structure contents</entry> + </row> + <row> + <entry><literal>)</literal></entry> + <entry><constant>SD_BUS_TYPE_STRUCT_END</constant></entry> + <entry>array end</entry> + </row> + + <row> + <entry><literal>{</literal></entry> + <entry><constant>SD_BUS_TYPE_DICT_ENTRY_BEGIN</constant></entry> + <entry>dictionary entry start</entry> + <entry morerows="1">determined by the nested types</entry> + <entry morerows="1">dictionary contents</entry> + </row> + <row> + <entry><literal>}</literal></entry> + <entry><constant>SD_BUS_TYPE_DICT_ENTRY_END</constant></entry> + <entry>dictionary entry end</entry> + </row> + </tbody> + </tgroup> + </table> + + </refsect1> + + <refsect1> + <title>Types String Grammar</title> + + <programlisting>types ::= complete_type* +complete_type ::= basic_type | variant | structure | array | dictionary +basic_type ::= "y" | "n" | "q" | "u" | "i" | "x" | "t" | "d" | + "b" | "h" | + "s" | "o" | "g" +variant ::= "v" +structure ::= "(" complete_type+ ")" +array ::= "a" complete_type +dictionary ::= "a" "{" basic_type complete_type "}" +</programlisting> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Append a single basic type (the string <literal>a string</literal>): + </para> + + <programlisting>sd_bus_message *m; +... +sd_bus_message_append(m, "s", "a string");</programlisting> + + <para>Append all types of integers:</para> + + <programlisting>uint8_t y = 1; +int16_t n = 2; +uint16_t q = 3; +int32_t i = 4; +uint32_t u = 5; +int32_t x = 6; +uint32_t t = 7; +double d = 8.0; +sd_bus_message_append(m, "ynqiuxtd", y, n, q, i, u, x, t, d);</programlisting> + + <para>Append a structure composed of a string and a D-Bus path:</para> + + <programlisting>sd_bus_message_append(m, "(so)", "a string", "/a/path"); +</programlisting> + + <para>Append an array of UNIX file descriptors:</para> + + <programlisting>sd_bus_message_append(m, "ah", 3, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO); +</programlisting> + + <para>Append a variant, with the real type "g" (signature), + and value "sdbusisgood":</para> + + <programlisting>sd_bus_message_append(m, "v", "g", "sdbusisgood");</programlisting> + + <para>Append a dictionary containing the mapping {1=>"a", 2=>"b", 3=>""}: + </para> + + <programlisting>sd_bus_message_append(m, "a{is}", 3, 1, "a", 2, "b", 3, NULL); + </programlisting> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, this call returns 0 or a positive + integer. On failure, this call returns a negative + errno-style error code.</para> + </refsect1> + + <xi:include href="sd_bus_message_append_basic.xml" xpointer="errors" /> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_open_user()</function> and other functions + described here are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd-bus</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_array</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_append_array.xml b/src/libsystemd/sd_bus_message_append_array.xml new file mode 100644 index 0000000000..27db2a96c3 --- /dev/null +++ b/src/libsystemd/sd_bus_message_append_array.xml @@ -0,0 +1,213 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_append_array" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_bus_message_append_array</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_append_array</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_append_array</refname> + <refname>sd_bus_message_append_array_memfd</refname> + <refname>sd_bus_message_append_array_iovec</refname> + <refname>sd_bus_message_append_array_space</refname> + + <refpurpose>Append an array of fields to a D-Bus + message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int sd_bus_message_append_array</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>char void *<parameter>ptr</parameter></paramdef> + <paramdef>size_t <parameter>size</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int sd_bus_message_append_array_memfd</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>int <parameter>memfd</parameter></paramdef> + <paramdef>uint64_t <parameter>offset</parameter></paramdef> + <paramdef>uint64_t <parameter>size</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int sd_bus_message_append_array_iovec</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>const struct iovec *<parameter>iov</parameter></paramdef> + <paramdef>unsigned <parameter>n</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int sd_bus_message_append_array_space</funcdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>size_t <parameter>size</parameter></paramdef> + <paramdef>void **<parameter>ptr</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The <function>sd_bus_message_append_array()</function> + function appends an array to a D-Bus message + <parameter>m</parameter>. A container will be opened, the array + contents appended, and the container closed. The parameter + <parameter>type</parameter> determines how the pointer + <parameter>p</parameter> is interpreted. + <parameter>type</parameter> must be one of the "trivial" types + <literal>y</literal>, <literal>n</literal>, <literal>q</literal>, + <literal>i</literal>, <literal>u</literal>, <literal>x</literal>, + <literal>t</literal>, <literal>d</literal> (but not + <literal>b</literal>), as defined by the <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#basic-types">Basic + Types</ulink> section of the D-Bus specification, and listed in + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + Pointer <parameter>p</parameter> must point to an array of size + <parameter>size</parameter> bytes containing items of the + respective type. Size <parameter>size</parameter> must be a + multiple of the size of the type <parameter>type</parameter>. As a + special case, <parameter>p</parameter> may be + <constant>NULL</constant>, if <parameter>size</parameter> is 0. + The memory pointed to by <parameter>p</parameter> is copied into + the memory area containing the message and stays in possession of + the caller. The caller may hence freely change the data after this + call without affecting the message the array was appended + to.</para> + + <para>The <function>sd_bus_message_append_array_memfd()</function> + function appends an array of a trivial type to message + <parameter>m</parameter>, similar to + <function>sd_bus_message_append_array()</function>. The contents + of the memory file descriptor <parameter>memfd</parameter> + starting at the specified offset and of the specified size is + used as the contents of the array. The offset and size must be a + multiple of the size of the type + <parameter>type</parameter>. However, as a special exception, if + the offset is specified as zero and the size specified as + UINT64_MAX the full memory file descriptor contents is used. The + memory file descriptor is sealed by this call if it has not been + sealed yet, and cannot be modified after this call. See + <citerefentry + project='man-pages'><refentrytitle>memfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details about memory file descriptors. Appending arrays with + memory file descriptors enables efficient zero-copy data transfer, + as the memory file descriptor may be passed as-is to the + destination, without copying the memory in it to the destination + process. Not all protocol transports support passing memory file + descriptors between participants, in which case this call will + automatically fall back to copying. Also, as memory file + descriptor passing is inefficient for smaller amounts of data, + copying might still be enforced even where memory file descriptor + passing is supported.</para> + + <para>The <function>sd_bus_message_append_array_iovec()</function> + function appends an array of a trivial type to the message + <parameter>m</parameter>, similar to + <function>sd_bus_message_append_array()</function>. Contents of + the I/O vector array <parameter>iov</parameter> are used as the + contents of the array. The total size of + <parameter>iov</parameter> payload (the sum of + <structfield>iov_len</structfield> fields) must be a multiple of + the size of the type <parameter>type</parameter>. The + <parameter>iov</parameter> argument must point to + <parameter>n</parameter> I/O vector structures. Each structure may + have the <structname>iov_base</structname> field set, in which + case the memory pointed to will be copied into the message, or + unset (set to zero), in which case a block of zeros of length + <structname>iov_len</structname> bytes will be inserted. The + memory pointed at by <parameter>iov</parameter> may be changed + after this call.</para> + + <para>The <function>sd_bus_message_append_array_space()</function> + function appends space for an array of a trivial type to message + <parameter>m</parameter>. It behaves the same as + <function>sd_bus_message_append_array()</function>, but instead of + copying items to the message, it returns a pointer to the + destination area to the caller in pointer + <parameter>p</parameter>. The caller should subsequently write the + array contents to this memory. Modifications to the memory + pointed to should only occur until the next operation on the bus + message is invoked. Most importantly, the memory should not be + altered anymore when another field has been added to the message + or the message has been sealed.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, they return a negative errno-style error code.</para> + </refsect1> + + <xi:include href="sd_bus_message_append_basic.xml" xpointer="errors" /> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_append_array()</function> and other + functions described here are available as a shared library, which + can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>memfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html">The D-Bus specification</ulink> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_append_basic.xml b/src/libsystemd/sd_bus_message_append_basic.xml new file mode 100644 index 0000000000..276953af69 --- /dev/null +++ b/src/libsystemd/sd_bus_message_append_basic.xml @@ -0,0 +1,295 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_append_basic"> + + <refentryinfo> + <title>sd_bus_message_append_basic</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_append_basic</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_append_basic</refname> + + <refpurpose>Attach a single field to a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int sd_bus_message_append_basic</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>const void *<parameter>p</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_message_append_basic()</function> appends a + single field to the message <parameter>m</parameter>. The + parameter <parameter>type</parameter> determines how the pointer + <parameter>p</parameter> is interpreted. + <parameter>type</parameter> must be one of the basic types as + defined by the <ulink + url="http://dbus.freedesktop.org/doc/dbus-specification.html#basic-types">Basic + Types</ulink> section of the D-Bus specification, and listed in + the table below. + </para> + + <table id='format-specifiers'> + <title>Item type specifiers</title> + + <tgroup cols='5'> + <colspec colname='specifier' /> + <colspec colname='constant' /> + <colspec colname='description' /> + <colspec colname='size' /> + <colspec colname='ctype' /> + <thead> + <row> + <entry>Specifier</entry> + <entry>Constant</entry> + <entry>Description</entry> + <entry>Size</entry> + <entry>Expected C Type</entry> + </row> + </thead> + <tbody> + <row> + <entry><literal>y</literal></entry> + <entry><constant>SD_BUS_TYPE_BYTE</constant></entry> + <entry>unsigned integer</entry> + <entry>1 byte</entry> + <entry>uint8_t</entry> + </row> + + <row> + <entry><literal>b</literal></entry> + <entry><constant>SD_BUS_TYPE_BOOLEAN</constant></entry> + <entry>boolean</entry> + <entry>4 bytes</entry> + <entry>int</entry> + </row> + + <row> + <entry><literal>n</literal></entry> + <entry><constant>SD_BUS_TYPE_INT16</constant></entry> + <entry>signed integer</entry> + <entry>2 bytes</entry> + <entry>int16_t</entry> + </row> + + <row> + <entry><literal>q</literal></entry> + <entry><constant>SD_BUS_TYPE_UINT16</constant></entry> + <entry>unsigned integer</entry> + <entry>2 bytes</entry> + <entry>uint16_t</entry> + </row> + + <row> + <entry><literal>i</literal></entry> + <entry><constant>SD_BUS_TYPE_INT32</constant></entry> + <entry>signed integer</entry> + <entry>4 bytes</entry> + <entry>int32_t</entry> + </row> + + <row> + <entry><literal>u</literal></entry> + <entry><constant>SD_BUS_TYPE_UINT32</constant></entry> + <entry>unsigned integer</entry> + <entry>4 bytes</entry> + <entry>uint32_t</entry> + </row> + + <row> + <entry><literal>x</literal></entry> + <entry><constant>SD_BUS_TYPE_INT64</constant></entry> + <entry>signed integer</entry> + <entry>8 bytes</entry> + <entry>int64_t</entry> + </row> + + <row> + <entry><literal>t</literal></entry> + <entry><constant>SD_BUS_TYPE_UINT64</constant></entry> + <entry>unsigned integer</entry> + <entry>8 bytes</entry> + <entry>uint64_t</entry> + </row> + + <row> + <entry><literal>d</literal></entry> + <entry><constant>SD_BUS_TYPE_DOUBLE</constant></entry> + <entry>floating-point</entry> + <entry>8 bytes</entry> + <entry>double</entry> + </row> + + <row> + <entry><literal>s</literal></entry> + <entry><constant>SD_BUS_TYPE_STRING</constant></entry> + <entry>Unicode string</entry> + <entry>variable</entry> + <entry>char[]</entry> + </row> + + <row> + <entry><literal>o</literal></entry> + <entry><constant>SD_BUS_TYPE_OBJECT_PATH</constant></entry> + <entry>object path</entry> + <entry>variable</entry> + <entry>char[]</entry> + </row> + + <row> + <entry><literal>g</literal></entry> + <entry><constant>SD_BUS_TYPE_SIGNATURE</constant></entry> + <entry>signature</entry> + <entry>variable</entry> + <entry>char[]</entry> + </row> + + <row> + <entry><literal>h</literal></entry> + <entry><constant>SD_BUS_TYPE_UNIX_FD</constant></entry> + <entry>UNIX file descriptor</entry> + <entry>4 bytes</entry> + <entry>int</entry> + </row> + </tbody> + </tgroup> + </table> + + <para>The value of the parameter is copied into a memory area held + by the message object, stays in the possession of the caller and + may hence be freely changed after this call without affecting the + bus message it has been added to. If <parameter>type</parameter> + is <literal>h</literal> (UNIX file descriptor), the descriptor is + duplicated by this call and the passed descriptor stays in + possession of the caller.</para> + + <para>For types <literal>s</literal>, <literal>o</literal>, and + <literal>g</literal>, the parameter <parameter>p</parameter> is + interpreted as a pointer to a <constant>NUL</constant>-terminated + character sequence. As a special case, a <constant>NULL</constant> + pointer is interpreted as an empty string. The string should be + valid Unicode string encoded as UTF-8. In case of the two latter + types, the additional requirements for a D-Bus object path or + type signature should be satisfied. Those requirements should be + verified by the recipient of the message. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, this call returns 0 or a positive integer. On + failure, it returns a negative errno-style error code.</para> + </refsect1> + + <refsect1 id='errors'> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>Specified parameter is invalid. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EPERM</constant></term> + + <listitem><para>Message has been sealed. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>Message is in invalid state. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>Message cannot be appended to. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_bus_append_basic()</function> function + described here is available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html">The D-Bus specification</ulink> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_append_string_memfd.xml b/src/libsystemd/sd_bus_message_append_string_memfd.xml new file mode 100644 index 0000000000..9e99999bf3 --- /dev/null +++ b/src/libsystemd/sd_bus_message_append_string_memfd.xml @@ -0,0 +1,153 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_append_string_memfd" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_bus_message_append_string_memfd</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_append_string_memfd</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_append_string_memfd</refname> + <refname>sd_bus_message_append_string_iovec</refname> + <refname>sd_bus_message_append_string_space</refname> + + <refpurpose>Attach a string to a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int sd_bus_message_append_string_memfd</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>int <parameter>memfd</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int sd_bus_message_append_string_iovec</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>const struct iovec *<parameter>iov</parameter></paramdef> + <paramdef>unsigned <parameter>n</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int sd_bus_message_append_string_space</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>size_t <parameter>size</parameter></paramdef> + <paramdef>char **<parameter>s</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The functions + <function>sd_bus_message_append_string_memfd</function> and + <function>sd_bus_message_append_string_iovec</function> can be + used to append a single string (item of type <literal>s</literal>) + to message <parameter>m</parameter>.</para> + + <para>In case of + <function>sd_bus_message_append_string_memfd</function>, the + contents of <parameter>memfd</parameter> are the string. They must + satisfy the same constraints as described for the + <literal>s</literal> type in + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>In case of + <function>sd_bus_message_append_string_iovec</function>, the + payload of <parameter>iov</parameter> is the string. It must + satisfy the same constraints as described for the + <literal>s</literal> type in + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>The <parameter>iov</parameter> argument must point to + <parameter>n</parameter> <structname>struct iovec</structname> + structures. Each structure may have the + <structname>iov_base</structname> field set, in which case the + memory pointed to will be copied into the message, or unset, in + which case a block of spaces (ASCII 32) of length + <structname>iov_len</structname> will be inserted. The + memory pointed at by <parameter>iov</parameter> may be changed + after this call.</para> + + <para>The + <function>sd_bus_message_append_string_space</function> function appends + space for a string to message <parameter>m</parameter>. It behaves + similar to <function>sd_bus_message_append_basic</function> with + type <literal>s</literal>, but instead of copying a string into + the message, it returns a pointer to the destination area to + the caller in pointer <parameter>p</parameter>. Space for the string + of length <parameter>size</parameter> plus the terminating + <constant>NUL</constant> is allocated.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, those calls return 0 or a positive integer. On + failure, they returns a negative errno-style error code.</para> + </refsect1> + + <xi:include href="sd_bus_message_append_basic.xml" xpointer="errors" /> + + <refsect1> + <title>Notes</title> + + <para>The functions described here are available as a shared library, + which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html">The D-Bus specification</ulink> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_append_strv.xml b/src/libsystemd/sd_bus_message_append_strv.xml new file mode 100644 index 0000000000..0f77adcc8b --- /dev/null +++ b/src/libsystemd/sd_bus_message_append_strv.xml @@ -0,0 +1,116 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_append_strv" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_bus_message_append_strv</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_append_strv</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_append_strv</refname> + + <refpurpose>Attach an array of strings to a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int sd_bus_message_append_strv</funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char **<parameter>l</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The <function>sd_bus_message_append</function> function can be + used to append an array of strings to message + <parameter>m</parameter>. The parameter <parameter>l</parameter> + shall point to a <constant>NULL</constant>-terminated array of pointers + to <constant>NUL</constant>-terminated strings. Each string must + satisfy the same constraints as described for the + <literal>s</literal> type in + <citerefentry><refentrytitle>sd_bus_message_append_basic</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + + <para>The memory pointed at by <parameter>p</parameter> and the + contents of the strings themselves are copied into the memory area + containing the message and may be changed after this call. Note + that the signature of <parameter>l</parameter> parameter is to be + treated as <type>const char *const *</type>, and the contents + will not be modified.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, this call returns 0 or a positive integer. On + failure, a negative errno-style error code is returned.</para> + </refsect1> + + <xi:include href="sd_bus_message_append_basic.xml" xpointer="errors" /> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_bus_append_append_strv()</function> function + described here is available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_append_array</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <ulink url="http://dbus.freedesktop.org/doc/dbus-specification.html">The D-Bus specification</ulink> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_get_cookie.xml b/src/libsystemd/sd_bus_message_get_cookie.xml new file mode 100644 index 0000000000..3328eead3d --- /dev/null +++ b/src/libsystemd/sd_bus_message_get_cookie.xml @@ -0,0 +1,146 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_get_cookie"> + + <refentryinfo> + <title>sd_bus_message_get_cookie</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_get_cookie</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_get_cookie</refname> + <refname>sd_bus_message_get_reply_cookie</refname> + <refpurpose>Returns the transaction cookie of a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_message_get_cookie</function></funcdef> + <paramdef>sd_bus_message *<parameter>message</parameter></paramdef> + <paramdef>uint64_t *<parameter>cookie</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_message_get_reply_cookie</function></funcdef> + <paramdef>sd_bus_message *<parameter>message</parameter></paramdef> + <paramdef>uint64_t *<parameter>cookie</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_message_get_cookie()</function> returns the + transaction cookie of a message. The cookie uniquely identifies a + message within each bus peer, but is not globally unique. It is + assigned when a message is sent.</para> + + <para><function>sd_bus_message_get_reply_cookie()</function> + returns the transaction cookie of the message the specified + message is a response to. When a reply message is generated for a + method call message, its cookie is copied over into this field. + Note that while every message that is transferred is identified by + a cookie, only response messages carry a reply cookie + field.</para> + + <para>Both functions take a message object as first parameter and + a place to store the 64-bit cookie in.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error + code.</para> + + <para>On success, the cookie/reply cookie is returned in the + specified 64-bit unsigned integer variable.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>A specified parameter + is invalid.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>No cookie has been assigned to this message. + This either indicates that the message has not been sent yet + and hence has no cookie assigned, or that the message is not a + method response message and hence carries a reply cookie + field.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_bus_message_get_cookie()</function> and + <function>sd_bus_message_get_reply_cookie()</function> interfaces + are available as a shared library, which can be compiled and + linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_get_monotonic_usec.xml b/src/libsystemd/sd_bus_message_get_monotonic_usec.xml new file mode 100644 index 0000000000..2c0a8a5d54 --- /dev/null +++ b/src/libsystemd/sd_bus_message_get_monotonic_usec.xml @@ -0,0 +1,181 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_get_monotonic_usec"> + + <refentryinfo> + <title>sd_bus_message_get_monotonic_usec</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_get_monotonic_usec</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_get_monotonic_usec</refname> + <refname>sd_bus_message_get_realtime_usec</refname> + <refname>sd_bus_message_get_seqnum</refname> + <refpurpose>Retrieve the sender timestamps and sequence number of a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_message_get_monotonic_usec</function></funcdef> + <paramdef>sd_bus_message *<parameter>message</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_message_get_realtime_usec</function></funcdef> + <paramdef>sd_bus_message *<parameter>message</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_message_get_seqnum</function></funcdef> + <paramdef>sd_bus_message *<parameter>message</parameter></paramdef> + <paramdef>uint64_t *<parameter>seqnum</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_message_get_monotonic_usec()</function> + returns the monotonic timestamp of the time the message was sent. + This value is in microseconds since the + <constant>CLOCK_MONOTONIC</constant> epoch, see + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details.</para> + + <para>Similarly, + <function>sd_bus_message_get_realtime_usec()</function> returns + the realtime (wallclock) timestamp of the time the message was + sent. This value is in microseconds since Jan 1st, 1970, i.e. in + the <constant>CLOCK_REALTIME</constant> clock.</para> + + <para><function>sd_bus_message_get_seqnum()</function> returns the + kernel-assigned sequence number of the message. The kernel assigns + a global, monotonically increasing sequence number to all messages + transmitted on the local system, at the time the message was sent. + This sequence number is useful for determining message send order, + even across different buses of the local system. The sequence + number combined with the boot ID of the system (as returned by + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry>) + is a suitable globally unique identifier for bus messages.</para> + + <para>Note that the sending order and receiving order of messages + might differ, in particular for broadcast messages. This means + that the sequence number and the timestamps of messages a client + reads are not necessarily monotonically increasing.</para> + + <para>These timestamps and the sequence number are attached to + each message by the kernel and cannot be manipulated by the + sender.</para> + + <para>Note that these timestamps are only available on some bus + transports, and only after support for them has been negotiated + with the + <citerefentry><refentrytitle>sd_bus_negotiate_timestamp</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error + code.</para> + + <para>On success, the timestamp or sequence number is returned in + the specified 64-bit unsigned integer variable.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>A specified parameter is + invalid.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>No timestamp or sequence number information is + attached to the passed message. This error is returned if the + underlying transport does not support timestamping or + assigning of sequence numbers, or if this feature has not been + negotiated with + <citerefentry><refentrytitle>sd_bus_negotiate_timestamp</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The + <function>sd_bus_message_get_monotonic_usec()</function>, + <function>sd_bus_message_get_realtime_usec()</function>, and + <function>sd_bus_message_get_seqnum()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_negotiate_timestamp</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_message_read_basic.xml b/src/libsystemd/sd_bus_message_read_basic.xml new file mode 100644 index 0000000000..6a46403159 --- /dev/null +++ b/src/libsystemd/sd_bus_message_read_basic.xml @@ -0,0 +1,113 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 Julian Orth + + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_message_read_basic"> + + <refentryinfo> + <title>sd_bus_message_read_basic</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <firstname>Julian</firstname> + <surname>Orth</surname> + <email>ju.orth@gmail.com</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_message_read_basic</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_message_read_basic</refname> + + <refpurpose>Read a basic type from a message</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_message_read_basic</function></funcdef> + <paramdef>sd_bus_message *<parameter>m</parameter></paramdef> + <paramdef>char <parameter>type</parameter></paramdef> + <paramdef>void *<parameter>p</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <function>sd_bus_message_read_basic()</function> reads a basic type from a + message and advances the read position in the message. The set of basic + types and their ascii codes passed in <parameter>type</parameter> are + described in the <ulink + url="https://dbus.freedesktop.org/doc/dbus-specification.html">D-Bus + Specification</ulink>. + </para> + + <para> + If <parameter>p</parameter> is not NULL, it should contain a pointer to an + appropriate object. For example, if <parameter>type</parameter> is + <constant>'y'</constant>, the object passed in <parameter>p</parameter> + should have type <code>uint8_t *</code>. If <parameter>type</parameter> + is <constant>'s'</constant>, the object passed in <parameter>p</parameter> + should have type <code>const char **</code>. Note that, if the basic type + is a pointer (e.g., <code>const char *</code> in the case of a string), + the pointer is only borrowed and the contents must be copied if they are + to be used after the end of the messages lifetime. Similarly, during the + lifetime of such a pointer, the message must not be modified. + </para> + + <para> + If there is no object of the specified type at the current position in the + message, an error is returned. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para> + On success, <function>sd_bus_message_read_basic()</function> returns 0 or + a positive integer. On failure, it returns a negative errno-style error + code. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_negotiate_fds.xml b/src/libsystemd/sd_bus_negotiate_fds.xml new file mode 100644 index 0000000000..a538b13cf0 --- /dev/null +++ b/src/libsystemd/sd_bus_negotiate_fds.xml @@ -0,0 +1,200 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_negotiate_fds"> + + <refentryinfo> + <title>sd_bus_negotiate_fds</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_negotiate_fds</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_negotiate_fds</refname> + <refname>sd_bus_negotiate_timestamp</refname> + <refname>sd_bus_negotiate_creds</refname> + + <refpurpose>Control feature negotiation on bus connections</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_negotiate_fds</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>int <parameter>b</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_negotiate_timestamp</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>int <parameter>b</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_negotiate_creds</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>int <parameter>b</parameter></paramdef> + <paramdef>uint64_t <parameter>mask</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_negotiate_fds()</function> controls whether + file descriptor passing shall be negotiated for the specified bus + connection. It takes a bus object and a boolean, which, when true, + enables file descriptor passing, and, when false, disables + it. Note that not all transports and servers support file + descriptor passing. In particular, networked transports generally + do not support file descriptor passing. To find out whether file + descriptor passing is available after negotiation, use + <citerefentry><refentrytitle>sd_bus_can_send</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and pass <constant>SD_BUS_TYPE_UNIX_FD</constant>. Note that file + descriptor passing is always enabled for both sending and + receiving or for neither, but never only in one direction. By + default, file descriptor passing is negotiated for all + connections.</para> + + <para>Note that when bus activation is used, it is highly + recommended to set the <option>AcceptFileDescriptors=</option> + setting in the <filename>.busname</filename> unit file to the same + setting as negotiated by the program ultimately activated. By + default, file descriptor passing is enabled for both.</para> + + <para><function>sd_bus_negotiate_timestamps()</function> controls + whether implicit sender timestamps shall be attached automatically + to all incoming messages. Takes a bus object and a boolean, which, + when true, enables timestamping, and, when false, disables it. + Use + <citerefentry><refentrytitle>sd_bus_message_get_monotonic_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_seqnum</refentrytitle><manvolnum>3</manvolnum></citerefentry> + to query the timestamps of incoming messages. If negotiation is + disabled or not supported, these calls will fail with + <constant>-ENODATA</constant>. Note that not all transports + support timestamping of messages. Specifically, timestamping is + only available on the kdbus transport, but not on dbus1. The + timestamping is applied by the kernel and cannot be manipulated by + userspace. By default, message timestamping is not negotiated for + connections.</para> + + <para><function>sd_bus_negotiate_creds()</function> controls + whether and which implicit sender credentials shall be attached + automatically to all incoming messages. Takes a bus object and a + boolean indicating whether to enable or disable the credential + parts encoded in the bit mask value argument. Note that not all + transports support attaching sender credentials to messages, or do + not support all types of sender credential parameters, or might + suppress them under certain circumstances for individual + messages. Specifically, implicit sender credentials on messages + are only fully supported on kdbus transports, and dbus1 only + supports <constant>SD_BUS_CREDS_UNIQUE_NAME</constant>. The sender + credentials are attached by the kernel and cannot be manipulated + by userspace, and are thus suitable for authorization + decisions. By default, only + <constant>SD_BUS_CREDS_WELL_KNOWN_NAMES</constant> and + <constant>SD_BUS_CREDS_UNIQUE_NAME</constant> are enabled. In + fact, these two credential fields are always sent along and cannot + be turned off.</para> + + <para>The <function>sd_bus_negotiate_fds()</function> function may + be called only before the connection has been started with + <citerefentry><refentrytitle>sd_bus_start</refentrytitle><manvolnum>3</manvolnum></citerefentry>. Both + <function>sd_bus_negotiate_timestamp()</function> and + <function>sd_bus_negotiate_creds()</function> may also be called + after a connection has been set up. Note that, when operating on a + connection that is shared between multiple components of the same + program (for example via + <citerefentry><refentrytitle>sd_bus_default</refentrytitle><manvolnum>3</manvolnum></citerefentry>), + it is highly recommended to only enable additional per message + metadata fields, but never disable them again, in order not to + disable functionality needed by other components.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a + positive integer. On failure, they return a negative errno-style + error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EPERM</constant></term> + + <listitem><para>The bus connection has already been started.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_negotiate_fds()</function> and the other + functions described here are available as a shared library, which + can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_start</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_can_send</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_monotonic_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_seqnum</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_message_get_creds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.busname</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_new.xml b/src/libsystemd/sd_bus_new.xml new file mode 100644 index 0000000000..d281b5dd44 --- /dev/null +++ b/src/libsystemd/sd_bus_new.xml @@ -0,0 +1,189 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_new"> + + <refentryinfo> + <title>sd_bus_new</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_new</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_new</refname> + <refname>sd_bus_ref</refname> + <refname>sd_bus_unref</refname> + <refname>sd_bus_unrefp</refname> + + <refpurpose>Create a new bus object and create or destroy references to it</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_new</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_bus *<function>sd_bus_ref</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_bus *<function>sd_bus_unref</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_bus_unrefp</function></funcdef> + <paramdef>sd_bus **<parameter>bus</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_new()</function> creates a new bus + object. This object is reference-counted, and will be destroyed + when all references are gone. Initially, the caller of this + function owns the sole reference and the bus object will not be + connected to any bus. To connect it to a bus, make sure + to set an address with + <citerefentry><refentrytitle>sd_bus_set_address</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or a related call, and then start the connection with + <citerefentry><refentrytitle>sd_bus_start</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>In most cases, it is a better idea to invoke + <citerefentry><refentrytitle>sd_bus_default_user</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_default_system</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or related calls instead of the more low-level + <function>sd_bus_new()</function> and + <function>sd_bus_start()</function>. The higher-level calls not + only allocate a bus object but also start the connection to a + well-known bus in a single function invocation.</para> + + <para><function>sd_bus_ref()</function> increases the reference + counter of <parameter>bus</parameter> by one.</para> + + <para><function>sd_bus_unref()</function> decreases the reference + counter of <parameter>bus</parameter> by one. Once the reference + count has dropped to zero, <parameter>bus</parameter> is destroyed + and cannot be used anymore, so further calls to + <function>sd_bus_ref()</function> or + <function>sd_bus_unref()</function> are illegal.</para> + + <para><function>sd_bus_unrefp()</function> is similar to + <function>sd_bus_unref()</function> but takes a pointer to a + pointer to an <type>sd_bus</type> object. This call is useful in + conjunction with GCC's and LLVM's <ulink + url="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html">Clean-up + Variable Attribute</ulink>. Note that this function is defined as + inline function. Use a declaration like the following, in order to + allocate a bus object that is freed automatically as the code + block is left:</para> + + <programlisting>{ + __attribute__((cleanup(sd_bus_unrefp)) sd_bus *bus = NULL; + int r; + … + r = sd_bus_default(&bus); + if (r < 0) + fprintf(stderr, "Failed to allocate bus: %s\n", strerror(-r)); + … +}</programlisting> + + <para><function>sd_bus_ref()</function>, + <function>sd_bus_unref()</function> and + <function>sd_bus_unrefp()</function> execute no operation if the + passed in bus object is <constant>NULL</constant>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_bus_new()</function> returns 0 or a + positive integer. On failure, it returns a negative errno-style + error code.</para> + + <para><function>sd_bus_ref()</function> always returns the argument. + </para> + + <para><function>sd_bus_unref()</function> always returns + <constant>NULL</constant>.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_new()</function> and other functions + described here are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_default_user</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_default_system</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_open_user</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_open_system</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_path_encode.xml b/src/libsystemd/sd_bus_path_encode.xml new file mode 100644 index 0000000000..3088243e45 --- /dev/null +++ b/src/libsystemd/sd_bus_path_encode.xml @@ -0,0 +1,188 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_path_encode"> + + <refentryinfo> + <title>sd_bus_path_encode</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>A monkey with a typewriter</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_path_encode</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_path_encode</refname> + <refname>sd_bus_path_encode_many</refname> + <refname>sd_bus_path_decode</refname> + <refname>sd_bus_path_decode_many</refname> + + <refpurpose>Convert an external identifier into an object path and back</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_path_encode</function></funcdef> + <paramdef>const char *<parameter>prefix</parameter></paramdef> + <paramdef>const char *<parameter>external_id</parameter></paramdef> + <paramdef>char **<parameter>ret_path</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_path_encode_many</function></funcdef> + <paramdef>char **<parameter>out</parameter></paramdef> + <paramdef>const char *<parameter>path_template</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_path_decode</function></funcdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + <paramdef>const char *<parameter>prefix</parameter></paramdef> + <paramdef>char **<parameter>ret_external_id</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_path_decode_many</function></funcdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + <paramdef>const char *<parameter>path_template</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_path_encode()</function> and + <function>sd_bus_path_decode()</function> convert external + identifier strings into object paths and back. These functions are + useful to map application-specific string identifiers of any kind + into bus object paths in a simple, reversible and safe way.</para> + + <para><function>sd_bus_path_encode()</function> takes a bus path + prefix and an external identifier string as arguments, plus a + place to store the returned bus path string. The bus path prefix + must be a valid bus path, starting with a slash + <literal>/</literal>, and not ending in one. The external + identifier string may be in any format, may be the empty string, + and has no restrictions on the charset — however, it must + always be <constant>NUL</constant>-terminated. The returned string + will be the concatenation of the bus path prefix plus an escaped + version of the external identifier string. This operation may be + reversed with <function>sd_bus_decode()</function>. It is + recommended to only use external identifiers that generally + require little escaping to be turned into valid bus path + identifiers (for example, by sticking to a 7-bit ASCII character + set), in order to ensure the resulting bus path is still short and + easily processed.</para> + + <para><function>sd_bus_path_decode()</function> reverses the + operation of <function>sd_bus_path_encode()</function> and thus + regenerates an external identifier string from a bus path. It + takes a bus path and a prefix string, plus a place to store the + returned external identifier string. If the bus path does not + start with the specified prefix, 0 is returned and the returned + string is set to <constant>NULL</constant>. Otherwise, the + string following the prefix is unescaped and returned in the + external identifier string.</para> + + <para>The escaping used will replace all characters which are + invalid in a bus object path by <literal>_</literal>, followed by a + hexadecimal value. As a special case, the empty string will be + replaced by a lone <literal>_</literal>.</para> + + <para><function>sd_bus_path_encode_many()</function> works like + its counterpart <function>sd_bus_path_encode()</function>, but + takes a path template as argument and encodes multiple labels + according to its embedded directives. For each + <literal>%</literal> character found in the template, the caller + must provide a string via varargs, which will be encoded and + embedded at the position of the <literal>%</literal> character. + Any other character in the template is copied verbatim into the + encoded path.</para> + + <para><function>sd_bus_path_decode_many()</function> does the + reverse of <function>sd_bus_path_encode_many()</function>. It + decodes the passed object path according to the given + path template. For each <literal>%</literal> character in the + template, the caller must provide an output storage + (<literal>char **</literal>) via varargs. The decoded label + will be stored there. Each <literal>%</literal> character will + only match the current label. It will never match across labels. + Furthermore, only a single directive is allowed per label. + If <literal>NULL</literal> is passed as output storage, the + label is verified but not returned to the caller.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_bus_path_encode()</function> + returns positive or 0, and a valid bus path in the return + argument. On success, <function>sd_bus_path_decode()</function> + returns a positive value if the prefixed matched, or 0 if it + did not. If the prefix matched, the external identifier is returned + in the return parameter. If it did not match, NULL is returned in + the return parameter. On failure, a negative errno-style error + number is returned by either function. The returned strings must + be + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry>'d + by the caller.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para><function>sd_bus_path_encode()</function> and + <function>sd_bus_path_decode()</function> are available as a + shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_process.xml b/src/libsystemd/sd_bus_process.xml new file mode 100644 index 0000000000..4b9f52e52f --- /dev/null +++ b/src/libsystemd/sd_bus_process.xml @@ -0,0 +1,111 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 Julian Orth + + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_process"> + + <refentryinfo> + <title>sd_bus_process</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <firstname>Julian</firstname> + <surname>Orth</surname> + <email>ju.orth@gmail.com</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_process</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_process</refname> + + <refpurpose>Drive the connection</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_process</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>sd_bus_message **<parameter>r</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para> + <function>sd_bus_process()</function> drives the connection between the + message bus and the client. That is, it handles connecting, + authentication, and message processing. It should be called in a loop + until no further progress can be made or an error occurs. + </para> + + <para> + Once no further progress can be made, + <citerefentry><refentrytitle>sd_bus_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry> + should be called. Alternatively the user can wait for incoming data on + the file descriptor returned by + <citerefentry><refentrytitle>sd_bus_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + + <para> + <function>sd_bus_process</function> processes at most one incoming + message per call. If the parameter <parameter>r</parameter> is not NULL + and the call processed a message, <code>*r</code> is set to this message. + The caller owns a reference to this message and should call + <citerefentry><refentrytitle>sd_bus_message_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + when the message is no longer needed. If <parameter>r</parameter> is not + NULL, progress was made, but no message was processed, <code>*r</code> is + set to NULL. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para> + If progress was made, a positive integer is returned. If no progress was + made, 0 is returned. If an error occurs, a negative errno-style error code + is returned. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_bus_request_name.xml b/src/libsystemd/sd_bus_request_name.xml new file mode 100644 index 0000000000..f07ae09555 --- /dev/null +++ b/src/libsystemd/sd_bus_request_name.xml @@ -0,0 +1,213 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_bus_request_name"> + + <refentryinfo> + <title>sd_bus_request_name</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_bus_request_name</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_bus_request_name</refname> + <refname>sd_bus_release_name</refname> + <refpurpose>Request or release a well-known service name on a bus</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-bus.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_bus_request_name</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + <paramdef>uint64_t <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_bus_release_name</function></funcdef> + <paramdef>sd_bus *<parameter>bus</parameter></paramdef> + <paramdef>const char *<parameter>name</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_bus_request_name()</function> requests a + well-known service name on a bus. It takes a bus connection, a + valid bus name and a flags parameter. The flags parameter is a + combination of the following flags:</para> + + <variablelist> + <varlistentry> + <term><varname>SD_BUS_NAME_ALLOW_REPLACEMENT</varname></term> + + <listitem><para>After acquiring the name successfully, permit + other peers to take over the name when they try to acquire it + with the <varname>SD_BUS_NAME_REPLACE_EXISTING</varname> flag + set. If <varname>SD_BUS_NAME_ALLOW_REPLACEMENT</varname> is + not set on the original request, such a request by other peers + will be denied.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>SD_BUS_NAME_REPLACE_EXISTING</varname></term> + + <listitem><para>Take over the name if it is already acquired + by another peer, and that other peer has permitted takeover by + setting <varname>SD_BUS_NAME_ALLOW_REPLACEMENT</varname> while + acquiring it.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>SD_BUS_NAME_QUEUE</varname></term> + + <listitem><para>Queue the acquisition of the name when the + name is already taken.</para></listitem> + </varlistentry> + </variablelist> + + <para><function>sd_bus_release_name()</function> releases an + acquired well-known name. It takes a bus connection and a valid + bus name as parameters.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error + code.</para> + + <para>If <varname>SD_BUS_NAME_QUEUE</varname> is specified, + <function>sd_bus_request_name()</function> will return 0 when the + name is already taken by another peer and the client has been + added to the queue for the name. In that case, the caller can + subscribe to <literal>NameOwnerChanged</literal> signals to be + notified when the name is successfully acquired. + <function>sd_bus_request_name()</function> returns > 0 when the + name has immediately been acquired successfully.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EALREADY</constant></term> + + <listitem><para>The caller already is the owner of the + specified name.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EEXIST</constant></term> + + <listitem><para>The name has already been acquired by a + different peer, and SD_BUS_NAME_REPLACE_EXISTING was not + specified or the other peer did not specify + SD_BUS_NAME_ALLOW_REPLACEMENT while acquiring the + name.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESRCH</constant></term> + + <listitem><para>It was attempted to release a name that is + currently not registered on the bus.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EADDRINUSE</constant></term> + + <listitem><para>It was attempted to release a name that is + owned by a different peer on the bus.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>A specified parameter is invalid. This is also + generated when the requested name is a special service name + reserved by the D-Bus specification, or when the operation is + requested on a connection that does not refer to a + bus.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOTCONN</constant></term> + + <listitem><para>The bus connection has been + disconnected.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The bus connection has been created in a + different process than the current one.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_bus_acquire_name()</function> and + <function>sd_bus_release_name()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-bus</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_bus_new</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_add_child.xml b/src/libsystemd/sd_event_add_child.xml new file mode 100644 index 0000000000..bc732db7fa --- /dev/null +++ b/src/libsystemd/sd_event_add_child.xml @@ -0,0 +1,246 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_add_child" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_add_child</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>More text</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_add_child</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_add_child</refname> + <refname>sd_event_source_get_child_pid</refname> + <refname>sd_event_child_handler_t</refname> + + <refpurpose>Add a child process state change event source to an event loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event_source sd_event_source;</funcsynopsisinfo> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_child_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>const siginfo_t *<parameter>si</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_child</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>int <parameter>options</parameter></paramdef> + <paramdef>sd_event_child_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_child_pid</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>pid_t *<parameter>pid</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_add_child()</function> adds a new child + process state change event source to an event loop. The event loop + object is specified in the <parameter>event</parameter> parameter, + the event source object is returned in the + <parameter>source</parameter> parameter. The + <parameter>pid</parameter> parameter specifies the PID of the + process to watch. The <parameter>handler</parameter> must + reference a function to call when the process changes state. The + handler function will be passed the + <parameter>userdata</parameter> pointer, which may be chosen + freely by the caller. The handler also receives a pointer to a + <structname>siginfo_t</structname> structure containing + information about the child process event. The + <parameter>options</parameter> parameter determines which state + changes will be watched for. It must contain an OR-ed mask of + <constant>WEXITED</constant> (watch for the child process + terminating), <constant>WSTOPPED</constant> (watch for the child + process being stopped by a signal), and + <constant>WCONTINUED</constant> (watch for the child process being + resumed by a signal). See <citerefentry + project='man-pages'><refentrytitle>waitid</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for further information.</para> + + <para>Only a single handler may be installed for a specific + child process. The handler is enabled for a single event + (<constant>SD_EVENT_ONESHOT</constant>), but this may be changed + with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If the handler function returns a negative error code, it will be + disabled after the invocation, even if the + <constant>SD_EVENT_ON</constant> mode was requested before. + </para> + + <para>To destroy an event source object use + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but note that the event source is only removed from the event loop + when all references to the event source are dropped. To make sure + an event source does not fire anymore, even when there's still a + reference to it kept, consider setting the event source to + <constant>SD_EVENT_OFF</constant> with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>If the second parameter of + <function>sd_event_add_child()</function> is passed as NULL no + reference to the event source object is returned. In this case the + event source is considered "floating", and will be destroyed + implicitly when the event loop itself is destroyed.</para> + + <para>Note that the <parameter>handler</parameter> function is + invoked at a time where the child process is not reaped yet (and + thus still is exposed as a zombie process by the kernel). However, + the child will be reaped automatically after the function + returns. Child processes for which no child process state change + event sources are installed will not be reaped by the event loop + implementation.</para> + + <para>If both a child process state change event source and a + <constant>SIGCHLD</constant> signal event source is installed in + the same event loop, the configured event source priorities decide + which event source is dispatched first. If the signal handler is + processed first, it should leave the child processes for which + child process state change event sources are installed unreaped.</para> + + <para><function>sd_event_source_get_child_pid()</function> + retrieves the configured PID of a child process state change event + source created previously with + <function>sd_event_add_child()</function>. It takes the event + source object as the <parameter>source</parameter> parameter and a + pointer to a <type>pid_t</type> variable to return the process ID + in. + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a positive + integer. On failure, they return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate an object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid argument has been passed. This includes + specifying an empty mask in <parameter>options</parameter> or a mask + which contains values different than a combination of + <constant>WEXITED</constant>, <constant>WSTOPPED</constant>, and + <constant>WCONTINUED</constant>. + </para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EBUSY</constant></term> + + <listitem><para>A handler is already installed for this + child process.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para>The passed event source is not a child process event source.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>waitid</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_add_defer.xml b/src/libsystemd/sd_event_add_defer.xml new file mode 100644 index 0000000000..d9ebd3b179 --- /dev/null +++ b/src/libsystemd/sd_event_add_defer.xml @@ -0,0 +1,216 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_add_defer" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_add_defer</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>More text</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_add_defer</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_add_defer</refname> + <refname>sd_event_add_post</refname> + <refname>sd_event_add_exit</refname> + <refname>sd_event_handler_t</refname> + + <refpurpose>Add static event sources to an event loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event_source sd_event_source;</funcsynopsisinfo> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_defer</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>sd_event_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_post</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>sd_event_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_exit</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>sd_event_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>These three functions add new static event sources to an + event loop. The event loop object is specified in the + <parameter>event</parameter> parameter, the event source object is + returned in the <parameter>source</parameter> parameter. The event + sources are enabled statically and will "fire" when the event loop + is run and the conditions described below are met. The handler + function will be passed the <parameter>userdata</parameter> + pointer, which may be chosen freely by the caller.</para> + + <para><function>sd_event_add_defer()</function> adds a new event + source that will be dispatched instantly, before the event loop + goes to sleep again and waits for new events. By default, the + handler will be called once + (<constant>SD_EVENT_ONESHOT</constant>). Note that if the event + source is set to <constant>SD_EVENT_ON</constant> the event loop + will never go to sleep again, but continuously call the handler, + possibly interleaved with other event sources.</para> + + <para><function>sd_event_add_post()</function> adds a new event + source that is run before the event loop will sleep and wait + for new events, but only after at least one other non-post event + source was dispatched. By default, the source is enabled + permanently (<constant>SD_EVENT_ON</constant>). Note that this + event source type will still allow the event loop to go to sleep + again, even if set to <constant>SD_EVENT_ON</constant>, as long as + no other event source is ever triggered.</para> + + <para><function>sd_event_add_exit()</function> adds a new event + source that will be dispatched when the event loop is terminated + with <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>The + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + function may be used to enable the event source permanently + (<constant>SD_EVENT_ON</constant>) or to make it fire just once + (<constant>SD_EVENT_ONESHOT</constant>).</para> + + <para>If the handler function returns a negative error code, it + will be disabled after the invocation, even if the + <constant>SD_EVENT_ON</constant> mode was requested before.</para> + + <para>To destroy an event source object use + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but note that the event source is only removed from the event loop + when all references to the event source are dropped. To make sure + an event source does not fire anymore, even when there's still a + reference to it kept, consider setting the event source to + <constant>SD_EVENT_OFF</constant> with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>If the second parameter of these functions is passed as + NULL no reference to the event source object is returned. In this + case the event source is considered "floating", and will be + destroyed implicitly when the event loop itself is + destroyed.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, this functions return 0 or a positive + integer. On failure, they return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate an object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid argument has been passed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_add_io.xml b/src/libsystemd/sd_event_add_io.xml new file mode 100644 index 0000000000..c3749164cd --- /dev/null +++ b/src/libsystemd/sd_event_add_io.xml @@ -0,0 +1,300 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_add_io" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_add_io</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_add_io</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_add_io</refname> + <refname>sd_event_source_get_io_events</refname> + <refname>sd_event_source_set_io_events</refname> + <refname>sd_event_source_get_io_revents</refname> + <refname>sd_event_source_get_io_fd</refname> + <refname>sd_event_source_set_io_fd</refname> + <refname>sd_event_source</refname> + <refname>sd_event_io_handler_t</refname> + + <refpurpose>Add an I/O event source to an event loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event_source sd_event_source;</funcsynopsisinfo> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_io_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>uint32_t <parameter>revents</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_io</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>uint32_t <parameter>events</parameter></paramdef> + <paramdef>sd_event_io_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_io_events</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint32_t *<parameter>events</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_io_events</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint32_t <parameter>events</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_io_revents</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint32_t *<parameter>revents</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_io_fd</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_io_fd</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>int <parameter>fd</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_add_io()</function> adds a new I/O event + source to an event loop. The event loop object is specified in the + <parameter>event</parameter> parameter, the event source object is + returned in the <parameter>source</parameter> parameter. The + <parameter>fd</parameter> parameter takes the UNIX file descriptor + to watch, which may refer to a socket, a FIFO, a message queue, a + serial connection, a character device, or any other file descriptor + compatible with Linux + <citerefentry project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry>. The + <parameter>events</parameter> parameter takes a bit mask of events + to watch for, a combination of the following event flags: + <constant>EPOLLIN</constant>, <constant>EPOLLOUT</constant>, + <constant>EPOLLRDHUP</constant>, <constant>EPOLLPRI</constant>, + and <constant>EPOLLET</constant>, see + <citerefentry project='man-pages'><refentrytitle>epoll_ctl</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details. The <parameter>handler</parameter> shall reference a + function to call when the event source is triggered. The + <parameter>userdata</parameter> pointer will be passed to the + handler function, and may be chosen freely by the caller. The + handler will also be passed the file descriptor the event was seen + on, as well as the actual event flags. It's generally a subset of + the events watched, however may additionally include + <constant>EPOLLERR</constant> and <constant>EPOLLHUP</constant>. + </para> + + <para>By default, an event source will stay enabled + continuously (<constant>SD_EVENT_ON</constant>), but this may be + changed with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If the handler function returns a negative error code, it will be + disabled after the invocation, even if the + <constant>SD_EVENT_ON</constant> mode was requested before. Note + that an event source set to <constant>SD_EVENT_ON</constant> will + fire continuously unless data is read from or written to the file + descriptor to reset the mask of events seen. + </para> + + <para>Setting the I/O event mask to watch for to 0 does not mean + that the event source won't be triggered anymore, as + <constant>EPOLLHUP</constant> and <constant>EPOLLERR</constant> + may be triggered even with a zero event mask. To temporarily + disable an I/O event source use + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with <constant>SD_EVENT_OFF</constant> instead.</para> + + <para>To destroy an event source object use + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but note that the event source is only removed from the event loop + when all references to the event source are dropped. To make sure + an event source does not fire anymore, even if it is still referenced, + disable the event source using + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with <constant>SD_EVENT_OFF</constant>.</para> + + <para>If the second parameter of + <function>sd_event_add_io()</function> is + <constant>NULL</constant> no reference to the event source object + is returned. In this case the event source is considered + "floating", and will be destroyed implicitly when the event loop + itself is destroyed.</para> + + <para>It is recommended to use + <function>sd_event_add_io()</function> only in conjunction with + file descriptors that have <constant>O_NONBLOCK</constant> set, to + ensure that all I/O operations from invoked handlers are properly + asynchronous and non-blocking. Using file descriptors without + <constant>O_NONBLOCK</constant> might result in unexpected + starvation of other event sources. See + <citerefentry project='man-pages'><refentrytitle>fcntl</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details on enabling <constant>O_NONBLOCK</constant> mode.</para> + + <para><function>sd_event_source_get_io_events()</function> retrieves + the configured mask of watched I/O events of an event source created + previously with <function>sd_event_add_io()</function>. It takes + the event source object and a pointer to a variable to store the + mask in.</para> + + <para><function>sd_event_source_set_io_events()</function> + configures the mask of watched I/O events of an event source created + previously with <function>sd_event_add_io()</function>. It takes the + event source object and the new event mask.</para> + + <para><function>sd_event_source_get_io_revents()</function> + retrieves the I/O event mask of currently seen but undispatched + events from an event source created previously with + <function>sd_event_add_io()</function>. It takes the event source + object and a pointer to a variable to store the event mask + in. When called from a handler function on the handler's event + source object this will return the same mask as passed to the + handler's <parameter>revents</parameter> parameter. This call is + primarily useful to check for undispatched events of an event + source from the handler of an unrelated (possibly higher priority) + event source. Note the relation between + <function>sd_event_source_get_pending()</function> and + <function>sd_event_source_get_io_revents()</function>: both + functions will report non-zero results when there's an event + pending for the event source, but the former applies to all event + source types, the latter only to I/O event sources.</para> + + <para><function>sd_event_source_get_io_fd()</function> retrieves + the UNIX file descriptor of an event source created previously + with <function>sd_event_add_io()</function>. It takes the event + source object and returns the non-negative file descriptor + or a negative error number on error (see below).</para> + + <para><function>sd_event_source_set_io_fd()</function> + changes the UNIX file descriptor of an I/O event source created + previously with <function>sd_event_add_io()</function>. It takes + the event source object and the new file descriptor.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a positive + integer. On failure, they return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned values may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate an object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid argument has been passed.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para>The passed event source is not an I/O event source.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_get_pending</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>epoll_ctl</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_add_signal.xml b/src/libsystemd/sd_event_add_signal.xml new file mode 100644 index 0000000000..e98f1d2682 --- /dev/null +++ b/src/libsystemd/sd_event_add_signal.xml @@ -0,0 +1,221 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_add_signal" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_add_signal</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>More text</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_add_signal</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_add_signal</refname> + <refname>sd_event_source_get_signal</refname> + <refname>sd_event_signal_handler_t</refname> + + <refpurpose>Add a UNIX process signal event source to an event + loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event_source sd_event_source;</funcsynopsisinfo> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_signal_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>const struct signalfd_siginfo *<parameter>si</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_signal</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>int <parameter>signal</parameter></paramdef> + <paramdef>sd_event_signal_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_signal</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_add_signal()</function> adds a new UNIX + process signal event source to an event loop. The event loop + object is specified in the <parameter>event</parameter> parameter, + and the event source object is returned in the + <parameter>source</parameter> parameter. The + <parameter>signal</parameter> parameter specifies the numeric + signal to be handled (see <citerefentry + project='man-pages'><refentrytitle>signal</refentrytitle><manvolnum>7</manvolnum></citerefentry>). + The <parameter>handler</parameter> parameter must reference a + function to call when the signal is received or be + <constant>NULL</constant>. The handler function will be passed + the <parameter>userdata</parameter> pointer, which may be chosen + freely by the caller. The handler also receives a pointer to a + <structname>signalfd_siginfo</structname> structure containing + information about the received signal. See <citerefentry + project='man-pages'><refentrytitle>signalfd</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for further information.</para> + + <para>Only a single handler may be installed for a specific + signal. The signal will be unblocked by this call, and must be + blocked before this function is called in all threads (using + <citerefentry + project='man-pages'><refentrytitle>sigprocmask</refentrytitle><manvolnum>2</manvolnum></citerefentry>). If + the handler is not specified (<parameter>handler</parameter> is + <constant>NULL</constant>), a default handler which causes the + program to exit cleanly will be used.</para> + + <para>By default, the event source is enabled permanently + (<constant>SD_EVENT_ON</constant>), but this may be changed with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If the handler function returns a negative error code, it will be + disabled after the invocation, even if the + <constant>SD_EVENT_ON</constant> mode was requested before. + </para> + + <para>To destroy an event source object use + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but note that the event source is only removed from the event loop + when all references to the event source are dropped. To make sure + an event source does not fire anymore, even if it is still referenced, + disable the event source using + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with <constant>SD_EVENT_OFF</constant>.</para> + + <para>If the second parameter of + <function>sd_event_add_signal()</function> is + <constant>NULL</constant> no reference to the event source object + is returned. In this case the event source is considered + "floating", and will be destroyed implicitly when the event loop + itself is destroyed.</para> + + <para><function>sd_event_source_get_signal()</function> returns + the configured signal number of an event source created previously + with <function>sd_event_add_signal()</function>. It takes the + event source object as the <parameter>source</parameter> + parameter.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a positive + integer. On failure, they return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate an object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid argument has been passed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EBUSY</constant></term> + + <listitem><para>A handler is already installed for this + signal or the signal was not blocked previously.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para>The passed event source is not a signal event source.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>signal</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>signalfd</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_add_time.xml b/src/libsystemd/sd_event_add_time.xml new file mode 100644 index 0000000000..5496b71529 --- /dev/null +++ b/src/libsystemd/sd_event_add_time.xml @@ -0,0 +1,313 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_add_time" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_add_time</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_add_time</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_add_time</refname> + <refname>sd_event_source_get_time</refname> + <refname>sd_event_source_set_time</refname> + <refname>sd_event_source_get_time_accuracy</refname> + <refname>sd_event_source_set_time_accuracy</refname> + <refname>sd_event_source_get_time_clock</refname> + <refname>sd_event_time_handler_t</refname> + + <refpurpose>Add a timer event source to an event loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event_source sd_event_source;</funcsynopsisinfo> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_time_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_add_time</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + <paramdef>clockid_t <parameter>clock</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + <paramdef>uint64_t <parameter>accuracy</parameter></paramdef> + <paramdef>sd_event_time_handler_t <parameter>handler</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_time</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_time</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_time_accuracy</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_time_accuracy</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_time_clock</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>clockid_t *<parameter>clock</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_add_time()</function> adds a new timer event source to an event loop. The event loop + object is specified in the <parameter>event</parameter> parameter, the event source object is returned in the + <parameter>source</parameter> parameter. The <parameter>clock</parameter> parameter takes a clock identifier, one + of <constant>CLOCK_REALTIME</constant>, <constant>CLOCK_MONOTONIC</constant>, <constant>CLOCK_BOOTTIME</constant>, + <constant>CLOCK_REALTIME_ALARM</constant>, or <constant>CLOCK_BOOTTIME_ALARM</constant>. See + <citerefentry><refentrytitle>timerfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry> for details + regarding the various types of clocks. The <parameter>usec</parameter> parameter specifies the earliest time, in + microseconds (µs), relative to the clock's epoch, when the timer shall be triggered. If a time already in the past + is specified (including <constant>0</constant>), this timer source "fires" immediately and is ready to be + dispatched. If the parameter is specified as <constant>UINT64_MAX</constant> the timer event will never elapse, + which may be used as an alternative to explicitly disabling a timer event source with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>. The + <parameter>accuracy</parameter> parameter specifies an additional accuracy value in µs specifying how much the + timer event may be delayed. Use <constant>0</constant> to select the default accuracy (250ms). Use 1µs for maximum + accuracy. Consider specifying 60000000µs (1min) or larger for long-running events that may be delayed + substantially. Picking higher accuracy values allows the system to coalesce timer events more aggressively, + improving power efficiency. The <parameter>handler</parameter> parameter shall reference a function to call when + the timer elapses. The handler function will be passed the <parameter>userdata</parameter> pointer, which may be + chosen freely by the caller. The handler is also passed the configured trigger time, even if it is actually called + slightly later, subject to the specified accuracy value, the kernel timer slack (see + <citerefentry><refentrytitle>prctl</refentrytitle><manvolnum>2</manvolnum></citerefentry>), and additional + scheduling latencies. To query the actual time the handler was called use + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>By default, the timer will elapse once + (<constant>SD_EVENT_ONESHOT</constant>), but this may be changed + with + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If the handler function returns a negative error code, it will be + disabled after the invocation, even if the + <constant>SD_EVENT_ON</constant> mode was requested before. Note + that a timer event set to <constant>SD_EVENT_ON</constant> will + fire continuously unless its configured time is updated using + <function>sd_event_source_set_time()</function>. + </para> + + <para>To destroy an event source object use + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + but note that the event source is only removed from the event loop + when all references to the event source are dropped. To make sure + an event source does not fire anymore, even if it is still referenced, + disable the event source using + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with <constant>SD_EVENT_OFF</constant>.</para> + + <para>If the second parameter of + <function>sd_event_add_time()</function> is + <constant>NULL</constant> no reference to the event source object + is returned. In this case the event source is considered + "floating", and will be destroyed implicitly when the event loop + itself is destroyed.</para> + + <para>If the <parameter>handler</parameter> to + <function>sd_event_add_time()</function> is + <constant>NULL</constant>, and the event source fires, this will + be considered a request to exit the event loop. In this case, the + <parameter>userdata</parameter> parameter, cast to an integer, is + used for the exit code passed to + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>Use <constant>CLOCK_BOOTTIME_ALARM</constant> and + <constant>CLOCK_REALTIME_ALARM</constant> to define event sources + that may wake up the system from suspend.</para> + + <para>In order to set up relative timers (that is, relative to the + current time), retrieve the current time via + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + add the desired timespan to it, and use the result as + the <parameter>usec</parameter> parameter to + <function>sd_event_add_time()</function>.</para> + + <para>In order to set up repetitive timers (that is, timers that + are triggered in regular intervals), set up the timer normally, + for the first invocation. Each time the event handler is invoked, + update the timer's trigger time with + <citerefentry><refentrytitle>sd_event_source_set_time</refentrytitle><manvolnum>3</manvolnum></citerefentry> for the next timer + iteration, and reenable the timer using + <function>sd_event_source_set_enabled()</function>. To calculate + the next point in time to pass to + <function>sd_event_source_set_time()</function>, either use as + base the <parameter>usec</parameter> parameter passed to the timer + callback, or the timestamp returned by + <function>sd_event_now()</function>. In the former case timer + events will be regular, while in the latter case the scheduling + latency will keep accumulating on the timer.</para> + + <para><function>sd_event_source_get_time()</function> retrieves + the configured time value of an event source created + previously with <function>sd_event_add_time()</function>. It takes + the event source object and a pointer to a variable to store the + time in, relative to the selected clock's epoch, in µs.</para> + + <para><function>sd_event_source_set_time()</function> changes the + time of an event source created previously with + <function>sd_event_add_time()</function>. It takes the event + source object and a time relative to the selected clock's epoch, + in µs.</para> + + <para><function>sd_event_source_get_time_accuracy()</function> + retrieves the configured accuracy value of an event source + created previously with <function>sd_event_add_time()</function>. It + takes the event source object and a pointer to a variable to store + the accuracy in. The accuracy is specified in µs.</para> + + <para><function>sd_event_source_set_time_accuracy()</function> + changes the configured accuracy of a timer event source created + previously with <function>sd_event_add_time()</function>. It takes + the event source object and accuracy, in µs.</para> + + <para><function>sd_event_source_get_time_clock()</function> + retrieves the configured clock of an event source created + previously with <function>sd_event_add_time()</function>. It takes + the event source object and a pointer to a variable to store the + clock identifier in.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a positive + integer. On failure, they return a negative errno-style error + code. </para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned values may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate an object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid argument has been passed.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EOPNOTSUPP</constant></term> + + <listitem><para>The selected clock is not supported by the event loop implementation.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para>The passed event source is not a timer event source.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_now</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>timerfd_create</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>prctl</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_exit.xml b/src/libsystemd/sd_event_exit.xml new file mode 100644 index 0000000000..9846a3eaf4 --- /dev/null +++ b/src/libsystemd/sd_event_exit.xml @@ -0,0 +1,163 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_exit" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_exit</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_exit</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_exit</refname> + <refname>sd_event_get_exit_code</refname> + + <refpurpose>Ask the event loop to exit</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_exit</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>int <parameter>code</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_get_exit_code</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>int *<parameter>code</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_exit()</function> requests the event loop + specified in the <parameter>event</parameter> event loop object to + exit. The <parameter>code</parameter> parameter may be any integer + value and is returned as-is by + <citerefentry><refentrytitle>sd_event_loop</refentrytitle><manvolnum>3</manvolnum></citerefentry> + after the last event loop iteration. It may also be queried + using <function>sd_event_get_exit_code()</function>, see + below. </para> + + <para>When exiting is requested the event loop will stop listening + for and dispatching regular event sources. Instead it will proceed + with executing only event sources registered with + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry> + in the order defined by their priority. After all exit event + sources have been dispatched the event loop is terminated.</para> + + <para>If <function>sd_event_exit()</function> is invoked a second + time while the event loop is still processing exit event sources, + the exit code stored in the event loop object is updated, but + otherwise no further operation is executed.</para> + + <para><function>sd_event_get_exit_code()</function> may be used to + query the exit code passed into + <function>sd_event_exit()</function> earlier.</para> + + <para>While the full positive and negative integer ranges may be used + for the exit code, care should be taken not pick exit codes that + conflict with regular exit codes returned by + <function>sd_event_loop()</function>, if these exit codes shall be + distinguishable.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_exit()</function> and + <function>sd_event_get_exit_code()</function> return 0 or a positive + integer. On failure, they return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The event loop object or error code pointer are invalid.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop was created in a different process.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop has exited already and all exit handlers are already processed.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The event loop has not been requested to exit yet.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_get_fd-glib-example.c b/src/libsystemd/sd_event_get_fd-glib-example.c new file mode 100644 index 0000000000..8f3168d0ea --- /dev/null +++ b/src/libsystemd/sd_event_get_fd-glib-example.c @@ -0,0 +1,68 @@ +/*** + Copyright 2014 Tom Gundersen + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +***/ + +#include <stdlib.h> + +typedef struct SDEventSource { + GSource source; + GPollFD pollfd; + sd_event *event; +} SDEventSource; + +static gboolean event_prepare(GSource *source, gint *timeout_) { + return sd_event_prepare(((SDEventSource *)source)->event) > 0; +} + +static gboolean event_check(GSource *source) { + return sd_event_wait(((SDEventSource *)source)->event, 0) > 0; +} + +static gboolean event_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) { + return sd_event_dispatch(((SDEventSource *)source)->event) > 0; +} + +static void event_finalize(GSource *source) { + sd_event_unref(((SDEventSource *)source)->event); +} + +static GSourceFuncs event_funcs = { + .prepare = event_prepare, + .check = event_check, + .dispatch = event_dispatch, + .finalize = event_finalize, +}; + +GSource *g_sd_event_create_source(sd_event *event) { + SDEventSource *source; + + source = (SDEventSource *)g_source_new(&event_funcs, sizeof(SDEventSource)); + + source->event = sd_event_ref(event); + source->pollfd.fd = sd_event_get_fd(event); + source->pollfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR; + + g_source_add_poll((GSource *)source, &source->pollfd); + + return (GSource *)source; +} diff --git a/src/libsystemd/sd_event_get_fd.xml b/src/libsystemd/sd_event_get_fd.xml new file mode 100644 index 0000000000..f68752dd0e --- /dev/null +++ b/src/libsystemd/sd_event_get_fd.xml @@ -0,0 +1,140 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_get_fd" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_get_fd</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>More text</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_get_fd</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_get_fd</refname> + + <refpurpose>Obtain a file descriptor to poll for event loop events</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_get_fd</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_get_fd()</function> returns the file + descriptor that an event loop object returned by the + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry> + function uses to wait for events. This file descriptor may itself + be polled for + <constant>POLLIN</constant>/<constant>EPOLLIN</constant> + events. This makes it possible to embed an + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry> + event loop into another, possibly foreign, event loop.</para> + + <para>The returned file descriptor refers to an <citerefentry + project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry> + object. It is recommended not to alter it by invoking + <citerefentry + project='man-pages'><refentrytitle>epoll_ctl</refentrytitle><manvolnum>2</manvolnum></citerefentry> + on it, in order to avoid interference with the event loop's inner + logic and assumptions.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_get_fd()</function> returns a + non-negative file descriptor. On failure, it returns a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>event</parameter> is not a valid + pointer to an <structname>sd_event</structname> structure. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <example> + <title>Integration in the GLib event loop</title> + + <programlisting><xi:include href="glib-event-glue.c" parse="text" /></programlisting> + </example> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>epoll_ctl</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>epoll</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_new.xml b/src/libsystemd/sd_event_new.xml new file mode 100644 index 0000000000..2c23b00a8c --- /dev/null +++ b/src/libsystemd/sd_event_new.xml @@ -0,0 +1,245 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_new" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_new</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_new</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_new</refname> + <refname>sd_event_default</refname> + <refname>sd_event_ref</refname> + <refname>sd_event_unref</refname> + <refname>sd_event_unrefp</refname> + <refname>sd_event_get_tid</refname> + <refname>sd_event</refname> + + <refpurpose>Acquire and release an event loop object</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>typedef</token> struct sd_event sd_event;</funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_new</function></funcdef> + <paramdef>sd_event **<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_default</function></funcdef> + <paramdef>sd_event **<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_event *<function>sd_event_ref</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_event *<function>sd_event_unref</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_event_unrefp</function></funcdef> + <paramdef>sd_event **<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_get_tid</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>pid_t *<parameter>tid</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_new()</function> allocates a new event + loop object. The event loop object is returned in the + <parameter>event</parameter> parameter. After use, drop + the returned reference with + <function>sd_event_unref()</function>. When the last reference is + dropped, the object is freed.</para> + + <para><function>sd_event_default()</function> acquires a reference + to the default event loop object of the calling thread, possibly + allocating a new object if no default event loop object has been + allocated yet for the thread. After use, drop the returned + reference with <function>sd_event_unref()</function>. When the + last reference is dropped, the event loop is freed. If this + function is called while the object returned from a previous call + from the same thread is still referenced, the same object is + returned again, but the reference is increased by one. It is + recommended to use this call instead of + <function>sd_event_new()</function> in order to share event loop + objects between various components that are dispatched in the same + thread. All threads have exactly either zero or one default event loop + objects associated, but never more.</para> + + <para>After allocating an event loop object, add event sources to + it with + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + and then execute the event loop using + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para><function>sd_event_ref()</function> increases the reference + count of the specified event loop object by one.</para> + + <para><function>sd_event_unref()</function> decreases the + reference count of the specified event loop object by one. If + the count hits zero, the object is freed. Note that it + is freed regardless of whether it is the default event loop object for a + thread or not. This means that allocating an event loop with + <function>sd_event_default()</function>, then releasing it, and + then acquiring a new one with + <function>sd_event_default()</function> will result in two + distinct objects. Note that, in order to free an event loop object, + all remaining event sources of the event loop also need to be + freed as each keeps a reference to it.</para> + + <para><function>sd_event_unrefp()</function> is similar to + <function>sd_event_unref()</function> but takes a pointer to a + pointer to an <type>sd_event</type> object. This call is useful in + conjunction with GCC's and LLVM's <ulink + url="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html">Clean-up + Variable Attribute</ulink>. Note that this function is defined as + inline function. Use a declaration like the following, + in order to allocate an event loop object that is freed + automatically as the code block is left:</para> + + <programlisting>{ + __attribute__((cleanup(sd_event_unrefp)) sd_event *event = NULL; + int r; + … + r = sd_event_default(&event); + if (r < 0) + fprintf(stderr, "Failed to allocate event loop: %s\n", strerror(-r)); + … +}</programlisting> + + <para><function>sd_event_ref()</function>, + <function>sd_event_unref()</function> and + <function>sd_event_unrefp()</function> execute no operation if the + passed in event loop object is <constant>NULL</constant>.</para> + + <para><function>sd_event_get_tid()</function> retrieves the thread + identifier ("TID") of the thread the specified event loop object + is associated with. This call is only supported for event loops + allocated with <function>sd_event_default()</function>, and + returns the identifier for the thread the event loop is the + default event loop of. See <citerefentry + project='man-pages'><refentrytitle>gettid</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for more information on thread identifiers.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_new()</function> and + <function>sd_event_default()</function> return 0 or a positive + integer. On failure, they return a negative errno-style error + code. <function>sd_event_ref()</function> always returns a pointer + to the event loop object passed + in. <function>sd_event_unref()</function> always returns + <constant>NULL</constant>.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to allocate the object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EMFILE</constant></term> + + <listitem><para>The maximum number of event loops has been allocated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para><function>sd_event_get_tid()</function> was + invoked on an event loop object that was not allocated with + <function>sd_event_default()</function>.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_post</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>gettid</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_now.xml b/src/libsystemd/sd_event_now.xml new file mode 100644 index 0000000000..2c83b0bcb5 --- /dev/null +++ b/src/libsystemd/sd_event_now.xml @@ -0,0 +1,146 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_now" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_now</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_now</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_now</refname> + + <refpurpose>Retrieve current event loop iteration timestamp</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_now</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>clockid_t <parameter>clock</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_now()</function> returns the time when + the most recent event loop iteration began. A timestamp + is taken right after returning from the event sleep, and before + dispatching any event sources. The <parameter>event</parameter> + parameter specifies the event loop object to retrieve the timestamp + from. The <parameter>clock</parameter> parameter specifies the clock to + retrieve the timestamp for, and is one of + <constant>CLOCK_REALTIME</constant> (or equivalently + <constant>CLOCK_REALTIME_ALARM</constant>), + <constant>CLOCK_MONOTONIC</constant>, or + <constant>CLOCK_BOOTTIME</constant> (or equivalently + <constant>CLOCK_BOOTTIME_ALARM</constant>), see + <citerefentry project='man-pages'><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for more information on the various clocks. The retrieved + timestamp is stored in the <parameter>usec</parameter> parameter, + in µs since the clock's epoch. If this function is invoked before + the first event loop iteration, the current time is returned, as + reported by <function>clock_gettime()</function>. To distinguish + this case from a regular invocation the return value will be + positive, and zero when the returned timestamp refers to an actual + event loop iteration.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>If the first event loop iteration has not run yet + <function>sd_event_now()</function> writes current time to + <parameter>usec</parameter> and returns a positive return value. + Otherwise, it will write the requested timestamp to <parameter>usec</parameter> + and return 0. On failure, the call returns a negative errno-style + error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned values may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An invalid parameter was + passed.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EOPNOTSUPP</constant></term> + + <listitem><para>Unsupported clock type. + </para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop object was created in a + different process.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_run.xml b/src/libsystemd/sd_event_run.xml new file mode 100644 index 0000000000..5b68959165 --- /dev/null +++ b/src/libsystemd/sd_event_run.xml @@ -0,0 +1,190 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_run" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_run</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Tom</firstname> + <surname>Gundersen</surname> + <email>teg@jklm.no</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_run</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_run</refname> + <refname>sd_event_loop</refname> + + <refpurpose>Run an event loop</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_run</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_loop</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_run()</function> may be used to run a single + iteration of the event loop specified in the + <parameter>event</parameter> parameter. The function waits until an event to + process is available, and dispatches the registered handler for + it. The <parameter>usec</parameter> parameter specifies the + maximum time (in microseconds) to wait for an event. Use + <constant>(uint64_t) -1</constant> to specify an infinite + timeout.</para> + + <para><function>sd_event_loop()</function> invokes + <function>sd_event_run()</function> in a loop, thus implementing + the actual event loop. The call returns as soon as exiting was + requested using + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>The event loop object <parameter>event</parameter> is + created with + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + Events sources to wait for and their handlers may be registered + with + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_post</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + + <para>For low-level control of event loop execution, use + <citerefentry><refentrytitle>sd_event_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_event_dispatch</refentrytitle><manvolnum>3</manvolnum></citerefentry> + which are wrapped by <function>sd_event_run()</function>. Along + with + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + these functions allow integration of an + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry> + event loop into foreign event loop implementations.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, these functions return a negative errno-style + error code. <function>sd_event_run()</function> returns a + positive, non-zero integer if an event source was dispatched, and + zero when the specified timeout hit before an event source has + seen any event, and hence no event source was + dispatched. <function>sd_event_loop()</function> returns the exit + code specified when invoking + <function>sd_event_exit()</function>.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The <parameter>event</parameter> parameter is + invalid or <constant>NULL</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EBUSY</constant></term> + + <listitem><para>The event loop object is not in the right + state (see + <citerefentry><refentrytitle>sd_event_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for an explanation of possible states).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + </variablelist> + + <para>Other errors are possible, too.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_post</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_wait</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <ulink url="https://developer.gnome.org/glib/unstable/glib-The-Main-Event-Loop.html">GLib Main Event Loop</ulink>. + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_set_watchdog.xml b/src/libsystemd/sd_event_set_watchdog.xml new file mode 100644 index 0000000000..cbc5bc0836 --- /dev/null +++ b/src/libsystemd/sd_event_set_watchdog.xml @@ -0,0 +1,177 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_set_watchdog" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_set_watchdog</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_set_watchdog</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_set_watchdog</refname> + <refname>sd_event_get_watchdog</refname> + + <refpurpose>Enable event loop watchdog support</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_set_watchdog</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>int b</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_get_watchdog</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_set_watchdog()</function> may be used to + enable or disable automatic watchdog notification support in the + event loop object specified in the <parameter>event</parameter> + parameter. Specifically, depending on the <parameter>b</parameter> + boolean argument this will make sure the event loop wakes up in + regular intervals and sends watchdog notification messages to the + service manager, if this was requested by the service + manager. Watchdog support is determined with + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + and watchdog messages are sent with + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>. See + the <varname>WatchdogSec=</varname> setting in + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details on how to enable watchdog support for a service and + the protocol used. The wake-up interval is chosen as half the + watchdog timeout declared by the service manager via the + <varname>$WATCHDOG_USEC</varname> environment variable. If the + service manager did not request watchdog notifications, or if the + process was not invoked by the service manager this call with a + true <parameter>b</parameter> parameter executes no + operation. Passing a false <parameter>b</parameter> parameter will + disable the automatic sending of watchdog notification messages if + it was enabled before. Newly allocated event loop objects have + this feature disabled.</para> + + <para>The first watchdog notification message is sent immediately + when <function>set_event_set_watchdog()</function> is invoked with + a true <parameter>b</parameter> parameter.</para> + + <para>The watchdog logic is designed to allow the service manager + to automatically detect services that ceased processing of + incoming events, and thus appear "hung". Watchdog notifications + are sent out only at the beginning of each event loop + iteration. If an event source dispatch function blocks for an + excessively long time and does not return execution to the event + loop quickly, this might hence cause the notification message to + be delayed, and possibly result in abnormal program termination, + as configured in the service unit file.</para> + + <para><function>sd_event_get_watchdog()</function> may be used to + determine whether watchdog support was previously requested by a + call to <function>sd_event_set_watchdog()</function> with a true + <parameter>b</parameter> parameter and successfully + enabled.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_set_watchdog()</function> and + <function>sd_event_get_watchdog()</function> return a non-zero + positive integer if the service manager requested watchdog support + and watchdog support was successfully enabled. They return zero if + the service manager did not request watchdog support, or if + watchdog support was explicitly disabled with a false + <parameter>b</parameter> parameter. On failure, they return a + negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The passed event loop object was invalid.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_post</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_get_event.xml b/src/libsystemd/sd_event_source_get_event.xml new file mode 100644 index 0000000000..2fdbd411bd --- /dev/null +++ b/src/libsystemd/sd_event_source_get_event.xml @@ -0,0 +1,100 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_get_event" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_get_event</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_get_event</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_get_event</refname> + + <refpurpose>Retrieve the event loop of an event source</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>sd_event* <function>sd_event_source_get_event</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_get_event()</function> may be used + to retrieve the event loop object the event source object specified + as <parameter>source</parameter> is associated with. The event + loop object is specified when creating an event source object with + calls such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_source_get_event()</function> + returns the associated event loop object. On failure, it returns + NULL.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_get_pending.xml b/src/libsystemd/sd_event_source_get_pending.xml new file mode 100644 index 0000000000..7f88bd1b87 --- /dev/null +++ b/src/libsystemd/sd_event_source_get_pending.xml @@ -0,0 +1,167 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_get_pending" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_get_pending</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_get_pending</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_get_pending</refname> + + <refpurpose>Determine pending state of event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_pending</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_get_pending()</function> may be + used to determine whether the event source object specified as + <parameter>source</parameter> has seen events but has not been + dispatched yet (and thus is marked "pending").</para> + + <para>Event source objects initially are not marked pending, when + they are created with calls such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + with the exception of those created with + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry> + which are immediately marked pending, and + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for which the "pending" concept is not defined. For details see + the respective manual pages.</para> + + <para>In each event loop iteration one event source of those + marked pending is dispatched, in the order defined by the event + source priority, as set with + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>For I/O event sources, as created with + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + the call + <citerefentry><refentrytitle>sd_event_source_get_io_revents</refentrytitle><manvolnum>3</manvolnum></citerefentry> + may be used to query the type of event pending in more + detail.</para> + + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, + <function>sd_event_source_get_pending()</function> returns an + integer greater than zero when the event source is marked pending, + and zero when the event source is not marked pending. On failure, + it returns a negative errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>source</parameter> is not a valid + pointer to an <structname>sd_event_source</structname> + object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para><parameter>source</parameter> refers to an + event source object created with + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_set_description.xml b/src/libsystemd/sd_event_source_set_description.xml new file mode 100644 index 0000000000..b9488a622f --- /dev/null +++ b/src/libsystemd/sd_event_source_set_description.xml @@ -0,0 +1,170 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_set_description" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_set_description</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>More text</contrib> + <firstname>Zbigniew</firstname> + <surname>Jędrzejewski-Szmek</surname> + <email>zbyszek@in.waw.pl</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_set_description</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_set_description</refname> + <refname>sd_event_source_get_description</refname> + + <refpurpose>Set or retrieve descriptive names of event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_description</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>const char *<parameter>description</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_description</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>const char **<parameter>description</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_set_description()</function> may + be used to set an arbitrary descriptive name for the event source + object specified as <parameter>source</parameter>. This name will + be used in debugging messages generated by + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for this event source, and may be queried using + <function>sd_event_source_get_description()</function> for + debugging purposes. The <parameter>description</parameter> parameter shall + point to a <constant>NUL</constant>-terminated string or be + <constant>NULL</constant>. In the latter case, the descriptive + name will be unset. The string is copied internally, hence the + <parameter>description</parameter> argument is not referenced + after the function returns.</para> + + <para><function>sd_event_source_get_description()</function> may + be used to query the current descriptive name assigned to the + event source object <parameter>source</parameter>. It returns a + pointer to the current name in <parameter>description</parameter>, + stored in memory internal to the event source. The memory is + invalidated when the event source is destroyed or the descriptive + name is changed.</para> + + <para>Event source objects generally have no description set when + they are created, except for UNIX signal event sources created + with + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + whose descriptive name is initialized to the signal's C constant + name (e.g. <literal>SIGINT</literal> or + <literal>SIGTERM</literal>).</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_source_set_description()</function> and + <function>sd_event_source_get_description()</function> return a + non-negative integer. On failure, they return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>source</parameter> is not a valid + pointer to an <structname>sd_event_source</structname> + object or the <parameter>description</parameter> argument for + <function>sd_event_source_get_description()</function> is + <constant>NULL</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory to copy the + name.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>No name was set for the event + source.</para></listitem> + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_set_enabled.xml b/src/libsystemd/sd_event_source_set_enabled.xml new file mode 100644 index 0000000000..6844f29a49 --- /dev/null +++ b/src/libsystemd/sd_event_source_set_enabled.xml @@ -0,0 +1,179 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_set_enabled" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_set_enabled</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_set_enabled</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_set_enabled</refname> + <refname>sd_event_source_get_enabled</refname> + <refname>SD_EVENT_ON</refname> + <refname>SD_EVENT_OFF</refname> + <refname>SD_EVENT_ONESHOT</refname> + + <refpurpose>Enable or disable event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>enum</token> { + <constant>SD_EVENT_OFF</constant> = 0, + <constant>SD_EVENT_ON</constant> = 1, + <constant>SD_EVENT_ONESHOT</constant> = -1, +};</funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_enabled</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>int <parameter>enabled</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_enabled</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>int *<parameter>enabled</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_set_enabled()</function> may be + used to enable or disable the event source object specified as + <parameter>source</parameter>. The <parameter>enabled</parameter> + parameter takes one of <constant>SD_EVENT_ON</constant> (to + enable), <constant>SD_EVENT_OFF</constant> (to disable) or + <constant>SD_EVENT_ONESHOT</constant>. If invoked with + <constant>SD_EVENT_ONESHOT</constant> the event source will be + enabled but automatically reset to + <constant>SD_EVENT_OFF</constant> after the event source was + dispatched once.</para> + + <para>Event sources that are disabled will not result in event + loop wakeups and will not be dispatched, until they are enabled + again.</para> + + <para><function>sd_event_source_get_enabled()</function> may be + used to query whether the event source object + <parameter>source</parameter> is currently enabled or not. It + returns the enablement state in + <parameter>enabled</parameter>.</para> + + <para>Event source objects are enabled when they are first created + with calls such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>. However, + depending on the event source type they are enabled continuously + (<constant>SD_EVENT_ON</constant>) or only for a single invocation + of the event source handler + (<constant>SD_EVENT_ONESHOT</constant>). For details see the + respective manual pages.</para> + + <para>As event source objects stay active and may be dispatched as + long as there is at least one reference to them, in many cases it + is a good idea to combine a call to + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with a prior call to + <function>sd_event_source_set_enabled()</function> with + <constant>SD_EVENT_OFF</constant>, to ensure the event source is + not dispatched again until all other remaining references are dropped.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_event_source_set_enabled()</function> and + <function>sd_event_source_get_enabled()</function> return a + non-negative integer. On failure, they return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>source</parameter> is not a valid + pointer to an <structname>sd_event_source</structname> + object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_unref</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_set_prepare.xml b/src/libsystemd/sd_event_source_set_prepare.xml new file mode 100644 index 0000000000..24861d01d9 --- /dev/null +++ b/src/libsystemd/sd_event_source_set_prepare.xml @@ -0,0 +1,171 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_set_prepare" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_set_prepare</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_set_prepare</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_set_prepare</refname> + + <refpurpose>Set a preparation callback for event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_prepare</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>sd_event_handler_t <parameter>callback</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>typedef int (*<function>sd_event_handler_t</function>)</funcdef> + <paramdef>sd_event_source *<parameter>s</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_set_prepare()</function> may be + used to set a preparation callback for the event source object + specified as <parameter>source</parameter>. The callback function + specified as <parameter>callback</parameter> will be invoked + immediately before the event loop goes to sleep to wait for + incoming events. It is invoked with the user data pointer passed + when the event source was created. The callback function may be + used to reconfigure the precise events to wait for. If the + <parameter>callback</parameter> parameter is passed as NULL the + callback function is reset. </para> + + <para>Event source objects have no preparation callback associated + when they are first created with calls such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>. Preparation + callback functions are supported for all event source types with + the exception of those created with + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>. Preparation + callback functions are dispatched in the order indicated by the + event source's priority field, as set with + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>. Preparation + callbacks of disabled event sources (see + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>) + are not invoked.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, + <function>sd_event_source_set_prepare()</function> returns a + non-negative integer. On failure, it returns a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>source</parameter> is not a valid + pointer to an <structname>sd_event_source</structname> + object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-EDOM</constant></term> + + <listitem><para>The specified event source has been created + with + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para></listitem> + + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_priority</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_userdata</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_set_priority.xml b/src/libsystemd/sd_event_source_set_priority.xml new file mode 100644 index 0000000000..8c9b39fe5e --- /dev/null +++ b/src/libsystemd/sd_event_source_set_priority.xml @@ -0,0 +1,189 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_set_priority" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_set_priority</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_set_priority</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_set_priority</refname> + <refname>sd_event_source_get_priority</refname> + <refname>SD_EVENT_PRIORITY_IMPORTANT</refname> + <refname>SD_EVENT_PRIORITY_NORMAL</refname> + <refname>SD_EVENT_PRIORITY_IDLE</refname> + + <refpurpose>Set or retrieve the priority of event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>enum</token> { + <constant>SD_EVENT_SOURCE_IMPORTANT</constant> = -100, + <constant>SD_EVENT_SOURCE_NORMAL</constant> = 0, + <constant>SD_EVENT_SOURCE_IDLE</constant> = 100, +};</funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_source_set_priority</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>int64_t <parameter>priority</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_source_get_priority</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>int64_t *<parameter>priority</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_set_priority()</function> may be + used to set the priority for the event source object specified as + <parameter>source</parameter>. The priority is specified as an + arbitrary signed 64bit integer. The priority is initialized to + <constant>SD_EVENT_PRIORITY_NORMAL</constant> (0) when the event + source is allocated with a call such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + and may be changed with this call. If multiple event sources have seen events at the same time, they are dispatched in the order indicated by the + event sources' priorities. Event sources with smaller priority + values are dispatched first. As well-known points of reference, + the constants <constant>SD_EVENT_PRIORITY_IMPORTANT</constant> + (-100), <constant>SD_EVENT_PRIORITY_NORMAL</constant> (0) and + <constant>SD_EVENT_PRIORITY_IDLE</constant> (100) may be used to + indicate event sources that shall be dispatched early, normally or + late. It is recommended to specify priorities based on these + definitions, and relative to them — however, the full 64bit + signed integer range is available for ordering event + sources.</para> + + <para>Priorities define the order in which event sources that have + seen events are dispatched. Care should be taken to ensure that + high-priority event sources (those with negative priority values + assigned) do not cause starvation of low-priority event sources + (those with positive priority values assigned).</para> + + <para>The order in which event sources with the same priority are + dispatched is undefined, but the event loop generally tries to + dispatch them in the order it learnt about events on them. As the + backing kernel primitives do not provide accurate information + about the order in which events occurred this is not necessarily + reliable. However, it is guaranteed that if events are seen on + multiple same-priority event sources at the same time, each one is + not dispatched again until all others have been dispatched + once. This behaviour guarantees that within each priority + particular event sources do not starve or dominate the event + loop.</para> + + <para><function>sd_event_source_get_priority()</function> may be + used to query the current priority assigned to the event source + object <parameter>source</parameter>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, + <function>sd_event_source_set_priority()</function> and + <function>sd_event_source_get_priority()</function> return a + non-negative integer. On failure, they return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para><parameter>source</parameter> is not a valid + pointer to an <structname>sd_event_source</structname> + object.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Not enough memory.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + </variablelist> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_set_userdata.xml b/src/libsystemd/sd_event_source_set_userdata.xml new file mode 100644 index 0000000000..533d491b13 --- /dev/null +++ b/src/libsystemd/sd_event_source_set_userdata.xml @@ -0,0 +1,119 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_set_userdata" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_set_userdata</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_set_userdata</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_set_userdata</refname> + <refname>sd_event_source_get_userdata</refname> + + <refpurpose>Set or retrieve user data pointer of event sources</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>void* <function>sd_event_source_set_userdata</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + <paramdef>void *<parameter>userdata</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void* <function>sd_event_source_get_userdata</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_set_userdata()</function> may be + used to set an arbitrary user data pointer for the event source + object specified as <parameter>source</parameter>. The user data + pointer is usually specified when creating an event source object + with calls such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + and may be updated with this call. The user data pointer is also + passed to all handler callback functions associated with the event + source. The <parameter>userdata</parameter> parameter specifies + the new user data pointer to set, the function returns the + previous user data pointer. Note that <constant>NULL</constant> is + a valid user data pointer.</para> + + <para><function>sd_event_source_get_userdata()</function> may be + used to query the current user data pointer assigned to the event + source object <parameter>source</parameter>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, + <function>sd_event_source_set_userdata()</function> and + <function>sd_event_source_get_userdata()</function> return the + previously set user data pointer. On failure, they return + NULL.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_description</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_source_unref.xml b/src/libsystemd/sd_event_source_unref.xml new file mode 100644 index 0000000000..2c4d450763 --- /dev/null +++ b/src/libsystemd/sd_event_source_unref.xml @@ -0,0 +1,142 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_source_unref" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_source_unref</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_source_unref</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_source_unref</refname> + <refname>sd_event_source_unrefp</refname> + <refname>sd_event_source_ref</refname> + + <refpurpose>Increase or decrease event source reference counters</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>sd_event_source* <function>sd_event_source_unref</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_event_source_unrefp</function></funcdef> + <paramdef>sd_event_source **<parameter>source</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_event_source* <function>sd_event_source_ref</function></funcdef> + <paramdef>sd_event_source *<parameter>source</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_event_source_unref()</function> may be used to + decrement by one the reference counter of the event source object + specified as <parameter>source</parameter>. The reference counter + is initially set to one, when the event source is created with calls + such as + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>. When + the reference counter reaches zero it is removed from its event loop + object and destroyed.</para> + + <para><function>sd_event_source_unrefp()</function> is similar to + <function>sd_event_source_unref()</function> but takes a pointer to a + pointer to an <type>sd_event_source</type> object. This call is useful in + conjunction with GCC's and LLVM's <ulink + url="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html">Clean-up + Variable Attribute</ulink>. Note that this function is defined as + inline function.</para> + + <para><function>sd_event_source_ref()</function> may be used + to increase by one the reference counter of the event source object + specified as <parameter>source</parameter>.</para> + + <para><function>sd_event_source_unref()</function>, + <function>sd_bus_creds_unrefp()</function> and + <function>sd_bus_creds_ref()</function> execute no operation if + the passed event source object is + <constant>NULL</constant>.</para> + + <para>Note that event source objects stay alive and may be + dispatched as long as they have a reference counter greater than + zero. In order to drop a reference of an event source and make + sure the associated event source handler function is not called + anymore it is recommended to combine a call of + <function>sd_event_source_unref()</function> with a prior call to + <function>sd_event_source_set_enabled()</function> with + <constant>SD_EVENT_OFF</constant>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_event_source_unref()</function> always returns + <constant>NULL</constant>. + <function>sd_event_source_ref()</function> always returns the + event source object passed in.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_child</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_event_wait.xml b/src/libsystemd/sd_event_wait.xml new file mode 100644 index 0000000000..26327dc688 --- /dev/null +++ b/src/libsystemd/sd_event_wait.xml @@ -0,0 +1,356 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" +"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_event_wait" xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_event_wait</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Tom</firstname> + <surname>Gundersen</surname> + <email>teg@jklm.no</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_event_wait</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_event_wait</refname> + <refname>sd_event_prepare</refname> + <refname>sd_event_dispatch</refname> + <refname>sd_event_get_state</refname> + <refname>sd_event_get_iteration</refname> + <refname>SD_EVENT_INITIAL</refname> + <refname>SD_EVENT_PREPARING</refname> + <refname>SD_EVENT_ARMED</refname> + <refname>SD_EVENT_PENDING</refname> + <refname>SD_EVENT_RUNNING</refname> + <refname>SD_EVENT_EXITING</refname> + <refname>SD_EVENT_FINISHED</refname> + + <refpurpose>Low-level event loop operations</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-event.h></funcsynopsisinfo> + + <funcsynopsisinfo><token>enum</token> { + <constant>SD_EVENT_INITIAL</constant>, + <constant>SD_EVENT_PREPARING</constant>, + <constant>SD_EVENT_ARMED</constant>, + <constant>SD_EVENT_PENDING</constant>, + <constant>SD_EVENT_RUNNING</constant>, + <constant>SD_EVENT_EXITING</constant>, + <constant>SD_EVENT_FINISHED</constant>, +};</funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_event_prepare</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_wait</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_dispatch</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_get_state</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_event_get_iteration</function></funcdef> + <paramdef>sd_event *<parameter>event</parameter></paramdef> + <paramdef>uint64_t *<parameter>ret</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para>The low-level <function>sd_event_prepare()</function>, + <function>sd_event_wait()</function> and + <function>sd_event_dispatch()</function> functions may be used to + execute specific phases of an event loop. See + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_event_loop</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for higher-level functions that execute individual but complete + iterations of an event loop or run it continuously.</para> + + <para><function>sd_event_prepare()</function> checks for pending + events and arms necessary timers. If any events are ready to be + processed ("pending"), it returns a positive, non-zero value, and the caller + should process these events with + <function>sd_event_dispatch()</function>.</para> + + <para><function>sd_event_dispatch()</function> dispatches the + highest priority event source that has a pending event. On + success, <function>sd_event_dispatch()</function> returns either + zero, which indicates that no further event sources may be + dispatched and exiting of the event loop was requested via + <citerefentry><refentrytitle>sd_event_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>; + or a positive non-zero value, which means that an event source was + dispatched and the loop returned to its initial state, and the + caller should initiate the next event loop iteration by invoking + <function>sd_event_prepare()</function> again.</para> + + <para>In case <function>sd_event_prepare()</function> returned + zero, <function>sd_event_wait()</function> should be called to + wait for further events or a timeout. If any events are ready to + be processed, it returns a positive, non-zero value, and the + events should be dispatched with + <function>sd_event_dispatch()</function>. Otherwise, the event + loop returned to its initial state and the next event loop + iteration should be initiated by invoking + <function>sd_event_prepare()</function> again.</para> + + <para><function>sd_event_get_state()</function> may be used to + determine the state the event loop is currently in. It returns one + of the states described below.</para> + + <para><function>sd_event_get_iteration()</function> may be used to determine the current iteration of the event + loop. It returns an unsigned 64bit integer containing a counter that increases monotonically with each iteration of + the event loop, starting with 0. The counter is increased at the time of the + <function>sd_event_prepare()</function> invocation.</para> + + <para>All five functions take, as the first argument, the event loop object <parameter>event</parameter> that has + been created with <function>sd_event_new()</function>. The timeout for <function>sd_event_wait()</function> is + specified in <parameter>usec</parameter> in microseconds. <constant>(uint64_t) -1</constant> may be used to + specify an infinite timeout.</para> +</refsect1> + + <refsect1> + <title>State Machine</title> + + <para>The event loop knows the following states, that may be + queried with <function>sd_event_get_state()</function>.</para> + + <variablelist> + <varlistentry> + <term><constant>SD_EVENT_INITIAL</constant></term> + + <listitem><para>The initial state the event loop is in, + before each event loop iteration. Use + <function>sd_event_prepare()</function> to transition the + event loop into the <constant>SD_EVENT_ARMED</constant> or + <constant>SD_EVENT_PENDING</constant> states.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_PREPARING</constant></term> + + <listitem><para>An event source is currently being prepared, + i.e. the preparation handler is currently being executed, as + set with + <citerefentry><refentrytitle>sd_event_set_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry>. This + state is only seen in the event source preparation handler + that is invoked from the + <function>sd_event_prepare()</function> call and is + immediately followed by <constant>SD_EVENT_ARMED</constant> or + <constant>SD_EVENT_PENDING</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_ARMED</constant></term> + + <listitem><para><function>sd_event_prepare()</function> has + been called and no event sources were ready to be + dispatched. Use <function>sd_event_wait()</function> to wait + for new events, and transition into + <constant>SD_EVENT_PENDING</constant> or back into + <constant>SD_EVENT_INITIAL</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_PENDING</constant></term> + + <listitem><para><function>sd_event_prepare()</function> or + <function>sd_event_wait()</function> have been called and + there were event sources with events pending. Use + <function>sd_event_dispatch()</function> to dispatch the + highest priority event source and transition back to + <constant>SD_EVENT_INITIAL</constant>, or + <constant>SD_EVENT_FINISHED</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_RUNNING</constant></term> + + <listitem><para>A regular event source is currently being + dispatched. This state is only seen in the event source + handler that is invoked from the + <function>sd_event_dispatch()</function> call, and is + immediately followed by <constant>SD_EVENT_INITIAL</constant> + or <constant>SD_EVENT_FINISHED</constant> as soon the event + source handler returns. Note that during dispatching of exit + event sources the <constant>SD_EVENT_EXITING</constant> state + is seen instead.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_EXITING</constant></term> + + <listitem><para>Similar to + <constant>SD_EVENT_RUNNING</constant> but is the state in + effect while dispatching exit event sources. It is followed by + <constant>SD_EVENT_INITIAL</constant> or + <constant>SD_EVENT_FINISHED</constant> as soon as the event + handler returns.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>SD_EVENT_FINISHED</constant></term> + + <listitem><para>The event loop has exited. All exit event + sources have run. If the event loop is in this state it serves + no purpose anymore, and should be freed.</para></listitem> + </varlistentry> + + </variablelist> + + <para>A simplified flow chart of the states and the calls to + transition between them is shown below. Note that + <constant>SD_EVENT_PREPARING</constant>, + <constant>SD_EVENT_RUNNING</constant> and + <constant>SD_EVENT_EXITING</constant> are not shown here.</para> + + <programlisting> + INITIAL -<---<---<---<---<---<---<---<---<---<---<---<---\ + | | + | ^ + | | + v ret == 0 | + sd_event_prepare() >--->--->--->--->- ARMED | + | | ^ + | ret > 0 | | + | | | + v v ret == 0 | + PENDING <---<---<---<---<---< sd_event_wait() >--->--->--+ + | ret > 0 ^ + | | + | | + v | + sd_event_dispatch() >--->--->--->--->--->--->--->--->--->--->/ + | ret > 0 + | ret == 0 + | + v + FINISHED + </programlisting> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these functions return 0 or a positive integer. + On failure, they return a negative errno-style error code. In case + of <function>sd_event_prepare()</function> and + <function>sd_event_wait()</function>, a positive, non-zero return + code indicates that events are ready to be processed and zero + indicates that no events are ready. In case of + <function>sd_event_dispatch()</function>, a positive, non-zero + return code indicates that the event loop returned to its initial + state and zero indicates the event loop has + exited. <function>sd_event_get_state()</function> returns a + positive or zero state on success.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>The <parameter>event</parameter> parameter is + invalid or <constant>NULL</constant>.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EBUSY</constant></term> + + <listitem><para>The event loop object is not in the right + state.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ESTALE</constant></term> + + <listitem><para>The event loop is already terminated.</para></listitem> + + </varlistentry> + + <varlistentry> + <term><constant>-ECHILD</constant></term> + + <listitem><para>The event loop has been created in a different process.</para></listitem> + + </varlistentry> + + </variablelist> + + <para>Other errors are possible, too.</para> + </refsect1> + + <xi:include href="libsystemd-pkgconfig.xml" /> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_new</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_io</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_time</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_signal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_defer</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_exit</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_add_post</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_run</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_get_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_source_set_prepare</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_get_seats.xml b/src/libsystemd/sd_get_seats.xml new file mode 100644 index 0000000000..37eb3fc894 --- /dev/null +++ b/src/libsystemd/sd_get_seats.xml @@ -0,0 +1,164 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_get_seats" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_get_seats</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_get_seats</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_get_seats</refname> + <refname>sd_get_sessions</refname> + <refname>sd_get_uids</refname> + <refname>sd_get_machine_names</refname> + <refpurpose>Determine available seats, sessions, logged in users and virtual machines/containers</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_get_seats</function></funcdef> + <paramdef>char ***<parameter>seats</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_get_sessions</function></funcdef> + <paramdef>char ***<parameter>sessions</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_get_uids</function></funcdef> + <paramdef>uid_t **<parameter>users</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_get_machine_names</function></funcdef> + <paramdef>char ***<parameter>machines</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_get_seats()</function> may be used to determine + all currently available local seats. Returns a + <constant>NULL</constant> terminated array of seat identifiers. + The returned array and all strings it references need to be freed + with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use. Note that instead of an empty array + <constant>NULL</constant> may be returned and should be considered + equivalent to an empty array.</para> + + <para>Similarly, <function>sd_get_sessions()</function> may be + used to determine all current login sessions.</para> + + <para>Similarly, <function>sd_get_uids()</function> may be used to + determine all Unix users who currently have login sessions.</para> + + <para>Similarly, <function>sd_get_machine_names()</function> may + be used to determine all current virtual machines and containers + on the system.</para> + + <para>Note that the returned lists are not sorted and in an + undefined order.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_get_seats()</function>, + <function>sd_get_sessions()</function>, + <function>sd_get_uids()</function> and + <function>sd_get_machine_names()</function> return the number of + entries in the arrays. On failure, these calls return a negative + errno-style error code.</para> + </refsect1> + + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_get_seats()</function>, + <function>sd_get_sessions()</function>, + <function>sd_get_uids()</function> and + <function>sd_get_machine_names()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_session_get_seat</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_id128_get_machine.xml b/src/libsystemd/sd_id128_get_machine.xml new file mode 100644 index 0000000000..2ad1f8f728 --- /dev/null +++ b/src/libsystemd/sd_id128_get_machine.xml @@ -0,0 +1,129 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_id128_get_machine"> + + <refentryinfo> + <title>sd_id128_get_machine</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_id128_get_machine</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_id128_get_machine</refname> + <refname>sd_id128_get_boot</refname> + <refpurpose>Retrieve 128-bit IDs</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-id128.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_id128_get_machine</function></funcdef> + <paramdef>sd_id128_t *<parameter>ret</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_id128_get_boot</function></funcdef> + <paramdef>sd_id128_t *<parameter>ret</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_id128_get_machine()</function> returns the + machine ID of the executing host. This reads and parses the + <citerefentry><refentrytitle>machine-id</refentrytitle><manvolnum>5</manvolnum></citerefentry> + file. This function caches the machine ID internally to make + retrieving the machine ID a cheap operation.</para> + + <para><function>sd_id128_get_boot()</function> returns the boot ID + of the executing kernel. This reads and parses the + <filename>/proc/sys/kernel/random/boot_id</filename> file exposed + by the kernel. It is randomly generated early at boot and is + unique for every running kernel instance. See + <citerefentry project='man-pages'><refentrytitle>random</refentrytitle><manvolnum>4</manvolnum></citerefentry> + for more information. This function also internally caches the + returned ID to make this call a cheap operation.</para> + + <para>Note that <function>sd_id128_get_boot()</function> always + returns a UUID v4 compatible ID. + <function>sd_id128_get_machine()</function> will also return a + UUID v4-compatible ID on new installations but might not on older. + It is possible to convert the machine ID into a UUID v4-compatible + one. For more information, see + <citerefentry><refentrytitle>machine-id</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para> + + <para>For more information about the <literal>sd_id128_t</literal> + type see + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The two calls return 0 on success (in which case + <parameter>ret</parameter> is filled in), or a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_id128_get_machine()</function> and + <function>sd_id128_get_boot()</function> interfaces are available + as a shared library, which can be compiled and linked to with the + <literal>libsystemd</literal> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>machine-id</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>random</refentrytitle><manvolnum>4</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_randomize</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_id128_randomize.xml b/src/libsystemd/sd_id128_randomize.xml new file mode 100644 index 0000000000..ab449d2937 --- /dev/null +++ b/src/libsystemd/sd_id128_randomize.xml @@ -0,0 +1,114 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_id128_randomize"> + + <refentryinfo> + <title>sd_id128_randomize</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_id128_randomize</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_id128_randomize</refname> + <refpurpose>Generate 128-bit IDs</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-id128.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_id128_randomize</function></funcdef> + <paramdef>sd_id128_t *<parameter>ret</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_id128_randomize()</function> generates a new + randomized 128-bit ID and returns it in + <parameter>ret</parameter>. Every invocation returns a new + randomly generated ID. This uses the + <filename>/dev/urandom</filename> kernel random number + generator.</para> + + <para>Note that <function>sd_id128_randomize()</function> always + returns a UUID v4-compatible ID.</para> + + <para>For more information about the <literal>sd_id128_t</literal> + type, see + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para><citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>'s + <option>--new-id</option> option may be used as a command line + front-end for <function>sd_id128_randomize()</function>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The call returns 0 on success (in which case + <parameter>ret</parameter> is filled in), or a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_id128_randomize()</function> interface is + available as a shared library, which can be compiled and linked to + with the + <literal>libsystemd</literal> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>machine-id</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>random</refentrytitle><manvolnum>4</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_get_machine</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_id128_to_string.xml b/src/libsystemd/sd_id128_to_string.xml new file mode 100644 index 0000000000..927d1ad5f2 --- /dev/null +++ b/src/libsystemd/sd_id128_to_string.xml @@ -0,0 +1,130 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_id128_to_string"> + + <refentryinfo> + <title>sd_id128_to_string</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_id128_to_string</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_id128_to_string</refname> + <refname>sd_id128_from_string</refname> + <refpurpose>Format or parse 128-bit IDs as strings</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-id128.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>char *<function>sd_id128_to_string</function></funcdef> + <paramdef>sd_id128_t <parameter>id</parameter>, char <parameter>s</parameter>[33]</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_id128_from_string</function></funcdef> + <paramdef>const char *<parameter>s</parameter>, sd_id128_t *<parameter>ret</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_id128_to_string()</function> formats a 128-bit + ID as a character string. It expects the ID and a string array + capable of storing 33 characters. The ID will be formatted as 32 + lowercase hexadecimal digits and be terminated by a + <constant>NUL</constant> byte.</para> + + <para><function>sd_id128_from_string()</function> implements the reverse operation: it takes a 33 character string + with 32 hexadecimal digits (either lowercase or uppercase, terminated by <constant>NUL</constant>) and parses them + back into a 128-bit ID returned in <parameter>ret</parameter>. Alternatively, this call can also parse a + 37-character string with a 128-bit ID formatted as RFC UUID. If <parameter>ret</parameter> is passed as NULL the + function will validate the passed ID string, but not actually return it in parsed form.</para> + + <para>For more information about the <literal>sd_id128_t</literal> + type see + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + Note that these calls operate the same way on all architectures, + i.e. the results do not depend on endianness.</para> + + <para>When formatting a 128-bit ID into a string, it is often + easier to use a format string for + <citerefentry project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + This is easily done using the + <function>SD_ID128_FORMAT_STR</function> and + <function>SD_ID128_FORMAT_VAL()</function> macros. For more + information see + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_id128_to_string()</function> always succeeds + and returns a pointer to the string array passed in. + <function>sd_id128_from_string</function> returns 0 on success, in + which case <parameter>ret</parameter> is filled in, or a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_id128_to_string()</function> and + <function>sd_id128_from_string()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <literal>libsystemd</literal> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-id128</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_is_fifo.xml b/src/libsystemd/sd_is_fifo.xml new file mode 100644 index 0000000000..627cb87aaf --- /dev/null +++ b/src/libsystemd/sd_is_fifo.xml @@ -0,0 +1,200 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_is_fifo" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_is_fifo</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_is_fifo</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_is_fifo</refname> + <refname>sd_is_socket</refname> + <refname>sd_is_socket_inet</refname> + <refname>sd_is_socket_unix</refname> + <refname>sd_is_mq</refname> + <refname>sd_is_special</refname> + <refpurpose>Check the type of a file descriptor</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_is_fifo</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_is_socket</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>int <parameter>family</parameter></paramdef> + <paramdef>int <parameter>type</parameter></paramdef> + <paramdef>int <parameter>listening</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_is_socket_inet</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>int <parameter>family</parameter></paramdef> + <paramdef>int <parameter>type</parameter></paramdef> + <paramdef>int <parameter>listening</parameter></paramdef> + <paramdef>uint16_t <parameter>port</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_is_socket_unix</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>int <parameter>type</parameter></paramdef> + <paramdef>int <parameter>listening</parameter></paramdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + <paramdef>size_t <parameter>length</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_is_mq</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_is_special</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_is_fifo()</function> may be called to check + whether the specified file descriptor refers to a FIFO or pipe. If + the <parameter>path</parameter> parameter is not + <constant>NULL</constant>, it is checked whether the FIFO is bound + to the specified file system path.</para> + + <para><function>sd_is_socket()</function> may be called to check + whether the specified file descriptor refers to a socket. If the + <parameter>family</parameter> parameter is not + <constant>AF_UNSPEC</constant>, it is checked whether the socket + is of the specified family (AF_UNIX, <constant>AF_INET</constant>, + ...). If the <parameter>type</parameter> parameter is not 0, it is + checked whether the socket is of the specified type + (<constant>SOCK_STREAM</constant>, + <constant>SOCK_DGRAM</constant>, ...). If the + <parameter>listening</parameter> parameter is positive, it is + checked whether the socket is in accepting mode, i.e. + <function>listen()</function> has been called for it. If + <parameter>listening</parameter> is 0, it is checked whether the + socket is not in this mode. If the parameter is negative, no such + check is made. The <parameter>listening</parameter> parameter + should only be used for stream sockets and should be set to a + negative value otherwise.</para> + + <para><function>sd_is_socket_inet()</function> is similar to + <function>sd_is_socket()</function>, but optionally checks the + IPv4 or IPv6 port number the socket is bound to, unless + <parameter>port</parameter> is zero. For this call + <parameter>family</parameter> must be passed as either + <constant>AF_UNSPEC</constant>, <constant>AF_INET</constant>, or + <constant>AF_INET6</constant>.</para> + + <para><function>sd_is_socket_unix()</function> is similar to + <function>sd_is_socket()</function> but optionally checks the + <constant>AF_UNIX</constant> path the socket is bound to, unless + the <parameter>path</parameter> parameter is + <constant>NULL</constant>. For normal file system + <constant>AF_UNIX</constant> sockets, set the + <parameter>length</parameter> parameter to 0. For Linux abstract + namespace sockets, set the <parameter>length</parameter> to the + size of the address, including the initial 0 byte, and set the + <parameter>path</parameter> to the initial 0 byte of the socket + address.</para> + + <para><function>sd_is_mq()</function> may be called to check + whether the specified file descriptor refers to a POSIX message + queue. If the <parameter>path</parameter> parameter is not + <constant>NULL</constant>, it is checked whether the message queue + is bound to the specified name.</para> + + <para><function>sd_is_special()</function> may be called to check + whether the specified file descriptor refers to a special file. If + the <parameter>path</parameter> parameter is not + <constant>NULL</constant>, it is checked whether the file + descriptor is bound to the specified file name. Special files in + this context are character device nodes and files in + <filename>/proc</filename> or <filename>/sys</filename>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, these calls return a negative errno-style error + code. If the file descriptor is of the specified type and bound to + the specified address, a positive return value is returned, + otherwise zero.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <xi:include href="libsystemd-pkgconfig.xml" xpointer="pkgconfig-text"/> + + <para>Internally, these function use a combination of + <filename>fstat()</filename> and + <filename>getsockname()</filename> to check the file descriptor + type and where it is bound to.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_add_match.xml b/src/libsystemd/sd_journal_add_match.xml new file mode 100644 index 0000000000..98415d53fd --- /dev/null +++ b/src/libsystemd/sd_journal_add_match.xml @@ -0,0 +1,216 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_add_match"> + + <refentryinfo> + <title>sd_journal_add_match</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_add_match</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_add_match</refname> + <refname>sd_journal_add_disjunction</refname> + <refname>sd_journal_add_conjunction</refname> + <refname>sd_journal_flush_matches</refname> + <refpurpose>Add or remove entry matches</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_add_match</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const void *<parameter>data</parameter></paramdef> + <paramdef>size_t <parameter>size</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_add_disjunction</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_add_conjunction</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_journal_flush_matches</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_add_match()</function> adds a match by + which to filter the entries of the journal file. Matches applied + with this call will filter what can be iterated through and read + from the journal file via calls like + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + Parameter <parameter>data</parameter> must be of the form + <literal><replaceable>FIELD</replaceable>=<replaceable>value</replaceable></literal>, + where the <replaceable>FIELD</replaceable> part is a short uppercase string consisting only + of 0–9, A–Z and the underscore; it may not begin with two underscores or be the empty + string. The <replaceable>value</replaceable> part may be anything, including binary. Parameter + <parameter>size</parameter> specifies the number of bytes in <parameter>data</parameter> + (i.e. the length of <replaceable>FIELD</replaceable>, plus one, plus the length of + <replaceable>value</replaceable>). Parameter <parameter>size</parameter> may also be + specified as <constant>0</constant>, in which case <parameter>data</parameter> + must be a <constant>NUL</constant>-terminated string, and the bytes before the terminating + zero are used as the match.</para> + + <para>If a match is applied, only entries with this field set + will be iterated. Multiple matches may be active at the same time: + If they apply to different fields, only entries with both fields + set like this will be iterated. If they apply to the same fields, + only entries where the field takes one of the specified values + will be iterated. Well known fields are documented in + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>. + Whenever a new match is added the current entry position is reset, + and + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + (or a similar call) needs to be called before entries can be read + again.</para> + + <para><function>sd_journal_add_disjunction()</function> may be + used to insert a disjunction (i.e. logical OR) in the match list. + If this call is invoked, all previously added matches since the + last invocation of + <function>sd_journal_add_disjunction()</function> or + <function>sd_journal_add_conjunction()</function> are combined in + an OR with all matches added afterwards, until + <function>sd_journal_add_disjunction()</function> or + <function>sd_journal_add_conjunction()</function> is invoked again + to begin the next OR or AND term. </para> + + <para><function>sd_journal_add_conjunction()</function> may be + used to insert a conjunction (i.e. logical AND) in the match list. + If this call is invoked, all previously added matches since the + last invocation of + <function>sd_journal_add_conjunction()</function> are combined in + an AND with all matches added afterwards, until + <function>sd_journal_add_conjunction()</function> is invoked again + to begin the next AND term. The combination of + <function>sd_journal_add_match()</function>, + <function>sd_journal_add_disjunction()</function> and + <function>sd_journal_add_conjunction()</function> may be used to + build complex search terms, even though full logical expressions + are not available. Note that + <function>sd_journal_add_conjunction()</function> operates one + level 'higher' than + <function>sd_journal_add_disjunction()</function>. It is hence + possible to build an expression of AND terms, consisting of OR + terms, consisting of AND terms, consisting of OR terms of matches + (the latter OR expression is implicitly created for matches with + the same field name, see above).</para> + + <para><function>sd_journal_flush_matches()</function> may be used + to flush all matches, disjunction and conjunction terms again. + After this call all filtering is removed and all entries in the + journal will be iterated again.</para> + + <para>Note that filtering via matches only applies to the way the + journal is read, it has no effect on storage on disk.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_add_match()</function>, + <function>sd_journal_add_disjunction()</function> and + <function>sd_journal_add_conjunction()</function> + return 0 on success or a negative errno-style error + code. <function>sd_journal_flush_matches()</function> + returns nothing.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_add_match()</function>, + <function>sd_journal_add_disjunction()</function>, + <function>sd_journal_add_conjunction()</function> and + <function>sd_journal_flush_matches()</function> + interfaces are available as a shared library, which can + be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>The following example adds matches to a journal context + object to iterate only through messages generated by the Avahi + service at the four error log levels, plus all messages of the + message ID 03bb1dab98ab4ecfbf6fff2738bdd964 coming from any + service (this example lacks the necessary error checking):</para> + + <programlisting>... +int add_matches(sd_journal *j) { + sd_journal_add_match(j, "_SYSTEMD_UNIT=avahi-daemon.service", 0); + sd_journal_add_match(j, "PRIORITY=0", 0); + sd_journal_add_match(j, "PRIORITY=1", 0); + sd_journal_add_match(j, "PRIORITY=2", 0); + sd_journal_add_match(j, "PRIORITY=3", 0); + sd_journal_add_disjunction(j); + sd_journal_add_match(j, "MESSAGE_ID=03bb1dab98ab4ecfbf6fff2738bdd964", 0); +}</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_enumerate_fields.xml b/src/libsystemd/sd_journal_enumerate_fields.xml new file mode 100644 index 0000000000..fa5884106b --- /dev/null +++ b/src/libsystemd/sd_journal_enumerate_fields.xml @@ -0,0 +1,161 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_enumerate_fields"> + + <refentryinfo> + <title>sd_journal_enumerate_fields</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_enumerate_fields</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_enumerate_fields</refname> + <refname>sd_journal_restart_fields</refname> + <refname>SD_JOURNAL_FOREACH_FIELD</refname> + <refpurpose>Read used field names from the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_enumerate_fields</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char **<parameter>field</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_journal_restart_fields</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef><function>SD_JOURNAL_FOREACH_FIELD</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char *<parameter>field</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_enumerate_fields()</function> may be used to iterate through all field names used in the + opened journal files. On each invocation the next field name is returned. The order of the returned field names is + not defined. It takes two arguments: the journal context object, plus a pointer to a constant string pointer where + the field name is stored in. The returned data is in a read-only memory map and is only valid until the next + invocation of <function>sd_journal_enumerate_fields()</function>. Note that this call is subject to the data field + size threshold as controlled by <function>sd_journal_set_data_threshold()</function>.</para> + + <para><function>sd_journal_restart_fields()</function> resets the field name enumeration index to the beginning of + the list. The next invocation of <function>sd_journal_enumerate_fields()</function> will return the first field + name again.</para> + + <para>The <function>SD_JOURNAL_FOREACH_FIELD()</function> macro may be used as a handy wrapper around + <function>sd_journal_restart_fields()</function> and <function>sd_journal_enumerate_fields()</function>.</para> + + <para>These functions currently are not influenced by matches set with <function>sd_journal_add_match()</function> + but this might change in a later version of this software.</para> + + <para>To retrieve the possible values a specific field can take use + <citerefentry><refentrytitle>sd_journal_query_unique</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_enumerate_fields()</function> returns a + positive integer if the next field name has been read, 0 when no + more field names are known, or a negative errno-style error code. + <function>sd_journal_restart_fields()</function> returns + nothing.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_enumerate_fields()</function> and <function>sd_journal_restart_fields()</function> + interfaces are available as a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Use the <function>SD_JOURNAL_FOREACH_FIELD</function> macro to iterate through all field names in use in the + current journal.</para> + + <programlisting>#include <stdio.h> +#include <string.h> +#include <systemd/sd-journal.h> + +int main(int argc, char *argv[]) { + sd_journal *j; + const char *field; + int r; + + r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY); + if (r < 0) { + fprintf(stderr, "Failed to open journal: %s\n", strerror(-r)); + return 1; + } + SD_JOURNAL_FOREACH_FIELD(j, field) + printf("%s\n", field); + sd_journal_close(j); + return 0; +}</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_query_unique</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_add_match</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_catalog.xml b/src/libsystemd/sd_journal_get_catalog.xml new file mode 100644 index 0000000000..c19eb11b20 --- /dev/null +++ b/src/libsystemd/sd_journal_get_catalog.xml @@ -0,0 +1,137 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_catalog"> + + <refentryinfo> + <title>sd_journal_get_catalog</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_catalog</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_catalog</refname> + <refname>sd_journal_get_catalog_for_message_id</refname> + <refpurpose>Retrieve message catalog entry</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_catalog</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>char **<parameter>ret</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_catalog_for_message_id</function></funcdef> + <paramdef>sd_id128_t <parameter>id</parameter></paramdef> + <paramdef>char **<parameter>ret</parameter></paramdef> + </funcprototype> + + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_catalog()</function> retrieves a + message catalog entry for the current journal entry. This will + look up an entry in the message catalog by using the + <literal>MESSAGE_ID=</literal> field of the current journal entry. + Before returning the entry all journal field names in the catalog + entry text enclosed in "@" will be replaced by the respective + field values of the current entry. If a field name referenced in + the message catalog entry does not exist, in the current journal + entry, the "@" will be removed, but the field name otherwise left + untouched.</para> + + <para><function>sd_journal_get_catalog_for_message_id()</function> + works similar to <function>sd_journal_get_catalog()</function> but + the entry is looked up by the specified message ID (no open + journal context is necessary for this), and no field substitution + is performed.</para> + + <para>For more information about the journal message catalog + please refer to the <ulink + url="http://www.freedesktop.org/wiki/Software/systemd/catalog">Journal + Message Catalogs</ulink> documentation page.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_catalog()</function> and + <function>sd_journal_get_catalog_for_message_id()</function> + return 0 on success or a negative errno-style error code. If no + matching message catalog entry is found, -ENOENT is + returned.</para> + + <para>On successful return, <parameter>ret</parameter> points to a + new string, which must be freed with + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + </para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_catalog()</function> and + <function>sd_journal_get_catalog_for_message_id()</function> + interfaces are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>malloc</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_cursor.xml b/src/libsystemd/sd_journal_get_cursor.xml new file mode 100644 index 0000000000..a400d8b1b5 --- /dev/null +++ b/src/libsystemd/sd_journal_get_cursor.xml @@ -0,0 +1,144 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_cursor"> + + <refentryinfo> + <title>sd_journal_get_cursor</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_cursor</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_cursor</refname> + <refname>sd_journal_test_cursor</refname> + <refpurpose>Get cursor string for or test cursor string against the current journal entry</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_cursor</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>char **<parameter>cursor</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_test_cursor</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char *<parameter>cursor</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_cursor()</function> returns a + cursor string for the current journal entry. A cursor is a + serialization of the current journal position formatted as text. + The string only contains printable characters and can be passed + around in text form. The cursor identifies a journal entry + globally and in a stable way and may be used to later seek to it + via + <citerefentry><refentrytitle>sd_journal_seek_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + The cursor string should be considered opaque and not be parsed by + clients. Seeking to a cursor position without the specific entry + being available locally will seek to the next closest (in terms of + time) available entry. The call takes two arguments: a journal + context object and a pointer to a string pointer where the cursor + string will be placed. The string is allocated via libc + <citerefentry project='man-pages'><refentrytitle>malloc</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and should be freed after use with + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>Note that <function>sd_journal_get_cursor()</function> will + not work before + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + (or related call) has been called at least once, in order to + position the read pointer at a valid entry.</para> + + <para><function>sd_journal_test_cursor()</function> + may be used to check whether the current position in + the journal matches the specified cursor. This is + useful since cursor strings do not uniquely identify + an entry: the same entry might be referred to by + multiple different cursor strings, and hence string + comparing cursors is not possible. Use this call to + verify after an invocation of + <citerefentry><refentrytitle>sd_journal_seek_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry> + whether the entry being sought to was actually found + in the journal or the next closest entry was used + instead.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_cursor()</function> returns 0 on + success or a negative errno-style error code. + <function>sd_journal_test_cursor()</function> returns positive if + the current entry matches the specified cursor, 0 if it does not + match the specified cursor or a negative errno-style error code on + failure.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_cursor()</function> and + <function>sd_journal_test_cursor()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_seek_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_cutoff_realtime_usec.xml b/src/libsystemd/sd_journal_get_cutoff_realtime_usec.xml new file mode 100644 index 0000000000..23e7cc65e8 --- /dev/null +++ b/src/libsystemd/sd_journal_get_cutoff_realtime_usec.xml @@ -0,0 +1,145 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_cutoff_realtime_usec"> + + <refentryinfo> + <title>sd_journal_get_cutoff_realtime_usec</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_cutoff_realtime_usec</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_cutoff_realtime_usec</refname> + <refname>sd_journal_get_cutoff_monotonic_usec</refname> + <refpurpose>Read cut-off timestamps from the current journal entry</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_cutoff_realtime_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t *<parameter>from</parameter></paramdef> + <paramdef>uint64_t *<parameter>to</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_cutoff_monotonic_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>sd_id128_t <parameter>boot_id</parameter></paramdef> + <paramdef>uint64_t *<parameter>from</parameter></paramdef> + <paramdef>uint64_t *<parameter>to</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_cutoff_realtime_usec()</function> + retrieves the realtime (wallclock) timestamps of the first and + last entries accessible in the journal. It takes three arguments: + the journal context object <parameter>j</parameter> and two + pointers <parameter>from</parameter> and <parameter>to</parameter> + pointing at 64-bit unsigned integers to store the timestamps in. + The timestamps are in microseconds since the epoch, i.e. + <constant>CLOCK_REALTIME</constant>. Either one of the two + timestamp arguments may be passed as <constant>NULL</constant> in + case the timestamp is not needed, but not both.</para> + + <para><function>sd_journal_get_cutoff_monotonic_usec()</function> + retrieves the monotonic timestamps of the first and last entries + accessible in the journal. It takes three arguments: the journal + context object <parameter>j</parameter>, a 128-bit identifier for + the boot <parameter>boot_id</parameter>, and two pointers to + 64-bit unsigned integers to store the timestamps, + <parameter>from</parameter> and <parameter>to</parameter>. The + timestamps are in microseconds since boot-up of the specific boot, + i.e. <constant>CLOCK_MONOTONIC</constant>. Since the monotonic + clock begins new with every reboot it only defines a well-defined + point in time when used together with an identifier identifying + the boot, see + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information. The function will return the timestamps for + the boot identified by the passed boot ID. Either one of the two + timestamp arguments may be passed as <constant>NULL</constant> in + case the timestamp is not needed, but not both.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_cutoff_realtime_usec()</function> + and <function>sd_journal_get_cutoff_monotonic_usec()</function> + return 1 on success, 0 if not suitable entries are in the journal + or a negative errno-style error code.</para> + + <para>Locations pointed to by parameters + <parameter>from</parameter> and <parameter>to</parameter> will be + set only if the return value is positive, and obviously, the + parameters are non-null.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The + <function>sd_journal_get_cutoff_realtime_usec()</function> and + <function>sd_journal_get_cutoff_monotonic_usec()</function> + interfaces are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_data.xml b/src/libsystemd/sd_journal_get_data.xml new file mode 100644 index 0000000000..1321114de0 --- /dev/null +++ b/src/libsystemd/sd_journal_get_data.xml @@ -0,0 +1,235 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_data"> + + <refentryinfo> + <title>sd_journal_get_data</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_data</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_data</refname> + <refname>sd_journal_enumerate_data</refname> + <refname>sd_journal_restart_data</refname> + <refname>SD_JOURNAL_FOREACH_DATA</refname> + <refname>sd_journal_set_data_threshold</refname> + <refname>sd_journal_get_data_threshold</refname> + <refpurpose>Read data fields from the current journal entry</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_data</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char *<parameter>field</parameter></paramdef> + <paramdef>const void **<parameter>data</parameter></paramdef> + <paramdef>size_t *<parameter>length</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_enumerate_data</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const void **<parameter>data</parameter></paramdef> + <paramdef>size_t *<parameter>length</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_journal_restart_data</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef><function>SD_JOURNAL_FOREACH_DATA</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const void *<parameter>data</parameter></paramdef> + <paramdef>size_t <parameter>length</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_set_data_threshold</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>size_t <parameter>sz</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_data_threshold</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>size_t *<parameter>sz</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_data()</function> gets the data + object associated with a specific field from the current journal + entry. It takes four arguments: the journal context object, a + string with the field name to request, plus a pair of pointers to + pointer/size variables where the data object and its size shall be + stored in. The field name should be an entry field name. + Well-known field names are listed in + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>. + The returned data is in a read-only memory map and is only valid + until the next invocation of + <function>sd_journal_get_data()</function> or + <function>sd_journal_enumerate_data()</function>, or the read + pointer is altered. Note that the data returned will be prefixed + with the field name and '='. Also note that, by default, data fields + larger than 64K might get truncated to 64K. This threshold may be + changed and turned off with + <function>sd_journal_set_data_threshold()</function> (see + below).</para> + + <para><function>sd_journal_enumerate_data()</function> may be used + to iterate through all fields of the current entry. On each + invocation the data for the next field is returned. The order of + these fields is not defined. The data returned is in the same + format as with <function>sd_journal_get_data()</function> and also + follows the same life-time semantics.</para> + + <para><function>sd_journal_restart_data()</function> resets the + data enumeration index to the beginning of the entry. The next + invocation of <function>sd_journal_enumerate_data()</function> + will return the first field of the entry again.</para> + + <para>Note that the <function>SD_JOURNAL_FOREACH_DATA()</function> + macro may be used as a handy wrapper around + <function>sd_journal_restart_data()</function> and + <function>sd_journal_enumerate_data()</function>.</para> + + <para>Note that these functions will not work before + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + (or related call) has been called at least once, in order to + position the read pointer at a valid entry.</para> + + <para><function>sd_journal_set_data_threshold()</function> may be + used to change the data field size threshold for data returned by + <function>sd_journal_get_data()</function>, + <function>sd_journal_enumerate_data()</function> and + <function>sd_journal_enumerate_unique()</function>. This threshold + is a hint only: it indicates that the client program is interested + only in the initial parts of the data fields, up to the threshold + in size — but the library might still return larger data objects. + That means applications should not rely exclusively on this + setting to limit the size of the data fields returned, but need to + apply an explicit size limit on the returned data as well. This + threshold defaults to 64K by default. To retrieve the complete + data fields this threshold should be turned off by setting it to + 0, so that the library always returns the complete data objects. + It is recommended to set this threshold as low as possible since + this relieves the library from having to decompress large + compressed data objects in full.</para> + + <para><function>sd_journal_get_data_threshold()</function> returns + the currently configured data field size threshold.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_data()</function> returns 0 on + success or a negative errno-style error code. If the current entry + does not include the specified field, -ENOENT is returned. If + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + has not been called at least once, -EADDRNOTAVAIL is returned. + <function>sd_journal_enumerate_data()</function> returns a + positive integer if the next field has been read, 0 when no more + fields are known, or a negative errno-style error code. + <function>sd_journal_restart_data()</function> returns nothing. + <function>sd_journal_set_data_threshold()</function> and + <function>sd_journal_get_threshold()</function> return 0 on + success or a negative errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_data()</function>, + <function>sd_journal_enumerate_data()</function>, + <function>sd_journal_restart_data()</function>, + <function>sd_journal_set_data_threshold()</function> and + <function>sd_journal_get_data_threshold()</function> interfaces + are available as a shared library, which can be compiled and + linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>See + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for a complete example how to use + <function>sd_journal_get_data()</function>.</para> + + <para>Use the + <function>SD_JOURNAL_FOREACH_DATA</function> macro to + iterate through all fields of the current journal + entry:</para> + + <programlisting>... +int print_fields(sd_journal *j) { + const void *data; + size_t length; + SD_JOURNAL_FOREACH_DATA(j, data, length) + printf("%.*s\n", (int) length, data); +} +...</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_query_unique</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_fd.xml b/src/libsystemd/sd_journal_get_fd.xml new file mode 100644 index 0000000000..61293f7f99 --- /dev/null +++ b/src/libsystemd/sd_journal_get_fd.xml @@ -0,0 +1,332 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_fd"> + + <refentryinfo> + <title>sd_journal_get_fd</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_fd</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_fd</refname> + <refname>sd_journal_get_events</refname> + <refname>sd_journal_get_timeout</refname> + <refname>sd_journal_process</refname> + <refname>sd_journal_wait</refname> + <refname>sd_journal_reliable_fd</refname> + <refname>SD_JOURNAL_NOP</refname> + <refname>SD_JOURNAL_APPEND</refname> + <refname>SD_JOURNAL_INVALIDATE</refname> + <refpurpose>Journal change notification + interface</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_fd</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_events</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_timeout</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t *<parameter>timeout_usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_process</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_wait</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t <parameter>timeout_usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_reliable_fd</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_fd()</function> returns a file + descriptor that may be asynchronously polled in an external event + loop and is signaled as soon as the journal changes, because new + entries or files were added, rotation took place, or files have + been deleted, and similar. The file descriptor is suitable for + usage in + <citerefentry><refentrytitle>poll</refentrytitle><manvolnum>2</manvolnum></citerefentry>. + Use <function>sd_journal_get_events()</function> for an events + mask to watch for. The call takes one argument: the journal + context object. Note that not all file systems are capable of + generating the necessary events for wakeups from this file + descriptor for changes to be noticed immediately. In particular + network files systems do not generate suitable file change events + in all cases. Cases like this can be detected with + <function>sd_journal_reliable_fd()</function>, below. + <function>sd_journal_get_timeout()</function> will ensure in these + cases that wake-ups happen frequently enough for changes to be + noticed, although with a certain latency.</para> + + <para><function>sd_journal_get_events()</function> will return the + <function>poll()</function> mask to wait for. This function will + return a combination of <constant>POLLIN</constant> and + <constant>POLLOUT</constant> and similar to fill into the + <literal>.events</literal> field of <varname>struct + pollfd</varname>.</para> + + <para><function>sd_journal_get_timeout()</function> will return a + timeout value for usage in <function>poll()</function>. This + returns a value in microseconds since the epoch of + <constant>CLOCK_MONOTONIC</constant> for timing out + <function>poll()</function> in <varname>timeout_usec</varname>. + See + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details about <constant>CLOCK_MONOTONIC</constant>. If there + is no timeout to wait for, this will fill in <constant>(uint64_t) + -1</constant> instead. Note that <function>poll()</function> takes + a relative timeout in milliseconds rather than an absolute timeout + in microseconds. To convert the absolute 'us' timeout into + relative 'ms', use code like the following:</para> + + <programlisting>uint64_t t; +int msec; +sd_journal_get_timeout(m, &t); +if (t == (uint64_t) -1) + msec = -1; +else { + struct timespec ts; + uint64_t n; + clock_getttime(CLOCK_MONOTONIC, &ts); + n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; + msec = t > n ? (int) ((t - n + 999) / 1000) : 0; +}</programlisting> + + <para>The code above does not do any error checking for brevity's + sake. The calculated <varname>msec</varname> integer can be passed + directly as <function>poll()</function>'s timeout + parameter.</para> + + <para>After each <function>poll()</function> wake-up + <function>sd_journal_process()</function> needs to be called to + process events. This call will also indicate what kind of change + has been detected (see below; note that spurious wake-ups are + possible).</para> + + <para>A synchronous alternative for using + <function>sd_journal_get_fd()</function>, + <function>sd_journal_get_events()</function>, + <function>sd_journal_get_timeout()</function> and + <function>sd_journal_process()</function> is + <function>sd_journal_wait()</function>. It will synchronously wait + until the journal gets changed. The maximum time this call sleeps + may be controlled with the <parameter>timeout_usec</parameter> + parameter. Pass <constant>(uint64_t) -1</constant> to wait + indefinitely. Internally this call simply combines + <function>sd_journal_get_fd()</function>, + <function>sd_journal_get_events()</function>, + <function>sd_journal_get_timeout()</function>, + <function>poll()</function> and + <function>sd_journal_process()</function> into one.</para> + + <para><function>sd_journal_reliable_fd()</function> may be used to + check whether the wakeup events from the file descriptor returned + by <function>sd_journal_get_fd()</function> are known to be + immediately triggered. On certain file systems where file change + events from the OS are not available (such as NFS) changes need to + be polled for repeatedly, and hence are detected only with a + certain latency. This call will return a positive value if the + journal changes are detected immediately and zero when they need + to be polled for and hence might be noticed only with a certain + latency. Note that there is usually no need to invoke this function + directly as <function>sd_journal_get_timeout()</function> on these + file systems will ask for timeouts explicitly anyway.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_fd()</function> returns a valid + file descriptor on success or a negative errno-style error + code.</para> + + <para><function>sd_journal_get_events()</function> returns a + combination of <constant>POLLIN</constant>, + <constant>POLLOUT</constant> and suchlike on success or a negative + errno-style error code.</para> + + <para><function>sd_journal_reliable_fd()</function> returns a + positive integer if the file descriptor returned by + <function>sd_journal_get_fd()</function> will generate wake-ups + immediately for all journal changes. Returns 0 if there might be a + latency involved.</para> + + <para><function>sd_journal_process()</function> and + <function>sd_journal_wait()</function> return one of + <constant>SD_JOURNAL_NOP</constant>, + <constant>SD_JOURNAL_APPEND</constant> or + <constant>SD_JOURNAL_INVALIDATE</constant> on success or a + negative errno-style error code. If + <constant>SD_JOURNAL_NOP</constant> is returned, the journal did + not change since the last invocation. If + <constant>SD_JOURNAL_APPEND</constant> is returned, new entries + have been appended to the end of the journal. If + <constant>SD_JOURNAL_INVALIDATE</constant>, journal files were + added or removed (possibly due to rotation). In the latter event, + live-view UIs should probably refresh their entire display, while + in the case of <constant>SD_JOURNAL_APPEND</constant>, it is + sufficient to simply continue reading at the previous end of the + journal.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_fd()</function>, + <function>sd_journal_get_events()</function>, + <function>sd_journal_reliable_fd()</function>, + <function>sd_journal_process()</function> and + <function>sd_journal_wait()</function> interfaces are available as + a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Iterating through the journal, in a live view tracking all + changes:</para> + + <programlisting>#include <stdio.h> +#include <string.h> +#include <systemd/sd-journal.h> + +int main(int argc, char *argv[]) { + int r; + sd_journal *j; + r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY); + if (r < 0) { + fprintf(stderr, "Failed to open journal: %s\n", strerror(-r)); + return 1; + } + for (;;) { + const void *d; + size_t l; + r = sd_journal_next(j); + if (r < 0) { + fprintf(stderr, "Failed to iterate to next entry: %s\n", strerror(-r)); + break; + } + if (r == 0) { + /* Reached the end, let's wait for changes, and try again */ + r = sd_journal_wait(j, (uint64_t) -1); + if (r < 0) { + fprintf(stderr, "Failed to wait for changes: %s\n", strerror(-r)); + break; + } + continue; + } + r = sd_journal_get_data(j, "MESSAGE", &d, &l); + if (r < 0) { + fprintf(stderr, "Failed to read message field: %s\n", strerror(-r)); + continue; + } + printf("%.*s\n", (int) l, (const char*) d); + } + sd_journal_close(j); + return 0; +}</programlisting> + + <para>Waiting with <function>poll()</function> (this + example lacks all error checking for the sake of + simplicity):</para> + + <programlisting>#include <poll.h> +#include <systemd/sd-journal.h> + +int wait_for_changes(sd_journal *j) { + struct pollfd pollfd; + int msec; + + sd_journal_get_timeout(m, &t); + if (t == (uint64_t) -1) + msec = -1; + else { + struct timespec ts; + uint64_t n; + clock_getttime(CLOCK_MONOTONIC, &ts); + n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; + msec = t > n ? (int) ((t - n + 999) / 1000) : 0; + } + + pollfd.fd = sd_journal_get_fd(j); + pollfd.events = sd_journal_get_events(j); + poll(&pollfd, 1, msec); + return sd_journal_process(j); +}</programlisting> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>poll</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_realtime_usec.xml b/src/libsystemd/sd_journal_get_realtime_usec.xml new file mode 100644 index 0000000000..607d74666b --- /dev/null +++ b/src/libsystemd/sd_journal_get_realtime_usec.xml @@ -0,0 +1,141 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_realtime_usec"> + + <refentryinfo> + <title>sd_journal_get_realtime_usec</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_realtime_usec</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_realtime_usec</refname> + <refname>sd_journal_get_monotonic_usec</refname> + <refpurpose>Read timestamps from the current journal entry</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_realtime_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_get_monotonic_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + <paramdef>sd_id128_t *<parameter>boot_id</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_realtime_usec()</function> gets the + realtime (wallclock) timestamp of the current journal entry. It + takes two arguments: the journal context object and a pointer to a + 64-bit unsigned integer to store the timestamp in. The timestamp + is in microseconds since the epoch, i.e. + <constant>CLOCK_REALTIME</constant>.</para> + + <para><function>sd_journal_get_monotonic_usec()</function> gets + the monotonic timestamp of the current journal entry. It takes + three arguments: the journal context object, a pointer to a 64-bit + unsigned integer to store the timestamp in, as well as a 128-bit + ID buffer to store the boot ID of the monotonic timestamp. The + timestamp is in microseconds since boot-up of the specific boot, + i.e. <constant>CLOCK_MONOTONIC</constant>. Since the monotonic + clock begins new with every reboot, it only defines a well-defined + point in time when used together with an identifier identifying + the boot. See + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information. If the boot ID parameter is passed + <constant>NULL</constant>, the function will fail if the monotonic + timestamp of the current entry is not of the current system + boot.</para> + + <para>Note that these functions will not work before + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + (or related call) has been called at least + once, in order to position the read pointer at a valid entry.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_realtime_usec()</function> and + <function>sd_journal_get_monotonic_usec()</function> returns 0 on + success or a negative errno-style error code. If the boot ID + parameter was passed <constant>NULL</constant> and the monotonic + timestamp of the current journal entry is not of the current + system boot, <constant>-ESTALE</constant> is returned by + <function>sd_journal_get_monotonic_usec()</function>.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_realtime_usec()</function> and + <function>sd_journal_get_monotonic_usec()</function> interfaces + are available as a shared library, which can be compiled and + linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_id128_get_boot</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cutoff_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_get_usage.xml b/src/libsystemd/sd_journal_get_usage.xml new file mode 100644 index 0000000000..72c804d834 --- /dev/null +++ b/src/libsystemd/sd_journal_get_usage.xml @@ -0,0 +1,100 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_get_usage"> + + <refentryinfo> + <title>sd_journal_get_usage</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_get_usage</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_get_usage</refname> + <refpurpose>Journal disk usage</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_get_usage</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t *<parameter>bytes</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_get_usage()</function> determines the + total disk space currently used by journal files (in bytes). If + <constant>SD_JOURNAL_LOCAL_ONLY</constant> was passed when opening + the journal, this value will only reflect the size of journal + files of the local host, otherwise of all hosts.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_get_usage()</function> returns 0 on + success or a negative errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_get_usage()</function> interface is + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_has_runtime_files.xml b/src/libsystemd/sd_journal_has_runtime_files.xml new file mode 100644 index 0000000000..237e649206 --- /dev/null +++ b/src/libsystemd/sd_journal_has_runtime_files.xml @@ -0,0 +1,95 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 2016 Jan Synáček + + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_has_runtime_files"> + + <refentryinfo> + <title>sd_journal_has_runtime_files</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Jan</firstname> + <surname>Synáček</surname> + <email>jan.synacek@gmail.com</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_has_runtime_files</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_has_runtime_files</refname> + <refname>sd_journal_has_persistent_files</refname> + <refpurpose>Query availability of runtime or persistent journal files.</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_has_runtime_files</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_has_persistent_files</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_has_runtime_files()</function> returns a positive value + if runtime journal files (present in /run/systemd/journal/) have been found. + Otherwise returns 0.</para> + + <para><function>sd_journal_has_persistent_files()</function> returns a positive value + if persistent journal files (present in /var/log/journal/) have been found. + Otherwise returns 0.</para> + </refsect1> + + <refsect1> + <title>Return value</title> + <para>Both <function>sd_journal_has_runtime_files()</function> + and <function>sd_journal_has_persistent_files()</function> return -EINVAL + if their argument is NULL. + </para> + </refsect1> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_next.xml b/src/libsystemd/sd_journal_next.xml new file mode 100644 index 0000000000..115fe26661 --- /dev/null +++ b/src/libsystemd/sd_journal_next.xml @@ -0,0 +1,207 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_next"> + + <refentryinfo> + <title>sd_journal_next</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_next</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_next</refname> + <refname>sd_journal_previous</refname> + <refname>sd_journal_next_skip</refname> + <refname>sd_journal_previous_skip</refname> + <refname>SD_JOURNAL_FOREACH</refname> + <refname>SD_JOURNAL_FOREACH_BACKWARDS</refname> + <refpurpose>Advance or set back the read pointer in the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_next</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_previous</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_next_skip</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t <parameter>skip</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_previous_skip</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t <parameter>skip</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef><function>SD_JOURNAL_FOREACH</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef><function>SD_JOURNAL_FOREACH_BACKWARDS</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_next()</function> advances the read + pointer into the journal by one entry. The only argument taken is + a journal context object as allocated via + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + After successful invocation the entry may be read with functions + such as + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>Similarly, <function>sd_journal_previous()</function> sets + the read pointer back one entry.</para> + + <para><function>sd_journal_next_skip()</function> and + <function>sd_journal_previous_skip()</function> advance/set back + the read pointer by multiple entries at once, as specified in the + <varname>skip</varname> parameter.</para> + + <para>The journal is strictly ordered by reception time, and hence + advancing to the next entry guarantees that the entry then + pointing to is later in time than then previous one, or has the + same timestamp.</para> + + <para>Note that + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and related calls will fail unless + <function>sd_journal_next()</function> has been invoked at least + once in order to position the read pointer on a journal + entry.</para> + + <para>Note that the <function>SD_JOURNAL_FOREACH()</function> + macro may be used as a wrapper around + <citerefentry><refentrytitle>sd_journal_seek_head</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and <function>sd_journal_next()</function> in order to make + iterating through the journal easier. See below for an example. + Similarly, <function>SD_JOURNAL_FOREACH_BACKWARDS()</function> may + be used for iterating the journal in reverse order.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The four calls return the number of entries advanced/set + back on success or a negative errno-style error code. When the end + or beginning of the journal is reached, a number smaller than + requested is returned. More specifically, if + <function>sd_journal_next()</function> or + <function>sd_journal_previous()</function> reach the end/beginning + of the journal they will return 0, instead of 1 when they are + successful. This should be considered an EOF marker.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_next()</function>, + <function>sd_journal_previous()</function>, + <function>sd_journal_next_skip()</function> and + <function>sd_journal_previous_skip()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Iterating through the journal:</para> + + <programlisting>#include <stdio.h> +#include <string.h> +#include <systemd/sd-journal.h> + +int main(int argc, char *argv[]) { + int r; + sd_journal *j; + r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY); + if (r < 0) { + fprintf(stderr, "Failed to open journal: %s\n", strerror(-r)); + return 1; + } + SD_JOURNAL_FOREACH(j) { + const char *d; + size_t l; + + r = sd_journal_get_data(j, "MESSAGE", (const void **)&d, &l); + if (r < 0) { + fprintf(stderr, "Failed to read message field: %s\n", strerror(-r)); + continue; + } + + printf("%.*s\n", (int) l, d); + } + sd_journal_close(j); + return 0; +}</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_open.xml b/src/libsystemd/sd_journal_open.xml new file mode 100644 index 0000000000..153af2387f --- /dev/null +++ b/src/libsystemd/sd_journal_open.xml @@ -0,0 +1,228 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_open"> + + <refentryinfo> + <title>sd_journal_open</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_open</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_open</refname> + <refname>sd_journal_open_directory</refname> + <refname>sd_journal_open_directory_fd</refname> + <refname>sd_journal_open_files</refname> + <refname>sd_journal_open_files_fd</refname> + <refname>sd_journal_close</refname> + <refname>sd_journal</refname> + <refname>SD_JOURNAL_LOCAL_ONLY</refname> + <refname>SD_JOURNAL_RUNTIME_ONLY</refname> + <refname>SD_JOURNAL_SYSTEM</refname> + <refname>SD_JOURNAL_CURRENT_USER</refname> + <refname>SD_JOURNAL_OS_ROOT</refname> + <refpurpose>Open the system journal for reading</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_open</function></funcdef> + <paramdef>sd_journal **<parameter>ret</parameter></paramdef> + <paramdef>int <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_open_directory</function></funcdef> + <paramdef>sd_journal **<parameter>ret</parameter></paramdef> + <paramdef>const char *<parameter>path</parameter></paramdef> + <paramdef>int <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_open_directory_fd</function></funcdef> + <paramdef>sd_journal **<parameter>ret</parameter></paramdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>int <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_open_files</function></funcdef> + <paramdef>sd_journal **<parameter>ret</parameter></paramdef> + <paramdef>const char **<parameter>paths</parameter></paramdef> + <paramdef>int <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_open_files_fd</function></funcdef> + <paramdef>sd_journal **<parameter>ret</parameter></paramdef> + <paramdef>int <parameter>fds[]</parameter></paramdef> + <paramdef>unsigned <parameter>n_fds</parameter></paramdef> + <paramdef>int <parameter>flags</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_journal_close</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_open()</function> opens the log journal + for reading. It will find all journal files automatically and + interleave them automatically when reading. As first argument it + takes a pointer to a <varname>sd_journal</varname> pointer, which, + on success, will contain a journal context object. The second + argument is a flags field, which may consist of the following + flags ORed together: <constant>SD_JOURNAL_LOCAL_ONLY</constant> + makes sure only journal files generated on the local machine will + be opened. <constant>SD_JOURNAL_RUNTIME_ONLY</constant> makes sure + only volatile journal files will be opened, excluding those which + are stored on persistent storage. + <constant>SD_JOURNAL_SYSTEM</constant> will cause journal files of + system services and the kernel (in opposition to user session + processes) to be opened. + <constant>SD_JOURNAL_CURRENT_USER</constant> will cause journal + files of the current user to be opened. If neither + <constant>SD_JOURNAL_SYSTEM</constant> nor + <constant>SD_JOURNAL_CURRENT_USER</constant> are specified, all + journal file types will be opened.</para> + + <para><function>sd_journal_open_directory()</function> is similar to <function>sd_journal_open()</function> but + takes an absolute directory path as argument. All journal files in this directory will be opened and interleaved + automatically. This call also takes a flags argument. The only flags parameter accepted by this call is + <constant>SD_JOURNAL_OS_ROOT</constant>. If specified, the journal files are searched below the usual + <filename>/var/log/journal</filename> and <filename>/run/log/journal</filename> relative to the specified path, + instead of directly beneath it.</para> + + <para><function>sd_journal_open_directory_fd()</function> is similar to + <function>sd_journal_open_directory()</function>, but takes a file descriptor referencing a directory in the file + system instead of an absolute file system path.</para> + + <para><function>sd_journal_open_files()</function> is similar to <function>sd_journal_open()</function> but takes a + <constant>NULL</constant>-terminated list of file paths to open. All files will be opened and interleaved + automatically. This call also takes a flags argument, but it must be passed as 0 as no flags are currently + understood for this call. Please note that in the case of a live journal, this function is only useful for + debugging, because individual journal files can be rotated at any moment, and the opening of specific files is + inherently racy.</para> + + <para><function>sd_journal_open_files_fd()</function> is similar to <function>sd_journal_open_files()</function> + but takes an array of open file descriptors that must reference journal files, instead of an array of file system + paths. Pass the array of file descriptors as second argument, and the number of array entries in the third. The + flags parameter must be passed as 0.</para> + + <para><varname>sd_journal</varname> objects cannot be used in the + child after a fork. Functions which take a journal object as an + argument (<function>sd_journal_next()</function> and others) will + return <constant>-ECHILD</constant> after a fork. + </para> + + <para><function>sd_journal_close()</function> will close the + journal context allocated with + <function>sd_journal_open()</function> or + <function>sd_journal_open_directory()</function> and free its + resources.</para> + + <para>When opening the journal only journal files accessible to + the calling user will be opened. If journal files are not + accessible to the caller, this will be silently ignored.</para> + + <para>See + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for an example of how to iterate through the journal after opening + it with <function>sd_journal_open()</function>.</para> + + <para>A journal context object returned by + <function>sd_journal_open()</function> references a specific + journal entry as <emphasis>current</emphasis> entry, similar to a + file seek index in a classic file system file, but without + absolute positions. It may be altered with + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and + <citerefentry><refentrytitle>sd_journal_seek_head</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and related calls. The current entry position may be exported in + <emphasis>cursor</emphasis> strings, as accessible via + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + Cursor strings may be used to globally identify a specific journal + entry in a stable way and then later to seek to it (or if the + specific entry is not available locally, to its closest entry in + time) + <citerefentry><refentrytitle>sd_journal_seek_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>Notification of journal changes is available via + <function>sd_journal_get_fd()</function> and related calls.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The <function>sd_journal_open()</function>, + <function>sd_journal_open_directory()</function>, and + <function>sd_journal_open_files()</function> calls return 0 on + success or a negative errno-style error code. + <function>sd_journal_close()</function> returns nothing.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_open()</function>, + <function>sd_journal_open_directory()</function> and + <function>sd_journal_close()</function> interfaces are available + as a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd-machined</refentrytitle><manvolnum>8</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_print.xml b/src/libsystemd/sd_journal_print.xml new file mode 100644 index 0000000000..76542527fc --- /dev/null +++ b/src/libsystemd/sd_journal_print.xml @@ -0,0 +1,245 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_print"> + + <refentryinfo> + <title>sd_journal_print</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_print</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_print</refname> + <refname>sd_journal_printv</refname> + <refname>sd_journal_send</refname> + <refname>sd_journal_sendv</refname> + <refname>sd_journal_perror</refname> + <refname>SD_JOURNAL_SUPPRESS_LOCATION</refname> + <refpurpose>Submit log entries to the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_print</function></funcdef> + <paramdef>int <parameter>priority</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_printv</function></funcdef> + <paramdef>int <parameter>priority</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>va_list <parameter>ap</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_send</function></funcdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_sendv</function></funcdef> + <paramdef>const struct iovec *<parameter>iov</parameter></paramdef> + <paramdef>int <parameter>n</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_perror</function></funcdef> + <paramdef>const char *<parameter>message</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_print()</function> may be used to submit simple, plain text log entries to the system + journal. The first argument is a priority value. This is followed by a format string and its parameters, similar to + <citerefentry project='man-pages'><refentrytitle>printf</refentrytitle><manvolnum>3</manvolnum></citerefentry> or + <citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + The priority value is one of <constant>LOG_EMERG</constant>, <constant>LOG_ALERT</constant>, + <constant>LOG_CRIT</constant>, <constant>LOG_ERR</constant>, <constant>LOG_WARNING</constant>, + <constant>LOG_NOTICE</constant>, <constant>LOG_INFO</constant>, <constant>LOG_DEBUG</constant>, as defined in + <filename>syslog.h</filename>, see <citerefentry + project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry> for details. It is + recommended to use this call to submit log messages in the application locale or system locale and in UTF-8 format, + but no such restrictions are enforced. Note that log messages written using this function are generally not + expected to end in a new-line character. However, as all trailing whitespace (including spaces, new-lines, + tabulators and carriage returns) are automatically stripped from the logged string, it is acceptable to specify one + (or more). Empty lines (after trailing whitespace removal) are suppressed. On non-empty lines, leading whitespace + (as well as inner whitespace) is left unmodified. </para> + + <para><function>sd_journal_printv()</function> is similar to + <function>sd_journal_print()</function> but takes a variable + argument list encapsulated in an object of type + <varname>va_list</varname> (see + <citerefentry project='man-pages'><refentrytitle>stdarg</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information) instead of the format string. It is + otherwise equivalent in behavior.</para> + + <para><function>sd_journal_send()</function> may be used to submit structured log entries to the system journal. It + takes a series of format strings, each immediately followed by their associated parameters, terminated by + <constant>NULL</constant>. The strings passed should be of the format <literal>VARIABLE=value</literal>. The + variable name must be in uppercase and consist only of characters, numbers and underscores, and may not begin with + an underscore. (All assignments that do not follow this syntax will be ignored.) The value can be of any size and + format. It is highly recommended to submit text strings formatted in the UTF-8 character encoding only, and submit + binary fields only when formatting in UTF-8 strings is not sensible. A number of well-known fields are defined, see + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry> for + details, but additional application defined fields may be used. A variable may be assigned more than one value per + entry. If this function is used, trailing whitespace is automatically removed from each formatted field.</para> + + <para><function>sd_journal_sendv()</function> is similar to <function>sd_journal_send()</function> but takes an + array of <varname>struct iovec</varname> (as defined in <filename>uio.h</filename>, see <citerefentry + project='man-pages'><refentrytitle>readv</refentrytitle><manvolnum>3</manvolnum></citerefentry> for details) + instead of the format string. Each structure should reference one field of the entry to submit. The second argument + specifies the number of structures in the array. <function>sd_journal_sendv()</function> is particularly useful to + submit binary objects to the journal where that is necessary. Note that this function wil not strip trailing + whitespace of the passed fields, but passes the specified data along unmodified. This is different from both + <function>sd_journal_print()</function> and <function>sd_journal_send()</function> described above, which are based + on format strings, and do strip trailing whitespace.</para> + + <para><function>sd_journal_perror()</function> is a similar to + <citerefentry project='die-net'><refentrytitle>perror</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and writes a message to the journal that consists of the passed + string, suffixed with ": " and a human-readable representation of + the current error code stored in + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If the message string is passed as <constant>NULL</constant> or + empty string, only the error string representation will be + written, prefixed with nothing. An additional journal field ERRNO= + is included in the entry containing the numeric error code + formatted as decimal string. The log priority used is + <constant>LOG_ERR</constant> (3).</para> + + <para>Note that <function>sd_journal_send()</function> is a + wrapper around <function>sd_journal_sendv()</function> to make it + easier to use when only text strings shall be submitted. Also, the + following two calls are mostly equivalent:</para> + + <programlisting>sd_journal_print(LOG_INFO, "Hello World, this is PID %lu!", (unsigned long) getpid()); + +sd_journal_send("MESSAGE=Hello World, this is PID %lu!", (unsigned long) getpid(), + "PRIORITY=%i", LOG_INFO, + NULL);</programlisting> + + <para>Note that these calls implicitly add fields for the source + file, function name and code line where invoked. This is + implemented with macros. If this is not desired, it can be turned + off by defining SD_JOURNAL_SUPPRESS_LOCATION before including + <filename>sd-journal.h</filename>.</para> + + <para><citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry> + and <function>sd_journal_print()</function> may + largely be used interchangeably + functionality-wise. However, note that log messages + logged via the former take a different path to the + journal server than the later, and hence global + chronological ordering between the two streams cannot + be guaranteed. Using + <function>sd_journal_print()</function> has the + benefit of logging source code line, filenames, and + functions as metadata along all entries, and + guaranteeing chronological ordering with structured + log entries that are generated via + <function>sd_journal_send()</function>. Using + <function>syslog()</function> has the benefit of being + more portable.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The four calls return 0 on success or a negative errno-style + error code. The + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry> + variable itself is not altered.</para> + + <para>If + <citerefentry><refentrytitle>systemd-journald</refentrytitle><manvolnum>8</manvolnum></citerefentry> + is not running (the socket is not present), those functions do + nothing, and also return 0.</para> + </refsect1> + + <refsect1> + <title>Async signal safety</title> + <para><function>sd_journal_sendv()</function> is "async signal + safe" in the meaning of + <citerefentry project='man-pages'><refentrytitle>signal</refentrytitle><manvolnum>7</manvolnum></citerefentry>. + </para> + + <para><function>sd_journal_print</function>, + <function>sd_journal_printv</function>, + <function>sd_journal_send</function>, and + <function>sd_journal_perror</function> are + not async signal safe.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_print()</function>, + <function>sd_journal_printv()</function>, + <function>sd_journal_send()</function> and + <function>sd_journal_sendv()</function> interfaces are available + as a shared library, which can be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_stream_fd</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='die-net'><refentrytitle>perror</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>errno</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>signal</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>socket</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_query_unique.xml b/src/libsystemd/sd_journal_query_unique.xml new file mode 100644 index 0000000000..dbff55c105 --- /dev/null +++ b/src/libsystemd/sd_journal_query_unique.xml @@ -0,0 +1,212 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_query_unique"> + + <refentryinfo> + <title>sd_journal_query_unique</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_query_unique</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_query_unique</refname> + <refname>sd_journal_enumerate_unique</refname> + <refname>sd_journal_restart_unique</refname> + <refname>SD_JOURNAL_FOREACH_UNIQUE</refname> + <refpurpose>Read unique data fields from the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_query_unique</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char *<parameter>field</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_enumerate_unique</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const void **<parameter>data</parameter></paramdef> + <paramdef>size_t *<parameter>length</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_journal_restart_unique</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef><function>SD_JOURNAL_FOREACH_UNIQUE</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const void *<parameter>data</parameter></paramdef> + <paramdef>size_t <parameter>length</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_query_unique()</function> queries the + journal for all unique values the specified field can take. It + takes two arguments: the journal to query and the field name to + look for. Well-known field names are listed on + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>. + Field names must be specified without a trailing '='. After this + function has been executed successfully the field values may be + queried using <function>sd_journal_enumerate_unique()</function>. + Invoking this call a second time will change the field name being + queried and reset the enumeration index to the first field value + that matches.</para> + + <para><function>sd_journal_enumerate_unique()</function> may be + used to iterate through all data fields which match the previously + selected field name as set with + <function>sd_journal_query_unique()</function>. On each invocation + the next field data matching the field name is returned. The order + of the returned data fields is not defined. It takes three + arguments: the journal context object, plus a pair of pointers to + pointer/size variables where the data object and its size shall be + stored in. The returned data is in a read-only memory map and is + only valid until the next invocation of + <function>sd_journal_enumerate_unique()</function>. Note that the + data returned will be prefixed with the field name and '='. Note + that this call is subject to the data field size threshold as + controlled by + <function>sd_journal_set_data_threshold()</function>.</para> + + <para><function>sd_journal_restart_unique()</function> resets the + data enumeration index to the beginning of the list. The next + invocation of <function>sd_journal_enumerate_unique()</function> + will return the first field data matching the field name + again.</para> + + <para>Note that the + <function>SD_JOURNAL_FOREACH_UNIQUE()</function> macro may be used + as a handy wrapper around + <function>sd_journal_restart_unique()</function> and + <function>sd_journal_enumerate_unique()</function>.</para> + + <para>Note that these functions currently are not influenced by + matches set with <function>sd_journal_add_match()</function> but + this might change in a later version of this software.</para> + + <para>To enumerate all field names currently in use (and thus all suitable field parameters for + <function>sd_journal_query_unique()</function>), use the + <citerefentry><refentrytitle>sd_journal_enumerate_fields</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para><function>sd_journal_query_unique()</function> returns 0 on + success or a negative errno-style error code. + <function>sd_journal_enumerate_unique()</function> returns a + positive integer if the next field data has been read, 0 when no + more fields are known, or a negative errno-style error code. + <function>sd_journal_restart_unique()</function> returns + nothing.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_query_unique()</function>, + <function>sd_journal_enumerate_unique()</function> and + <function>sd_journal_restart_unique()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Use the <function>SD_JOURNAL_FOREACH_UNIQUE</function> macro + to iterate through all values a field of the journal can take. The + following example lists all unit names referenced in the + journal:</para> + + <programlisting>#include <stdio.h> +#include <string.h> +#include <systemd/sd-journal.h> + +int main(int argc, char *argv[]) { + sd_journal *j; + const void *d; + size_t l; + int r; + + r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY); + if (r < 0) { + fprintf(stderr, "Failed to open journal: %s\n", strerror(-r)); + return 1; + } + r = sd_journal_query_unique(j, "_SYSTEMD_UNIT"); + if (r < 0) { + fprintf(stderr, "Failed to query journal: %s\n", strerror(-r)); + return 1; + } + SD_JOURNAL_FOREACH_UNIQUE(j, d, l) + printf("%.*s\n", (int) l, (const char*) d); + sd_journal_close(j); + return 0; +}</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_enumerate_fields</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_add_match</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_seek_head.xml b/src/libsystemd/sd_journal_seek_head.xml new file mode 100644 index 0000000000..d74c2d5bbc --- /dev/null +++ b/src/libsystemd/sd_journal_seek_head.xml @@ -0,0 +1,172 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_seek_head"> + + <refentryinfo> + <title>sd_journal_seek_head</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_seek_head</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_seek_head</refname> + <refname>sd_journal_seek_tail</refname> + <refname>sd_journal_seek_monotonic_usec</refname> + <refname>sd_journal_seek_realtime_usec</refname> + <refname>sd_journal_seek_cursor</refname> + <refpurpose>Seek to a position in the + journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_seek_head</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_seek_tail</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_seek_monotonic_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>sd_id128_t <parameter>boot_id</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_seek_realtime_usec</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>uint64_t <parameter>usec</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_journal_seek_cursor</function></funcdef> + <paramdef>sd_journal *<parameter>j</parameter></paramdef> + <paramdef>const char *<parameter>cursor</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_seek_head()</function> seeks to the + beginning of the journal, i.e. the oldest available entry.</para> + + <para>Similarly, <function>sd_journal_seek_tail()</function> may + be used to seek to the end of the journal, i.e. the most recent + available entry.</para> + + <para><function>sd_journal_seek_monotonic_usec()</function> seeks + to the entry with the specified monotonic timestamp, i.e. + <constant>CLOCK_MONOTONIC</constant>. Since monotonic time + restarts on every reboot a boot ID needs to be specified as + well.</para> + + <para><function>sd_journal_seek_realtime_usec()</function> seeks + to the entry with the specified realtime (wallclock) timestamp, + i.e. <constant>CLOCK_REALTIME</constant>. Note that the realtime + clock is not necessarily monotonic. If a realtime timestamp is + ambiguous, it is not defined which position is sought to.</para> + + <para><function>sd_journal_seek_cursor()</function> seeks to the + entry located at the specified cursor string. For details on + cursors, see + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If no entry matching the specified cursor is found the call will + seek to the next closest entry (in terms of time) instead. To + verify whether the newly selected entry actually matches the + cursor, use + <citerefentry><refentrytitle>sd_journal_test_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>.</para> + + <para>Note that these calls do not actually make any entry the new + current entry, this needs to be done in a separate step with a + subsequent + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + invocation (or a similar call). Only then, entry data may be + retrieved via + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>. + If no entry exists that matches exactly the specified seek + address, the next closest is sought to. If + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry> + is used, the closest following entry will be sought to, if + <citerefentry><refentrytitle>sd_journal_previous</refentrytitle><manvolnum>3</manvolnum></citerefentry> + is used the closest preceding entry is sought to.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The functions return 0 on success or a negative errno-style + error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_seek_head()</function>, + <function>sd_journal_seek_tail()</function>, + <function>sd_journal_seek_monotonic_usec()</function>, + <function>sd_journal_seek_realtime_usec()</function>, + and <function>sd_journal_seek_cursor()</function> + interfaces are available as a shared library, which can + be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_open</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_next</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_data</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_cursor</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_get_realtime_usec</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_journal_stream_fd.xml b/src/libsystemd/sd_journal_stream_fd.xml new file mode 100644 index 0000000000..2ea7731b48 --- /dev/null +++ b/src/libsystemd/sd_journal_stream_fd.xml @@ -0,0 +1,163 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_journal_stream_fd"> + + <refentryinfo> + <title>sd_journal_stream_fd</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_journal_stream_fd</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_journal_stream_fd</refname> + <refpurpose>Create log stream file descriptor to the journal</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-journal.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_journal_stream_fd</function></funcdef> + <paramdef>const char *<parameter>identifier</parameter></paramdef> + <paramdef>int <parameter>priority</parameter></paramdef> + <paramdef>int <parameter>level_prefix</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_journal_stream_fd()</function> may be used to + create a log stream file descriptor. Log messages written to this + file descriptor as simple newline-separated text strings are + written to the journal. This file descriptor can be used + internally by applications or be made standard output or standard + error of other processes executed.</para> + + <para><function>sd_journal_stream_fd()</function> takes a short + program identifier string as first argument, which will be written + to the journal as _SYSLOG_IDENTIFIER= field for each log entry + (see + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry> + for more information). The second argument shall be the default + priority level for all messages. The priority level is one of + <constant>LOG_EMERG</constant>, <constant>LOG_ALERT</constant>, + <constant>LOG_CRIT</constant>, <constant>LOG_ERR</constant>, + <constant>LOG_WARNING</constant>, <constant>LOG_NOTICE</constant>, + <constant>LOG_INFO</constant>, <constant>LOG_DEBUG</constant>, as + defined in <filename>syslog.h</filename>, see + <citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for details. The third argument is a boolean: if true kernel-style + log level prefixes (such as <constant>SD_WARNING</constant>) are + interpreted, see + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for more information.</para> + + <para>It is recommended that applications log UTF-8 messages only + with this API, but this is not enforced.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>The call returns a valid write-only file descriptor on + success or a negative errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_journal_stream_fd()</function> interface is + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>Examples</title> + + <para>Creating a log stream suitable for + <citerefentry project='man-pages'><refentrytitle>fprintf</refentrytitle><manvolnum>3</manvolnum></citerefentry>:</para> + + <programlisting>#include <syslog.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <systemd/sd-journal.h> +#include <systemd/sd-daemon.h> + +int main(int argc, char *argv[]) { + int fd; + FILE *log; + fd = sd_journal_stream_fd("test", LOG_INFO, 1); + if (fd < 0) { + fprintf(stderr, "Failed to create stream fd: %s\n", strerror(-fd)); + return 1; + } + log = fdopen(fd, "w"); + if (!log) { + fprintf(stderr, "Failed to create file object: %m\n"); + close(fd); + return 1; + } + fprintf(log, "Hello World!\n"); + fprintf(log, SD_WARNING "This is a warning!\n"); + fclose(log); + return 0; +}</programlisting> + + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-journal</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_journal_print</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>syslog</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry project='man-pages'><refentrytitle>fprintf</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.journal-fields</refentrytitle><manvolnum>7</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_listen_fds.xml b/src/libsystemd/sd_listen_fds.xml new file mode 100644 index 0000000000..93bf8d853f --- /dev/null +++ b/src/libsystemd/sd_listen_fds.xml @@ -0,0 +1,257 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_listen_fds" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_listen_fds</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_listen_fds</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_listen_fds</refname> + <refname>sd_listen_fds_with_names</refname> + <refname>SD_LISTEN_FDS_START</refname> + <refpurpose>Check for file descriptors passed by the system manager</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + + <funcsynopsisinfo>#define SD_LISTEN_FDS_START 3</funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_listen_fds</function></funcdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_listen_fds_with_names</function></funcdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>char*** <parameter>names</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_listen_fds()</function> may be invoked by a + daemon to check for file descriptors passed by the service manager as + part of the socket-based activation logic. It returns the number + of received file descriptors. If no file descriptors have been + received, zero is returned. The first file descriptor may be found + at file descriptor number 3 + (i.e. <constant>SD_LISTEN_FDS_START</constant>), the remaining + descriptors follow at 4, 5, 6, ..., if any.</para> + + <para>If a daemon receives more than one file descriptor, they + will be passed in the same order as configured in the systemd + socket unit file (see + <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details). Nonetheless, it is recommended to verify the correct + socket types before using them. To simplify this checking, the + functions + <citerefentry><refentrytitle>sd_is_fifo</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket_inet</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket_unix</refentrytitle><manvolnum>3</manvolnum></citerefentry> + are provided. In order to maximize flexibility, it is recommended + to make these checks as loose as possible without allowing + incorrect setups. i.e. often, the actual port number a socket is + bound to matters little for the service to work, hence it should + not be verified. On the other hand, whether a socket is a datagram + or stream socket matters a lot for the most common program logics + and should be checked.</para> + + <para>This function call will set the FD_CLOEXEC flag for all + passed file descriptors to avoid further inheritance to children + of the calling process.</para> + + <para>If multiple socket units activate the same service, the order + of the file descriptors passed to its main process is undefined. + If additional file descriptors have been passed to the service + manager using + <citerefentry><refentrytitle>sd_pid_notify_with_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>'s + <literal>FDSTORE=1</literal> messages, these file descriptors are + passed last, in arbitrary order, and with duplicates + removed.</para> + + <para>If the <parameter>unset_environment</parameter> parameter is + non-zero, <function>sd_listen_fds()</function> will unset the + <varname>$LISTEN_FDS</varname>, <varname>$LISTEN_PID</varname> and + <varname>$LISTEN_FDNAMES</varname> environment variables before + returning (regardless of whether the function call itself + succeeded or not). Further calls to + <function>sd_listen_fds()</function> will then return zero, but the + variables are no longer inherited by child processes.</para> + + <para><function>sd_listen_fds_with_names()</function> is like + <function>sd_listen_fds()</function>, but optionally also returns + an array of strings with identification names for the passed file + descriptors, if that is available and the + <parameter>names</parameter> parameter is non-NULL. This + information is read from the <varname>$LISTEN_FDNAMES</varname> + variable, which may contain a colon-separated list of names. For + socket-activated services, these names may be configured with the + <varname>FileDescriptorName=</varname> setting in socket unit + files, see + <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details. For file descriptors pushed into the file descriptor + store (see above), the name is set via the + <varname>FDNAME=</varname> field transmitted via + <function>sd_pid_notify_with_fds()</function>. The primary usecase + for these names are services which accept a variety of file + descriptors which are not recognizable with functions like + <function>sd_is_socket()</function> alone, and thus require + identification via a name. It is recommended to rely on named file + descriptors only if identification via + <function>sd_is_socket()</function> and related calls is not + sufficient. Note that the names used are not unique in any + way. The returned array of strings has as many entries as file + descriptors have been received, plus a final NULL pointer + terminating the array. The caller needs to free the array itself + and each of its elements with libc's <function>free()</function> + call after use. If the <parameter>names</parameter> parameter is + NULL, the call is entirely equivalent to + <function>sd_listen_fds()</function>.</para> + + <para>Under specific conditions, the following automatic file + descriptor names are returned: + + <table> + <title> + <command>Special names</command> + </title> + + <tgroup cols='2'> + <thead> + <row> + <entry>Name</entry> + <entry>Description</entry> + </row> + </thead> + <tbody> + <row> + <entry><literal>unknown</literal></entry> + <entry>The process received no name for the specific file descriptor from the service manager.</entry> + </row> + + <row> + <entry><literal>stored</literal></entry> + <entry>The file descriptor originates in the service manager's per-service file descriptor store, and the <varname>FDNAME=</varname> field was absent when the file descriptor was submitted to the service manager.</entry> + </row> + + <row> + <entry><literal>connection</literal></entry> + <entry>The service was activated in per-connection style using <varname>Accept=yes</varname> in the socket unit file, and the file descriptor is the connection socket.</entry> + </row> + </tbody> + </tgroup> + </table> + </para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, these calls returns a negative errno-style error + code. If + <varname>$LISTEN_FDS</varname>/<varname>$LISTEN_PID</varname> was + not set or was not correctly set for this daemon and hence no file + descriptors were received, 0 is returned. Otherwise, the number of + file descriptors passed is returned. The application may find them + starting with file descriptor SD_LISTEN_FDS_START, i.e. file + descriptor 3.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <xi:include href="libsystemd-pkgconfig.xml" xpointer="pkgconfig-text"/> + + <para>Internally, <function>sd_listen_fds()</function> checks + whether the <varname>$LISTEN_PID</varname> environment variable + equals the daemon PID. If not, it returns immediately. Otherwise, + it parses the number passed in the <varname>$LISTEN_FDS</varname> + environment variable, then sets the FD_CLOEXEC flag for the parsed + number of file descriptors starting from SD_LISTEN_FDS_START. + Finally, it returns the parsed + number. <function>sd_listen_fds_with_names()</function> does the + same but also parses <varname>$LISTEN_FDNAMES</varname> if + set.</para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist class='environment-variables'> + <varlistentry> + <term><varname>$LISTEN_PID</varname></term> + <term><varname>$LISTEN_FDS</varname></term> + <term><varname>$LISTEN_FDNAMES</varname></term> + + <listitem><para>Set by the service manager for supervised + processes that use socket-based activation. This environment + variable specifies the data + <function>sd_listen_fds()</function> and + <function>sd_listen_fds_with_names()</function> parses. See + above for details.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_fifo</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket_inet</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_is_socket_unix</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_pid_notify_with_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_login_monitor_new.xml b/src/libsystemd/sd_login_monitor_new.xml new file mode 100644 index 0000000000..5625ab9207 --- /dev/null +++ b/src/libsystemd/sd_login_monitor_new.xml @@ -0,0 +1,287 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_login_monitor_new" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_login_monitor_new</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_login_monitor_new</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_login_monitor_new</refname> + <refname>sd_login_monitor_unref</refname> + <refname>sd_login_monitor_unrefp</refname> + <refname>sd_login_monitor_flush</refname> + <refname>sd_login_monitor_get_fd</refname> + <refname>sd_login_monitor_get_events</refname> + <refname>sd_login_monitor_get_timeout</refname> + <refname>sd_login_monitor</refname> + <refpurpose>Monitor login sessions, seats, users and virtual machines/containers</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_login_monitor_new</function></funcdef> + <paramdef>const char *<parameter>category</parameter></paramdef> + <paramdef>sd_login_monitor **<parameter>ret</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>sd_login_monitor *<function>sd_login_monitor_unref</function></funcdef> + <paramdef>sd_login_monitor *<parameter>m</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>void <function>sd_login_monitor_unrefp</function></funcdef> + <paramdef>sd_login_monitor **<parameter>m</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_login_monitor_flush</function></funcdef> + <paramdef>sd_login_monitor *<parameter>m</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_login_monitor_get_fd</function></funcdef> + <paramdef>sd_login_monitor *<parameter>m</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_login_monitor_get_events</function></funcdef> + <paramdef>sd_login_monitor *<parameter>m</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_login_monitor_get_timeout</function></funcdef> + <paramdef>sd_login_monitor *<parameter>m</parameter></paramdef> + <paramdef>uint64_t *<parameter>timeout_usec</parameter></paramdef> + </funcprototype> + + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_login_monitor_new()</function> may be used to + monitor login sessions, users, seats, and virtual + machines/containers. Via a monitor object a file descriptor can be + integrated into an application defined event loop which is woken + up each time a user logs in, logs out or a seat is added or + removed, or a session, user, seat or virtual machine/container + changes state otherwise. The first parameter takes a string which + can be <literal>seat</literal> (to get only notifications about + seats being added, removed or changed), <literal>session</literal> + (to get only notifications about sessions being created or removed + or changed), <literal>uid</literal> (to get only notifications + when a user changes state in respect to logins) or + <literal>machine</literal> (to get only notifications when a + virtual machine or container is started or stopped). If + notifications shall be generated in all these conditions, + <constant>NULL</constant> may be passed. Note that in the future + additional categories may be defined. The second parameter returns + a monitor object and needs to be freed with the + <function>sd_login_monitor_unref()</function> call after + use.</para> + + <para><function>sd_login_monitor_unref()</function> may be used to + destroy a monitor object. Note that this will invalidate any file + descriptor returned by + <function>sd_login_monitor_get_fd()</function>.</para> + + <para><function>sd_login_monitor_unrefp()</function> is similar to + <function>sd_login_monitor_unref()</function> but takes a pointer + to a pointer to an <type>sd_login_monitor</type> object. This call + is useful in conjunction with GCC's and LLVM's <ulink + url="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html">Clean-up + Variable Attribute</ulink>. Note that this function is defined as + inline function. Use a declaration like the following, in order to + allocate a login monitor object that is freed automatically as the + code block is left:</para> + + <programlisting>{ + __attribute__((cleanup(sd_login_monitor_unrefp)) sd_login_monitor *m = NULL; + int r; + … + r = sd_login_monitor_default(&m); + if (r < 0) + fprintf(stderr, "Failed to allocate login monitor object: %s\n", strerror(-r)); + … +}</programlisting> + + <para><function>sd_login_monitor_flush()</function> may be used to + reset the wakeup state of the monitor object. Whenever an event + causes the monitor to wake up the event loop via the file + descriptor this function needs to be called to reset the wake-up + state. If this call is not invoked, the file descriptor will + immediately wake up the event loop again.</para> + + <para><function>sd_login_monitor_unref()</function> and + <function>sd_login_monitor_unrefp()</function> execute no + operation if the passed in monitor object is + <constant>NULL</constant>.</para> + + <para><function>sd_login_monitor_get_fd()</function> may be used + to retrieve the file descriptor of the monitor object that may be + integrated in an application defined event loop, based around + <citerefentry><refentrytitle>poll</refentrytitle><manvolnum>2</manvolnum></citerefentry> + or a similar interface. The application should include the + returned file descriptor as wake-up source for the events mask + returned by <function>sd_login_monitor_get_events()</function>. It + should pass a timeout value as returned by + <function>sd_login_monitor_get_timeout()</function>. Whenever a + wake-up is triggered the file descriptor needs to be reset via + <function>sd_login_monitor_flush()</function>. An application + needs to reread the login state with a function like + <citerefentry><refentrytitle>sd_get_seats</refentrytitle><manvolnum>3</manvolnum></citerefentry> + or similar to determine what changed.</para> + + <para><function>sd_login_monitor_get_events()</function> will + return the <function>poll()</function> mask to wait for. This + function will return a combination of <constant>POLLIN</constant>, + <constant>POLLOUT</constant> and similar to fill into the + <literal>.events</literal> field of <varname>struct + pollfd</varname>.</para> + + <para><function>sd_login_monitor_get_timeout()</function> will + return a timeout value for usage in <function>poll()</function>. + This returns a value in microseconds since the epoch of + <constant>CLOCK_MONOTONIC</constant> for timing out + <function>poll()</function> in <varname>timeout_usec</varname>. + See + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + for details about <constant>CLOCK_MONOTONIC</constant>. If there + is no timeout to wait for this will fill in <constant>(uint64_t) + -1</constant> instead. Note that <function>poll()</function> takes + a relative timeout in milliseconds rather than an absolute timeout + in microseconds. To convert the absolute 'µs' timeout into + relative 'ms', use code like the following:</para> + + <programlisting>uint64_t t; +int msec; +sd_login_monitor_get_timeout(m, &t); +if (t == (uint64_t) -1) + msec = -1; +else { + struct timespec ts; + uint64_t n; + clock_getttime(CLOCK_MONOTONIC, &ts); + n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; + msec = t > n ? (int) ((t - n + 999) / 1000) : 0; +}</programlisting> + + <para>The code above does not do any error checking for brevity's + sake. The calculated <varname>msec</varname> integer can be passed + directly as <function>poll()</function>'s timeout + parameter.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, + <function>sd_login_monitor_new()</function>, + <function>sd_login_monitor_flush()</function> and + <function>sd_login_monitor_get_timeout()</function> + return 0 or a positive integer. On success, + <function>sd_login_monitor_get_fd()</function> returns + a Unix file descriptor. On success, + <function>sd_login_monitor_get_events()</function> + returns a combination of <constant>POLLIN</constant>, + <constant>POLLOUT</constant> and suchlike. On failure, + these calls return a negative errno-style error + code.</para> + + <para><function>sd_login_monitor_unref()</function> + always returns <constant>NULL</constant>.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted). The specified category to + watch is not known.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_login_monitor_new()</function>, + <function>sd_login_monitor_unref()</function>, + <function>sd_login_monitor_flush()</function>, + <function>sd_login_monitor_get_fd()</function>, + <function>sd_login_monitor_get_events()</function> and + <function>sd_login_monitor_get_timeout()</function> + interfaces are available as a shared library, which can be + compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_get_seats</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>poll</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry><refentrytitle>clock_gettime</refentrytitle><manvolnum>2</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_machine_get_class.xml b/src/libsystemd/sd_machine_get_class.xml new file mode 100644 index 0000000000..ef604139da --- /dev/null +++ b/src/libsystemd/sd_machine_get_class.xml @@ -0,0 +1,152 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_machine_get_class"> + + <refentryinfo> + <title>sd_machine_get_class</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_machine_get_class</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_machine_get_class</refname> + <refname>sd_machine_get_ifindices</refname> + <refpurpose>Determine the class and network interface indices of a + locally running virtual machine or container.</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_machine_get_class</function></funcdef> + <paramdef>const char* <parameter>machine</parameter></paramdef> + <paramdef>char **<parameter>class</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_machine_get_ifindices</function></funcdef> + <paramdef>const char* <parameter>machine</parameter></paramdef> + <paramdef>int **<parameter>ifindices</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_machine_get_class()</function> may be used to + determine the class of a locally running virtual machine or + container that is registered with + <citerefentry><refentrytitle>systemd-machined.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>. + The string returned is either <literal>vm</literal> or + <literal>container</literal>. The returned string needs to be + freed with the libc <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_machine_get_ifindices()</function> may be used + to determine the numeric indices of the network interfaces on the + host that are pointing towards the specified locally running + virtual machine or container that is registered with + <citerefentry><refentrytitle>systemd-machined.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>. + The returned array needs to be freed with the libc <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>The specified machine does not exist or is currently not running.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_machine_get_class()</function> and + <function>sd_machine_get_ifindices()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd-machined.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_pid_get_machine_name</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_notify.xml b/src/libsystemd/sd_notify.xml new file mode 100644 index 0000000000..025fbec6c1 --- /dev/null +++ b/src/libsystemd/sd_notify.xml @@ -0,0 +1,408 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_notify" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_notify</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_notify</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_notify</refname> + <refname>sd_notifyf</refname> + <refname>sd_pid_notify</refname> + <refname>sd_pid_notifyf</refname> + <refname>sd_pid_notify_with_fds</refname> + <refpurpose>Notify service manager about start-up completion and other service status changes</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_notify</function></funcdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>const char *<parameter>state</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_notifyf</function></funcdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_notify</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>const char *<parameter>state</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_notifyf</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>const char *<parameter>format</parameter></paramdef> + <paramdef>...</paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_notify_with_fds</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>const char *<parameter>state</parameter></paramdef> + <paramdef>const int *<parameter>fds</parameter></paramdef> + <paramdef>unsigned <parameter>n_fds</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para><function>sd_notify()</function> may be called by a service + to notify the service manager about state changes. It can be used + to send arbitrary information, encoded in an + environment-block-like string. Most importantly, it can be used for + start-up completion notification.</para> + + <para>If the <parameter>unset_environment</parameter> parameter is + non-zero, <function>sd_notify()</function> will unset the + <varname>$NOTIFY_SOCKET</varname> environment variable before + returning (regardless of whether the function call itself + succeeded or not). Further calls to + <function>sd_notify()</function> will then fail, but the variable + is no longer inherited by child processes.</para> + + <para>The <parameter>state</parameter> parameter should contain a + newline-separated list of variable assignments, similar in style + to an environment block. A trailing newline is implied if none is + specified. The string may contain any kind of variable + assignments, but the following shall be considered + well-known:</para> + + <variablelist> + <varlistentry> + <term>READY=1</term> + + <listitem><para>Tells the service manager that service startup + is finished. This is only used by systemd if the service + definition file has Type=notify set. Since there is little + value in signaling non-readiness, the only value services + should send is <literal>READY=1</literal> (i.e. + <literal>READY=0</literal> is not defined).</para></listitem> + </varlistentry> + + <varlistentry> + <term>RELOADING=1</term> + + <listitem><para>Tells the service manager that the service is + reloading its configuration. This is useful to allow the + service manager to track the service's internal state, and + present it to the user. Note that a service that sends this + notification must also send a <literal>READY=1</literal> + notification when it completed reloading its + configuration.</para></listitem> + </varlistentry> + + <varlistentry> + <term>STOPPING=1</term> + + <listitem><para>Tells the service manager that the service is + beginning its shutdown. This is useful to allow the service + manager to track the service's internal state, and present it + to the user.</para></listitem> + </varlistentry> + + <varlistentry> + <term>STATUS=...</term> + + <listitem><para>Passes a single-line UTF-8 status string back + to the service manager that describes the service state. This + is free-form and can be used for various purposes: general + state feedback, fsck-like programs could pass completion + percentages and failing programs could pass a human-readable + error message. Example: <literal>STATUS=Completed 66% of file + system check...</literal></para></listitem> + </varlistentry> + + <varlistentry> + <term>ERRNO=...</term> + + <listitem><para>If a service fails, the errno-style error + code, formatted as string. Example: <literal>ERRNO=2</literal> + for ENOENT.</para></listitem> + </varlistentry> + + <varlistentry> + <term>BUSERROR=...</term> + + <listitem><para>If a service fails, the D-Bus error-style + error code. Example: + <literal>BUSERROR=org.freedesktop.DBus.Error.TimedOut</literal></para></listitem> + </varlistentry> + + <varlistentry> + <term>MAINPID=...</term> + + <listitem><para>The main process ID (PID) of the service, in + case the service manager did not fork off the process itself. + Example: <literal>MAINPID=4711</literal></para></listitem> + </varlistentry> + + <varlistentry> + <term>WATCHDOG=1</term> + + <listitem><para>Tells the service manager to update the + watchdog timestamp. This is the keep-alive ping that services + need to issue in regular intervals if + <varname>WatchdogSec=</varname> is enabled for it. See + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for information how to enable this functionality and + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry> + for the details of how the service can check whether the + watchdog is enabled. </para></listitem> + </varlistentry> + + + <varlistentry> + <term>FDSTORE=1</term> + + <listitem><para>Stores additional file descriptors in the + service manager. File descriptors sent this way will be + maintained per-service by the service manager and be passed + again using the usual file descriptor passing logic on the + next invocation of the service (see + <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>). + This is useful for implementing service restart schemes where + services serialize their state to <filename>/run</filename>, + push their file descriptors to the system manager, and are + then restarted, retrieving their state again via socket + passing and <filename>/run</filename>. Note that the service + manager will accept messages for a service only if + <varname>FileDescriptorStoreMax=</varname> is set to non-zero + for it (defaults to zero). See + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details. Multiple arrays of file descriptors may be sent + in separate messages, in which case the arrays are combined. + Note that the service manager removes duplicate file + descriptors before passing them to the service. Use + <function>sd_pid_notify_with_fds()</function> to send messages + with <literal>FDSTORE=1</literal>, see + below.</para></listitem> + </varlistentry> + + <varlistentry> + <term>FDNAME=...</term> + + <listitem><para>When used in combination with + <varname>FDSTORE=1</varname>, specifies a name for the + submitted file descriptors. This name is passed to the service + during activation, and may be queried using + <citerefentry><refentrytitle>sd_listen_fds_with_names</refentrytitle><manvolnum>3</manvolnum></citerefentry>. File + descriptors submitted without this field set, will implicitly + get the name <literal>stored</literal> assigned. Note that, if + multiple file descriptors are submitted at once, the specified + name will be assigned to all of them. In order to assign + different names to submitted file descriptors, submit them in + separate invocations of + <function>sd_pid_notify_with_fds()</function>. The name may + consist of any ASCII character, but must not contain control + characters or <literal>:</literal>. It may not be longer than + 255 characters. If a submitted name does not follow these + restrictions, it is ignored.</para></listitem> + </varlistentry> + + <varlistentry> + <term>WATCHDOG_USEC=...</term> + + <listitem><para>Reset <varname>watchdog_usec</varname> value during runtime. + Notice that this is not available when using <function>sd_event_set_watchdog()</function> + or <function>sd_watchdog_enabled()</function>. + Example : <literal>WATCHDOG_USEC=20000000</literal></para></listitem> + </varlistentry> + + </variablelist> + + <para>It is recommended to prefix variable names that are not + listed above with <varname>X_</varname> to avoid namespace + clashes.</para> + + <para>Note that systemd will accept status data sent from a + service only if the <varname>NotifyAccess=</varname> option is + correctly set in the service definition file. See + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details.</para> + + <para><function>sd_notifyf()</function> is similar to + <function>sd_notify()</function> but takes a + <function>printf()</function>-like format string plus + arguments.</para> + + <para><function>sd_pid_notify()</function> and + <function>sd_pid_notifyf()</function> are similar to + <function>sd_notify()</function> and + <function>sd_notifyf()</function> but take a process ID (PID) to + use as originating PID for the message as first argument. This is + useful to send notification messages on behalf of other processes, + provided the appropriate privileges are available. If the PID + argument is specified as 0, the process ID of the calling process + is used, in which case the calls are fully equivalent to + <function>sd_notify()</function> and + <function>sd_notifyf()</function>.</para> + + <para><function>sd_pid_notify_with_fds()</function> is similar to + <function>sd_pid_notify()</function> but takes an additional array + of file descriptors. These file descriptors are sent along the + notification message to the service manager. This is particularly + useful for sending <literal>FDSTORE=1</literal> messages, as + described above. The additional arguments are a pointer to the + file descriptor array plus the number of file descriptors in the + array. If the number of file descriptors is passed as 0, the call + is fully equivalent to <function>sd_pid_notify()</function>, i.e. + no file descriptors are passed. Note that sending file descriptors + to the service manager on messages that do not expect them (i.e. + without <literal>FDSTORE=1</literal>) they are immediately closed + on reception.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, these calls return a negative errno-style error + code. If <varname>$NOTIFY_SOCKET</varname> was not set and hence + no status data could be sent, 0 is returned. If the status was + sent, these functions return with a positive return value. In + order to support both, init systems that implement this scheme and + those which do not, it is generally recommended to ignore the + return value of this call.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <xi:include href="libsystemd-pkgconfig.xml" xpointer="pkgconfig-text"/> + + <para>These functions send a single datagram with the + state string as payload to the <constant>AF_UNIX</constant> socket + referenced in the <varname>$NOTIFY_SOCKET</varname> environment + variable. If the first character of + <varname>$NOTIFY_SOCKET</varname> is <literal>@</literal>, the + string is understood as Linux abstract namespace socket. The + datagram is accompanied by the process credentials of the sending + service, using SCM_CREDENTIALS.</para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist class='environment-variables'> + <varlistentry> + <term><varname>$NOTIFY_SOCKET</varname></term> + + <listitem><para>Set by the service manager for supervised + processes for status and start-up completion notification. + This environment variable specifies the socket + <function>sd_notify()</function> talks to. See above for + details.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Examples</title> + + <example> + <title>Start-up Notification</title> + + <para>When a service finished starting up, it might issue the + following call to notify the service manager:</para> + + <programlisting>sd_notify(0, "READY=1");</programlisting> + </example> + + <example> + <title>Extended Start-up Notification</title> + + <para>A service could send the following after completing + initialization:</para> + + <programlisting>sd_notifyf(0, "READY=1\n" + "STATUS=Processing requests...\n" + "MAINPID=%lu", + (unsigned long) getpid());</programlisting> + </example> + + <example> + <title>Error Cause Notification</title> + + <para>A service could send the following shortly before exiting, on failure:</para> + + <programlisting>sd_notifyf(0, "STATUS=Failed to start up: %s\n" + "ERRNO=%i", + strerror(errno), + errno);</programlisting> + </example> + + <example> + <title>Store a File Descriptor in the Service Manager</title> + + <para>To store an open file descriptor in the service manager, + in order to continue operation after a service restart without + losing state, use <literal>FDSTORE=1</literal>:</para> + + <programlisting>sd_pid_notify_with_fds(0, 0, "FDSTORE=1\nFDNAME=foobar", &fd, 1);</programlisting> + </example> + </refsect1> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_listen_fds_with_names</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_watchdog_enabled</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_pid_get_session.xml b/src/libsystemd/sd_pid_get_session.xml new file mode 100644 index 0000000000..806cff34e4 --- /dev/null +++ b/src/libsystemd/sd_pid_get_session.xml @@ -0,0 +1,359 @@ +<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_pid_get_session" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_pid_get_session</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_pid_get_session</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_pid_get_session</refname> + <refname>sd_pid_get_unit</refname> + <refname>sd_pid_get_user_unit</refname> + <refname>sd_pid_get_owner_uid</refname> + <refname>sd_pid_get_machine_name</refname> + <refname>sd_pid_get_slice</refname> + <refname>sd_pid_get_user_slice</refname> + <refname>sd_pid_get_cgroup</refname> + <refname>sd_peer_get_session</refname> + <refname>sd_peer_get_unit</refname> + <refname>sd_peer_get_user_unit</refname> + <refname>sd_peer_get_owner_uid</refname> + <refname>sd_peer_get_machine_name</refname> + <refname>sd_peer_get_slice</refname> + <refname>sd_peer_get_user_slice</refname> + <refname>sd_peer_get_cgroup</refname> + <refpurpose>Determine session, unit, owner of a session, + container/VM or slice of a specific PID or socket + peer</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_pid_get_session</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>session</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_unit</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_user_unit</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_owner_uid</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_machine_name</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>name</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_slice</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_user_slice</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_pid_get_cgroup</function></funcdef> + <paramdef>pid_t <parameter>pid</parameter></paramdef> + <paramdef>char **<parameter>cgroup</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_session</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>session</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_unit</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_user_unit</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>unit</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_owner_uid</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_machine_name</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>name</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_slice</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_user_slice</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>slice</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_peer_get_cgroup</function></funcdef> + <paramdef>int <parameter>fd</parameter></paramdef> + <paramdef>char **<parameter>cgroup</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_pid_get_session()</function> may be used to + determine the login session identifier of a process identified by + the specified process identifier. The session identifier is a + short string, suitable for usage in file system paths. Note that + not all processes are part of a login session (e.g. system service + processes, user processes that are shared between multiple + sessions of the same user, or kernel threads). For processes not + being part of a login session, this function will fail with + -ENODATA. The returned string needs to be freed with the libc + <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_pid_get_unit()</function> may be used to + determine the systemd system unit (i.e. system service or scope + unit) identifier of a process identified by the specified PID. The + unit name is a short string, suitable for usage in file system + paths. Note that not all processes are part of a system + unit/service (e.g. user processes, or kernel threads). For + processes not being part of a systemd system unit, this function + will fail with -ENODATA. (More specifically, this call will not + work for kernel threads.) The returned string needs to be freed + with the libc <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_pid_get_user_unit()</function> may be used to + determine the systemd user unit (i.e. user service or scope unit) + identifier of a process identified by the specified PID. This is + similar to <function>sd_pid_get_unit()</function>, but applies to + user units instead of system units.</para> + + <para><function>sd_pid_get_owner_uid()</function> may be used to + determine the Unix UID (user identifier) of the owner of the + session of a process identified the specified PID. Note that this + function will succeed for user processes which are shared between + multiple login sessions of the same user, whereas + <function>sd_pid_get_session()</function> will fail. For processes + not being part of a login session and not being a shared process + of a user, this function will fail with -ENODATA.</para> + + <para><function>sd_pid_get_machine_name()</function> may be used + to determine the name of the VM or container is a member of. The + machine name is a short string, suitable for usage in file system + paths. The returned string needs to be freed with the libc + <citerefentry + project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use. For processes not part of a VM or containers, this + function fails with -ENODATA.</para> + + <para><function>sd_pid_get_slice()</function> may be used to + determine the slice unit the process is a member of. See + <citerefentry><refentrytitle>systemd.slice</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details about slices. The returned string needs to be freed + with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para>Similarly, <function>sd_pid_get_user_slice()</function> + returns the user slice (as managed by the user's systemd instance) + of a process.</para> + + <para><function>sd_pid_get_cgroup()</function> returns the control + group path of the specified process, relative to the root of the + hierarchy. Returns the path without trailing slash, except for + processes located in the root control group, where "/" is + returned. To find the actual control group path in the file system, + the returned path needs to be prefixed with + <filename>/sys/fs/cgroup/</filename> (if the unified control group + setup is used), or + <filename>/sys/fs/cgroup/<replaceable>HIERARCHY</replaceable>/</filename> + (if the legacy multi-hierarchy control group setup is used).</para> + + <para>If the <varname>pid</varname> parameter of any of these + functions is passed as 0, the operation is executed for the + calling process.</para> + + <para>The <function>sd_peer_get_session()</function>, + <function>sd_peer_get_unit()</function>, + <function>sd_peer_get_user_unit()</function>, + <function>sd_peer_get_owner_uid()</function>, + <function>sd_peer_get_machine_name()</function>, + <function>sd_peer_get_slice()</function>, + <function>sd_peer_get_user_slice()</function> and + <function>sd_peer_get_cgroup()</function> calls operate similar to + their PID counterparts, but operate on a connected AF_UNIX socket + and retrieve information about the connected peer process. Note + that these fields are retrieved via <filename>/proc</filename>, + and hence are not suitable for authorization purposes, as they are + subject to races.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, these calls return 0 or a positive integer. On + failure, these calls return a negative errno-style error + code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ESRCH</constant></term> + + <listitem><para>The specified PID does not refer to a running + process.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-BADF</constant></term> + + <listitem><para>The specified socket file descriptor was + invalid.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The given field is not specified for the described + process or peer.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_pid_get_session()</function>, + <function>sd_pid_get_unit()</function>, + <function>sd_pid_get_user_unit()</function>, + <function>sd_pid_get_owner_uid()</function>, + <function>sd_pid_get_machine_name()</function>, + <function>sd_pid_get_slice()</function>, + <function>sd_pid_get_user_slice()</function>, + <function>sd_peer_get_session()</function>, + <function>sd_peer_get_unit()</function>, + <function>sd_peer_get_user_unit()</function>, + <function>sd_peer_get_owner_uid()</function>, + <function>sd_peer_get_machine_name()</function>, + <function>sd_peer_get_slice()</function> and + <function>sd_peer_get_user_slice()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the <constant>libsystemd</constant> <citerefentry + project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + + <para>Note that the login session identifier as + returned by <function>sd_pid_get_session()</function> + is completely unrelated to the process session + identifier as returned by + <citerefentry><refentrytitle>getsid</refentrytitle><manvolnum>2</manvolnum></citerefentry>.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_session_is_active</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>getsid</refentrytitle><manvolnum>2</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.slice</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd-machined.service</refentrytitle><manvolnum>8</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_seat_get_active.xml b/src/libsystemd/sd_seat_get_active.xml new file mode 100644 index 0000000000..c5e6ddab02 --- /dev/null +++ b/src/libsystemd/sd_seat_get_active.xml @@ -0,0 +1,212 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_seat_get_active" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_seat_get_active</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_seat_get_active</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_seat_get_active</refname> + <refname>sd_seat_get_sessions</refname> + <refname>sd_seat_can_multi_session</refname> + <refname>sd_seat_can_tty</refname> + <refname>sd_seat_can_graphical</refname> + <refpurpose>Determine state of a specific seat</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_seat_get_active</function></funcdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + <paramdef>char **<parameter>session</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_seat_get_sessions</function></funcdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + <paramdef>char ***<parameter>sessions</parameter></paramdef> + <paramdef>uid_t **<parameter>uid</parameter></paramdef> + <paramdef>unsigned int *<parameter>n_uids</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_seat_can_multi_session</function></funcdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_seat_can_tty</function></funcdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_seat_can_graphical</function></funcdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_seat_get_active()</function> may be used to + determine which session is currently active on a seat, if there is + any. Returns the session identifier and the user identifier of the + Unix user the session is belonging to. Either the session or the + user identifier parameter can be passed <constant>NULL</constant>, + in case only one of the parameters shall be queried. The returned + string needs to be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_seat_get_sessions()</function> may be used to + determine all sessions on the specified seat. Returns two arrays, + one (<constant>NULL</constant> terminated) with the session + identifiers of the sessions and one with the user identifiers of + the Unix users the sessions belong to. An additional parameter may + be used to return the number of entries in the latter array. The + two arrays and the latter parameter may be passed as + <constant>NULL</constant> in case these values need not to be + determined. The arrays and the strings referenced by them need to + be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use. Note that instead of an empty array + <constant>NULL</constant> may be returned and should be considered + equivalent to an empty array.</para> + + <para><function>sd_seat_can_multi_session()</function> may be used + to determine whether a specific seat is capable of multi-session, + i.e. allows multiple login sessions in parallel (with only one + being active at a time).</para> + + <para><function>sd_seat_can_tty()</function> may be used to + determine whether a specific seat provides TTY functionality, i.e. + is useful as a text console.</para> + + <para><function>sd_seat_can_graphical()</function> may be used to + determine whether a specific seat provides graphics functionality, + i.e. is useful as a graphics display.</para> + + <para>If the <varname>seat</varname> parameter of any of these + functions is passed as <constant>NULL</constant>, the operation is + executed for the seat of the session of the calling process, if + there is any.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para> On success, <function>sd_seat_get_active()</function> + returns 0 or a positive integer. On success, + <function>sd_seat_get_sessions()</function> returns the number of + entries in the session identifier array. If the test succeeds, + <function>sd_seat_can_multi_session</function>, + <function>sd_seat_can_tty</function> and + <function>sd_seat_can_graphical</function> return a positive + integer, if it fails 0. On failure, these calls return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The given field is not specified for the described + seat.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>The specified seat is unknown.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_seat_get_active()</function>, + <function>sd_seat_get_sessions()</function>, + <function>sd_seat_can_multi_session()</function>, + <function>sd_seat_can_tty()</function> and + <function>sd_seat_can_graphical()</function> interfaces are + available as a shared library, which can be compiled and linked to + with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_session_get_seat</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_session_is_active.xml b/src/libsystemd/sd_session_is_active.xml new file mode 100644 index 0000000000..a6076b177a --- /dev/null +++ b/src/libsystemd/sd_session_is_active.xml @@ -0,0 +1,359 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_session_is_active" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_session_is_active</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_session_is_active</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_session_is_active</refname> + <refname>sd_session_is_remote</refname> + <refname>sd_session_get_state</refname> + <refname>sd_session_get_uid</refname> + <refname>sd_session_get_seat</refname> + <refname>sd_session_get_service</refname> + <refname>sd_session_get_type</refname> + <refname>sd_session_get_class</refname> + <refname>sd_session_get_desktop</refname> + <refname>sd_session_get_display</refname> + <refname>sd_session_get_tty</refname> + <refname>sd_session_get_vt</refname> + <refname>sd_session_get_remote_host</refname> + <refname>sd_session_get_remote_user</refname> + <refpurpose>Determine state of a specific session</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_session_is_active</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_is_remote</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_state</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>state</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_uid</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>uid_t *<parameter>uid</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_seat</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>seat</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_service</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>service</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_type</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>type</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_class</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>class</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_desktop</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>desktop</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_display</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>display</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_remote_host</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>remote_host</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_remote_user</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>remote_user</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_tty</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>char **<parameter>tty</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_session_get_vt</function></funcdef> + <paramdef>const char *<parameter>session</parameter></paramdef> + <paramdef>unsigned int *<parameter>vt</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_session_is_active()</function> may be used to + determine whether the session identified by the specified session + identifier is currently active (i.e. currently in the foreground + and available for user input) or not.</para> + + <para><function>sd_session_is_remote()</function> may be used to + determine whether the session identified by the specified session + identifier is a remote session (i.e. its remote host is known) or + not.</para> + + <para><function>sd_session_get_state()</function> may be used to + determine the state of the session identified by the specified + session identifier. The following states are currently known: + <literal>online</literal> (session logged in, but session not + active, i.e. not in the foreground), <literal>active</literal> + (session logged in and active, i.e. in the foreground), + <literal>closing</literal> (session nominally logged out, but some + processes belonging to it are still around). In the future + additional states might be defined, client code should be written + to be robust in regards to additional state strings being + returned. This function is a more generic version of + <function>sd_session_is_active()</function>. The returned string + needs to be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_uid()</function> may be used to + determine the user identifier of the Unix user the session + identified by the specified session identifier belongs to.</para> + + <para><function>sd_session_get_seat()</function> may be used to + determine the seat identifier of the seat the session identified + by the specified session identifier belongs to. Note that not all + sessions are attached to a seat, this call will fail for them. The + returned string needs to be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_service()</function> may be used to + determine the name of the service (as passed during PAM session + setup) that registered the session identified by the specified + session identifier. The returned string needs to be freed with the + libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_type()</function> may be used to + determine the type of the session identified by the specified + session identifier. The returned string is one of + <literal>x11</literal>, <literal>wayland</literal>, + <literal>tty</literal>, <literal>mir</literal> or + <literal>unspecified</literal> and needs to be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_class()</function> may be used to + determine the class of the session identified by the specified + session identifier. The returned string is one of + <literal>user</literal>, <literal>greeter</literal>, + <literal>lock-screen</literal>, or <literal>background</literal> + and needs to be freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_desktop()</function> may be used to + determine the brand of the desktop running on the session + identified by the specified session identifier. This field can be + set freely by desktop environments and does not follow any special + formatting. However, desktops are strongly recommended to use the + same identifiers and capitalization as for + <varname>$XDG_CURRENT_DESKTOP</varname>, as defined by the <ulink + url="http://standards.freedesktop.org/desktop-entry-spec/latest/">Desktop + Entry Specification</ulink>. The returned string needs to be freed + with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_display()</function> may be used to + determine the X11 display of the session identified by the + specified session identifier. The returned string needs to be + freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_remote_host()</function> may be + used to determine the remote hostname of the session identified by + the specified session identifier. The returned string needs to be + freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_remote_user()</function> may be + used to determine the remote username of the session identified by + the specified session identifier. The returned string needs to be + freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use. Note that this value is rarely known to the + system, and even then should not be relied on.</para> + + <para><function>sd_session_get_tty()</function> may be used to + determine the TTY device of the session identified by the + specified session identifier. The returned string needs to be + freed with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_session_get_vt()</function> may be used to + determine the VT number of the session identified by the specified + session identifier. This function will return an error if the seat + does not support VTs.</para> + + <para>If the <varname>session</varname> parameter of any of these + functions is passed as <constant>NULL</constant>, the operation is + executed for the session the calling process is a member of, if + there is any.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>If the test succeeds, + <function>sd_session_is_active()</function> and + <function>sd_session_is_remote()</function> return a + positive integer; if it fails, 0. On success, + <function>sd_session_get_state()</function>, + <function>sd_session_get_uid()</function>, + <function>sd_session_get_seat()</function>, + <function>sd_session_get_service()</function>, + <function>sd_session_get_type()</function>, + <function>sd_session_get_class()</function>, + <function>sd_session_get_display()</function>, + <function>sd_session_get_remote_user()</function>, + <function>sd_session_get_remote_host()</function> and + <function>sd_session_get_tty()</function> return 0 or + a positive integer. On failure, these calls return a + negative errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>The specified session does not exist.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The given field is not specified for the described + session.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted).</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>The <function>sd_session_is_active()</function>, + <function>sd_session_get_state()</function>, + <function>sd_session_get_uid()</function>, + <function>sd_session_get_seat()</function>, + <function>sd_session_get_service()</function>, + <function>sd_session_get_type()</function>, + <function>sd_session_get_class()</function>, + <function>sd_session_get_display()</function>, + <function>sd_session_get_remote_host()</function>, + <function>sd_session_get_remote_user()</function> and + <function>sd_session_get_tty()</function> + interfaces are available as a shared library, which can + be compiled and linked to with the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + file.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_pid_get_session</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_uid_get_state.xml b/src/libsystemd/sd_uid_get_state.xml new file mode 100644 index 0000000000..130af761da --- /dev/null +++ b/src/libsystemd/sd_uid_get_state.xml @@ -0,0 +1,230 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_uid_get_state" conditional='HAVE_PAM'> + + <refentryinfo> + <title>sd_uid_get_state</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_uid_get_state</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_uid_get_state</refname> + <refname>sd_uid_is_on_seat</refname> + <refname>sd_uid_get_sessions</refname> + <refname>sd_uid_get_seats</refname> + <refname>sd_uid_get_display</refname> + <refpurpose>Determine login state of a specific Unix user ID</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-login.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_uid_get_state</function></funcdef> + <paramdef>uid_t <parameter>uid</parameter></paramdef> + <paramdef>char **<parameter>state</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_uid_is_on_seat</function></funcdef> + <paramdef>uid_t <parameter>uid</parameter></paramdef> + <paramdef>int <parameter>require_active</parameter></paramdef> + <paramdef>const char *<parameter>seat</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_uid_get_sessions</function></funcdef> + <paramdef>uid_t <parameter>uid</parameter></paramdef> + <paramdef>int <parameter>require_active</parameter></paramdef> + <paramdef>char ***<parameter>sessions</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_uid_get_seats</function></funcdef> + <paramdef>uid_t <parameter>uid</parameter></paramdef> + <paramdef>int <parameter>require_active</parameter></paramdef> + <paramdef>char ***<parameter>seats</parameter></paramdef> + </funcprototype> + + <funcprototype> + <funcdef>int <function>sd_uid_get_display</function></funcdef> + <paramdef>uid_t <parameter>uid</parameter></paramdef> + <paramdef>char **<parameter>session</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + + <para><function>sd_uid_get_state()</function> may be used to + determine the login state of a specific Unix user identifier. The + following states are currently known: <literal>offline</literal> + (user not logged in at all), <literal>lingering</literal> (user + not logged in, but some user services running), + <literal>online</literal> (user logged in, but not active, i.e. + has no session in the foreground), <literal>active</literal> (user + logged in, and has at least one active session, i.e. one session + in the foreground), <literal>closing</literal> (user not logged + in, and not lingering, but some processes are still around). In + the future additional states might be defined, client code should + be written to be robust in regards to additional state strings + being returned. The returned string needs to be freed with the + libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use.</para> + + <para><function>sd_uid_is_on_seat()</function> may be used to + determine whether a specific user is logged in or active on a + specific seat. Accepts a Unix user identifier and a seat + identifier string as parameters. The + <parameter>require_active</parameter> parameter is a boolean + value. If non-zero (true), this function will test if the user is + active (i.e. has a session that is in the foreground and accepting + user input) on the specified seat, otherwise (false) only if the + user is logged in (and possibly inactive) on the specified + seat.</para> + + <para><function>sd_uid_get_sessions()</function> may be used to + determine the current sessions of the specified user. Accepts a + Unix user identifier as parameter. The + <parameter>require_active</parameter> parameter controls whether + the returned list shall consist of only those sessions where the + user is currently active (> 0), where the user is currently + online but possibly inactive (= 0), or logged in at all but + possibly closing the session (< 0). The call returns a + <constant>NULL</constant> terminated string array of session + identifiers in <parameter>sessions</parameter> which needs to be + freed by the caller with the libc + <citerefentry project='man-pages'><refentrytitle>free</refentrytitle><manvolnum>3</manvolnum></citerefentry> + call after use, including all the strings referenced. If the + string array parameter is passed as <constant>NULL</constant>, the + array will not be filled in, but the return code still indicates + the number of current sessions. Note that instead of an empty + array <constant>NULL</constant> may be returned and should be + considered equivalent to an empty array.</para> + + <para>Similarly, <function>sd_uid_get_seats()</function> may be + used to determine the list of seats on which the user currently + has sessions. Similar semantics apply, however note that the user + may have multiple sessions on the same seat as well as sessions + with no attached seat and hence the number of entries in the + returned array may differ from the one returned by + <function>sd_uid_get_sessions()</function>.</para> + + <para><function>sd_uid_get_display()</function> returns the name + of the "primary" session of a user. If the user has graphical + sessions, it will be the oldest graphical session. Otherwise, it + will be the oldest open session.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On success, <function>sd_uid_get_state()</function> returns + 0 or a positive integer. If the test succeeds, + <function>sd_uid_is_on_seat()</function> returns a positive + integer; if it fails, 0. + <function>sd_uid_get_sessions()</function> and + <function>sd_uid_get_seats()</function> return the number of + entries in the returned arrays. + <function>sd_uid_get_display()</function> returns a non-negative + code on success. On failure, these calls return a negative + errno-style error code.</para> + </refsect1> + + <refsect1> + <title>Errors</title> + + <para>Returned errors may indicate the following problems:</para> + + <variablelist> + + <varlistentry> + <term><constant>-ENODATA</constant></term> + + <listitem><para>The given field is not specified for the described + user.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENXIO</constant></term> + + <listitem><para>The specified seat is unknown.</para> + </listitem> + </varlistentry> + + <varlistentry> + <term><constant>-EINVAL</constant></term> + + <listitem><para>An input parameter was invalid (out of range, + or NULL, where that is not accepted). This is also returned if + the passed user ID is 0xFFFF or 0xFFFFFFFF, which are + undefined on Linux.</para></listitem> + </varlistentry> + + <varlistentry> + <term><constant>-ENOMEM</constant></term> + + <listitem><para>Memory allocation failed.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>Notes</title> + + <para>Functions described here are available as a shared library, + and can be compiled and linked to using the + <constant>libsystemd</constant> <citerefentry project='die-net'><refentrytitle>pkg-config</refentrytitle><manvolnum>1</manvolnum></citerefentry> + entry.</para> + </refsect1> + + <refsect1> + <title>See Also</title> + + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-login</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_pid_get_owner_uid</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/sd_watchdog_enabled.xml b/src/libsystemd/sd_watchdog_enabled.xml new file mode 100644 index 0000000000..3de9899453 --- /dev/null +++ b/src/libsystemd/sd_watchdog_enabled.xml @@ -0,0 +1,169 @@ +<?xml version='1.0'?> <!--*-nxml-*--> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" + "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> + +<!-- + 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 <http://www.gnu.org/licenses/>. +--> + +<refentry id="sd_watchdog_enabled" + xmlns:xi="http://www.w3.org/2001/XInclude"> + + <refentryinfo> + <title>sd_watchdog_enabled</title> + <productname>systemd</productname> + + <authorgroup> + <author> + <contrib>Developer</contrib> + <firstname>Lennart</firstname> + <surname>Poettering</surname> + <email>lennart@poettering.net</email> + </author> + </authorgroup> + </refentryinfo> + + <refmeta> + <refentrytitle>sd_watchdog_enabled</refentrytitle> + <manvolnum>3</manvolnum> + </refmeta> + + <refnamediv> + <refname>sd_watchdog_enabled</refname> + <refpurpose>Check whether the service manager expects watchdog keep-alive notifications from a service</refpurpose> + </refnamediv> + + <refsynopsisdiv> + <funcsynopsis> + <funcsynopsisinfo>#include <systemd/sd-daemon.h></funcsynopsisinfo> + + <funcprototype> + <funcdef>int <function>sd_watchdog_enabled</function></funcdef> + <paramdef>int <parameter>unset_environment</parameter></paramdef> + <paramdef>uint64_t *<parameter>usec</parameter></paramdef> + </funcprototype> + </funcsynopsis> + </refsynopsisdiv> + + <refsect1> + <title>Description</title> + <para><function>sd_watchdog_enabled()</function> may be called by + a service to detect whether the service manager expects regular + keep-alive watchdog notification events from it, and the timeout + after which the manager will act on the service if it did not get + such a notification.</para> + + <para>If the <varname>$WATCHDOG_USEC</varname> environment + variable is set, and the <varname>$WATCHDOG_PID</varname> variable + is unset or set to the PID of the current process, the service + manager expects notifications from this process. The manager will + usually terminate a service when it does not get a notification + message within the specified time after startup and after each + previous message. It is recommended that a daemon sends a + keep-alive notification message to the service manager every half + of the time returned here. Notification messages may be sent with + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry> + with a message string of <literal>WATCHDOG=1</literal>.</para> + + <para>If the <parameter>unset_environment</parameter> parameter is + non-zero, <function>sd_watchdog_enabled()</function> will unset + the <varname>$WATCHDOG_USEC</varname> and + <varname>$WATCHDOG_PID</varname> environment variables before + returning (regardless of whether the function call itself + succeeded or not). Those variables are no longer inherited by + child processes. Further calls to + <function>sd_watchdog_enabled()</function> will also return with + zero.</para> + + <para>If the <parameter>usec</parameter> parameter is non-NULL, + <function>sd_watchdog_enabled()</function> will write the timeout + in µs for the watchdog logic to it.</para> + + <para>To enable service supervision with the watchdog logic, use + <varname>WatchdogSec=</varname> in service files. See + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry> + for details.</para> + + <para>Use + <citerefentry><refentrytitle>sd_event_set_watchdog</refentrytitle><manvolnum>3</manvolnum></citerefentry> + to enable automatic watchdog support in + <citerefentry><refentrytitle>sd-event</refentrytitle><manvolnum>3</manvolnum></citerefentry>-based event loops.</para> + </refsect1> + + <refsect1> + <title>Return Value</title> + + <para>On failure, this call returns a negative errno-style error + code. If the service manager expects watchdog keep-alive + notification messages to be sent, > 0 is returned, otherwise 0 + is returned. Only if the return value is > 0, the + <parameter>usec</parameter> parameter is valid after the + call.</para> + </refsect1> + + <refsect1> + <title>Notes</title> + + <xi:include href="libsystemd-pkgconfig.xml" xpointer="pkgconfig-text"/> + + <para>Internally, this functions parses the + <varname>$WATCHDOG_PID</varname> and + <varname>$WATCHDOG_USEC</varname> environment variable. The call + will ignore these variables if <varname>$WATCHDOG_PID</varname> + does not contain the PID of the current process, under the + assumption that in that case, the variables were set for a + different process further up the process tree.</para> + </refsect1> + + <refsect1> + <title>Environment</title> + + <variablelist class='environment-variables'> + <varlistentry> + <term><varname>$WATCHDOG_PID</varname></term> + + <listitem><para>Set by the system manager for supervised + process for which watchdog support is enabled, and contains + the PID of that process. See above for + details.</para></listitem> + </varlistentry> + + <varlistentry> + <term><varname>$WATCHDOG_USEC</varname></term> + + <listitem><para>Set by the system manager for supervised + process for which watchdog support is enabled, and contains + the watchdog timeout in µs See above for + details.</para></listitem> + </varlistentry> + </variablelist> + </refsect1> + + <refsect1> + <title>See Also</title> + <para> + <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>, + <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>, + <citerefentry><refentrytitle>sd_event_set_watchdog</refentrytitle><manvolnum>3</manvolnum></citerefentry> + </para> + </refsect1> + +</refentry> diff --git a/src/libsystemd/src/Makefile b/src/libsystemd/src/Makefile new file mode 100644 index 0000000000..afcbf8d4e6 --- /dev/null +++ b/src/libsystemd/src/Makefile @@ -0,0 +1,208 @@ +# -*- Mode: makefile; indent-tabs-mode: t -*- +# +# This file is part of systemd. +# +# Copyright 2010-2012 Lennart Poettering +# Copyright 2010-2012 Kay Sievers +# Copyright 2013 Zbigniew Jędrzejewski-Szmek +# Copyright 2013 David Strauss +# Copyright 2016 Luke Shumaker +# +# 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 <http://www.gnu.org/licenses/>. +include $(dir $(lastword $(MAKEFILE_LIST)))/../../../config.mk +include $(topsrcdir)/build-aux/Makefile.head.mk + +libsystemd_internal_la_SOURCES = \ + src/systemd/sd-bus.h \ + src/systemd/sd-bus-protocol.h \ + src/systemd/sd-bus-vtable.h \ + src/systemd/sd-utf8.h \ + src/systemd/sd-event.h \ + src/systemd/sd-netlink.h \ + src/systemd/sd-resolve.h \ + src/systemd/sd-login.h \ + src/systemd/sd-id128.h \ + src/systemd/sd-daemon.h \ + src/systemd/sd-path.h \ + src/systemd/sd-network.h \ + src/systemd/sd-hwdb.h \ + src/systemd/sd-device.h \ + src/libsystemd/libsystemd.sym \ + src/libsystemd/sd-bus/sd-bus.c \ + src/libsystemd/sd-bus/bus-control.c \ + src/libsystemd/sd-bus/bus-control.h \ + src/libsystemd/sd-bus/bus-error.c \ + src/libsystemd/sd-bus/bus-error.h \ + src/libsystemd/sd-bus/bus-common-errors.h \ + src/libsystemd/sd-bus/bus-common-errors.c \ + src/libsystemd/sd-bus/bus-internal.c \ + src/libsystemd/sd-bus/bus-internal.h \ + src/libsystemd/sd-bus/bus-socket.c \ + src/libsystemd/sd-bus/bus-socket.h \ + src/libsystemd/sd-bus/bus-kernel.c \ + src/libsystemd/sd-bus/bus-kernel.h \ + src/libsystemd/sd-bus/bus-container.c \ + src/libsystemd/sd-bus/bus-container.h \ + src/libsystemd/sd-bus/bus-message.c \ + src/libsystemd/sd-bus/bus-message.h \ + src/libsystemd/sd-bus/bus-creds.c \ + src/libsystemd/sd-bus/bus-creds.h \ + src/libsystemd/sd-bus/bus-signature.c \ + src/libsystemd/sd-bus/bus-signature.h \ + src/libsystemd/sd-bus/bus-type.c \ + src/libsystemd/sd-bus/bus-type.h \ + src/libsystemd/sd-bus/bus-match.c \ + src/libsystemd/sd-bus/bus-match.h \ + src/libsystemd/sd-bus/bus-bloom.c \ + src/libsystemd/sd-bus/bus-bloom.h \ + src/libsystemd/sd-bus/bus-introspect.c \ + src/libsystemd/sd-bus/bus-introspect.h \ + src/libsystemd/sd-bus/bus-objects.c \ + src/libsystemd/sd-bus/bus-objects.h \ + src/libsystemd/sd-bus/bus-gvariant.c \ + src/libsystemd/sd-bus/bus-gvariant.h \ + src/libsystemd/sd-bus/bus-convenience.c \ + src/libsystemd/sd-bus/bus-track.c \ + src/libsystemd/sd-bus/bus-track.h \ + src/libsystemd/sd-bus/bus-slot.c \ + src/libsystemd/sd-bus/bus-slot.h \ + src/libsystemd/sd-bus/bus-protocol.h \ + src/libsystemd/sd-bus/kdbus.h \ + src/libsystemd/sd-bus/bus-dump.c \ + src/libsystemd/sd-bus/bus-dump.h \ + src/libsystemd/sd-utf8/sd-utf8.c \ + src/libsystemd/sd-event/sd-event.c \ + src/libsystemd/sd-netlink/sd-netlink.c \ + src/libsystemd/sd-netlink/netlink-internal.h \ + src/libsystemd/sd-netlink/netlink-message.c \ + src/libsystemd/sd-netlink/netlink-socket.c \ + src/libsystemd/sd-netlink/rtnl-message.c \ + src/libsystemd/sd-netlink/netlink-types.h \ + src/libsystemd/sd-netlink/netlink-types.c \ + src/libsystemd/sd-netlink/netlink-util.h \ + src/libsystemd/sd-netlink/netlink-util.c \ + src/libsystemd/sd-netlink/local-addresses.h \ + src/libsystemd/sd-netlink/local-addresses.c \ + src/libsystemd/sd-id128/sd-id128.c \ + src/libsystemd/sd-id128/id128-util.h \ + src/libsystemd/sd-id128/id128-util.c \ + src/libsystemd/sd-daemon/sd-daemon.c \ + src/libsystemd/sd-login/sd-login.c \ + src/libsystemd/sd-path/sd-path.c \ + src/libsystemd/sd-network/sd-network.c \ + src/libsystemd/sd-network/network-util.h \ + src/libsystemd/sd-network/network-util.c \ + src/libsystemd/sd-hwdb/sd-hwdb.c \ + src/libsystemd/sd-hwdb/hwdb-util.h \ + src/libsystemd/sd-hwdb/hwdb-internal.h \ + src/libsystemd/sd-device/device-internal.h \ + src/libsystemd/sd-device/device-util.h \ + src/libsystemd/sd-device/device-enumerator.c \ + src/libsystemd/sd-device/device-enumerator-private.h \ + src/libsystemd/sd-device/sd-device.c \ + src/libsystemd/sd-device/device-private.c \ + src/libsystemd/sd-device/device-private.h \ + src/libsystemd/sd-resolve/sd-resolve.c + +libsystemd_internal_la_LIBADD = \ + -lresolv + +noinst_LTLIBRARIES += \ + libsystemd-internal.la + +pkginclude_HEADERS += \ + src/systemd/sd-journal.h \ + src/systemd/sd-messages.h \ + src/systemd/_sd-common.h + +libsystemd_journal_internal_la_SOURCES = \ + src/journal/sd-journal.c \ + src/systemd/sd-journal.h \ + src/systemd/_sd-common.h \ + src/journal/journal-file.c \ + src/journal/journal-file.h \ + src/journal/journal-vacuum.c \ + src/journal/journal-vacuum.h \ + src/journal/journal-verify.c \ + src/journal/journal-verify.h \ + src/journal/lookup3.c \ + src/journal/lookup3.h \ + src/journal/journal-send.c \ + src/journal/journal-def.h \ + src/journal/compress.h \ + src/journal/catalog.c \ + src/journal/catalog.h \ + src/journal/mmap-cache.c \ + src/journal/mmap-cache.h \ + src/journal/compress.c \ + src/journal/audit-type.h \ + src/journal/audit-type.c \ + src/shared/gcrypt-util.h \ + src/shared/gcrypt-util.c + +nodist_libsystemd_journal_internal_la_SOURCES = \ + src/journal/audit_type-to-name.h + +gperf_txt_sources += \ + src/journal/audit_type-list.txt + +# using _CFLAGS = in the conditional below would suppress AM_CFLAGS +libsystemd_journal_internal_la_CFLAGS = \ + +libsystemd_journal_internal_la_LIBADD = + +ifneq ($(HAVE_XZ),) +libsystemd_journal_internal_la_CFLAGS += \ + $(XZ_CFLAGS) + +libsystemd_journal_internal_la_LIBADD += \ + $(XZ_LIBS) +endif # HAVE_XZ + +ifneq ($(HAVE_LZ4),) +libsystemd_journal_internal_la_CFLAGS += \ + $(LZ4_CFLAGS) + +libsystemd_journal_internal_la_LIBADD += \ + $(LZ4_LIBS) +endif # HAVE_LZ4 + +ifneq ($(HAVE_GCRYPT),) +libsystemd_journal_internal_la_SOURCES += \ + src/journal/journal-authenticate.c \ + src/journal/journal-authenticate.h \ + src/journal/fsprg.c \ + src/journal/fsprg.h + +libsystemd_journal_internal_la_LIBADD += \ + $(GCRYPT_LIBS) + +endif # HAVE_GCRYPT + +noinst_LTLIBRARIES += \ + libsystemd-journal-internal.la + +nested.subdirs += sd-bus +nested.subdirs += sd-daemon +nested.subdirs += sd-device +nested.subdirs += sd-event +nested.subdirs += sd-hwdb +nested.subdirs += sd-id128 +nested.subdirs += sd-journal +nested.subdirs += sd-login +nested.subdirs += sd-netlink +nested.subdirs += sd-network +nested.subdirs += sd-resolve + +include $(topsrcdir)/build-aux/Makefile.tail.mk diff --git a/src/libsystemd/sd-bus/DIFFERENCES b/src/libsystemd/src/sd-bus/DIFFERENCES index db269675a7..db269675a7 100644 --- a/src/libsystemd/sd-bus/DIFFERENCES +++ b/src/libsystemd/src/sd-bus/DIFFERENCES diff --git a/src/libsystemd/sd-bus/GVARIANT-SERIALIZATION b/src/libsystemd/src/sd-bus/GVARIANT-SERIALIZATION index 6aeb11364a..6aeb11364a 100644 --- a/src/libsystemd/sd-bus/GVARIANT-SERIALIZATION +++ b/src/libsystemd/src/sd-bus/GVARIANT-SERIALIZATION diff --git a/src/libsystemd/src/sd-bus/Makefile b/src/libsystemd/src/sd-bus/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-bus/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-bus/PORTING-DBUS1 b/src/libsystemd/src/sd-bus/PORTING-DBUS1 index 2dedb28bcf..2dedb28bcf 100644 --- a/src/libsystemd/sd-bus/PORTING-DBUS1 +++ b/src/libsystemd/src/sd-bus/PORTING-DBUS1 diff --git a/src/libsystemd/sd-bus/bus-bloom.c b/src/libsystemd/src/sd-bus/bus-bloom.c index 112769fcb6..7441c1a7aa 100644 --- a/src/libsystemd/sd-bus/bus-bloom.c +++ b/src/libsystemd/src/sd-bus/bus-bloom.c @@ -17,9 +17,10 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/siphash24.h" +#include "systemd-basic/util.h" + #include "bus-bloom.h" -#include "siphash24.h" -#include "util.h" static inline void set_bit(uint64_t filter[], unsigned long b) { filter[b >> 6] |= 1ULL << (b & 63); diff --git a/src/libsystemd/sd-bus/bus-bloom.h b/src/libsystemd/src/sd-bus/bus-bloom.h index c824622b95..c824622b95 100644 --- a/src/libsystemd/sd-bus/bus-bloom.h +++ b/src/libsystemd/src/sd-bus/bus-bloom.h diff --git a/src/libsystemd/sd-bus/bus-common-errors.c b/src/libsystemd/src/sd-bus/bus-common-errors.c index 02e3bf904c..a19e98e94b 100644 --- a/src/libsystemd/sd-bus/bus-common-errors.c +++ b/src/libsystemd/src/sd-bus/bus-common-errors.c @@ -19,7 +19,7 @@ #include <errno.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> #include "bus-common-errors.h" #include "bus-error.h" diff --git a/src/libsystemd/sd-bus/bus-common-errors.h b/src/libsystemd/src/sd-bus/bus-common-errors.h index c8f369cb78..c8f369cb78 100644 --- a/src/libsystemd/sd-bus/bus-common-errors.h +++ b/src/libsystemd/src/sd-bus/bus-common-errors.h diff --git a/src/libsystemd/sd-bus/bus-container.c b/src/libsystemd/src/sd-bus/bus-container.c index 3191d27ded..2f91ffc8dd 100644 --- a/src/libsystemd/sd-bus/bus-container.c +++ b/src/libsystemd/src/sd-bus/bus-container.c @@ -20,12 +20,13 @@ #include <fcntl.h> #include <unistd.h> +#include "systemd-basic/fd-util.h" +#include "systemd-basic/process-util.h" +#include "systemd-basic/util.h" + #include "bus-container.h" #include "bus-internal.h" #include "bus-socket.h" -#include "fd-util.h" -#include "process-util.h" -#include "util.h" int bus_container_connect_socket(sd_bus *b) { _cleanup_close_pair_ int pair[2] = { -1, -1 }; diff --git a/src/libsystemd/sd-bus/bus-container.h b/src/libsystemd/src/sd-bus/bus-container.h index 509ef45624..5cd6d15ede 100644 --- a/src/libsystemd/sd-bus/bus-container.h +++ b/src/libsystemd/src/sd-bus/bus-container.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> int bus_container_connect_socket(sd_bus *b); int bus_container_connect_kernel(sd_bus *b); diff --git a/src/libsystemd/sd-bus/bus-control.c b/src/libsystemd/src/sd-bus/bus-control.c index 52128e7b5c..606cdc44ba 100644 --- a/src/libsystemd/sd-bus/bus-control.c +++ b/src/libsystemd/src/sd-bus/bus-control.c @@ -24,19 +24,20 @@ #include <errno.h> #include <stddef.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/capability-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/user-util.h" -#include "alloc-util.h" #include "bus-bloom.h" #include "bus-control.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-util.h" -#include "capability-util.h" -#include "stdio-util.h" -#include "string-util.h" -#include "strv.h" -#include "user-util.h" _public_ int sd_bus_get_unique_name(sd_bus *bus, const char **unique) { int r; diff --git a/src/libsystemd/sd-bus/bus-control.h b/src/libsystemd/src/sd-bus/bus-control.h index c181aa7959..229c95efb0 100644 --- a/src/libsystemd/sd-bus/bus-control.h +++ b/src/libsystemd/src/sd-bus/bus-control.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> #include "bus-match.h" diff --git a/src/libsystemd/sd-bus/bus-convenience.c b/src/libsystemd/src/sd-bus/bus-convenience.c index 2d06bf541f..e6a92679cf 100644 --- a/src/libsystemd/sd-bus/bus-convenience.c +++ b/src/libsystemd/src/sd-bus/bus-convenience.c @@ -17,12 +17,13 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/string-util.h" + #include "bus-internal.h" #include "bus-message.h" #include "bus-signature.h" #include "bus-type.h" #include "bus-util.h" -#include "string-util.h" _public_ int sd_bus_emit_signal( sd_bus *bus, diff --git a/src/libsystemd/sd-bus/bus-creds.c b/src/libsystemd/src/sd-bus/bus-creds.c index c4f693dee9..3b4ebe9ee0 100644 --- a/src/libsystemd/sd-bus/bus-creds.c +++ b/src/libsystemd/src/sd-bus/bus-creds.c @@ -17,28 +17,30 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include <linux/capability.h> #include <stdlib.h> -#include "alloc-util.h" -#include "audit-util.h" +#include <linux/capability.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/audit-util.h" +#include "systemd-basic/bus-label.h" +#include "systemd-basic/capability-util.h" +#include "systemd-basic/cgroup-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/process-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/terminal-util.h" +#include "systemd-basic/user-util.h" +#include "systemd-basic/util.h" + #include "bus-creds.h" -#include "bus-label.h" #include "bus-message.h" #include "bus-util.h" -#include "capability-util.h" -#include "cgroup-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "formats-util.h" -#include "hexdecoct.h" -#include "parse-util.h" -#include "process-util.h" -#include "string-util.h" -#include "strv.h" -#include "terminal-util.h" -#include "user-util.h" -#include "util.h" enum { CAP_OFFSET_INHERITABLE = 0, diff --git a/src/libsystemd/sd-bus/bus-creds.h b/src/libsystemd/src/sd-bus/bus-creds.h index df8a1f1005..3e2311f91d 100644 --- a/src/libsystemd/sd-bus/bus-creds.h +++ b/src/libsystemd/src/sd-bus/bus-creds.h @@ -21,7 +21,7 @@ #include <stdbool.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> struct sd_bus_creds { bool allocated; diff --git a/src/libsystemd/sd-bus/bus-dump.c b/src/libsystemd/src/sd-bus/bus-dump.c index 21a6b20a11..447aa5d9d7 100644 --- a/src/libsystemd/sd-bus/bus-dump.c +++ b/src/libsystemd/src/sd-bus/bus-dump.c @@ -17,21 +17,22 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "alloc-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/cap-list.h" +#include "systemd-basic/capability-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/locale-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/terminal-util.h" +#include "systemd-basic/util.h" + #include "bus-dump.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-type.h" -#include "cap-list.h" -#include "capability-util.h" -#include "fileio.h" -#include "formats-util.h" -#include "locale-util.h" -#include "macro.h" -#include "string-util.h" -#include "strv.h" -#include "terminal-util.h" -#include "util.h" static char *indent(unsigned level, unsigned flags) { char *p; diff --git a/src/libsystemd/sd-bus/bus-dump.h b/src/libsystemd/src/sd-bus/bus-dump.h index 874e86d09c..68fa043786 100644 --- a/src/libsystemd/sd-bus/bus-dump.h +++ b/src/libsystemd/src/sd-bus/bus-dump.h @@ -22,7 +22,7 @@ #include <stdbool.h> #include <stdio.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> enum { BUS_MESSAGE_DUMP_WITH_HEADER = 1, diff --git a/src/libsystemd/sd-bus/bus-error.c b/src/libsystemd/src/sd-bus/bus-error.c index 26219bdeed..d6b45c47bc 100644 --- a/src/libsystemd/sd-bus/bus-error.c +++ b/src/libsystemd/src/sd-bus/bus-error.c @@ -24,13 +24,14 @@ #include <stdlib.h> #include <string.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/errno-list.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-error.h" -#include "errno-list.h" -#include "string-util.h" -#include "util.h" BUS_ERROR_MAP_ELF_REGISTER const sd_bus_error_map bus_standard_errors[] = { SD_BUS_ERROR_MAP("org.freedesktop.DBus.Error.Failed", EACCES), diff --git a/src/libsystemd/sd-bus/bus-error.h b/src/libsystemd/src/sd-bus/bus-error.h index e2c4cf4b3f..308cf92f24 100644 --- a/src/libsystemd/sd-bus/bus-error.h +++ b/src/libsystemd/src/sd-bus/bus-error.h @@ -21,9 +21,9 @@ #include <stdbool.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> -#include "macro.h" +#include "systemd-basic/macro.h" bool bus_error_is_dirty(sd_bus_error *e); diff --git a/src/libsystemd/sd-bus/bus-gvariant.c b/src/libsystemd/src/sd-bus/bus-gvariant.c index 58782767fa..58782767fa 100644 --- a/src/libsystemd/sd-bus/bus-gvariant.c +++ b/src/libsystemd/src/sd-bus/bus-gvariant.c diff --git a/src/libsystemd/sd-bus/bus-gvariant.h b/src/libsystemd/src/sd-bus/bus-gvariant.h index 6da637fb05..45afe01631 100644 --- a/src/libsystemd/sd-bus/bus-gvariant.h +++ b/src/libsystemd/src/sd-bus/bus-gvariant.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "macro.h" +#include "systemd-basic/macro.h" int bus_gvariant_get_size(const char *signature) _pure_; int bus_gvariant_get_alignment(const char *signature) _pure_; diff --git a/src/libsystemd/sd-bus/bus-internal.c b/src/libsystemd/src/sd-bus/bus-internal.c index caca679086..bd63e453e4 100644 --- a/src/libsystemd/sd-bus/bus-internal.c +++ b/src/libsystemd/src/sd-bus/bus-internal.c @@ -17,11 +17,12 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "alloc-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/string-util.h" + #include "bus-internal.h" #include "bus-message.h" -#include "hexdecoct.h" -#include "string-util.h" bool object_path_is_valid(const char *p) { const char *q; diff --git a/src/libsystemd/sd-bus/bus-internal.h b/src/libsystemd/src/sd-bus/bus-internal.h index 216d9f62bc..6e74da3283 100644 --- a/src/libsystemd/sd-bus/bus-internal.h +++ b/src/libsystemd/src/sd-bus/bus-internal.h @@ -22,18 +22,19 @@ #include <pthread.h> #include <sys/socket.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/hashmap.h" +#include "systemd-basic/list.h" +#include "systemd-basic/prioq.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" #include "bus-error.h" #include "bus-kernel.h" #include "bus-match.h" -#include "hashmap.h" #include "kdbus.h" -#include "list.h" -#include "prioq.h" -#include "refcnt.h" -#include "socket-util.h" -#include "util.h" struct reply_callback { sd_bus_message_handler_t callback; diff --git a/src/libsystemd/sd-bus/bus-introspect.c b/src/libsystemd/src/sd-bus/bus-introspect.c index 8f93edb8da..85400c865f 100644 --- a/src/libsystemd/sd-bus/bus-introspect.c +++ b/src/libsystemd/src/sd-bus/bus-introspect.c @@ -17,14 +17,15 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" + #include "bus-internal.h" #include "bus-introspect.h" #include "bus-protocol.h" #include "bus-signature.h" -#include "fd-util.h" -#include "fileio.h" -#include "string-util.h" -#include "util.h" int introspect_begin(struct introspect *i, bool trusted) { assert(i); diff --git a/src/libsystemd/sd-bus/bus-introspect.h b/src/libsystemd/src/sd-bus/bus-introspect.h index 8e2f3800ca..4a83e2aa38 100644 --- a/src/libsystemd/sd-bus/bus-introspect.h +++ b/src/libsystemd/src/sd-bus/bus-introspect.h @@ -21,9 +21,9 @@ #include <stdio.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> -#include "set.h" +#include "systemd-basic/set.h" struct introspect { FILE *f; diff --git a/src/libsystemd/sd-bus/bus-kernel.c b/src/libsystemd/src/sd-bus/bus-kernel.c index 59398b841d..3321a54a51 100644 --- a/src/libsystemd/sd-bus/bus-kernel.c +++ b/src/libsystemd/src/sd-bus/bus-kernel.c @@ -32,24 +32,25 @@ #include <libgen.h> #undef basename -#include "alloc-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/bus-label.h" +#include "systemd-basic/capability-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/memfd-util.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/user-util.h" +#include "systemd-basic/util.h" + #include "bus-bloom.h" #include "bus-internal.h" #include "bus-kernel.h" -#include "bus-label.h" #include "bus-message.h" #include "bus-util.h" -#include "capability-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "formats-util.h" -#include "memfd-util.h" -#include "parse-util.h" -#include "stdio-util.h" -#include "string-util.h" -#include "strv.h" -#include "user-util.h" -#include "util.h" #define UNIQUE_NAME_MAX (3+DECIMAL_STR_MAX(uint64_t)) diff --git a/src/libsystemd/sd-bus/bus-kernel.h b/src/libsystemd/src/sd-bus/bus-kernel.h index 53ba3bdcf3..2927ba26a5 100644 --- a/src/libsystemd/sd-bus/bus-kernel.h +++ b/src/libsystemd/src/sd-bus/bus-kernel.h @@ -21,7 +21,7 @@ #include <stdbool.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> #define KDBUS_ITEM_NEXT(item) \ (typeof(item))(((uint8_t *)item) + ALIGN8((item)->size)) diff --git a/src/libsystemd/sd-bus/bus-match.c b/src/libsystemd/src/sd-bus/bus-match.c index db01f21135..37a391b46a 100644 --- a/src/libsystemd/sd-bus/bus-match.c +++ b/src/libsystemd/src/sd-bus/bus-match.c @@ -17,16 +17,17 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "alloc-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" + #include "bus-internal.h" #include "bus-match.h" #include "bus-message.h" #include "bus-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "hexdecoct.h" -#include "string-util.h" -#include "strv.h" /* Example: * diff --git a/src/libsystemd/sd-bus/bus-match.h b/src/libsystemd/src/sd-bus/bus-match.h index 8cbbb63b11..54b40d5be8 100644 --- a/src/libsystemd/sd-bus/bus-match.h +++ b/src/libsystemd/src/sd-bus/bus-match.h @@ -19,9 +19,9 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> -#include "hashmap.h" +#include "systemd-basic/hashmap.h" enum bus_match_node_type { BUS_MATCH_ROOT, diff --git a/src/libsystemd/sd-bus/bus-message.c b/src/libsystemd/src/sd-bus/bus-message.c index 5cec804e32..181f6bccb2 100644 --- a/src/libsystemd/sd-bus/bus-message.c +++ b/src/libsystemd/src/sd-bus/bus-message.c @@ -21,23 +21,24 @@ #include <fcntl.h> #include <sys/mman.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/memfd-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/time-util.h" +#include "systemd-basic/utf8.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-gvariant.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-signature.h" #include "bus-type.h" #include "bus-util.h" -#include "fd-util.h" -#include "io-util.h" -#include "memfd-util.h" -#include "string-util.h" -#include "strv.h" -#include "time-util.h" -#include "utf8.h" -#include "util.h" static int message_append_basic(sd_bus_message *m, char type, const void *p, const void **stored); diff --git a/src/libsystemd/sd-bus/bus-message.h b/src/libsystemd/src/sd-bus/bus-message.h index 4710c106b9..93bbb9b00d 100644 --- a/src/libsystemd/sd-bus/bus-message.h +++ b/src/libsystemd/src/sd-bus/bus-message.h @@ -23,12 +23,13 @@ #include <stdbool.h> #include <sys/socket.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/macro.h" +#include "systemd-basic/time-util.h" #include "bus-creds.h" #include "bus-protocol.h" -#include "macro.h" -#include "time-util.h" struct bus_container { char enclosing; diff --git a/src/libsystemd/sd-bus/bus-objects.c b/src/libsystemd/src/sd-bus/bus-objects.c index 9bd07ffcab..a732a0a928 100644 --- a/src/libsystemd/sd-bus/bus-objects.c +++ b/src/libsystemd/src/sd-bus/bus-objects.c @@ -17,7 +17,11 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "alloc-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/set.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" + #include "bus-internal.h" #include "bus-introspect.h" #include "bus-message.h" @@ -26,9 +30,6 @@ #include "bus-slot.h" #include "bus-type.h" #include "bus-util.h" -#include "set.h" -#include "string-util.h" -#include "strv.h" static int node_vtable_get_userdata( sd_bus *bus, diff --git a/src/libsystemd/sd-bus/bus-objects.h b/src/libsystemd/src/sd-bus/bus-objects.h index e0b8c534ed..e0b8c534ed 100644 --- a/src/libsystemd/sd-bus/bus-objects.h +++ b/src/libsystemd/src/sd-bus/bus-objects.h diff --git a/src/libsystemd/sd-bus/bus-protocol.h b/src/libsystemd/src/sd-bus/bus-protocol.h index 9d180cb284..732b512d3f 100644 --- a/src/libsystemd/sd-bus/bus-protocol.h +++ b/src/libsystemd/src/sd-bus/bus-protocol.h @@ -21,7 +21,7 @@ #include <endian.h> -#include "macro.h" +#include "systemd-basic/macro.h" /* Packet header */ diff --git a/src/libsystemd/sd-bus/bus-signature.c b/src/libsystemd/src/sd-bus/bus-signature.c index 7bc243494a..4e7cf02ec1 100644 --- a/src/libsystemd/sd-bus/bus-signature.c +++ b/src/libsystemd/src/sd-bus/bus-signature.c @@ -17,7 +17,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include <util.h> +#include "systemd-basic/util.h" #include "bus-signature.h" #include "bus-type.h" diff --git a/src/libsystemd/sd-bus/bus-signature.h b/src/libsystemd/src/sd-bus/bus-signature.h index 1e0cd7f587..1e0cd7f587 100644 --- a/src/libsystemd/sd-bus/bus-signature.h +++ b/src/libsystemd/src/sd-bus/bus-signature.h diff --git a/src/libsystemd/sd-bus/bus-slot.c b/src/libsystemd/src/sd-bus/bus-slot.c index 8e9074c7df..ffe992013a 100644 --- a/src/libsystemd/sd-bus/bus-slot.c +++ b/src/libsystemd/src/sd-bus/bus-slot.c @@ -17,13 +17,14 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/string-util.h" -#include "alloc-util.h" #include "bus-control.h" #include "bus-objects.h" #include "bus-slot.h" -#include "string-util.h" sd_bus_slot *bus_slot_allocate( sd_bus *bus, diff --git a/src/libsystemd/sd-bus/bus-slot.h b/src/libsystemd/src/sd-bus/bus-slot.h index 3b8b94dc6b..b862799d1c 100644 --- a/src/libsystemd/sd-bus/bus-slot.h +++ b/src/libsystemd/src/sd-bus/bus-slot.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> #include "bus-internal.h" diff --git a/src/libsystemd/sd-bus/bus-socket.c b/src/libsystemd/src/sd-bus/bus-socket.c index cfd7753139..9beb7dffb3 100644 --- a/src/libsystemd/sd-bus/bus-socket.c +++ b/src/libsystemd/src/sd-bus/bus-socket.c @@ -22,25 +22,26 @@ #include <stdlib.h> #include <unistd.h> -#include "sd-bus.h" -#include "sd-daemon.h" +#include <systemd/sd-bus.h> +#include <systemd/sd-daemon.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/selinux-util.h" +#include "systemd-basic/signal-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/user-util.h" +#include "systemd-basic/utf8.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-socket.h" -#include "fd-util.h" -#include "formats-util.h" -#include "hexdecoct.h" -#include "macro.h" -#include "missing.h" -#include "selinux-util.h" -#include "signal-util.h" -#include "stdio-util.h" -#include "string-util.h" -#include "user-util.h" -#include "utf8.h" -#include "util.h" #define SNDBUF_SIZE (8*1024*1024) diff --git a/src/libsystemd/sd-bus/bus-socket.h b/src/libsystemd/src/sd-bus/bus-socket.h index 684feead74..6e1d32e6a7 100644 --- a/src/libsystemd/sd-bus/bus-socket.h +++ b/src/libsystemd/src/sd-bus/bus-socket.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> void bus_socket_setup(sd_bus *b); diff --git a/src/libsystemd/sd-bus/bus-track.c b/src/libsystemd/src/sd-bus/bus-track.c index 1f436fe560..86b321bdea 100644 --- a/src/libsystemd/sd-bus/bus-track.c +++ b/src/libsystemd/src/sd-bus/bus-track.c @@ -17,9 +17,10 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" -#include "alloc-util.h" #include "bus-internal.h" #include "bus-track.h" #include "bus-util.h" diff --git a/src/libsystemd/sd-bus/bus-track.h b/src/libsystemd/src/sd-bus/bus-track.h index 7d93a727d6..7d93a727d6 100644 --- a/src/libsystemd/sd-bus/bus-track.h +++ b/src/libsystemd/src/sd-bus/bus-track.h diff --git a/src/libsystemd/sd-bus/bus-type.c b/src/libsystemd/src/sd-bus/bus-type.c index c692afc580..c692afc580 100644 --- a/src/libsystemd/sd-bus/bus-type.c +++ b/src/libsystemd/src/sd-bus/bus-type.c diff --git a/src/libsystemd/sd-bus/bus-type.h b/src/libsystemd/src/sd-bus/bus-type.h index 5c87eb5f08..a9cfa6ef36 100644 --- a/src/libsystemd/sd-bus/bus-type.h +++ b/src/libsystemd/src/sd-bus/bus-type.h @@ -21,9 +21,9 @@ #include <stdbool.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> -#include "macro.h" +#include "systemd-basic/macro.h" bool bus_type_is_valid(char c) _const_; bool bus_type_is_valid_in_signature(char c) _const_; diff --git a/src/libsystemd/src/sd-bus/bus-util.c b/src/libsystemd/src/sd-bus/bus-util.c new file mode 100644 index 0000000000..c82390634e --- /dev/null +++ b/src/libsystemd/src/sd-bus/bus-util.c @@ -0,0 +1,1551 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <fcntl.h> +#include <inttypes.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/resource.h> +#include <sys/socket.h> +#include <unistd.h> + +#include <systemd/sd-bus-protocol.h> +#include <systemd/sd-bus.h> +#include <systemd/sd-daemon.h> +#include <systemd/sd-event.h> +#include <systemd/sd-id128.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/bus-label.h" +#include "systemd-basic/def.h" +#include "systemd-basic/escape.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/proc-cmdline.h" +#include "systemd-basic/rlimit-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/user-util.h" + +#include "bus-internal.h" +#include "bus-message.h" +#include "bus-util.h" + +static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { + sd_event *e = userdata; + + assert(m); + assert(e); + + sd_bus_close(sd_bus_message_get_bus(m)); + sd_event_exit(e, 0); + + return 1; +} + +int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) { + _cleanup_free_ char *match = NULL; + const char *unique; + int r; + + assert(e); + assert(bus); + assert(name); + + /* We unregister the name here and then wait for the + * NameOwnerChanged signal for this event to arrive before we + * quit. We do this in order to make sure that any queued + * requests are still processed before we really exit. */ + + r = sd_bus_get_unique_name(bus, &unique); + if (r < 0) + return r; + + r = asprintf(&match, + "sender='org.freedesktop.DBus'," + "type='signal'," + "interface='org.freedesktop.DBus'," + "member='NameOwnerChanged'," + "path='/org/freedesktop/DBus'," + "arg0='%s'," + "arg1='%s'," + "arg2=''", name, unique); + if (r < 0) + return -ENOMEM; + + r = sd_bus_add_match(bus, NULL, match, name_owner_change_callback, e); + if (r < 0) + return r; + + r = sd_bus_release_name(bus, name); + if (r < 0) + return r; + + return 0; +} + +int bus_event_loop_with_idle( + sd_event *e, + sd_bus *bus, + const char *name, + usec_t timeout, + check_idle_t check_idle, + void *userdata) { + bool exiting = false; + int r, code; + + assert(e); + assert(bus); + assert(name); + + for (;;) { + bool idle; + + r = sd_event_get_state(e); + if (r < 0) + return r; + if (r == SD_EVENT_FINISHED) + break; + + if (check_idle) + idle = check_idle(userdata); + else + idle = true; + + r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout); + if (r < 0) + return r; + + if (r == 0 && !exiting && idle) { + + r = sd_bus_try_close(bus); + if (r == -EBUSY) + continue; + + /* Fallback for dbus1 connections: we + * unregister the name and wait for the + * response to come through for it */ + if (r == -EOPNOTSUPP) { + + /* Inform the service manager that we + * are going down, so that it will + * queue all further start requests, + * instead of assuming we are already + * running. */ + sd_notify(false, "STOPPING=1"); + + r = bus_async_unregister_and_exit(e, bus, name); + if (r < 0) + return r; + + exiting = true; + continue; + } + + if (r < 0) + return r; + + sd_event_exit(e, 0); + break; + } + } + + r = sd_event_get_exit_code(e, &code); + if (r < 0) + return r; + + return code; +} + +int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) { + _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL; + int r, has_owner = 0; + + assert(c); + assert(name); + + r = sd_bus_call_method(c, + "org.freedesktop.DBus", + "/org/freedesktop/dbus", + "org.freedesktop.DBus", + "NameHasOwner", + error, + &rep, + "s", + name); + if (r < 0) + return r; + + r = sd_bus_message_read_basic(rep, 'b', &has_owner); + if (r < 0) + return sd_bus_error_set_errno(error, r); + + return has_owner; +} + +static int check_good_user(sd_bus_message *m, uid_t good_user) { + _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL; + uid_t sender_uid; + int r; + + assert(m); + + if (good_user == UID_INVALID) + return 0; + + r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds); + if (r < 0) + return r; + + /* Don't trust augmented credentials for authorization */ + assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM); + + r = sd_bus_creds_get_euid(creds, &sender_uid); + if (r < 0) + return r; + + return sender_uid == good_user; +} + +int bus_test_polkit( + sd_bus_message *call, + int capability, + const char *action, + const char **details, + uid_t good_user, + bool *_challenge, + sd_bus_error *e) { + + int r; + + assert(call); + assert(action); + + /* Tests non-interactively! */ + + r = check_good_user(call, good_user); + if (r != 0) + return r; + + r = sd_bus_query_sender_privilege(call, capability); + if (r < 0) + return r; + else if (r > 0) + return 1; +#ifdef ENABLE_POLKIT + else { + _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL; + _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; + int authorized = false, challenge = false; + const char *sender, **k, **v; + + sender = sd_bus_message_get_sender(call); + if (!sender) + return -EBADMSG; + + r = sd_bus_message_new_method_call( + call->bus, + &request, + "org.freedesktop.PolicyKit1", + "/org/freedesktop/PolicyKit1/Authority", + "org.freedesktop.PolicyKit1.Authority", + "CheckAuthorization"); + if (r < 0) + return r; + + r = sd_bus_message_append( + request, + "(sa{sv})s", + "system-bus-name", 1, "name", "s", sender, + action); + if (r < 0) + return r; + + r = sd_bus_message_open_container(request, 'a', "{ss}"); + if (r < 0) + return r; + + STRV_FOREACH_PAIR(k, v, details) { + r = sd_bus_message_append(request, "{ss}", *k, *v); + if (r < 0) + return r; + } + + r = sd_bus_message_close_container(request); + if (r < 0) + return r; + + r = sd_bus_message_append(request, "us", 0, NULL); + if (r < 0) + return r; + + r = sd_bus_call(call->bus, request, 0, e, &reply); + if (r < 0) { + /* Treat no PK available as access denied */ + if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) { + sd_bus_error_free(e); + return -EACCES; + } + + return r; + } + + r = sd_bus_message_enter_container(reply, 'r', "bba{ss}"); + if (r < 0) + return r; + + r = sd_bus_message_read(reply, "bb", &authorized, &challenge); + if (r < 0) + return r; + + if (authorized) + return 1; + + if (_challenge) { + *_challenge = challenge; + return 0; + } + } +#endif + + return -EACCES; +} + +#ifdef ENABLE_POLKIT + +typedef struct AsyncPolkitQuery { + sd_bus_message *request, *reply; + sd_bus_message_handler_t callback; + void *userdata; + sd_bus_slot *slot; + Hashmap *registry; +} AsyncPolkitQuery; + +static void async_polkit_query_free(AsyncPolkitQuery *q) { + + if (!q) + return; + + sd_bus_slot_unref(q->slot); + + if (q->registry && q->request) + hashmap_remove(q->registry, q->request); + + sd_bus_message_unref(q->request); + sd_bus_message_unref(q->reply); + + free(q); +} + +static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) { + _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL; + AsyncPolkitQuery *q = userdata; + int r; + + assert(reply); + assert(q); + + q->slot = sd_bus_slot_unref(q->slot); + q->reply = sd_bus_message_ref(reply); + + r = sd_bus_message_rewind(q->request, true); + if (r < 0) { + r = sd_bus_reply_method_errno(q->request, r, NULL); + goto finish; + } + + r = q->callback(q->request, q->userdata, &error_buffer); + r = bus_maybe_reply_error(q->request, r, &error_buffer); + +finish: + async_polkit_query_free(q); + + return r; +} + +#endif + +int bus_verify_polkit_async( + sd_bus_message *call, + int capability, + const char *action, + const char **details, + bool interactive, + uid_t good_user, + Hashmap **registry, + sd_bus_error *error) { + +#ifdef ENABLE_POLKIT + _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL; + AsyncPolkitQuery *q; + const char *sender, **k, **v; + sd_bus_message_handler_t callback; + void *userdata; + int c; +#endif + int r; + + assert(call); + assert(action); + assert(registry); + + r = check_good_user(call, good_user); + if (r != 0) + return r; + +#ifdef ENABLE_POLKIT + q = hashmap_get(*registry, call); + if (q) { + int authorized, challenge; + + /* This is the second invocation of this function, and + * there's already a response from polkit, let's + * process it */ + assert(q->reply); + + if (sd_bus_message_is_method_error(q->reply, NULL)) { + const sd_bus_error *e; + + /* Copy error from polkit reply */ + e = sd_bus_message_get_error(q->reply); + sd_bus_error_copy(error, e); + + /* Treat no PK available as access denied */ + if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) + return -EACCES; + + return -sd_bus_error_get_errno(e); + } + + r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}"); + if (r >= 0) + r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge); + + if (r < 0) + return r; + + if (authorized) + return 1; + + if (challenge) + return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required."); + + return -EACCES; + } +#endif + + r = sd_bus_query_sender_privilege(call, capability); + if (r < 0) + return r; + else if (r > 0) + return 1; + +#ifdef ENABLE_POLKIT + if (sd_bus_get_current_message(call->bus) != call) + return -EINVAL; + + callback = sd_bus_get_current_handler(call->bus); + if (!callback) + return -EINVAL; + + userdata = sd_bus_get_current_userdata(call->bus); + + sender = sd_bus_message_get_sender(call); + if (!sender) + return -EBADMSG; + + c = sd_bus_message_get_allow_interactive_authorization(call); + if (c < 0) + return c; + if (c > 0) + interactive = true; + + r = hashmap_ensure_allocated(registry, NULL); + if (r < 0) + return r; + + r = sd_bus_message_new_method_call( + call->bus, + &pk, + "org.freedesktop.PolicyKit1", + "/org/freedesktop/PolicyKit1/Authority", + "org.freedesktop.PolicyKit1.Authority", + "CheckAuthorization"); + if (r < 0) + return r; + + r = sd_bus_message_append( + pk, + "(sa{sv})s", + "system-bus-name", 1, "name", "s", sender, + action); + if (r < 0) + return r; + + r = sd_bus_message_open_container(pk, 'a', "{ss}"); + if (r < 0) + return r; + + STRV_FOREACH_PAIR(k, v, details) { + r = sd_bus_message_append(pk, "{ss}", *k, *v); + if (r < 0) + return r; + } + + r = sd_bus_message_close_container(pk); + if (r < 0) + return r; + + r = sd_bus_message_append(pk, "us", !!interactive, NULL); + if (r < 0) + return r; + + q = new0(AsyncPolkitQuery, 1); + if (!q) + return -ENOMEM; + + q->request = sd_bus_message_ref(call); + q->callback = callback; + q->userdata = userdata; + + r = hashmap_put(*registry, call, q); + if (r < 0) { + async_polkit_query_free(q); + return r; + } + + q->registry = *registry; + + r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0); + if (r < 0) { + async_polkit_query_free(q); + return r; + } + + return 0; +#endif + + return -EACCES; +} + +void bus_verify_polkit_async_registry_free(Hashmap *registry) { +#ifdef ENABLE_POLKIT + AsyncPolkitQuery *q; + + while ((q = hashmap_steal_first(registry))) + async_polkit_query_free(q); + + hashmap_free(registry); +#endif +} + +int bus_check_peercred(sd_bus *c) { + struct ucred ucred; + socklen_t l; + int fd; + + assert(c); + + fd = sd_bus_get_fd(c); + if (fd < 0) + return fd; + + l = sizeof(struct ucred); + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0) + return -errno; + + if (l != sizeof(struct ucred)) + return -E2BIG; + + if (ucred.uid != 0 && ucred.uid != geteuid()) + return -EPERM; + + return 1; +} + +int bus_connect_system_systemd(sd_bus **_bus) { + _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL; + int r; + + assert(_bus); + + if (geteuid() != 0) + return sd_bus_default_system(_bus); + + /* If we are root and kdbus is not available, then let's talk + * directly to the system instance, instead of going via the + * bus */ + + r = sd_bus_new(&bus); + if (r < 0) + return r; + + r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS); + if (r < 0) + return r; + + bus->bus_client = true; + + r = sd_bus_start(bus); + if (r >= 0) { + *_bus = bus; + bus = NULL; + return 0; + } + + bus = sd_bus_unref(bus); + + r = sd_bus_new(&bus); + if (r < 0) + return r; + + r = sd_bus_set_address(bus, "unix:path=/run/systemd/private"); + if (r < 0) + return r; + + r = sd_bus_start(bus); + if (r < 0) + return sd_bus_default_system(_bus); + + r = bus_check_peercred(bus); + if (r < 0) + return r; + + *_bus = bus; + bus = NULL; + + return 0; +} + +int bus_connect_user_systemd(sd_bus **_bus) { + _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL; + _cleanup_free_ char *ee = NULL; + const char *e; + int r; + + /* Try via kdbus first, and then directly */ + + assert(_bus); + + r = sd_bus_new(&bus); + if (r < 0) + return r; + + if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0) + return -ENOMEM; + + bus->bus_client = true; + + r = sd_bus_start(bus); + if (r >= 0) { + *_bus = bus; + bus = NULL; + return 0; + } + + bus = sd_bus_unref(bus); + + e = secure_getenv("XDG_RUNTIME_DIR"); + if (!e) + return sd_bus_default_user(_bus); + + ee = bus_address_escape(e); + if (!ee) + return -ENOMEM; + + r = sd_bus_new(&bus); + if (r < 0) + return r; + + bus->address = strjoin("unix:path=", ee, "/systemd/private", NULL); + if (!bus->address) + return -ENOMEM; + + r = sd_bus_start(bus); + if (r < 0) + return sd_bus_default_user(_bus); + + r = bus_check_peercred(bus); + if (r < 0) + return r; + + *_bus = bus; + bus = NULL; + + return 0; +} + +#define print_property(name, fmt, ...) \ + do { \ + if (value) \ + printf(fmt "\n", __VA_ARGS__); \ + else \ + printf("%s=" fmt "\n", name, __VA_ARGS__); \ + } while(0) + +int bus_print_property(const char *name, sd_bus_message *property, bool value, bool all) { + char type; + const char *contents; + int r; + + assert(name); + assert(property); + + r = sd_bus_message_peek_type(property, &type, &contents); + if (r < 0) + return r; + + switch (type) { + + case SD_BUS_TYPE_STRING: { + const char *s; + + r = sd_bus_message_read_basic(property, type, &s); + if (r < 0) + return r; + + if (all || !isempty(s)) { + _cleanup_free_ char *escaped = NULL; + + escaped = xescape(s, "\n"); + if (!escaped) + return -ENOMEM; + + print_property(name, "%s", escaped); + } + + return 1; + } + + case SD_BUS_TYPE_BOOLEAN: { + int b; + + r = sd_bus_message_read_basic(property, type, &b); + if (r < 0) + return r; + + print_property(name, "%s", yes_no(b)); + + return 1; + } + + case SD_BUS_TYPE_UINT64: { + uint64_t u; + + r = sd_bus_message_read_basic(property, type, &u); + if (r < 0) + return r; + + /* Yes, heuristics! But we can change this check + * should it turn out to not be sufficient */ + + if (endswith(name, "Timestamp")) { + char timestamp[FORMAT_TIMESTAMP_MAX], *t; + + t = format_timestamp(timestamp, sizeof(timestamp), u); + if (t || all) + print_property(name, "%s", strempty(t)); + + } else if (strstr(name, "USec")) { + char timespan[FORMAT_TIMESPAN_MAX]; + + print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0)); + } else + print_property(name, "%"PRIu64, u); + + return 1; + } + + case SD_BUS_TYPE_INT64: { + int64_t i; + + r = sd_bus_message_read_basic(property, type, &i); + if (r < 0) + return r; + + print_property(name, "%"PRIi64, i); + + return 1; + } + + case SD_BUS_TYPE_UINT32: { + uint32_t u; + + r = sd_bus_message_read_basic(property, type, &u); + if (r < 0) + return r; + + if (strstr(name, "UMask") || strstr(name, "Mode")) + print_property(name, "%04o", u); + else + print_property(name, "%"PRIu32, u); + + return 1; + } + + case SD_BUS_TYPE_INT32: { + int32_t i; + + r = sd_bus_message_read_basic(property, type, &i); + if (r < 0) + return r; + + print_property(name, "%"PRIi32, i); + return 1; + } + + case SD_BUS_TYPE_DOUBLE: { + double d; + + r = sd_bus_message_read_basic(property, type, &d); + if (r < 0) + return r; + + print_property(name, "%g", d); + return 1; + } + + case SD_BUS_TYPE_ARRAY: + if (streq(contents, "s")) { + bool first = true; + const char *str; + + r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents); + if (r < 0) + return r; + + while ((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) { + _cleanup_free_ char *escaped = NULL; + + if (first && !value) + printf("%s=", name); + + escaped = xescape(str, "\n "); + if (!escaped) + return -ENOMEM; + + printf("%s%s", first ? "" : " ", escaped); + + first = false; + } + if (r < 0) + return r; + + if (first && all && !value) + printf("%s=", name); + if (!first || all) + puts(""); + + r = sd_bus_message_exit_container(property); + if (r < 0) + return r; + + return 1; + + } else if (streq(contents, "y")) { + const uint8_t *u; + size_t n; + + r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n); + if (r < 0) + return r; + + if (all || n > 0) { + unsigned int i; + + if (!value) + printf("%s=", name); + + for (i = 0; i < n; i++) + printf("%02x", u[i]); + + puts(""); + } + + return 1; + + } else if (streq(contents, "u")) { + uint32_t *u; + size_t n; + + r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n); + if (r < 0) + return r; + + if (all || n > 0) { + unsigned int i; + + if (!value) + printf("%s=", name); + + for (i = 0; i < n; i++) + printf("%08x", u[i]); + + puts(""); + } + + return 1; + } + + break; + } + + return 0; +} + +int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool value, bool all) { + _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; + _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; + int r; + + assert(bus); + assert(path); + + r = sd_bus_call_method(bus, + dest, + path, + "org.freedesktop.DBus.Properties", + "GetAll", + &error, + &reply, + "s", ""); + if (r < 0) + return r; + + r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}"); + if (r < 0) + return r; + + while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) { + const char *name; + const char *contents; + + r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name); + if (r < 0) + return r; + + if (!filter || strv_find(filter, name)) { + r = sd_bus_message_peek_type(reply, NULL, &contents); + if (r < 0) + return r; + + r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents); + if (r < 0) + return r; + + r = bus_print_property(name, reply, value, all); + if (r < 0) + return r; + if (r == 0) { + if (all) + printf("%s=[unprintable]\n", name); + /* skip what we didn't read */ + r = sd_bus_message_skip(reply, contents); + if (r < 0) + return r; + } + + r = sd_bus_message_exit_container(reply); + if (r < 0) + return r; + } else { + r = sd_bus_message_skip(reply, "v"); + if (r < 0) + return r; + } + + r = sd_bus_message_exit_container(reply); + if (r < 0) + return r; + } + if (r < 0) + return r; + + r = sd_bus_message_exit_container(reply); + if (r < 0) + return r; + + return 0; +} + +int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) { + sd_id128_t *p = userdata; + const void *v; + size_t n; + int r; + + r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n); + if (r < 0) + return r; + + if (n == 0) + *p = SD_ID128_NULL; + else if (n == 16) + memcpy((*p).bytes, v, n); + else + return -EINVAL; + + return 0; +} + +static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) { + char type; + int r; + + r = sd_bus_message_peek_type(m, &type, NULL); + if (r < 0) + return r; + + switch (type) { + case SD_BUS_TYPE_STRING: { + const char *s; + char **p = userdata; + + r = sd_bus_message_read_basic(m, type, &s); + if (r < 0) + break; + + if (isempty(s)) + break; + + r = free_and_strdup(p, s); + break; + } + + case SD_BUS_TYPE_ARRAY: { + _cleanup_strv_free_ char **l = NULL; + char ***p = userdata; + + r = bus_message_read_strv_extend(m, &l); + if (r < 0) + break; + + strv_free(*p); + *p = l; + l = NULL; + + break; + } + + case SD_BUS_TYPE_BOOLEAN: { + unsigned b; + int *p = userdata; + + r = sd_bus_message_read_basic(m, type, &b); + if (r < 0) + break; + + *p = b; + + break; + } + + case SD_BUS_TYPE_UINT32: { + uint32_t u; + uint32_t *p = userdata; + + r = sd_bus_message_read_basic(m, type, &u); + if (r < 0) + break; + + *p = u; + + break; + } + + case SD_BUS_TYPE_UINT64: { + uint64_t t; + uint64_t *p = userdata; + + r = sd_bus_message_read_basic(m, type, &t); + if (r < 0) + break; + + *p = t; + + break; + } + + case SD_BUS_TYPE_DOUBLE: { + double d; + double *p = userdata; + + r = sd_bus_message_read_basic(m, type, &d); + if (r < 0) + break; + + *p = d; + + break; + } + + default: + break; + } + + return r; +} + +int bus_message_map_all_properties( + sd_bus_message *m, + const struct bus_properties_map *map, + void *userdata) { + + _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; + int r; + + assert(m); + assert(map); + + r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}"); + if (r < 0) + return r; + + while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) { + const struct bus_properties_map *prop; + const char *member; + const char *contents; + void *v; + unsigned i; + + r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member); + if (r < 0) + return r; + + for (i = 0, prop = NULL; map[i].member; i++) + if (streq(map[i].member, member)) { + prop = &map[i]; + break; + } + + if (prop) { + r = sd_bus_message_peek_type(m, NULL, &contents); + if (r < 0) + return r; + + r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents); + if (r < 0) + return r; + + v = (uint8_t *)userdata + prop->offset; + if (map[i].set) + r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v); + else + r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v); + if (r < 0) + return r; + + r = sd_bus_message_exit_container(m); + if (r < 0) + return r; + } else { + r = sd_bus_message_skip(m, "v"); + if (r < 0) + return r; + } + + r = sd_bus_message_exit_container(m); + if (r < 0) + return r; + } + if (r < 0) + return r; + + return sd_bus_message_exit_container(m); +} + +int bus_message_map_properties_changed( + sd_bus_message *m, + const struct bus_properties_map *map, + void *userdata) { + + const char *member; + int r, invalidated, i; + + assert(m); + assert(map); + + r = bus_message_map_all_properties(m, map, userdata); + if (r < 0) + return r; + + r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s"); + if (r < 0) + return r; + + invalidated = 0; + while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0) + for (i = 0; map[i].member; i++) + if (streq(map[i].member, member)) { + ++invalidated; + break; + } + if (r < 0) + return r; + + r = sd_bus_message_exit_container(m); + if (r < 0) + return r; + + return invalidated; +} + +int bus_map_all_properties( + sd_bus *bus, + const char *destination, + const char *path, + const struct bus_properties_map *map, + void *userdata) { + + _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; + _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; + int r; + + assert(bus); + assert(destination); + assert(path); + assert(map); + + r = sd_bus_call_method( + bus, + destination, + path, + "org.freedesktop.DBus.Properties", + "GetAll", + &error, + &m, + "s", ""); + if (r < 0) + return r; + + return bus_message_map_all_properties(m, map, userdata); +} + +int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) { + int r; + + assert(transport >= 0); + assert(transport < _BUS_TRANSPORT_MAX); + assert(bus); + + assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL); + assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP); + + switch (transport) { + + case BUS_TRANSPORT_LOCAL: + if (user) + r = sd_bus_default_user(bus); + else + r = sd_bus_default_system(bus); + + break; + + case BUS_TRANSPORT_REMOTE: + r = sd_bus_open_system_remote(bus, host); + break; + + case BUS_TRANSPORT_MACHINE: + r = sd_bus_open_system_machine(bus, host); + break; + + default: + assert_not_reached("Hmm, unknown transport type."); + } + + return r; +} + +int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) { + int r; + + assert(transport >= 0); + assert(transport < _BUS_TRANSPORT_MAX); + assert(bus); + + assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL); + assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP); + + switch (transport) { + + case BUS_TRANSPORT_LOCAL: + if (user) + r = bus_connect_user_systemd(bus); + else + r = bus_connect_system_systemd(bus); + + break; + + case BUS_TRANSPORT_REMOTE: + r = sd_bus_open_system_remote(bus, host); + break; + + case BUS_TRANSPORT_MACHINE: + r = sd_bus_open_system_machine(bus, host); + break; + + default: + assert_not_reached("Hmm, unknown transport type."); + } + + return r; +} + +int bus_property_get_bool( + sd_bus *bus, + const char *path, + const char *interface, + const char *property, + sd_bus_message *reply, + void *userdata, + sd_bus_error *error) { + + int b = *(bool*) userdata; + + return sd_bus_message_append_basic(reply, 'b', &b); +} + +#if __SIZEOF_SIZE_T__ != 8 +int bus_property_get_size( + sd_bus *bus, + const char *path, + const char *interface, + const char *property, + sd_bus_message *reply, + void *userdata, + sd_bus_error *error) { + + uint64_t sz = *(size_t*) userdata; + + return sd_bus_message_append_basic(reply, 't', &sz); +} +#endif + +#if __SIZEOF_LONG__ != 8 +int bus_property_get_long( + sd_bus *bus, + const char *path, + const char *interface, + const char *property, + sd_bus_message *reply, + void *userdata, + sd_bus_error *error) { + + int64_t l = *(long*) userdata; + + return sd_bus_message_append_basic(reply, 'x', &l); +} + +int bus_property_get_ulong( + sd_bus *bus, + const char *path, + const char *interface, + const char *property, + sd_bus_message *reply, + void *userdata, + sd_bus_error *error) { + + uint64_t ul = *(unsigned long*) userdata; + + return sd_bus_message_append_basic(reply, 't', &ul); +} +#endif + +int bus_log_parse_error(int r) { + return log_error_errno(r, "Failed to parse bus message: %m"); +} + +int bus_log_create_error(int r) { + return log_error_errno(r, "Failed to create bus message: %m"); +} + +/** + * bus_path_encode_unique() - encode unique object path + * @b: bus connection or NULL + * @prefix: object path prefix + * @sender_id: unique-name of client, or NULL + * @external_id: external ID to be chosen by client, or NULL + * @ret_path: storage for encoded object path pointer + * + * Whenever we provide a bus API that allows clients to create and manage + * server-side objects, we need to provide a unique name for these objects. If + * we let the server choose the name, we suffer from a race condition: If a + * client creates an object asynchronously, it cannot destroy that object until + * it received the method reply. It cannot know the name of the new object, + * thus, it cannot destroy it. Furthermore, it enforces a round-trip. + * + * Therefore, many APIs allow the client to choose the unique name for newly + * created objects. There're two problems to solve, though: + * 1) Object names are usually defined via dbus object paths, which are + * usually globally namespaced. Therefore, multiple clients must be able + * to choose unique object names without interference. + * 2) If multiple libraries share the same bus connection, they must be + * able to choose unique object names without interference. + * The first problem is solved easily by prefixing a name with the + * unique-bus-name of a connection. The server side must enforce this and + * reject any other name. The second problem is solved by providing unique + * suffixes from within sd-bus. + * + * This helper allows clients to create unique object-paths. It uses the + * template '/prefix/sender_id/external_id' and returns the new path in + * @ret_path (must be freed by the caller). + * If @sender_id is NULL, the unique-name of @b is used. If @external_id is + * NULL, this function allocates a unique suffix via @b (by requesting a new + * cookie). If both @sender_id and @external_id are given, @b can be passed as + * NULL. + * + * Returns: 0 on success, negative error code on failure. + */ +int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) { + _cleanup_free_ char *sender_label = NULL, *external_label = NULL; + char external_buf[DECIMAL_STR_MAX(uint64_t)], *p; + int r; + + assert_return(b || (sender_id && external_id), -EINVAL); + assert_return(object_path_is_valid(prefix), -EINVAL); + assert_return(ret_path, -EINVAL); + + if (!sender_id) { + r = sd_bus_get_unique_name(b, &sender_id); + if (r < 0) + return r; + } + + if (!external_id) { + xsprintf(external_buf, "%"PRIu64, ++b->cookie); + external_id = external_buf; + } + + sender_label = bus_label_escape(sender_id); + if (!sender_label) + return -ENOMEM; + + external_label = bus_label_escape(external_id); + if (!external_label) + return -ENOMEM; + + p = strjoin(prefix, "/", sender_label, "/", external_label, NULL); + if (!p) + return -ENOMEM; + + *ret_path = p; + return 0; +} + +/** + * bus_path_decode_unique() - decode unique object path + * @path: object path to decode + * @prefix: object path prefix + * @ret_sender: output parameter for sender-id label + * @ret_external: output parameter for external-id label + * + * This does the reverse of bus_path_encode_unique() (see its description for + * details). Both trailing labels, sender-id and external-id, are unescaped and + * returned in the given output parameters (the caller must free them). + * + * Note that this function returns 0 if the path does not match the template + * (see bus_path_encode_unique()), 1 if it matched. + * + * Returns: Negative error code on failure, 0 if the given object path does not + * match the template (return parameters are set to NULL), 1 if it was + * parsed successfully (return parameters contain allocated labels). + */ +int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) { + const char *p, *q; + char *sender, *external; + + assert(object_path_is_valid(path)); + assert(object_path_is_valid(prefix)); + assert(ret_sender); + assert(ret_external); + + p = object_path_startswith(path, prefix); + if (!p) { + *ret_sender = NULL; + *ret_external = NULL; + return 0; + } + + q = strchr(p, '/'); + if (!q) { + *ret_sender = NULL; + *ret_external = NULL; + return 0; + } + + sender = bus_label_unescape_n(p, q - p); + external = bus_label_unescape(q + 1); + if (!sender || !external) { + free(sender); + free(external); + return -ENOMEM; + } + + *ret_sender = sender; + *ret_external = external; + return 1; +} + +int bus_property_get_rlimit( + sd_bus *bus, + const char *path, + const char *interface, + const char *property, + sd_bus_message *reply, + void *userdata, + sd_bus_error *error) { + + struct rlimit *rl; + uint64_t u; + rlim_t x; + const char *is_soft; + + assert(bus); + assert(reply); + assert(userdata); + + is_soft = endswith(property, "Soft"); + rl = *(struct rlimit**) userdata; + if (rl) + x = is_soft ? rl->rlim_cur : rl->rlim_max; + else { + struct rlimit buf = {}; + int z; + const char *s; + + s = is_soft ? strndupa(property, is_soft - property) : property; + + z = rlimit_from_string(strstr(s, "Limit")); + assert(z >= 0); + + getrlimit(z, &buf); + x = is_soft ? buf.rlim_cur : buf.rlim_max; + } + + /* rlim_t might have different sizes, let's map + * RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on + * all archs */ + u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x; + + return sd_bus_message_append(reply, "t", u); +} diff --git a/src/libsystemd/src/sd-bus/bus-util.h b/src/libsystemd/src/sd-bus/bus-util.h new file mode 100644 index 0000000000..6b45fad3ce --- /dev/null +++ b/src/libsystemd/src/sd-bus/bus-util.h @@ -0,0 +1,160 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> +#include <sys/types.h> + +#include <systemd/sd-bus.h> +#include <systemd/sd-event.h> + +#include "systemd-basic/hashmap.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/string-util.h" + +typedef enum BusTransport { + BUS_TRANSPORT_LOCAL, + BUS_TRANSPORT_REMOTE, + BUS_TRANSPORT_MACHINE, + _BUS_TRANSPORT_MAX, + _BUS_TRANSPORT_INVALID = -1 +} BusTransport; + +typedef int (*bus_property_set_t) (sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata); + +struct bus_properties_map { + const char *member; + const char *signature; + bus_property_set_t set; + size_t offset; +}; + +int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata); + +int bus_message_map_all_properties(sd_bus_message *m, const struct bus_properties_map *map, void *userdata); +int bus_message_map_properties_changed(sd_bus_message *m, const struct bus_properties_map *map, void *userdata); +int bus_map_all_properties(sd_bus *bus, const char *destination, const char *path, const struct bus_properties_map *map, void *userdata); + +int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name); + +typedef bool (*check_idle_t)(void *userdata); + +int bus_event_loop_with_idle(sd_event *e, sd_bus *bus, const char *name, usec_t timeout, check_idle_t check_idle, void *userdata); + +int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error); + +int bus_check_peercred(sd_bus *c); + +int bus_test_polkit(sd_bus_message *call, int capability, const char *action, const char **details, uid_t good_user, bool *_challenge, sd_bus_error *e); + +int bus_verify_polkit_async(sd_bus_message *call, int capability, const char *action, const char **details, bool interactive, uid_t good_user, Hashmap **registry, sd_bus_error *error); +void bus_verify_polkit_async_registry_free(Hashmap *registry); + +int bus_connect_system_systemd(sd_bus **_bus); +int bus_connect_user_systemd(sd_bus **_bus); + +int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **bus); +int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus); + +int bus_print_property(const char *name, sd_bus_message *property, bool value, bool all); +int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool value, bool all); + +int bus_property_get_bool(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error); + +#define bus_property_get_usec ((sd_bus_property_get_t) NULL) +#define bus_property_set_usec ((sd_bus_property_set_t) NULL) + +assert_cc(sizeof(int) == sizeof(int32_t)); +#define bus_property_get_int ((sd_bus_property_get_t) NULL) + +assert_cc(sizeof(unsigned) == sizeof(unsigned)); +#define bus_property_get_unsigned ((sd_bus_property_get_t) NULL) + +/* On 64bit machines we can use the default serializer for size_t and + * friends, otherwise we need to cast this manually */ +#if __SIZEOF_SIZE_T__ == 8 +#define bus_property_get_size ((sd_bus_property_get_t) NULL) +#else +int bus_property_get_size(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error); +#endif + +#if __SIZEOF_LONG__ == 8 +#define bus_property_get_long ((sd_bus_property_get_t) NULL) +#define bus_property_get_ulong ((sd_bus_property_get_t) NULL) +#else +int bus_property_get_long(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error); +int bus_property_get_ulong(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error); +#endif + +/* uid_t and friends on Linux 32 bit. This means we can just use the + * default serializer for 32bit unsigned, for serializing it, and map + * it to NULL here */ +assert_cc(sizeof(uid_t) == sizeof(uint32_t)); +#define bus_property_get_uid ((sd_bus_property_get_t) NULL) + +assert_cc(sizeof(gid_t) == sizeof(uint32_t)); +#define bus_property_get_gid ((sd_bus_property_get_t) NULL) + +assert_cc(sizeof(pid_t) == sizeof(uint32_t)); +#define bus_property_get_pid ((sd_bus_property_get_t) NULL) + +assert_cc(sizeof(mode_t) == sizeof(uint32_t)); +#define bus_property_get_mode ((sd_bus_property_get_t) NULL) + +int bus_log_parse_error(int r); +int bus_log_create_error(int r); + +#define BUS_DEFINE_PROPERTY_GET_ENUM(function, name, type) \ + int function(sd_bus *bus, \ + const char *path, \ + const char *interface, \ + const char *property, \ + sd_bus_message *reply, \ + void *userdata, \ + sd_bus_error *error) { \ + \ + const char *value; \ + type *field = userdata; \ + int r; \ + \ + assert(bus); \ + assert(reply); \ + assert(field); \ + \ + value = strempty(name##_to_string(*field)); \ + \ + r = sd_bus_message_append_basic(reply, 's', value); \ + if (r < 0) \ + return r; \ + \ + return 1; \ + } \ + struct __useless_struct_to_allow_trailing_semicolon__ + +#define BUS_PROPERTY_DUAL_TIMESTAMP(name, offset, flags) \ + SD_BUS_PROPERTY(name, "t", bus_property_get_usec, (offset) + offsetof(struct dual_timestamp, realtime), (flags)), \ + SD_BUS_PROPERTY(name "Monotonic", "t", bus_property_get_usec, (offset) + offsetof(struct dual_timestamp, monotonic), (flags)) + +int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path); +int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external); + +int bus_property_get_rlimit(sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error); diff --git a/src/libsystemd/sd-bus/kdbus.h b/src/libsystemd/src/sd-bus/kdbus.h index ecffc6b13c..ecffc6b13c 100644 --- a/src/libsystemd/sd-bus/kdbus.h +++ b/src/libsystemd/src/sd-bus/kdbus.h diff --git a/src/libsystemd/sd-bus/sd-bus.c b/src/libsystemd/src/sd-bus/sd-bus.c index ed5f94e136..52d3e8f2b3 100644 --- a/src/libsystemd/sd-bus/sd-bus.c +++ b/src/libsystemd/src/sd-bus/sd-bus.c @@ -25,14 +25,26 @@ #include <sys/mman.h> #include <unistd.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/bus-label.h" +#include "systemd-basic/cgroup-util.h" +#include "systemd-basic/def.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/hostname-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-container.h" #include "bus-control.h" #include "bus-internal.h" #include "bus-kernel.h" -#include "bus-label.h" #include "bus-message.h" #include "bus-objects.h" #include "bus-protocol.h" @@ -41,17 +53,6 @@ #include "bus-track.h" #include "bus-type.h" #include "bus-util.h" -#include "cgroup-util.h" -#include "def.h" -#include "fd-util.h" -#include "hexdecoct.h" -#include "hostname-util.h" -#include "macro.h" -#include "missing.h" -#include "parse-util.h" -#include "string-util.h" -#include "strv.h" -#include "util.h" #define log_debug_bus_message(m) \ do { \ diff --git a/src/libsystemd/sd-bus/test-bus-benchmark.c b/src/libsystemd/src/sd-bus/test-bus-benchmark.c index 56ac2ab3dd..4561e830c7 100644 --- a/src/libsystemd/sd-bus/test-bus-benchmark.c +++ b/src/libsystemd/src/sd-bus/test-bus-benchmark.c @@ -19,16 +19,17 @@ #include <sys/wait.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/def.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/time-util.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-internal.h" #include "bus-kernel.h" #include "bus-util.h" -#include "def.h" -#include "fd-util.h" -#include "time-util.h" -#include "util.h" #define MAX_SIZE (2*1024*1024) diff --git a/src/libsystemd/sd-bus/test-bus-chat.c b/src/libsystemd/src/sd-bus/test-bus-chat.c index 048c0d19e2..6dc643c173 100644 --- a/src/libsystemd/sd-bus/test-bus-chat.c +++ b/src/libsystemd/src/sd-bus/test-bus-chat.c @@ -22,18 +22,19 @@ #include <stdlib.h> #include <unistd.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-error.h" #include "bus-internal.h" #include "bus-match.h" #include "bus-util.h" -#include "fd-util.h" -#include "formats-util.h" -#include "log.h" -#include "macro.h" -#include "util.h" static int match_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { log_info("Match triggered! interface=%s member=%s", strna(sd_bus_message_get_interface(m)), strna(sd_bus_message_get_member(m))); diff --git a/src/libsystemd/sd-bus/test-bus-cleanup.c b/src/libsystemd/src/sd-bus/test-bus-cleanup.c index 250a5b2908..1a461032cc 100644 --- a/src/libsystemd/sd-bus/test-bus-cleanup.c +++ b/src/libsystemd/src/sd-bus/test-bus-cleanup.c @@ -19,12 +19,13 @@ #include <stdio.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/refcnt.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-util.h" -#include "refcnt.h" static void test_bus_new(void) { _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL; diff --git a/src/libsystemd/sd-bus/test-bus-creds.c b/src/libsystemd/src/sd-bus/test-bus-creds.c index e9ef483bdd..fd226e06d2 100644 --- a/src/libsystemd/sd-bus/test-bus-creds.c +++ b/src/libsystemd/src/sd-bus/test-bus-creds.c @@ -17,11 +17,12 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/cgroup-util.h" #include "bus-dump.h" #include "bus-util.h" -#include "cgroup-util.h" int main(int argc, char *argv[]) { _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL; diff --git a/src/libsystemd/sd-bus/test-bus-error.c b/src/libsystemd/src/sd-bus/test-bus-error.c index 66a3874f10..dbc120b4df 100644 --- a/src/libsystemd/sd-bus/test-bus-error.c +++ b/src/libsystemd/src/sd-bus/test-bus-error.c @@ -17,12 +17,13 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/errno-list.h" #include "bus-common-errors.h" #include "bus-error.h" #include "bus-util.h" -#include "errno-list.h" static void test_error(void) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL, second = SD_BUS_ERROR_NULL; diff --git a/src/libsystemd/sd-bus/test-bus-gvariant.c b/src/libsystemd/src/sd-bus/test-bus-gvariant.c index 83f114a0fe..ca396bd426 100644 --- a/src/libsystemd/sd-bus/test-bus-gvariant.c +++ b/src/libsystemd/src/sd-bus/test-bus-gvariant.c @@ -21,16 +21,17 @@ #include <glib.h> #endif -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-dump.h" #include "bus-gvariant.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-util.h" -#include "macro.h" -#include "util.h" static void test_bus_gvariant_is_fixed_size(void) { assert_se(bus_gvariant_is_fixed_size("") > 0); diff --git a/src/libsystemd/sd-bus/test-bus-introspect.c b/src/libsystemd/src/sd-bus/test-bus-introspect.c index 4425cfae26..76a33fee67 100644 --- a/src/libsystemd/sd-bus/test-bus-introspect.c +++ b/src/libsystemd/src/sd-bus/test-bus-introspect.c @@ -17,8 +17,9 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/log.h" + #include "bus-introspect.h" -#include "log.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; diff --git a/src/libsystemd/sd-bus/test-bus-kernel-bloom.c b/src/libsystemd/src/sd-bus/test-bus-kernel-bloom.c index eb6179d7d2..ace45d770d 100644 --- a/src/libsystemd/sd-bus/test-bus-kernel-bloom.c +++ b/src/libsystemd/src/sd-bus/test-bus-kernel-bloom.c @@ -17,14 +17,15 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-kernel.h" #include "bus-util.h" -#include "fd-util.h" -#include "log.h" -#include "util.h" static int test_match(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { int *found = userdata; diff --git a/src/libsystemd/sd-bus/test-bus-kernel.c b/src/libsystemd/src/sd-bus/test-bus-kernel.c index 2214817312..040bfe0dcf 100644 --- a/src/libsystemd/sd-bus/test-bus-kernel.c +++ b/src/libsystemd/src/sd-bus/test-bus-kernel.c @@ -19,15 +19,16 @@ #include <fcntl.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-dump.h" #include "bus-kernel.h" #include "bus-util.h" -#include "fd-util.h" -#include "log.h" -#include "util.h" int main(int argc, char *argv[]) { _cleanup_close_ int bus_ref = -1; diff --git a/src/libsystemd/sd-bus/test-bus-marshal.c b/src/libsystemd/src/sd-bus/test-bus-marshal.c index a28cc5b79e..9c66ba4538 100644 --- a/src/libsystemd/sd-bus/test-bus-marshal.c +++ b/src/libsystemd/src/sd-bus/test-bus-marshal.c @@ -28,17 +28,18 @@ #include <dbus/dbus.h> #endif -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/bus-label.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/log.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-dump.h" -#include "bus-label.h" #include "bus-message.h" #include "bus-util.h" -#include "fd-util.h" -#include "hexdecoct.h" -#include "log.h" -#include "util.h" static void test_bus_path_encode_unique(void) { _cleanup_free_ char *a = NULL, *b = NULL, *c = NULL, *d = NULL, *e = NULL; diff --git a/src/libsystemd/sd-bus/test-bus-match.c b/src/libsystemd/src/sd-bus/test-bus-match.c index 29c4529f95..bedc4d41bd 100644 --- a/src/libsystemd/sd-bus/test-bus-match.c +++ b/src/libsystemd/src/sd-bus/test-bus-match.c @@ -17,12 +17,13 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" + #include "bus-match.h" #include "bus-message.h" #include "bus-slot.h" #include "bus-util.h" -#include "log.h" -#include "macro.h" static bool mask[32]; diff --git a/src/libsystemd/sd-bus/test-bus-objects.c b/src/libsystemd/src/sd-bus/test-bus-objects.c index f11cafd888..379c6f85ee 100644 --- a/src/libsystemd/sd-bus/test-bus-objects.c +++ b/src/libsystemd/src/sd-bus/test-bus-objects.c @@ -20,17 +20,18 @@ #include <pthread.h> #include <stdlib.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-dump.h" #include "bus-internal.h" #include "bus-message.h" #include "bus-util.h" -#include "log.h" -#include "macro.h" -#include "strv.h" -#include "util.h" struct context { int fds[2]; diff --git a/src/libsystemd/sd-bus/test-bus-server.c b/src/libsystemd/src/sd-bus/test-bus-server.c index b6272efc30..ce78faaefb 100644 --- a/src/libsystemd/sd-bus/test-bus-server.c +++ b/src/libsystemd/src/sd-bus/test-bus-server.c @@ -20,13 +20,14 @@ #include <pthread.h> #include <stdlib.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/util.h" #include "bus-internal.h" #include "bus-util.h" -#include "log.h" -#include "macro.h" -#include "util.h" struct context { int fds[2]; diff --git a/src/libsystemd/sd-bus/test-bus-signature.c b/src/libsystemd/src/sd-bus/test-bus-signature.c index 4f4fd093bf..ae50f50f08 100644 --- a/src/libsystemd/sd-bus/test-bus-signature.c +++ b/src/libsystemd/src/sd-bus/test-bus-signature.c @@ -17,10 +17,11 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ +#include "systemd-basic/log.h" +#include "systemd-basic/string-util.h" + #include "bus-internal.h" #include "bus-signature.h" -#include "log.h" -#include "string-util.h" int main(int argc, char *argv[]) { char prefix[256]; diff --git a/src/libsystemd/sd-bus/test-bus-zero-copy.c b/src/libsystemd/src/sd-bus/test-bus-zero-copy.c index 3380e8500a..32ff9c0364 100644 --- a/src/libsystemd/sd-bus/test-bus-zero-copy.c +++ b/src/libsystemd/src/sd-bus/test-bus-zero-copy.c @@ -19,17 +19,18 @@ #include <sys/mman.h> -#include "sd-bus.h" +#include <systemd/sd-bus.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/memfd-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" -#include "alloc-util.h" #include "bus-dump.h" #include "bus-kernel.h" #include "bus-message.h" -#include "fd-util.h" -#include "log.h" -#include "memfd-util.h" -#include "string-util.h" -#include "util.h" #define FIRST_ARRAY 17 #define SECOND_ARRAY 33 diff --git a/src/libsystemd/src/sd-daemon/Makefile b/src/libsystemd/src/sd-daemon/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-daemon/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-daemon/sd-daemon.c b/src/libsystemd/src/sd-daemon/sd-daemon.c index b20a7ebb4c..1424d60a78 100644 --- a/src/libsystemd/sd-daemon/sd-daemon.c +++ b/src/libsystemd/src/sd-daemon/sd-daemon.c @@ -31,16 +31,16 @@ #include <sys/un.h> #include <unistd.h> -#include "sd-daemon.h" - -#include "alloc-util.h" -#include "fd-util.h" -#include "fs-util.h" -#include "parse-util.h" -#include "path-util.h" -#include "socket-util.h" -#include "strv.h" -#include "util.h" +#include <systemd/sd-daemon.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" #define SNDBUF_SIZE (8*1024*1024) diff --git a/src/libsystemd/src/sd-device/Makefile b/src/libsystemd/src/sd-device/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-device/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-device/device-enumerator-private.h b/src/libsystemd/src/sd-device/device-enumerator-private.h index eb06f9542d..7bf39d188a 100644 --- a/src/libsystemd/sd-device/device-enumerator-private.h +++ b/src/libsystemd/src/sd-device/device-enumerator-private.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-device.h" +#include "systemd-staging/sd-device.h" int device_enumerator_scan_devices(sd_device_enumerator *enumeartor); int device_enumerator_scan_subsystems(sd_device_enumerator *enumeartor); diff --git a/src/libsystemd/sd-device/device-enumerator.c b/src/libsystemd/src/sd-device/device-enumerator.c index 62d03ae00d..b4577a5a39 100644 --- a/src/libsystemd/sd-device/device-enumerator.c +++ b/src/libsystemd/src/sd-device/device-enumerator.c @@ -18,18 +18,18 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-device.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/dirent-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/prioq.h" +#include "systemd-basic/set.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-device.h" -#include "alloc-util.h" #include "device-enumerator-private.h" #include "device-util.h" -#include "dirent-util.h" -#include "fd-util.h" -#include "prioq.h" -#include "set.h" -#include "string-util.h" -#include "strv.h" -#include "util.h" #define DEVICE_ENUMERATE_MAX_DEPTH 256 diff --git a/src/libsystemd/sd-device/device-internal.h b/src/libsystemd/src/sd-device/device-internal.h index 9fad388953..c2539feb89 100644 --- a/src/libsystemd/sd-device/device-internal.h +++ b/src/libsystemd/src/sd-device/device-internal.h @@ -20,8 +20,8 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "hashmap.h" -#include "set.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/set.h" struct sd_device { uint64_t n_ref; diff --git a/src/libsystemd/sd-device/device-private.c b/src/libsystemd/src/sd-device/device-private.c index 9082d377f4..03c04b5eae 100644 --- a/src/libsystemd/sd-device/device-private.c +++ b/src/libsystemd/src/sd-device/device-private.c @@ -22,28 +22,28 @@ #include <net/if.h> #include <sys/types.h> -#include "sd-device.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/mkdir.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/set.h" +#include "systemd-basic/string-table.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/strxcpyx.h" +#include "systemd-basic/user-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-device.h" -#include "alloc-util.h" #include "device-internal.h" #include "device-private.h" #include "device-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "fs-util.h" -#include "hashmap.h" -#include "macro.h" -#include "mkdir.h" -#include "parse-util.h" -#include "path-util.h" -#include "refcnt.h" -#include "set.h" -#include "string-table.h" -#include "string-util.h" -#include "strv.h" -#include "strxcpyx.h" -#include "user-util.h" -#include "util.h" int device_add_property(sd_device *device, const char *key, const char *value) { int r; diff --git a/src/libsystemd/sd-device/device-private.h b/src/libsystemd/src/sd-device/device-private.h index 29b3e155fb..504507e3cb 100644 --- a/src/libsystemd/sd-device/device-private.h +++ b/src/libsystemd/src/sd-device/device-private.h @@ -23,7 +23,7 @@ #include <stdbool.h> #include <sys/types.h> -#include "sd-device.h" +#include "systemd-staging/sd-device.h" int device_new_from_nulstr(sd_device **ret, uint8_t *nulstr, size_t len); int device_new_from_strv(sd_device **ret, char **strv); diff --git a/src/libsystemd/sd-device/device-util.h b/src/libsystemd/src/sd-device/device-util.h index 5b42e11de6..40bfa62de1 100644 --- a/src/libsystemd/sd-device/device-util.h +++ b/src/libsystemd/src/sd-device/device-util.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "util.h" +#include "systemd-basic/util.h" #define FOREACH_DEVICE_PROPERTY(device, key, value) \ for (key = sd_device_get_property_first(device, &(value)); \ diff --git a/src/libsystemd/sd-device/sd-device.c b/src/libsystemd/src/sd-device/sd-device.c index 0c4ad966bd..3f7e21af96 100644 --- a/src/libsystemd/sd-device/sd-device.c +++ b/src/libsystemd/src/sd-device/sd-device.c @@ -22,25 +22,25 @@ #include <net/if.h> #include <sys/types.h> -#include "sd-device.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/set.h" +#include "systemd-basic/stat-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/strxcpyx.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-device.h" -#include "alloc-util.h" #include "device-internal.h" #include "device-private.h" #include "device-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "fs-util.h" -#include "hashmap.h" -#include "macro.h" -#include "parse-util.h" -#include "path-util.h" -#include "set.h" -#include "stat-util.h" -#include "string-util.h" -#include "strv.h" -#include "strxcpyx.h" -#include "util.h" int device_new_aux(sd_device **ret) { _cleanup_(sd_device_unrefp) sd_device *device = NULL; diff --git a/src/libsystemd/src/sd-event/Makefile b/src/libsystemd/src/sd-event/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-event/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-event/sd-event.c b/src/libsystemd/src/sd-event/sd-event.c index 9857f8b1fc..3dcf70999c 100644 --- a/src/libsystemd/sd-event/sd-event.c +++ b/src/libsystemd/src/sd-event/sd-event.c @@ -21,24 +21,24 @@ #include <sys/timerfd.h> #include <sys/wait.h> -#include "sd-daemon.h" -#include "sd-event.h" -#include "sd-id128.h" - -#include "alloc-util.h" -#include "fd-util.h" -#include "hashmap.h" -#include "list.h" -#include "macro.h" -#include "missing.h" -#include "prioq.h" -#include "process-util.h" -#include "set.h" -#include "signal-util.h" -#include "string-table.h" -#include "string-util.h" -#include "time-util.h" -#include "util.h" +#include <systemd/sd-daemon.h> +#include <systemd/sd-event.h> +#include <systemd/sd-id128.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/list.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/prioq.h" +#include "systemd-basic/process-util.h" +#include "systemd-basic/set.h" +#include "systemd-basic/signal-util.h" +#include "systemd-basic/string-table.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/time-util.h" +#include "systemd-basic/util.h" #define DEFAULT_ACCURACY_USEC (250 * USEC_PER_MSEC) diff --git a/src/libsystemd/sd-event/test-event.c b/src/libsystemd/src/sd-event/test-event.c index 289114490c..7c1289423f 100644 --- a/src/libsystemd/sd-event/test-event.c +++ b/src/libsystemd/src/sd-event/test-event.c @@ -17,13 +17,13 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-event.h" +#include <systemd/sd-event.h> -#include "fd-util.h" -#include "log.h" -#include "macro.h" -#include "signal-util.h" -#include "util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/signal-util.h" +#include "systemd-basic/util.h" static int prepare_handler(sd_event_source *s, void *userdata) { log_info("preparing %c", PTR_TO_INT(userdata)); diff --git a/src/libsystemd/src/sd-hwdb/Makefile b/src/libsystemd/src/sd-hwdb/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-hwdb/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-hwdb/hwdb-internal.h b/src/libsystemd/src/sd-hwdb/hwdb-internal.h index 8ffb5e5c74..35d4378122 100644 --- a/src/libsystemd/sd-hwdb/hwdb-internal.h +++ b/src/libsystemd/src/sd-hwdb/hwdb-internal.h @@ -19,8 +19,8 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sparse-endian.h" -#include "util.h" +#include "systemd-basic/sparse-endian.h" +#include "systemd-basic/util.h" #define HWDB_SIG { 'K', 'S', 'L', 'P', 'H', 'H', 'R', 'H' } diff --git a/src/libsystemd/sd-hwdb/hwdb-util.h b/src/libsystemd/src/sd-hwdb/hwdb-util.h index 5e21e5008b..5585965c83 100644 --- a/src/libsystemd/sd-hwdb/hwdb-util.h +++ b/src/libsystemd/src/sd-hwdb/hwdb-util.h @@ -19,8 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-hwdb.h" - -#include "util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-hwdb.h" bool hwdb_validate(sd_hwdb *hwdb); diff --git a/src/libsystemd/sd-hwdb/sd-hwdb.c b/src/libsystemd/src/sd-hwdb/sd-hwdb.c index 062fa97b17..0891719604 100644 --- a/src/libsystemd/sd-hwdb/sd-hwdb.c +++ b/src/libsystemd/src/sd-hwdb/sd-hwdb.c @@ -27,15 +27,15 @@ #include <string.h> #include <sys/mman.h> -#include "sd-hwdb.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/string-util.h" +#include "systemd-staging/sd-hwdb.h" -#include "alloc-util.h" -#include "fd-util.h" -#include "hashmap.h" #include "hwdb-internal.h" #include "hwdb-util.h" -#include "refcnt.h" -#include "string-util.h" struct sd_hwdb { RefCount n_ref; diff --git a/src/libsystemd/src/sd-id128/Makefile b/src/libsystemd/src/sd-id128/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-id128/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-id128/id128-util.c b/src/libsystemd/src/sd-id128/id128-util.c index c3f527d657..cd32543d0c 100644 --- a/src/libsystemd/sd-id128/id128-util.c +++ b/src/libsystemd/src/sd-id128/id128-util.c @@ -20,11 +20,12 @@ #include <fcntl.h> #include <unistd.h> -#include "fd-util.h" -#include "hexdecoct.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/stdio-util.h" + #include "id128-util.h" -#include "io-util.h" -#include "stdio-util.h" char *id128_to_uuid_string(sd_id128_t id, char s[37]) { unsigned n, k = 0; diff --git a/src/libsystemd/sd-id128/id128-util.h b/src/libsystemd/src/sd-id128/id128-util.h index 3ba59acbca..0c57d693e5 100644 --- a/src/libsystemd/sd-id128/id128-util.h +++ b/src/libsystemd/src/sd-id128/id128-util.h @@ -21,8 +21,9 @@ #include <stdbool.h> -#include "sd-id128.h" -#include "macro.h" +#include <systemd/sd-id128.h> + +#include "systemd-basic/macro.h" char *id128_to_uuid_string(sd_id128_t id, char s[37]); diff --git a/src/libsystemd/sd-id128/sd-id128.c b/src/libsystemd/src/sd-id128/sd-id128.c index 9f47d04e61..9c036fb4cb 100644 --- a/src/libsystemd/sd-id128/sd-id128.c +++ b/src/libsystemd/src/sd-id128/sd-id128.c @@ -21,15 +21,16 @@ #include <fcntl.h> #include <unistd.h> -#include "sd-id128.h" +#include <systemd/sd-id128.h> + +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/random-util.h" +#include "systemd-basic/util.h" -#include "fd-util.h" -#include "hexdecoct.h" #include "id128-util.h" -#include "io-util.h" -#include "macro.h" -#include "random-util.h" -#include "util.h" _public_ char *sd_id128_to_string(sd_id128_t id, char s[SD_ID128_STRING_MAX]) { unsigned n; diff --git a/src/libsystemd/src/sd-journal/Makefile b/src/libsystemd/src/sd-journal/Makefile new file mode 100644 index 0000000000..d0415fb0d3 --- /dev/null +++ b/src/libsystemd/src/sd-journal/Makefile @@ -0,0 +1,42 @@ +# -*- Mode: makefile; indent-tabs-mode: t -*- +# +# This file is part of systemd. +# +# Copyright 2010-2012 Lennart Poettering +# Copyright 2010-2012 Kay Sievers +# Copyright 2013 Zbigniew Jędrzejewski-Szmek +# Copyright 2013 David Strauss +# Copyright 2016 Luke Shumaker +# +# 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 <http://www.gnu.org/licenses/>. +include $(dir $(lastword $(MAKEFILE_LIST)))/../../../../config.mk +include $(topsrcdir)/build-aux/Makefile.head.mk + +audit_list_includes = -include linux/audit.h -include missing.h +ifneq ($(HAVE_AUDIT),) +audit_list_includes += -include libaudit.h +endif # HAVE_AUDIT + +$(outdir)/audit_type-list.txt: + $(AM_V_GEN)$(CPP) $(sd.ALL_CPPFLAGS) -dM $(audit_list_includes) - </dev/null | grep -vE 'AUDIT_.*(FIRST|LAST)_' | $(SED) -r -n 's/^#define\s+AUDIT_(\w+)\s+([0-9]{4})\s*$$/\1\t\2/p' | sort -k2 >$@ + +$(outdir)/audit_type-to-name.h: $(outdir)/audit_type-list.txt + $(AM_V_GEN)$(AWK) 'BEGIN{ print "const char *audit_type_to_string(int type) {\n\tswitch(type) {" } {printf " case AUDIT_%s: return \"%s\";\n", $$1, $$1 } END{ print " default: return NULL;\n\t}\n}\n" }' <$< >$@ + +# fsprg.c is a drop-in file using void pointer arithmetic +libsystemd_journal_internal_la_CFLAGS += \ + $(GCRYPT_CFLAGS) \ + -Wno-pointer-arith + +include $(topsrcdir)/build-aux/Makefile.tail.mk diff --git a/src/libsystemd/src/sd-journal/audit-type.c b/src/libsystemd/src/sd-journal/audit-type.c new file mode 100644 index 0000000000..1644e3f1b1 --- /dev/null +++ b/src/libsystemd/src/sd-journal/audit-type.c @@ -0,0 +1,31 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <stdio.h> + +#include <linux/audit.h> +#ifdef HAVE_AUDIT +# include <libaudit.h> +#endif + +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" + +#include "audit-type.h" +#include "audit_type-to-name.h" diff --git a/src/libsystemd/src/sd-journal/audit-type.h b/src/libsystemd/src/sd-journal/audit-type.h new file mode 100644 index 0000000000..0b4748b01f --- /dev/null +++ b/src/libsystemd/src/sd-journal/audit-type.h @@ -0,0 +1,37 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include "systemd-basic/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/libsystemd/src/sd-journal/catalog.c b/src/libsystemd/src/sd-journal/catalog.c new file mode 100644 index 0000000000..fce4649f6f --- /dev/null +++ b/src/libsystemd/src/sd-journal/catalog.c @@ -0,0 +1,768 @@ +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <fcntl.h> +#include <locale.h> +#include <stdio.h> +#include <string.h> +#include <sys/mman.h> +#include <unistd.h> + +#include <systemd/sd-id128.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/conf-files.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/log.h" +#include "systemd-basic/mkdir.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/siphash24.h" +#include "systemd-basic/sparse-endian.h" +#include "systemd-basic/strbuf.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" + +#include "catalog.h" + +const char * const catalog_file_dirs[] = { + "/usr/local/lib/systemd/catalog/", + "/usr/lib/systemd/catalog/", + NULL +}; + +#define CATALOG_SIGNATURE (uint8_t[]) { 'R', 'H', 'H', 'H', 'K', 'S', 'L', 'P' } + +typedef struct CatalogHeader { + uint8_t signature[8]; /* "RHHHKSLP" */ + le32_t compatible_flags; + le32_t incompatible_flags; + le64_t header_size; + le64_t n_items; + le64_t catalog_item_size; +} CatalogHeader; + +typedef struct CatalogItem { + sd_id128_t id; + char language[32]; + le64_t offset; +} CatalogItem; + +static void catalog_hash_func(const void *p, struct siphash *state) { + const CatalogItem *i = p; + + siphash24_compress(&i->id, sizeof(i->id), state); + siphash24_compress(i->language, strlen(i->language), state); +} + +static int catalog_compare_func(const void *a, const void *b) { + const CatalogItem *i = a, *j = b; + unsigned k; + + for (k = 0; k < ELEMENTSOF(j->id.bytes); k++) { + if (i->id.bytes[k] < j->id.bytes[k]) + return -1; + if (i->id.bytes[k] > j->id.bytes[k]) + return 1; + } + + return strcmp(i->language, j->language); +} + +const struct hash_ops catalog_hash_ops = { + .hash = catalog_hash_func, + .compare = catalog_compare_func +}; + +static bool next_header(const char **s) { + const char *e; + + e = strchr(*s, '\n'); + + /* Unexpected end */ + if (!e) + return false; + + /* End of headers */ + if (e == *s) + return false; + + *s = e + 1; + return true; +} + +static const char *skip_header(const char *s) { + while (next_header(&s)) + ; + return s; +} + +static char *combine_entries(const char *one, const char *two) { + const char *b1, *b2; + size_t l1, l2, n; + char *dest, *p; + + /* Find split point of headers to body */ + b1 = skip_header(one); + b2 = skip_header(two); + + l1 = strlen(one); + l2 = strlen(two); + dest = new(char, l1 + l2 + 1); + if (!dest) { + log_oom(); + return NULL; + } + + p = dest; + + /* Headers from @one */ + n = b1 - one; + p = mempcpy(p, one, n); + + /* Headers from @two, these will only be found if not present above */ + n = b2 - two; + p = mempcpy(p, two, n); + + /* Body from @one */ + n = l1 - (b1 - one); + if (n > 0) { + memcpy(p, b1, n); + p += n; + + /* Body from @two */ + } else { + n = l2 - (b2 - two); + memcpy(p, b2, n); + p += n; + } + + assert(p - dest <= (ptrdiff_t)(l1 + l2)); + p[0] = '\0'; + return dest; +} + +static int finish_item( + Hashmap *h, + sd_id128_t id, + const char *language, + char *payload, size_t payload_size) { + + _cleanup_free_ CatalogItem *i = NULL; + _cleanup_free_ char *prev = NULL, *combined = NULL; + + assert(h); + assert(payload); + assert(payload_size > 0); + + i = new0(CatalogItem, 1); + if (!i) + return log_oom(); + + i->id = id; + if (language) { + assert(strlen(language) > 1 && strlen(language) < 32); + strcpy(i->language, language); + } + + prev = hashmap_get(h, i); + if (prev) { + /* Already have such an item, combine them */ + combined = combine_entries(payload, prev); + if (!combined) + return log_oom(); + + if (hashmap_update(h, i, combined) < 0) + return log_oom(); + combined = NULL; + } else { + /* A new item */ + combined = memdup(payload, payload_size + 1); + if (!combined) + return log_oom(); + + if (hashmap_put(h, i, combined) < 0) + return log_oom(); + i = NULL; + combined = NULL; + } + + return 0; +} + +int catalog_file_lang(const char* filename, char **lang) { + char *beg, *end, *_lang; + + end = endswith(filename, ".catalog"); + if (!end) + return 0; + + beg = end - 1; + while (beg > filename && *beg != '.' && *beg != '/' && end - beg < 32) + beg--; + + if (*beg != '.' || end <= beg + 1) + return 0; + + _lang = strndup(beg + 1, end - beg - 1); + if (!_lang) + return -ENOMEM; + + *lang = _lang; + return 1; +} + +static int catalog_entry_lang(const char* filename, int line, + const char* t, const char* deflang, char **lang) { + size_t c; + + c = strlen(t); + if (c == 0) { + log_error("[%s:%u] Language too short.", filename, line); + return -EINVAL; + } + if (c > 31) { + log_error("[%s:%u] language too long.", filename, line); + return -EINVAL; + } + + if (deflang) { + if (streq(t, deflang)) { + log_warning("[%s:%u] language specified unnecessarily", + filename, line); + return 0; + } else + log_warning("[%s:%u] language differs from default for file", + filename, line); + } + + *lang = strdup(t); + if (!*lang) + return -ENOMEM; + + return 0; +} + +int catalog_import_file(Hashmap *h, const char *path) { + _cleanup_fclose_ FILE *f = NULL; + _cleanup_free_ char *payload = NULL; + size_t payload_size = 0, payload_allocated = 0; + unsigned n = 0; + sd_id128_t id; + _cleanup_free_ char *deflang = NULL, *lang = NULL; + bool got_id = false, empty_line = true; + int r; + + assert(h); + assert(path); + + f = fopen(path, "re"); + if (!f) + return log_error_errno(errno, "Failed to open file %s: %m", path); + + r = catalog_file_lang(path, &deflang); + if (r < 0) + log_error_errno(r, "Failed to determine language for file %s: %m", path); + if (r == 1) + log_debug("File %s has language %s.", path, deflang); + + for (;;) { + char line[LINE_MAX]; + size_t line_len; + + if (!fgets(line, sizeof(line), f)) { + if (feof(f)) + break; + + return log_error_errno(errno, "Failed to read file %s: %m", path); + } + + n++; + + truncate_nl(line); + + if (line[0] == 0) { + empty_line = true; + continue; + } + + if (strchr(COMMENTS "\n", line[0])) + continue; + + if (empty_line && + strlen(line) >= 2+1+32 && + line[0] == '-' && + line[1] == '-' && + line[2] == ' ' && + (line[2+1+32] == ' ' || line[2+1+32] == '\0')) { + + bool with_language; + sd_id128_t jd; + + /* New entry */ + + with_language = line[2+1+32] != '\0'; + line[2+1+32] = '\0'; + + if (sd_id128_from_string(line + 2 + 1, &jd) >= 0) { + + if (got_id) { + if (payload_size == 0) { + log_error("[%s:%u] No payload text.", path, n); + return -EINVAL; + } + + r = finish_item(h, id, lang ?: deflang, payload, payload_size); + if (r < 0) + return r; + + lang = mfree(lang); + payload_size = 0; + } + + if (with_language) { + char *t; + + t = strstrip(line + 2 + 1 + 32 + 1); + r = catalog_entry_lang(path, n, t, deflang, &lang); + if (r < 0) + return r; + } + + got_id = true; + empty_line = false; + id = jd; + + continue; + } + } + + /* Payload */ + if (!got_id) { + log_error("[%s:%u] Got payload before ID.", path, n); + return -EINVAL; + } + + line_len = strlen(line); + if (!GREEDY_REALLOC(payload, payload_allocated, + payload_size + (empty_line ? 1 : 0) + line_len + 1 + 1)) + return log_oom(); + + if (empty_line) + payload[payload_size++] = '\n'; + memcpy(payload + payload_size, line, line_len); + payload_size += line_len; + payload[payload_size++] = '\n'; + payload[payload_size] = '\0'; + + empty_line = false; + } + + if (got_id) { + if (payload_size == 0) { + log_error("[%s:%u] No payload text.", path, n); + return -EINVAL; + } + + r = finish_item(h, id, lang ?: deflang, payload, payload_size); + if (r < 0) + return r; + } + + return 0; +} + +static int64_t write_catalog(const char *database, struct strbuf *sb, + CatalogItem *items, size_t n) { + CatalogHeader header; + _cleanup_fclose_ FILE *w = NULL; + int r; + _cleanup_free_ char *d, *p = NULL; + size_t k; + + d = dirname_malloc(database); + if (!d) + return log_oom(); + + r = mkdir_p(d, 0775); + if (r < 0) + return log_error_errno(r, "Recursive mkdir %s: %m", d); + + r = fopen_temporary(database, &w, &p); + if (r < 0) + return log_error_errno(r, "Failed to open database for writing: %s: %m", + database); + + zero(header); + memcpy(header.signature, CATALOG_SIGNATURE, sizeof(header.signature)); + header.header_size = htole64(ALIGN_TO(sizeof(CatalogHeader), 8)); + header.catalog_item_size = htole64(sizeof(CatalogItem)); + header.n_items = htole64(n); + + r = -EIO; + + k = fwrite(&header, 1, sizeof(header), w); + if (k != sizeof(header)) { + log_error("%s: failed to write header.", p); + goto error; + } + + k = fwrite(items, 1, n * sizeof(CatalogItem), w); + if (k != n * sizeof(CatalogItem)) { + log_error("%s: failed to write database.", p); + goto error; + } + + k = fwrite(sb->buf, 1, sb->len, w); + if (k != sb->len) { + log_error("%s: failed to write strings.", p); + goto error; + } + + r = fflush_and_check(w); + if (r < 0) { + log_error_errno(r, "%s: failed to write database: %m", p); + goto error; + } + + fchmod(fileno(w), 0644); + + if (rename(p, database) < 0) { + r = log_error_errno(errno, "rename (%s -> %s) failed: %m", p, database); + goto error; + } + + return ftello(w); + +error: + (void) unlink(p); + return r; +} + +int catalog_update(const char* database, const char* root, const char* const* dirs) { + _cleanup_strv_free_ char **files = NULL; + char **f; + struct strbuf *sb = NULL; + _cleanup_hashmap_free_free_free_ Hashmap *h = NULL; + _cleanup_free_ CatalogItem *items = NULL; + ssize_t offset; + char *payload; + CatalogItem *i; + Iterator j; + unsigned n; + int r; + int64_t sz; + + h = hashmap_new(&catalog_hash_ops); + sb = strbuf_new(); + + if (!h || !sb) { + r = log_oom(); + goto finish; + } + + r = conf_files_list_strv(&files, ".catalog", root, dirs); + if (r < 0) { + log_error_errno(r, "Failed to get catalog files: %m"); + goto finish; + } + + STRV_FOREACH(f, files) { + log_debug("Reading file '%s'", *f); + r = catalog_import_file(h, *f); + if (r < 0) { + log_error_errno(r, "Failed to import file '%s': %m", *f); + goto finish; + } + } + + if (hashmap_size(h) <= 0) { + log_info("No items in catalog."); + goto finish; + } else + log_debug("Found %u items in catalog.", hashmap_size(h)); + + items = new(CatalogItem, hashmap_size(h)); + if (!items) { + r = log_oom(); + goto finish; + } + + n = 0; + HASHMAP_FOREACH_KEY(payload, i, h, j) { + log_debug("Found " SD_ID128_FORMAT_STR ", language %s", + SD_ID128_FORMAT_VAL(i->id), + isempty(i->language) ? "C" : i->language); + + offset = strbuf_add_string(sb, payload, strlen(payload)); + if (offset < 0) { + r = log_oom(); + goto finish; + } + i->offset = htole64((uint64_t) offset); + items[n++] = *i; + } + + assert(n == hashmap_size(h)); + qsort_safe(items, n, sizeof(CatalogItem), catalog_compare_func); + + strbuf_complete(sb); + + sz = write_catalog(database, sb, items, n); + if (sz < 0) + r = log_error_errno(sz, "Failed to write %s: %m", database); + else { + r = 0; + log_debug("%s: wrote %u items, with %zu bytes of strings, %"PRIi64" total size.", + database, n, sb->len, sz); + } + +finish: + strbuf_cleanup(sb); + + return r; +} + +static int open_mmap(const char *database, int *_fd, struct stat *_st, void **_p) { + const CatalogHeader *h; + int fd; + void *p; + struct stat st; + + assert(_fd); + assert(_st); + assert(_p); + + fd = open(database, O_RDONLY|O_CLOEXEC); + if (fd < 0) + return -errno; + + if (fstat(fd, &st) < 0) { + safe_close(fd); + return -errno; + } + + if (st.st_size < (off_t) sizeof(CatalogHeader)) { + safe_close(fd); + return -EINVAL; + } + + p = mmap(NULL, PAGE_ALIGN(st.st_size), PROT_READ, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + safe_close(fd); + return -errno; + } + + h = p; + if (memcmp(h->signature, CATALOG_SIGNATURE, sizeof(h->signature)) != 0 || + le64toh(h->header_size) < sizeof(CatalogHeader) || + le64toh(h->catalog_item_size) < sizeof(CatalogItem) || + h->incompatible_flags != 0 || + le64toh(h->n_items) <= 0 || + st.st_size < (off_t) (le64toh(h->header_size) + le64toh(h->catalog_item_size) * le64toh(h->n_items))) { + safe_close(fd); + munmap(p, st.st_size); + return -EBADMSG; + } + + *_fd = fd; + *_st = st; + *_p = p; + + return 0; +} + +static const char *find_id(void *p, sd_id128_t id) { + CatalogItem key, *f = NULL; + const CatalogHeader *h = p; + const char *loc; + + zero(key); + key.id = id; + + loc = setlocale(LC_MESSAGES, NULL); + if (loc && loc[0] && !streq(loc, "C") && !streq(loc, "POSIX")) { + strncpy(key.language, loc, sizeof(key.language)); + key.language[strcspn(key.language, ".@")] = 0; + + f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func); + if (!f) { + char *e; + + e = strchr(key.language, '_'); + if (e) { + *e = 0; + f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func); + } + } + } + + if (!f) { + zero(key.language); + f = bsearch(&key, (const uint8_t*) p + le64toh(h->header_size), le64toh(h->n_items), le64toh(h->catalog_item_size), catalog_compare_func); + } + + if (!f) + return NULL; + + return (const char*) p + + le64toh(h->header_size) + + le64toh(h->n_items) * le64toh(h->catalog_item_size) + + le64toh(f->offset); +} + +int catalog_get(const char* database, sd_id128_t id, char **_text) { + _cleanup_close_ int fd = -1; + void *p = NULL; + struct stat st = {}; + char *text = NULL; + int r; + const char *s; + + assert(_text); + + r = open_mmap(database, &fd, &st, &p); + if (r < 0) + return r; + + s = find_id(p, id); + if (!s) { + r = -ENOENT; + goto finish; + } + + text = strdup(s); + if (!text) { + r = -ENOMEM; + goto finish; + } + + *_text = text; + r = 0; + +finish: + if (p) + munmap(p, st.st_size); + + return r; +} + +static char *find_header(const char *s, const char *header) { + + for (;;) { + const char *v; + + v = startswith(s, header); + if (v) { + v += strspn(v, WHITESPACE); + return strndup(v, strcspn(v, NEWLINE)); + } + + if (!next_header(&s)) + return NULL; + } +} + +static void dump_catalog_entry(FILE *f, sd_id128_t id, const char *s, bool oneline) { + if (oneline) { + _cleanup_free_ char *subject = NULL, *defined_by = NULL; + + subject = find_header(s, "Subject:"); + defined_by = find_header(s, "Defined-By:"); + + fprintf(f, SD_ID128_FORMAT_STR " %s: %s\n", + SD_ID128_FORMAT_VAL(id), + strna(defined_by), strna(subject)); + } else + fprintf(f, "-- " SD_ID128_FORMAT_STR "\n%s\n", + SD_ID128_FORMAT_VAL(id), s); +} + + +int catalog_list(FILE *f, const char *database, bool oneline) { + _cleanup_close_ int fd = -1; + void *p = NULL; + struct stat st; + const CatalogHeader *h; + const CatalogItem *items; + int r; + unsigned n; + sd_id128_t last_id; + bool last_id_set = false; + + r = open_mmap(database, &fd, &st, &p); + if (r < 0) + return r; + + h = p; + items = (const CatalogItem*) ((const uint8_t*) p + le64toh(h->header_size)); + + for (n = 0; n < le64toh(h->n_items); n++) { + const char *s; + + if (last_id_set && sd_id128_equal(last_id, items[n].id)) + continue; + + assert_se(s = find_id(p, items[n].id)); + + dump_catalog_entry(f, items[n].id, s, oneline); + + last_id_set = true; + last_id = items[n].id; + } + + munmap(p, st.st_size); + + return 0; +} + +int catalog_list_items(FILE *f, const char *database, bool oneline, char **items) { + char **item; + int r = 0; + + STRV_FOREACH(item, items) { + sd_id128_t id; + int k; + _cleanup_free_ char *msg = NULL; + + k = sd_id128_from_string(*item, &id); + if (k < 0) { + log_error_errno(k, "Failed to parse id128 '%s': %m", *item); + if (r == 0) + r = k; + continue; + } + + k = catalog_get(database, id, &msg); + if (k < 0) { + log_full_errno(k == -ENOENT ? LOG_NOTICE : LOG_ERR, k, + "Failed to retrieve catalog entry for '%s': %m", *item); + if (r == 0) + r = k; + continue; + } + + dump_catalog_entry(f, id, msg, oneline); + } + + return r; +} diff --git a/src/libsystemd/src/sd-journal/catalog.h b/src/libsystemd/src/sd-journal/catalog.h new file mode 100644 index 0000000000..49fec555a4 --- /dev/null +++ b/src/libsystemd/src/sd-journal/catalog.h @@ -0,0 +1,36 @@ +#pragma once + +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <stdbool.h> + +#include <systemd/sd-id128.h> + +#include "systemd-basic/hashmap.h" +#include "systemd-basic/strbuf.h" + +int catalog_import_file(Hashmap *h, const char *path); +int catalog_update(const char* database, const char* root, const char* const* dirs); +int catalog_get(const char* database, sd_id128_t id, char **data); +int catalog_list(FILE *f, const char* database, bool oneline); +int catalog_list_items(FILE *f, const char* database, bool oneline, char **items); +int catalog_file_lang(const char *filename, char **lang); +extern const char * const catalog_file_dirs[]; +extern const struct hash_ops catalog_hash_ops; diff --git a/src/libsystemd/src/sd-journal/compress.c b/src/libsystemd/src/sd-journal/compress.c new file mode 100644 index 0000000000..c6c5f3c500 --- /dev/null +++ b/src/libsystemd/src/sd-journal/compress.c @@ -0,0 +1,684 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> +#include <unistd.h> + +#ifdef HAVE_XZ +#include <lzma.h> +#endif + +#ifdef HAVE_LZ4 +#include <lz4.h> +#include <lz4frame.h> +#endif + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/sparse-endian.h" +#include "systemd-basic/string-table.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" + +#include "compress.h" +#include "journal-def.h" + +#ifdef HAVE_LZ4 +DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_compressionContext_t, LZ4F_freeCompressionContext); +DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_decompressionContext_t, LZ4F_freeDecompressionContext); +#endif + +#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t)) + +static const char* const object_compressed_table[_OBJECT_COMPRESSED_MAX] = { + [OBJECT_COMPRESSED_XZ] = "XZ", + [OBJECT_COMPRESSED_LZ4] = "LZ4", +}; + +DEFINE_STRING_TABLE_LOOKUP(object_compressed, int); + +int compress_blob_xz(const void *src, uint64_t src_size, + void *dst, size_t dst_alloc_size, size_t *dst_size) { +#ifdef HAVE_XZ + static const lzma_options_lzma opt = { + 1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT, + LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4 + }; + static const lzma_filter filters[] = { + { LZMA_FILTER_LZMA2, (lzma_options_lzma*) &opt }, + { LZMA_VLI_UNKNOWN, NULL } + }; + lzma_ret ret; + size_t out_pos = 0; + + assert(src); + assert(src_size > 0); + assert(dst); + assert(dst_alloc_size > 0); + assert(dst_size); + + /* Returns < 0 if we couldn't compress the data or the + * compressed result is longer than the original */ + + if (src_size < 80) + return -ENOBUFS; + + ret = lzma_stream_buffer_encode((lzma_filter*) filters, LZMA_CHECK_NONE, NULL, + src, src_size, dst, &out_pos, dst_alloc_size); + if (ret != LZMA_OK) + return -ENOBUFS; + + *dst_size = out_pos; + return 0; +#else + return -EPROTONOSUPPORT; +#endif +} + +int compress_blob_lz4(const void *src, uint64_t src_size, + void *dst, size_t dst_alloc_size, size_t *dst_size) { +#ifdef HAVE_LZ4 + int r; + + assert(src); + assert(src_size > 0); + assert(dst); + assert(dst_alloc_size > 0); + assert(dst_size); + + /* Returns < 0 if we couldn't compress the data or the + * compressed result is longer than the original */ + + if (src_size < 9) + return -ENOBUFS; + + r = LZ4_compress_limitedOutput(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8); + if (r <= 0) + return -ENOBUFS; + + *(le64_t*) dst = htole64(src_size); + *dst_size = r + 8; + + return 0; +#else + return -EPROTONOSUPPORT; +#endif +} + + +int decompress_blob_xz(const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { + +#ifdef HAVE_XZ + _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; + lzma_ret ret; + size_t space; + + assert(src); + assert(src_size > 0); + assert(dst); + assert(dst_alloc_size); + assert(dst_size); + assert(*dst_alloc_size == 0 || *dst); + + ret = lzma_stream_decoder(&s, UINT64_MAX, 0); + if (ret != LZMA_OK) + return -ENOMEM; + + space = MIN(src_size * 2, dst_max ?: (size_t) -1); + if (!greedy_realloc(dst, dst_alloc_size, space, 1)) + return -ENOMEM; + + s.next_in = src; + s.avail_in = src_size; + + s.next_out = *dst; + s.avail_out = space; + + for (;;) { + size_t used; + + ret = lzma_code(&s, LZMA_FINISH); + + if (ret == LZMA_STREAM_END) + break; + else if (ret != LZMA_OK) + return -ENOMEM; + + if (dst_max > 0 && (space - s.avail_out) >= dst_max) + break; + else if (dst_max > 0 && space == dst_max) + return -ENOBUFS; + + used = space - s.avail_out; + space = MIN(2 * space, dst_max ?: (size_t) -1); + if (!greedy_realloc(dst, dst_alloc_size, space, 1)) + return -ENOMEM; + + s.avail_out = space - used; + s.next_out = *(uint8_t**)dst + used; + } + + *dst_size = space - s.avail_out; + return 0; +#else + return -EPROTONOSUPPORT; +#endif +} + +int decompress_blob_lz4(const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { + +#ifdef HAVE_LZ4 + char* out; + int r, size; /* LZ4 uses int for size */ + + assert(src); + assert(src_size > 0); + assert(dst); + assert(dst_alloc_size); + assert(dst_size); + assert(*dst_alloc_size == 0 || *dst); + + if (src_size <= 8) + return -EBADMSG; + + size = le64toh( *(le64_t*)src ); + if (size < 0 || (unsigned) size != le64toh(*(le64_t*)src)) + return -EFBIG; + if ((size_t) size > *dst_alloc_size) { + out = realloc(*dst, size); + if (!out) + return -ENOMEM; + *dst = out; + *dst_alloc_size = size; + } else + out = *dst; + + r = LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size); + if (r < 0 || r != size) + return -EBADMSG; + + *dst_size = size; + return 0; +#else + return -EPROTONOSUPPORT; +#endif +} + +int decompress_blob(int compression, + const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) { + if (compression == OBJECT_COMPRESSED_XZ) + return decompress_blob_xz(src, src_size, + dst, dst_alloc_size, dst_size, dst_max); + else if (compression == OBJECT_COMPRESSED_LZ4) + return decompress_blob_lz4(src, src_size, + dst, dst_alloc_size, dst_size, dst_max); + else + return -EBADMSG; +} + + +int decompress_startswith_xz(const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra) { + +#ifdef HAVE_XZ + _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; + lzma_ret ret; + + /* Checks whether the decompressed blob starts with the + * mentioned prefix. The byte extra needs to follow the + * prefix */ + + assert(src); + assert(src_size > 0); + assert(buffer); + assert(buffer_size); + assert(prefix); + assert(*buffer_size == 0 || *buffer); + + ret = lzma_stream_decoder(&s, UINT64_MAX, 0); + if (ret != LZMA_OK) + return -EBADMSG; + + if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1))) + return -ENOMEM; + + s.next_in = src; + s.avail_in = src_size; + + s.next_out = *buffer; + s.avail_out = *buffer_size; + + for (;;) { + ret = lzma_code(&s, LZMA_FINISH); + + if (ret != LZMA_STREAM_END && ret != LZMA_OK) + return -EBADMSG; + + if (*buffer_size - s.avail_out >= prefix_len + 1) + return memcmp(*buffer, prefix, prefix_len) == 0 && + ((const uint8_t*) *buffer)[prefix_len] == extra; + + if (ret == LZMA_STREAM_END) + return 0; + + s.avail_out += *buffer_size; + + if (!(greedy_realloc(buffer, buffer_size, *buffer_size * 2, 1))) + return -ENOMEM; + + s.next_out = *(uint8_t**)buffer + *buffer_size - s.avail_out; + } + +#else + return -EPROTONOSUPPORT; +#endif +} + +int decompress_startswith_lz4(const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra) { +#ifdef HAVE_LZ4 + /* Checks whether the decompressed blob starts with the + * mentioned prefix. The byte extra needs to follow the + * prefix */ + + int r; + size_t size; + + assert(src); + assert(src_size > 0); + assert(buffer); + assert(buffer_size); + assert(prefix); + assert(*buffer_size == 0 || *buffer); + + if (src_size <= 8) + return -EBADMSG; + + if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1))) + return -ENOMEM; + + r = LZ4_decompress_safe_partial((char*)src + 8, *buffer, src_size - 8, + prefix_len + 1, *buffer_size); + if (r >= 0) + size = (unsigned) r; + else { + /* lz4 always tries to decode full "sequence", so in + * pathological cases might need to decompress the + * full field. */ + r = decompress_blob_lz4(src, src_size, buffer, buffer_size, &size, 0); + if (r < 0) + return r; + } + + if (size >= prefix_len + 1) + return memcmp(*buffer, prefix, prefix_len) == 0 && + ((const uint8_t*) *buffer)[prefix_len] == extra; + else + return 0; + +#else + return -EPROTONOSUPPORT; +#endif +} + +int decompress_startswith(int compression, + const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra) { + if (compression == OBJECT_COMPRESSED_XZ) + return decompress_startswith_xz(src, src_size, + buffer, buffer_size, + prefix, prefix_len, + extra); + else if (compression == OBJECT_COMPRESSED_LZ4) + return decompress_startswith_lz4(src, src_size, + buffer, buffer_size, + prefix, prefix_len, + extra); + else + return -EBADMSG; +} + +int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes) { +#ifdef HAVE_XZ + _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; + lzma_ret ret; + uint8_t buf[BUFSIZ], out[BUFSIZ]; + lzma_action action = LZMA_RUN; + + assert(fdf >= 0); + assert(fdt >= 0); + + ret = lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64); + if (ret != LZMA_OK) { + log_error("Failed to initialize XZ encoder: code %u", ret); + return -EINVAL; + } + + for (;;) { + if (s.avail_in == 0 && action == LZMA_RUN) { + size_t m = sizeof(buf); + ssize_t n; + + if (max_bytes != (uint64_t) -1 && (uint64_t) m > max_bytes) + m = (size_t) max_bytes; + + n = read(fdf, buf, m); + if (n < 0) + return -errno; + if (n == 0) + action = LZMA_FINISH; + else { + s.next_in = buf; + s.avail_in = n; + + if (max_bytes != (uint64_t) -1) { + assert(max_bytes >= (uint64_t) n); + max_bytes -= n; + } + } + } + + if (s.avail_out == 0) { + s.next_out = out; + s.avail_out = sizeof(out); + } + + ret = lzma_code(&s, action); + if (ret != LZMA_OK && ret != LZMA_STREAM_END) { + log_error("Compression failed: code %u", ret); + return -EBADMSG; + } + + if (s.avail_out == 0 || ret == LZMA_STREAM_END) { + ssize_t n, k; + + n = sizeof(out) - s.avail_out; + + k = loop_write(fdt, out, n, false); + if (k < 0) + return k; + + if (ret == LZMA_STREAM_END) { + log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)", + s.total_in, s.total_out, + (double) s.total_out / s.total_in * 100); + + return 0; + } + } + } +#else + return -EPROTONOSUPPORT; +#endif +} + +#define LZ4_BUFSIZE (512*1024u) + +int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) { + +#ifdef HAVE_LZ4 + LZ4F_errorCode_t c; + _cleanup_(LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL; + _cleanup_free_ char *buf = NULL; + char *src = NULL; + size_t size, n, total_in = 0, total_out, offset = 0, frame_size; + struct stat st; + int r; + static const LZ4F_compressOptions_t options = { + .stableSrc = 1, + }; + static const LZ4F_preferences_t preferences = { + .frameInfo.blockSizeID = 5, + }; + + c = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); + if (LZ4F_isError(c)) + return -ENOMEM; + + if (fstat(fdf, &st) < 0) + return log_debug_errno(errno, "fstat() failed: %m"); + + frame_size = LZ4F_compressBound(LZ4_BUFSIZE, &preferences); + size = frame_size + 64*1024; /* add some space for header and trailer */ + buf = malloc(size); + if (!buf) + return -ENOMEM; + + n = offset = total_out = LZ4F_compressBegin(ctx, buf, size, &preferences); + if (LZ4F_isError(n)) + return -EINVAL; + + src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0); + if (src == MAP_FAILED) + return -errno; + + log_debug("Buffer size is %zu bytes, header size %zu bytes.", size, n); + + while (total_in < (size_t) st.st_size) { + ssize_t k; + + k = MIN(LZ4_BUFSIZE, st.st_size - total_in); + n = LZ4F_compressUpdate(ctx, buf + offset, size - offset, + src + total_in, k, &options); + if (LZ4F_isError(n)) { + r = -ENOTRECOVERABLE; + goto cleanup; + } + + total_in += k; + offset += n; + total_out += n; + + if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) { + log_debug("Compressed stream longer than %"PRIu64" bytes", max_bytes); + return -EFBIG; + } + + if (size - offset < frame_size + 4) { + k = loop_write(fdt, buf, offset, false); + if (k < 0) { + r = k; + goto cleanup; + } + offset = 0; + } + } + + n = LZ4F_compressEnd(ctx, buf + offset, size - offset, &options); + if (LZ4F_isError(n)) { + r = -ENOTRECOVERABLE; + goto cleanup; + } + + offset += n; + total_out += n; + r = loop_write(fdt, buf, offset, false); + if (r < 0) + goto cleanup; + + log_debug("LZ4 compression finished (%zu -> %zu bytes, %.1f%%)", + total_in, total_out, + (double) total_out / total_in * 100); + cleanup: + munmap(src, st.st_size); + return r; +#else + return -EPROTONOSUPPORT; +#endif +} + +int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) { + +#ifdef HAVE_XZ + _cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT; + lzma_ret ret; + + uint8_t buf[BUFSIZ], out[BUFSIZ]; + lzma_action action = LZMA_RUN; + + assert(fdf >= 0); + assert(fdt >= 0); + + ret = lzma_stream_decoder(&s, UINT64_MAX, 0); + if (ret != LZMA_OK) { + log_debug("Failed to initialize XZ decoder: code %u", ret); + return -ENOMEM; + } + + for (;;) { + if (s.avail_in == 0 && action == LZMA_RUN) { + ssize_t n; + + n = read(fdf, buf, sizeof(buf)); + if (n < 0) + return -errno; + if (n == 0) + action = LZMA_FINISH; + else { + s.next_in = buf; + s.avail_in = n; + } + } + + if (s.avail_out == 0) { + s.next_out = out; + s.avail_out = sizeof(out); + } + + ret = lzma_code(&s, action); + if (ret != LZMA_OK && ret != LZMA_STREAM_END) { + log_debug("Decompression failed: code %u", ret); + return -EBADMSG; + } + + if (s.avail_out == 0 || ret == LZMA_STREAM_END) { + ssize_t n, k; + + n = sizeof(out) - s.avail_out; + + if (max_bytes != (uint64_t) -1) { + if (max_bytes < (uint64_t) n) + return -EFBIG; + + max_bytes -= n; + } + + k = loop_write(fdt, out, n, false); + if (k < 0) + return k; + + if (ret == LZMA_STREAM_END) { + log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)", + s.total_in, s.total_out, + (double) s.total_out / s.total_in * 100); + + return 0; + } + } + } +#else + log_debug("Cannot decompress file. Compiled without XZ support."); + return -EPROTONOSUPPORT; +#endif +} + +int decompress_stream_lz4(int in, int out, uint64_t max_bytes) { +#ifdef HAVE_LZ4 + size_t c; + _cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL; + _cleanup_free_ char *buf = NULL; + char *src; + struct stat st; + int r = 0; + size_t total_in = 0, total_out = 0; + + c = LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION); + if (LZ4F_isError(c)) + return -ENOMEM; + + if (fstat(in, &st) < 0) + return log_debug_errno(errno, "fstat() failed: %m"); + + buf = malloc(LZ4_BUFSIZE); + if (!buf) + return -ENOMEM; + + src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, in, 0); + if (src == MAP_FAILED) + return -errno; + + while (total_in < (size_t) st.st_size) { + size_t produced = LZ4_BUFSIZE; + size_t used = st.st_size - total_in; + + c = LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL); + if (LZ4F_isError(c)) { + r = -EBADMSG; + goto cleanup; + } + + total_in += used; + total_out += produced; + + if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) { + log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes); + r = -EFBIG; + goto cleanup; + } + + r = loop_write(out, buf, produced, false); + if (r < 0) + goto cleanup; + } + + log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)", + total_in, total_out, + (double) total_out / total_in * 100); + cleanup: + munmap(src, st.st_size); + return r; +#else + log_debug("Cannot decompress file. Compiled without LZ4 support."); + return -EPROTONOSUPPORT; +#endif +} + +int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes) { + + if (endswith(filename, ".lz4")) + return decompress_stream_lz4(fdf, fdt, max_bytes); + else if (endswith(filename, ".xz")) + return decompress_stream_xz(fdf, fdt, max_bytes); + else + return -EPROTONOSUPPORT; +} diff --git a/src/libsystemd/src/sd-journal/compress.h b/src/libsystemd/src/sd-journal/compress.h new file mode 100644 index 0000000000..c138099d9a --- /dev/null +++ b/src/libsystemd/src/sd-journal/compress.h @@ -0,0 +1,85 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <unistd.h> + +#include "journal-def.h" + +const char* object_compressed_to_string(int compression); +int object_compressed_from_string(const char *compression); + +int compress_blob_xz(const void *src, uint64_t src_size, + void *dst, size_t dst_alloc_size, size_t *dst_size); +int compress_blob_lz4(const void *src, uint64_t src_size, + void *dst, size_t dst_alloc_size, size_t *dst_size); + +static inline int compress_blob(const void *src, uint64_t src_size, + void *dst, size_t dst_alloc_size, size_t *dst_size) { + int r; +#ifdef HAVE_LZ4 + r = compress_blob_lz4(src, src_size, dst, dst_alloc_size, dst_size); + if (r == 0) + return OBJECT_COMPRESSED_LZ4; +#else + r = compress_blob_xz(src, src_size, dst, dst_alloc_size, dst_size); + if (r == 0) + return OBJECT_COMPRESSED_XZ; +#endif + return r; +} + +int decompress_blob_xz(const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); +int decompress_blob_lz4(const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); +int decompress_blob(int compression, + const void *src, uint64_t src_size, + void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max); + +int decompress_startswith_xz(const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra); +int decompress_startswith_lz4(const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra); +int decompress_startswith(int compression, + const void *src, uint64_t src_size, + void **buffer, size_t *buffer_size, + const void *prefix, size_t prefix_len, + uint8_t extra); + +int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes); +int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes); + +int decompress_stream_xz(int fdf, int fdt, uint64_t max_size); +int decompress_stream_lz4(int fdf, int fdt, uint64_t max_size); + +#ifdef HAVE_LZ4 +# define compress_stream compress_stream_lz4 +# define COMPRESSED_EXT ".lz4" +#else +# define compress_stream compress_stream_xz +# define COMPRESSED_EXT ".xz" +#endif + +int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes); diff --git a/src/libsystemd/src/sd-journal/fsprg.c b/src/libsystemd/src/sd-journal/fsprg.c new file mode 100644 index 0000000000..c0f59b28fd --- /dev/null +++ b/src/libsystemd/src/sd-journal/fsprg.c @@ -0,0 +1,375 @@ +/* + * fsprg v0.1 - (seekable) forward-secure pseudorandom generator + * Copyright (C) 2012 B. Poettering + * Contact: fsprg@point-at-infinity.org + * + * 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.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301 USA + */ + +/* + * See "Practical Secure Logging: Seekable Sequential Key Generators" + * by G. A. Marson, B. Poettering for details: + * + * http://eprint.iacr.org/2013/397 + */ + +#include <gcrypt.h> +#include <string.h> + +#include "systemd-gcrypt/gcrypt-util.h" + +#include "fsprg.h" + +#define ISVALID_SECPAR(secpar) (((secpar) % 16 == 0) && ((secpar) >= 16) && ((secpar) <= 16384)) +#define VALIDATE_SECPAR(secpar) assert(ISVALID_SECPAR(secpar)); + +#define RND_HASH GCRY_MD_SHA256 +#define RND_GEN_P 0x01 +#define RND_GEN_Q 0x02 +#define RND_GEN_X 0x03 + +/******************************************************************************/ + +static void mpi_export(void *buf, size_t buflen, const gcry_mpi_t x) { + unsigned len; + size_t nwritten; + + assert(gcry_mpi_cmp_ui(x, 0) >= 0); + len = (gcry_mpi_get_nbits(x) + 7) / 8; + assert(len <= buflen); + memzero(buf, buflen); + gcry_mpi_print(GCRYMPI_FMT_USG, buf + (buflen - len), len, &nwritten, x); + assert(nwritten == len); +} + +static gcry_mpi_t mpi_import(const void *buf, size_t buflen) { + gcry_mpi_t h; + unsigned len; + + assert_se(gcry_mpi_scan(&h, GCRYMPI_FMT_USG, buf, buflen, NULL) == 0); + len = (gcry_mpi_get_nbits(h) + 7) / 8; + assert(len <= buflen); + assert(gcry_mpi_cmp_ui(h, 0) >= 0); + + return h; +} + +static void uint64_export(void *buf, size_t buflen, uint64_t x) { + assert(buflen == 8); + ((uint8_t*) buf)[0] = (x >> 56) & 0xff; + ((uint8_t*) buf)[1] = (x >> 48) & 0xff; + ((uint8_t*) buf)[2] = (x >> 40) & 0xff; + ((uint8_t*) buf)[3] = (x >> 32) & 0xff; + ((uint8_t*) buf)[4] = (x >> 24) & 0xff; + ((uint8_t*) buf)[5] = (x >> 16) & 0xff; + ((uint8_t*) buf)[6] = (x >> 8) & 0xff; + ((uint8_t*) buf)[7] = (x >> 0) & 0xff; +} + +_pure_ static uint64_t uint64_import(const void *buf, size_t buflen) { + assert(buflen == 8); + return + (uint64_t)(((uint8_t*) buf)[0]) << 56 | + (uint64_t)(((uint8_t*) buf)[1]) << 48 | + (uint64_t)(((uint8_t*) buf)[2]) << 40 | + (uint64_t)(((uint8_t*) buf)[3]) << 32 | + (uint64_t)(((uint8_t*) buf)[4]) << 24 | + (uint64_t)(((uint8_t*) buf)[5]) << 16 | + (uint64_t)(((uint8_t*) buf)[6]) << 8 | + (uint64_t)(((uint8_t*) buf)[7]) << 0; +} + +/* deterministically generate from seed/idx a string of buflen pseudorandom bytes */ +static void det_randomize(void *buf, size_t buflen, const void *seed, size_t seedlen, uint32_t idx) { + gcry_md_hd_t hd, hd2; + size_t olen, cpylen; + uint32_t ctr; + + olen = gcry_md_get_algo_dlen(RND_HASH); + gcry_md_open(&hd, RND_HASH, 0); + gcry_md_write(hd, seed, seedlen); + gcry_md_putc(hd, (idx >> 24) & 0xff); + gcry_md_putc(hd, (idx >> 16) & 0xff); + gcry_md_putc(hd, (idx >> 8) & 0xff); + gcry_md_putc(hd, (idx >> 0) & 0xff); + + for (ctr = 0; buflen; ctr++) { + gcry_md_copy(&hd2, hd); + gcry_md_putc(hd2, (ctr >> 24) & 0xff); + gcry_md_putc(hd2, (ctr >> 16) & 0xff); + gcry_md_putc(hd2, (ctr >> 8) & 0xff); + gcry_md_putc(hd2, (ctr >> 0) & 0xff); + gcry_md_final(hd2); + cpylen = (buflen < olen) ? buflen : olen; + memcpy(buf, gcry_md_read(hd2, RND_HASH), cpylen); + gcry_md_close(hd2); + buf += cpylen; + buflen -= cpylen; + } + gcry_md_close(hd); +} + +/* deterministically generate from seed/idx a prime of length `bits' that is 3 (mod 4) */ +static gcry_mpi_t genprime3mod4(int bits, const void *seed, size_t seedlen, uint32_t idx) { + size_t buflen = bits / 8; + uint8_t buf[buflen]; + gcry_mpi_t p; + + assert(bits % 8 == 0); + assert(buflen > 0); + + det_randomize(buf, buflen, seed, seedlen, idx); + buf[0] |= 0xc0; /* set upper two bits, so that n=pq has maximum size */ + buf[buflen - 1] |= 0x03; /* set lower two bits, to have result 3 (mod 4) */ + + p = mpi_import(buf, buflen); + while (gcry_prime_check(p, 0)) + gcry_mpi_add_ui(p, p, 4); + + return p; +} + +/* deterministically generate from seed/idx a quadratic residue (mod n) */ +static gcry_mpi_t gensquare(const gcry_mpi_t n, const void *seed, size_t seedlen, uint32_t idx, unsigned secpar) { + size_t buflen = secpar / 8; + uint8_t buf[buflen]; + gcry_mpi_t x; + + det_randomize(buf, buflen, seed, seedlen, idx); + buf[0] &= 0x7f; /* clear upper bit, so that we have x < n */ + x = mpi_import(buf, buflen); + assert(gcry_mpi_cmp(x, n) < 0); + gcry_mpi_mulm(x, x, x, n); + return x; +} + +/* compute 2^m (mod phi(p)), for a prime p */ +static gcry_mpi_t twopowmodphi(uint64_t m, const gcry_mpi_t p) { + gcry_mpi_t phi, r; + int n; + + phi = gcry_mpi_new(0); + gcry_mpi_sub_ui(phi, p, 1); + + /* count number of used bits in m */ + for (n = 0; (1ULL << n) <= m; n++) + ; + + r = gcry_mpi_new(0); + gcry_mpi_set_ui(r, 1); + while (n) { /* square and multiply algorithm for fast exponentiation */ + n--; + gcry_mpi_mulm(r, r, r, phi); + if (m & ((uint64_t)1 << n)) { + gcry_mpi_add(r, r, r); + if (gcry_mpi_cmp(r, phi) >= 0) + gcry_mpi_sub(r, r, phi); + } + } + + gcry_mpi_release(phi); + return r; +} + +/* Decompose $x \in Z_n$ into $(xp,xq) \in Z_p \times Z_q$ using Chinese Remainder Theorem */ +static void CRT_decompose(gcry_mpi_t *xp, gcry_mpi_t *xq, const gcry_mpi_t x, const gcry_mpi_t p, const gcry_mpi_t q) { + *xp = gcry_mpi_new(0); + *xq = gcry_mpi_new(0); + gcry_mpi_mod(*xp, x, p); + gcry_mpi_mod(*xq, x, q); +} + +/* Compose $(xp,xq) \in Z_p \times Z_q$ into $x \in Z_n$ using Chinese Remainder Theorem */ +static void CRT_compose(gcry_mpi_t *x, const gcry_mpi_t xp, const gcry_mpi_t xq, const gcry_mpi_t p, const gcry_mpi_t q) { + gcry_mpi_t a, u; + + a = gcry_mpi_new(0); + u = gcry_mpi_new(0); + *x = gcry_mpi_new(0); + gcry_mpi_subm(a, xq, xp, q); + gcry_mpi_invm(u, p, q); + gcry_mpi_mulm(a, a, u, q); /* a = (xq - xp) / p (mod q) */ + gcry_mpi_mul(*x, p, a); + gcry_mpi_add(*x, *x, xp); /* x = p * ((xq - xp) / p mod q) + xp */ + gcry_mpi_release(a); + gcry_mpi_release(u); +} + +/******************************************************************************/ + +size_t FSPRG_mskinbytes(unsigned _secpar) { + VALIDATE_SECPAR(_secpar); + return 2 + 2 * (_secpar / 2) / 8; /* to store header,p,q */ +} + +size_t FSPRG_mpkinbytes(unsigned _secpar) { + VALIDATE_SECPAR(_secpar); + return 2 + _secpar / 8; /* to store header,n */ +} + +size_t FSPRG_stateinbytes(unsigned _secpar) { + VALIDATE_SECPAR(_secpar); + return 2 + 2 * _secpar / 8 + 8; /* to store header,n,x,epoch */ +} + +static void store_secpar(void *buf, uint16_t secpar) { + secpar = secpar / 16 - 1; + ((uint8_t*) buf)[0] = (secpar >> 8) & 0xff; + ((uint8_t*) buf)[1] = (secpar >> 0) & 0xff; +} + +static uint16_t read_secpar(const void *buf) { + uint16_t secpar; + secpar = + (uint16_t)(((uint8_t*) buf)[0]) << 8 | + (uint16_t)(((uint8_t*) buf)[1]) << 0; + return 16 * (secpar + 1); +} + +void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned _secpar) { + uint8_t iseed[FSPRG_RECOMMENDED_SEEDLEN]; + gcry_mpi_t n, p, q; + uint16_t secpar; + + VALIDATE_SECPAR(_secpar); + secpar = _secpar; + + initialize_libgcrypt(false); + + if (!seed) { + gcry_randomize(iseed, FSPRG_RECOMMENDED_SEEDLEN, GCRY_STRONG_RANDOM); + seed = iseed; + seedlen = FSPRG_RECOMMENDED_SEEDLEN; + } + + p = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_P); + q = genprime3mod4(secpar / 2, seed, seedlen, RND_GEN_Q); + + if (msk) { + store_secpar(msk + 0, secpar); + mpi_export(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8, p); + mpi_export(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8, q); + } + + if (mpk) { + n = gcry_mpi_new(0); + gcry_mpi_mul(n, p, q); + assert(gcry_mpi_get_nbits(n) == secpar); + + store_secpar(mpk + 0, secpar); + mpi_export(mpk + 2, secpar / 8, n); + + gcry_mpi_release(n); + } + + gcry_mpi_release(p); + gcry_mpi_release(q); +} + +void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen) { + gcry_mpi_t n, x; + uint16_t secpar; + + initialize_libgcrypt(false); + + secpar = read_secpar(mpk + 0); + n = mpi_import(mpk + 2, secpar / 8); + x = gensquare(n, seed, seedlen, RND_GEN_X, secpar); + + memcpy(state, mpk, 2 + secpar / 8); + mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x); + memzero(state + 2 + 2 * secpar / 8, 8); + + gcry_mpi_release(n); + gcry_mpi_release(x); +} + +void FSPRG_Evolve(void *state) { + gcry_mpi_t n, x; + uint16_t secpar; + uint64_t epoch; + + initialize_libgcrypt(false); + + secpar = read_secpar(state + 0); + n = mpi_import(state + 2 + 0 * secpar / 8, secpar / 8); + x = mpi_import(state + 2 + 1 * secpar / 8, secpar / 8); + epoch = uint64_import(state + 2 + 2 * secpar / 8, 8); + + gcry_mpi_mulm(x, x, x, n); + epoch++; + + mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, x); + uint64_export(state + 2 + 2 * secpar / 8, 8, epoch); + + gcry_mpi_release(n); + gcry_mpi_release(x); +} + +uint64_t FSPRG_GetEpoch(const void *state) { + uint16_t secpar; + secpar = read_secpar(state + 0); + return uint64_import(state + 2 + 2 * secpar / 8, 8); +} + +void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen) { + gcry_mpi_t p, q, n, x, xp, xq, kp, kq, xm; + uint16_t secpar; + + initialize_libgcrypt(false); + + secpar = read_secpar(msk + 0); + p = mpi_import(msk + 2 + 0 * (secpar / 2) / 8, (secpar / 2) / 8); + q = mpi_import(msk + 2 + 1 * (secpar / 2) / 8, (secpar / 2) / 8); + + n = gcry_mpi_new(0); + gcry_mpi_mul(n, p, q); + + x = gensquare(n, seed, seedlen, RND_GEN_X, secpar); + CRT_decompose(&xp, &xq, x, p, q); /* split (mod n) into (mod p) and (mod q) using CRT */ + + kp = twopowmodphi(epoch, p); /* compute 2^epoch (mod phi(p)) */ + kq = twopowmodphi(epoch, q); /* compute 2^epoch (mod phi(q)) */ + + gcry_mpi_powm(xp, xp, kp, p); /* compute x^(2^epoch) (mod p) */ + gcry_mpi_powm(xq, xq, kq, q); /* compute x^(2^epoch) (mod q) */ + + CRT_compose(&xm, xp, xq, p, q); /* combine (mod p) and (mod q) to (mod n) using CRT */ + + store_secpar(state + 0, secpar); + mpi_export(state + 2 + 0 * secpar / 8, secpar / 8, n); + mpi_export(state + 2 + 1 * secpar / 8, secpar / 8, xm); + uint64_export(state + 2 + 2 * secpar / 8, 8, epoch); + + gcry_mpi_release(p); + gcry_mpi_release(q); + gcry_mpi_release(n); + gcry_mpi_release(x); + gcry_mpi_release(xp); + gcry_mpi_release(xq); + gcry_mpi_release(kp); + gcry_mpi_release(kq); + gcry_mpi_release(xm); +} + +void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx) { + uint16_t secpar; + + initialize_libgcrypt(false); + + secpar = read_secpar(state + 0); + det_randomize(key, keylen, state + 2, 2 * secpar / 8 + 8, idx); +} diff --git a/src/libsystemd/src/sd-journal/fsprg.h b/src/libsystemd/src/sd-journal/fsprg.h new file mode 100644 index 0000000000..15a4e04fe8 --- /dev/null +++ b/src/libsystemd/src/sd-journal/fsprg.h @@ -0,0 +1,65 @@ +#ifndef __fsprgh__ +#define __fsprgh__ + +/* + * fsprg v0.1 - (seekable) forward-secure pseudorandom generator + * Copyright (C) 2012 B. Poettering + * Contact: fsprg@point-at-infinity.org + * + * 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.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301 USA + * + */ + +#include <inttypes.h> +#include <sys/types.h> + +#include "systemd-basic/macro.h" +#include "systemd-basic/util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define FSPRG_RECOMMENDED_SECPAR 1536 +#define FSPRG_RECOMMENDED_SEEDLEN (96/8) + +size_t FSPRG_mskinbytes(unsigned secpar) _const_; +size_t FSPRG_mpkinbytes(unsigned secpar) _const_; +size_t FSPRG_stateinbytes(unsigned secpar) _const_; + +/* Setup msk and mpk. Providing seed != NULL makes this algorithm deterministic. */ +void FSPRG_GenMK(void *msk, void *mpk, const void *seed, size_t seedlen, unsigned secpar); + +/* Initialize state deterministically in dependence on seed. */ +/* Note: in case one wants to run only one GenState0 per GenMK it is safe to use + the same seed for both GenMK and GenState0. +*/ +void FSPRG_GenState0(void *state, const void *mpk, const void *seed, size_t seedlen); + +void FSPRG_Evolve(void *state); + +uint64_t FSPRG_GetEpoch(const void *state) _pure_; + +/* Seek to any arbitrary state (by providing msk together with seed from GenState0). */ +void FSPRG_Seek(void *state, uint64_t epoch, const void *msk, const void *seed, size_t seedlen); + +void FSPRG_GetKey(const void *state, void *key, size_t keylen, uint32_t idx); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/libsystemd/src/sd-journal/journal-authenticate.c b/src/libsystemd/src/sd-journal/journal-authenticate.c new file mode 100644 index 0000000000..f3a207d88d --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-authenticate.c @@ -0,0 +1,552 @@ +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <fcntl.h> +#include <sys/mman.h> + +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hexdecoct.h" +#include "systemd-gcrypt/gcrypt-util.h" + +#include "fsprg.h" +#include "journal-authenticate.h" +#include "journal-def.h" +#include "journal-file.h" + +static uint64_t journal_file_tag_seqnum(JournalFile *f) { + uint64_t r; + + assert(f); + + r = le64toh(f->header->n_tags) + 1; + f->header->n_tags = htole64(r); + + return r; +} + +int journal_file_append_tag(JournalFile *f) { + Object *o; + uint64_t p; + int r; + + assert(f); + + if (!f->seal) + return 0; + + if (!f->hmac_running) + return 0; + + assert(f->hmac); + + r = journal_file_append_object(f, OBJECT_TAG, sizeof(struct TagObject), &o, &p); + if (r < 0) + return r; + + o->tag.seqnum = htole64(journal_file_tag_seqnum(f)); + o->tag.epoch = htole64(FSPRG_GetEpoch(f->fsprg_state)); + + log_debug("Writing tag %"PRIu64" for epoch %"PRIu64"", + le64toh(o->tag.seqnum), + FSPRG_GetEpoch(f->fsprg_state)); + + /* Add the tag object itself, so that we can protect its + * header. This will exclude the actual hash value in it */ + r = journal_file_hmac_put_object(f, OBJECT_TAG, o, p); + if (r < 0) + return r; + + /* Get the HMAC tag and store it in the object */ + memcpy(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH); + f->hmac_running = false; + + return 0; +} + +int journal_file_hmac_start(JournalFile *f) { + uint8_t key[256 / 8]; /* Let's pass 256 bit from FSPRG to HMAC */ + assert(f); + + if (!f->seal) + return 0; + + if (f->hmac_running) + return 0; + + /* Prepare HMAC for next cycle */ + gcry_md_reset(f->hmac); + FSPRG_GetKey(f->fsprg_state, key, sizeof(key), 0); + gcry_md_setkey(f->hmac, key, sizeof(key)); + + f->hmac_running = true; + + return 0; +} + +static int journal_file_get_epoch(JournalFile *f, uint64_t realtime, uint64_t *epoch) { + uint64_t t; + + assert(f); + assert(epoch); + assert(f->seal); + + if (f->fss_start_usec == 0 || + f->fss_interval_usec == 0) + return -EOPNOTSUPP; + + if (realtime < f->fss_start_usec) + return -ESTALE; + + t = realtime - f->fss_start_usec; + t = t / f->fss_interval_usec; + + *epoch = t; + return 0; +} + +static int journal_file_fsprg_need_evolve(JournalFile *f, uint64_t realtime) { + uint64_t goal, epoch; + int r; + assert(f); + + if (!f->seal) + return 0; + + r = journal_file_get_epoch(f, realtime, &goal); + if (r < 0) + return r; + + epoch = FSPRG_GetEpoch(f->fsprg_state); + if (epoch > goal) + return -ESTALE; + + return epoch != goal; +} + +int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime) { + uint64_t goal, epoch; + int r; + + assert(f); + + if (!f->seal) + return 0; + + r = journal_file_get_epoch(f, realtime, &goal); + if (r < 0) + return r; + + epoch = FSPRG_GetEpoch(f->fsprg_state); + if (epoch < goal) + log_debug("Evolving FSPRG key from epoch %"PRIu64" to %"PRIu64".", epoch, goal); + + for (;;) { + if (epoch > goal) + return -ESTALE; + if (epoch == goal) + return 0; + + FSPRG_Evolve(f->fsprg_state); + epoch = FSPRG_GetEpoch(f->fsprg_state); + } +} + +int journal_file_fsprg_seek(JournalFile *f, uint64_t goal) { + void *msk; + uint64_t epoch; + + assert(f); + + if (!f->seal) + return 0; + + assert(f->fsprg_seed); + + if (f->fsprg_state) { + /* Cheaper... */ + + epoch = FSPRG_GetEpoch(f->fsprg_state); + if (goal == epoch) + return 0; + + if (goal == epoch+1) { + FSPRG_Evolve(f->fsprg_state); + return 0; + } + } else { + f->fsprg_state_size = FSPRG_stateinbytes(FSPRG_RECOMMENDED_SECPAR); + f->fsprg_state = malloc(f->fsprg_state_size); + + if (!f->fsprg_state) + return -ENOMEM; + } + + log_debug("Seeking FSPRG key to %"PRIu64".", goal); + + msk = alloca(FSPRG_mskinbytes(FSPRG_RECOMMENDED_SECPAR)); + FSPRG_GenMK(msk, NULL, f->fsprg_seed, f->fsprg_seed_size, FSPRG_RECOMMENDED_SECPAR); + FSPRG_Seek(f->fsprg_state, goal, msk, f->fsprg_seed, f->fsprg_seed_size); + return 0; +} + +int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime) { + int r; + + assert(f); + + if (!f->seal) + return 0; + + if (realtime <= 0) + realtime = now(CLOCK_REALTIME); + + r = journal_file_fsprg_need_evolve(f, realtime); + if (r <= 0) + return 0; + + r = journal_file_append_tag(f); + if (r < 0) + return r; + + r = journal_file_fsprg_evolve(f, realtime); + if (r < 0) + return r; + + return 0; +} + +int journal_file_hmac_put_object(JournalFile *f, ObjectType type, Object *o, uint64_t p) { + int r; + + assert(f); + + if (!f->seal) + return 0; + + r = journal_file_hmac_start(f); + if (r < 0) + return r; + + if (!o) { + r = journal_file_move_to_object(f, type, p, &o); + if (r < 0) + return r; + } else { + if (type > OBJECT_UNUSED && o->object.type != type) + return -EBADMSG; + } + + gcry_md_write(f->hmac, o, offsetof(ObjectHeader, payload)); + + switch (o->object.type) { + + case OBJECT_DATA: + /* All but hash and payload are mutable */ + gcry_md_write(f->hmac, &o->data.hash, sizeof(o->data.hash)); + gcry_md_write(f->hmac, o->data.payload, le64toh(o->object.size) - offsetof(DataObject, payload)); + break; + + case OBJECT_FIELD: + /* Same here */ + gcry_md_write(f->hmac, &o->field.hash, sizeof(o->field.hash)); + gcry_md_write(f->hmac, o->field.payload, le64toh(o->object.size) - offsetof(FieldObject, payload)); + break; + + case OBJECT_ENTRY: + /* All */ + gcry_md_write(f->hmac, &o->entry.seqnum, le64toh(o->object.size) - offsetof(EntryObject, seqnum)); + break; + + case OBJECT_FIELD_HASH_TABLE: + case OBJECT_DATA_HASH_TABLE: + case OBJECT_ENTRY_ARRAY: + /* Nothing: everything is mutable */ + break; + + case OBJECT_TAG: + /* All but the tag itself */ + gcry_md_write(f->hmac, &o->tag.seqnum, sizeof(o->tag.seqnum)); + gcry_md_write(f->hmac, &o->tag.epoch, sizeof(o->tag.epoch)); + break; + default: + return -EINVAL; + } + + return 0; +} + +int journal_file_hmac_put_header(JournalFile *f) { + int r; + + assert(f); + + if (!f->seal) + return 0; + + r = journal_file_hmac_start(f); + if (r < 0) + return r; + + /* All but state+reserved, boot_id, arena_size, + * tail_object_offset, n_objects, n_entries, + * tail_entry_seqnum, head_entry_seqnum, entry_array_offset, + * head_entry_realtime, tail_entry_realtime, + * tail_entry_monotonic, n_data, n_fields, n_tags, + * n_entry_arrays. */ + + gcry_md_write(f->hmac, f->header->signature, offsetof(Header, state) - offsetof(Header, signature)); + gcry_md_write(f->hmac, &f->header->file_id, offsetof(Header, boot_id) - offsetof(Header, file_id)); + gcry_md_write(f->hmac, &f->header->seqnum_id, offsetof(Header, arena_size) - offsetof(Header, seqnum_id)); + gcry_md_write(f->hmac, &f->header->data_hash_table_offset, offsetof(Header, tail_object_offset) - offsetof(Header, data_hash_table_offset)); + + return 0; +} + +int journal_file_fss_load(JournalFile *f) { + int r, fd = -1; + char *p = NULL; + struct stat st; + FSSHeader *m = NULL; + sd_id128_t machine; + + assert(f); + + if (!f->seal) + return 0; + + r = sd_id128_get_machine(&machine); + if (r < 0) + return r; + + if (asprintf(&p, "/var/log/journal/" SD_ID128_FORMAT_STR "/fss", + SD_ID128_FORMAT_VAL(machine)) < 0) + return -ENOMEM; + + fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY, 0600); + if (fd < 0) { + if (errno != ENOENT) + log_error_errno(errno, "Failed to open %s: %m", p); + + r = -errno; + goto finish; + } + + if (fstat(fd, &st) < 0) { + r = -errno; + goto finish; + } + + if (st.st_size < (off_t) sizeof(FSSHeader)) { + r = -ENODATA; + goto finish; + } + + m = mmap(NULL, PAGE_ALIGN(sizeof(FSSHeader)), PROT_READ, MAP_SHARED, fd, 0); + if (m == MAP_FAILED) { + m = NULL; + r = -errno; + goto finish; + } + + if (memcmp(m->signature, FSS_HEADER_SIGNATURE, 8) != 0) { + r = -EBADMSG; + goto finish; + } + + if (m->incompatible_flags != 0) { + r = -EPROTONOSUPPORT; + goto finish; + } + + if (le64toh(m->header_size) < sizeof(FSSHeader)) { + r = -EBADMSG; + goto finish; + } + + if (le64toh(m->fsprg_state_size) != FSPRG_stateinbytes(le16toh(m->fsprg_secpar))) { + r = -EBADMSG; + goto finish; + } + + f->fss_file_size = le64toh(m->header_size) + le64toh(m->fsprg_state_size); + if ((uint64_t) st.st_size < f->fss_file_size) { + r = -ENODATA; + goto finish; + } + + if (!sd_id128_equal(machine, m->machine_id)) { + r = -EHOSTDOWN; + goto finish; + } + + if (le64toh(m->start_usec) <= 0 || + le64toh(m->interval_usec) <= 0) { + r = -EBADMSG; + goto finish; + } + + f->fss_file = mmap(NULL, PAGE_ALIGN(f->fss_file_size), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + if (f->fss_file == MAP_FAILED) { + f->fss_file = NULL; + r = -errno; + goto finish; + } + + f->fss_start_usec = le64toh(f->fss_file->start_usec); + f->fss_interval_usec = le64toh(f->fss_file->interval_usec); + + f->fsprg_state = (uint8_t*) f->fss_file + le64toh(f->fss_file->header_size); + f->fsprg_state_size = le64toh(f->fss_file->fsprg_state_size); + + r = 0; + +finish: + if (m) + munmap(m, PAGE_ALIGN(sizeof(FSSHeader))); + + safe_close(fd); + free(p); + + return r; +} + +int journal_file_hmac_setup(JournalFile *f) { + gcry_error_t e; + + if (!f->seal) + return 0; + + initialize_libgcrypt(true); + + e = gcry_md_open(&f->hmac, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); + if (e != 0) + return -EOPNOTSUPP; + + return 0; +} + +int journal_file_append_first_tag(JournalFile *f) { + int r; + uint64_t p; + + if (!f->seal) + return 0; + + log_debug("Calculating first tag..."); + + r = journal_file_hmac_put_header(f); + if (r < 0) + return r; + + p = le64toh(f->header->field_hash_table_offset); + if (p < offsetof(Object, hash_table.items)) + return -EINVAL; + p -= offsetof(Object, hash_table.items); + + r = journal_file_hmac_put_object(f, OBJECT_FIELD_HASH_TABLE, NULL, p); + if (r < 0) + return r; + + p = le64toh(f->header->data_hash_table_offset); + if (p < offsetof(Object, hash_table.items)) + return -EINVAL; + p -= offsetof(Object, hash_table.items); + + r = journal_file_hmac_put_object(f, OBJECT_DATA_HASH_TABLE, NULL, p); + if (r < 0) + return r; + + r = journal_file_append_tag(f); + if (r < 0) + return r; + + return 0; +} + +int journal_file_parse_verification_key(JournalFile *f, const char *key) { + uint8_t *seed; + size_t seed_size, c; + const char *k; + int r; + unsigned long long start, interval; + + seed_size = FSPRG_RECOMMENDED_SEEDLEN; + seed = malloc(seed_size); + if (!seed) + return -ENOMEM; + + k = key; + for (c = 0; c < seed_size; c++) { + int x, y; + + while (*k == '-') + k++; + + x = unhexchar(*k); + if (x < 0) { + free(seed); + return -EINVAL; + } + k++; + y = unhexchar(*k); + if (y < 0) { + free(seed); + return -EINVAL; + } + k++; + + seed[c] = (uint8_t) (x * 16 + y); + } + + if (*k != '/') { + free(seed); + return -EINVAL; + } + k++; + + r = sscanf(k, "%llx-%llx", &start, &interval); + if (r != 2) { + free(seed); + return -EINVAL; + } + + f->fsprg_seed = seed; + f->fsprg_seed_size = seed_size; + + f->fss_start_usec = start * interval; + f->fss_interval_usec = interval; + + return 0; +} + +bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u) { + uint64_t epoch; + + assert(f); + assert(u); + + if (!f->seal) + return false; + + epoch = FSPRG_GetEpoch(f->fsprg_state); + + *u = (usec_t) (f->fss_start_usec + f->fss_interval_usec * epoch + f->fss_interval_usec); + + return true; +} diff --git a/src/libsystemd/src/sd-journal/journal-authenticate.h b/src/libsystemd/src/sd-journal/journal-authenticate.h new file mode 100644 index 0000000000..6c87319ede --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-authenticate.h @@ -0,0 +1,41 @@ +#pragma once + +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <stdbool.h> + +#include "journal-file.h" + +int journal_file_append_tag(JournalFile *f); +int journal_file_maybe_append_tag(JournalFile *f, uint64_t realtime); +int journal_file_append_first_tag(JournalFile *f); + +int journal_file_hmac_setup(JournalFile *f); +int journal_file_hmac_start(JournalFile *f); +int journal_file_hmac_put_header(JournalFile *f); +int journal_file_hmac_put_object(JournalFile *f, ObjectType type, Object *o, uint64_t p); + +int journal_file_fss_load(JournalFile *f); +int journal_file_parse_verification_key(JournalFile *f, const char *key); + +int journal_file_fsprg_evolve(JournalFile *f, uint64_t realtime); +int journal_file_fsprg_seek(JournalFile *f, uint64_t epoch); + +bool journal_file_next_evolve_usec(JournalFile *f, usec_t *u); diff --git a/src/libsystemd/src/sd-journal/journal-def.h b/src/libsystemd/src/sd-journal/journal-def.h new file mode 100644 index 0000000000..1c604487fb --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-def.h @@ -0,0 +1,233 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <systemd/sd-id128.h> + +#include "systemd-basic/macro.h" +#include "systemd-basic/sparse-endian.h" + +/* + * If you change this file you probably should also change its documentation: + * + * http://www.freedesktop.org/wiki/Software/systemd/journal-files + * + */ + +typedef struct Header Header; +typedef struct ObjectHeader ObjectHeader; +typedef union Object Object; +typedef struct DataObject DataObject; +typedef struct FieldObject FieldObject; +typedef struct EntryObject EntryObject; +typedef struct HashTableObject HashTableObject; +typedef struct EntryArrayObject EntryArrayObject; +typedef struct TagObject TagObject; +typedef struct EntryItem EntryItem; +typedef struct HashItem HashItem; +typedef struct FSSHeader FSSHeader; + +/* Object types */ +typedef enum ObjectType { + OBJECT_UNUSED, /* also serves as "any type" or "additional context" */ + OBJECT_DATA, + OBJECT_FIELD, + OBJECT_ENTRY, + OBJECT_DATA_HASH_TABLE, + OBJECT_FIELD_HASH_TABLE, + OBJECT_ENTRY_ARRAY, + OBJECT_TAG, + _OBJECT_TYPE_MAX +} ObjectType; + +/* Object flags */ +enum { + OBJECT_COMPRESSED_XZ = 1 << 0, + OBJECT_COMPRESSED_LZ4 = 1 << 1, + _OBJECT_COMPRESSED_MAX +}; + +#define OBJECT_COMPRESSION_MASK (OBJECT_COMPRESSED_XZ | OBJECT_COMPRESSED_LZ4) + +struct ObjectHeader { + uint8_t type; + uint8_t flags; + uint8_t reserved[6]; + le64_t size; + uint8_t payload[]; +} _packed_; + +struct DataObject { + ObjectHeader object; + le64_t hash; + le64_t next_hash_offset; + le64_t next_field_offset; + le64_t entry_offset; /* the first array entry we store inline */ + le64_t entry_array_offset; + le64_t n_entries; + uint8_t payload[]; +} _packed_; + +struct FieldObject { + ObjectHeader object; + le64_t hash; + le64_t next_hash_offset; + le64_t head_data_offset; + uint8_t payload[]; +} _packed_; + +struct EntryItem { + le64_t object_offset; + le64_t hash; +} _packed_; + +struct EntryObject { + ObjectHeader object; + le64_t seqnum; + le64_t realtime; + le64_t monotonic; + sd_id128_t boot_id; + le64_t xor_hash; + EntryItem items[]; +} _packed_; + +struct HashItem { + le64_t head_hash_offset; + le64_t tail_hash_offset; +} _packed_; + +struct HashTableObject { + ObjectHeader object; + HashItem items[]; +} _packed_; + +struct EntryArrayObject { + ObjectHeader object; + le64_t next_entry_array_offset; + le64_t items[]; +} _packed_; + +#define TAG_LENGTH (256/8) + +struct TagObject { + ObjectHeader object; + le64_t seqnum; + le64_t epoch; + uint8_t tag[TAG_LENGTH]; /* SHA-256 HMAC */ +} _packed_; + +union Object { + ObjectHeader object; + DataObject data; + FieldObject field; + EntryObject entry; + HashTableObject hash_table; + EntryArrayObject entry_array; + TagObject tag; +}; + +enum { + STATE_OFFLINE = 0, + STATE_ONLINE = 1, + STATE_ARCHIVED = 2, + _STATE_MAX +}; + +/* Header flags */ +enum { + HEADER_INCOMPATIBLE_COMPRESSED_XZ = 1 << 0, + HEADER_INCOMPATIBLE_COMPRESSED_LZ4 = 1 << 1, +}; + +#define HEADER_INCOMPATIBLE_ANY (HEADER_INCOMPATIBLE_COMPRESSED_XZ|HEADER_INCOMPATIBLE_COMPRESSED_LZ4) + +#if defined(HAVE_XZ) && defined(HAVE_LZ4) +# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_ANY +#elif defined(HAVE_XZ) +# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_COMPRESSED_XZ +#elif defined(HAVE_LZ4) +# define HEADER_INCOMPATIBLE_SUPPORTED HEADER_INCOMPATIBLE_COMPRESSED_LZ4 +#else +# define HEADER_INCOMPATIBLE_SUPPORTED 0 +#endif + +enum { + HEADER_COMPATIBLE_SEALED = 1 +}; + +#define HEADER_COMPATIBLE_ANY HEADER_COMPATIBLE_SEALED +#ifdef HAVE_GCRYPT +# define HEADER_COMPATIBLE_SUPPORTED HEADER_COMPATIBLE_SEALED +#else +# define HEADER_COMPATIBLE_SUPPORTED 0 +#endif + +#define HEADER_SIGNATURE ((char[]) { 'L', 'P', 'K', 'S', 'H', 'H', 'R', 'H' }) + +struct Header { + uint8_t signature[8]; /* "LPKSHHRH" */ + le32_t compatible_flags; + le32_t incompatible_flags; + uint8_t state; + uint8_t reserved[7]; + sd_id128_t file_id; + sd_id128_t machine_id; + sd_id128_t boot_id; /* last writer */ + sd_id128_t seqnum_id; + le64_t header_size; + le64_t arena_size; + le64_t data_hash_table_offset; + le64_t data_hash_table_size; + le64_t field_hash_table_offset; + le64_t field_hash_table_size; + le64_t tail_object_offset; + le64_t n_objects; + le64_t n_entries; + le64_t tail_entry_seqnum; + le64_t head_entry_seqnum; + le64_t entry_array_offset; + le64_t head_entry_realtime; + le64_t tail_entry_realtime; + le64_t tail_entry_monotonic; + /* Added in 187 */ + le64_t n_data; + le64_t n_fields; + /* Added in 189 */ + le64_t n_tags; + le64_t n_entry_arrays; + + /* Size: 240 */ +} _packed_; + +#define FSS_HEADER_SIGNATURE ((char[]) { 'K', 'S', 'H', 'H', 'R', 'H', 'L', 'P' }) + +struct FSSHeader { + uint8_t signature[8]; /* "KSHHRHLP" */ + le32_t compatible_flags; + le32_t incompatible_flags; + sd_id128_t machine_id; + sd_id128_t boot_id; /* last writer */ + le64_t header_size; + le64_t start_usec; + le64_t interval_usec; + le16_t fsprg_secpar; + le16_t reserved[3]; + le64_t fsprg_state_size; +} _packed_; diff --git a/src/libsystemd/src/sd-journal/journal-file.c b/src/libsystemd/src/sd-journal/journal-file.c new file mode 100644 index 0000000000..7910270925 --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-file.c @@ -0,0 +1,3619 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <fcntl.h> +#include <pthread.h> +#include <stddef.h> +#include <sys/mman.h> +#include <sys/statvfs.h> +#include <sys/uio.h> +#include <unistd.h> + +#include <linux/fs.h> + +#include <systemd/sd-event.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/btrfs-util.h" +#include "systemd-basic/chattr-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/random-util.h" +#include "systemd-basic/set.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/xattr-util.h" + +#include "compress.h" +#include "journal-authenticate.h" +#include "journal-def.h" +#include "journal-file.h" +#include "lookup3.h" + +#define DEFAULT_DATA_HASH_TABLE_SIZE (2047ULL*sizeof(HashItem)) +#define DEFAULT_FIELD_HASH_TABLE_SIZE (333ULL*sizeof(HashItem)) + +#define COMPRESSION_SIZE_THRESHOLD (512ULL) + +/* This is the minimum journal file size */ +#define JOURNAL_FILE_SIZE_MIN (512ULL*1024ULL) /* 512 KiB */ + +/* These are the lower and upper bounds if we deduce the max_use value + * from the file system size */ +#define DEFAULT_MAX_USE_LOWER (1ULL*1024ULL*1024ULL) /* 1 MiB */ +#define DEFAULT_MAX_USE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */ + +/* This is the default minimal use limit, how much we'll use even if keep_free suggests otherwise. */ +#define DEFAULT_MIN_USE (1ULL*1024ULL*1024ULL) /* 1 MiB */ + +/* This is the upper bound if we deduce max_size from max_use */ +#define DEFAULT_MAX_SIZE_UPPER (128ULL*1024ULL*1024ULL) /* 128 MiB */ + +/* This is the upper bound if we deduce the keep_free value from the + * file system size */ +#define DEFAULT_KEEP_FREE_UPPER (4ULL*1024ULL*1024ULL*1024ULL) /* 4 GiB */ + +/* This is the keep_free value when we can't determine the system + * size */ +#define DEFAULT_KEEP_FREE (1024ULL*1024ULL) /* 1 MB */ + +/* This is the default maximum number of journal files to keep around. */ +#define DEFAULT_N_MAX_FILES (100) + +/* n_data was the first entry we added after the initial file format design */ +#define HEADER_SIZE_MIN ALIGN64(offsetof(Header, n_data)) + +/* How many entries to keep in the entry array chain cache at max */ +#define CHAIN_CACHE_MAX 20 + +/* How much to increase the journal file size at once each time we allocate something new. */ +#define FILE_SIZE_INCREASE (8ULL*1024ULL*1024ULL) /* 8MB */ + +/* Reread fstat() of the file for detecting deletions at least this often */ +#define LAST_STAT_REFRESH_USEC (5*USEC_PER_SEC) + +/* The mmap context to use for the header we pick as one above the last defined typed */ +#define CONTEXT_HEADER _OBJECT_TYPE_MAX + +/* This may be called from a separate thread to prevent blocking the caller for the duration of fsync(). + * As a result we use atomic operations on f->offline_state for inter-thread communications with + * journal_file_set_offline() and journal_file_set_online(). */ +static void journal_file_set_offline_internal(JournalFile *f) { + assert(f); + assert(f->fd >= 0); + assert(f->header); + + for (;;) { + switch (f->offline_state) { + case OFFLINE_CANCEL: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_DONE)) + continue; + return; + + case OFFLINE_AGAIN_FROM_SYNCING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_SYNCING)) + continue; + break; + + case OFFLINE_AGAIN_FROM_OFFLINING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_SYNCING)) + continue; + break; + + case OFFLINE_SYNCING: + (void) fsync(f->fd); + + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_OFFLINING)) + continue; + + f->header->state = f->archive ? STATE_ARCHIVED : STATE_OFFLINE; + (void) fsync(f->fd); + break; + + case OFFLINE_OFFLINING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_DONE)) + continue; + /* fall through */ + + case OFFLINE_DONE: + return; + + case OFFLINE_JOINED: + log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()"); + return; + } + } +} + +static void * journal_file_set_offline_thread(void *arg) { + JournalFile *f = arg; + + journal_file_set_offline_internal(f); + + return NULL; +} + +static int journal_file_set_offline_thread_join(JournalFile *f) { + int r; + + assert(f); + + if (f->offline_state == OFFLINE_JOINED) + return 0; + + r = pthread_join(f->offline_thread, NULL); + if (r) + return -r; + + f->offline_state = OFFLINE_JOINED; + + if (mmap_cache_got_sigbus(f->mmap, f->fd)) + return -EIO; + + return 0; +} + +/* Trigger a restart if the offline thread is mid-flight in a restartable state. */ +static bool journal_file_set_offline_try_restart(JournalFile *f) { + for (;;) { + switch (f->offline_state) { + case OFFLINE_AGAIN_FROM_SYNCING: + case OFFLINE_AGAIN_FROM_OFFLINING: + return true; + + case OFFLINE_CANCEL: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_CANCEL, OFFLINE_AGAIN_FROM_SYNCING)) + continue; + return true; + + case OFFLINE_SYNCING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_AGAIN_FROM_SYNCING)) + continue; + return true; + + case OFFLINE_OFFLINING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_OFFLINING, OFFLINE_AGAIN_FROM_OFFLINING)) + continue; + return true; + + default: + return false; + } + } +} + +/* Sets a journal offline. + * + * If wait is false then an offline is dispatched in a separate thread for a + * subsequent journal_file_set_offline() or journal_file_set_online() of the + * same journal to synchronize with. + * + * If wait is true, then either an existing offline thread will be restarted + * and joined, or if none exists the offline is simply performed in this + * context without involving another thread. + */ +int journal_file_set_offline(JournalFile *f, bool wait) { + bool restarted; + int r; + + assert(f); + + if (!f->writable) + return -EPERM; + + if (!(f->fd >= 0 && f->header)) + return -EINVAL; + + /* An offlining journal is implicitly online and may modify f->header->state, + * we must also join any potentially lingering offline thread when not online. */ + if (!journal_file_is_offlining(f) && f->header->state != STATE_ONLINE) + return journal_file_set_offline_thread_join(f); + + /* Restart an in-flight offline thread and wait if needed, or join a lingering done one. */ + restarted = journal_file_set_offline_try_restart(f); + if ((restarted && wait) || !restarted) { + r = journal_file_set_offline_thread_join(f); + if (r < 0) + return r; + } + + if (restarted) + return 0; + + /* Initiate a new offline. */ + f->offline_state = OFFLINE_SYNCING; + + if (wait) /* Without using a thread if waiting. */ + journal_file_set_offline_internal(f); + else { + r = pthread_create(&f->offline_thread, NULL, journal_file_set_offline_thread, f); + if (r > 0) { + f->offline_state = OFFLINE_JOINED; + return -r; + } + } + + return 0; +} + +static int journal_file_set_online(JournalFile *f) { + bool joined = false; + + assert(f); + + if (!f->writable) + return -EPERM; + + if (!(f->fd >= 0 && f->header)) + return -EINVAL; + + while (!joined) { + switch (f->offline_state) { + case OFFLINE_JOINED: + /* No offline thread, no need to wait. */ + joined = true; + break; + + case OFFLINE_SYNCING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_SYNCING, OFFLINE_CANCEL)) + continue; + /* Canceled syncing prior to offlining, no need to wait. */ + break; + + case OFFLINE_AGAIN_FROM_SYNCING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_SYNCING, OFFLINE_CANCEL)) + continue; + /* Canceled restart from syncing, no need to wait. */ + break; + + case OFFLINE_AGAIN_FROM_OFFLINING: + if (!__sync_bool_compare_and_swap(&f->offline_state, OFFLINE_AGAIN_FROM_OFFLINING, OFFLINE_CANCEL)) + continue; + /* Canceled restart from offlining, must wait for offlining to complete however. */ + + /* fall through to wait */ + default: { + int r; + + r = journal_file_set_offline_thread_join(f); + if (r < 0) + return r; + + joined = true; + break; + } + } + } + + if (mmap_cache_got_sigbus(f->mmap, f->fd)) + return -EIO; + + switch (f->header->state) { + case STATE_ONLINE: + return 0; + + case STATE_OFFLINE: + f->header->state = STATE_ONLINE; + (void) fsync(f->fd); + return 0; + + default: + return -EINVAL; + } +} + +bool journal_file_is_offlining(JournalFile *f) { + assert(f); + + __sync_synchronize(); + + if (f->offline_state == OFFLINE_DONE || + f->offline_state == OFFLINE_JOINED) + return false; + + return true; +} + +JournalFile* journal_file_close(JournalFile *f) { + assert(f); + +#ifdef HAVE_GCRYPT + /* Write the final tag */ + if (f->seal && f->writable) + journal_file_append_tag(f); +#endif + + if (f->post_change_timer) { + int enabled; + + if (sd_event_source_get_enabled(f->post_change_timer, &enabled) >= 0) + if (enabled == SD_EVENT_ONESHOT) + journal_file_post_change(f); + + (void) sd_event_source_set_enabled(f->post_change_timer, SD_EVENT_OFF); + sd_event_source_unref(f->post_change_timer); + } + + journal_file_set_offline(f, true); + + if (f->mmap && f->fd >= 0) + mmap_cache_close_fd(f->mmap, f->fd); + + if (f->fd >= 0 && f->defrag_on_close) { + + /* Be friendly to btrfs: turn COW back on again now, + * and defragment the file. We won't write to the file + * ever again, hence remove all fragmentation, and + * reenable all the good bits COW usually provides + * (such as data checksumming). */ + + (void) chattr_fd(f->fd, 0, FS_NOCOW_FL); + (void) btrfs_defrag_fd(f->fd); + } + + if (f->close_fd) + safe_close(f->fd); + free(f->path); + + mmap_cache_unref(f->mmap); + + ordered_hashmap_free_free(f->chain_cache); + +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + free(f->compress_buffer); +#endif + +#ifdef HAVE_GCRYPT + if (f->fss_file) + munmap(f->fss_file, PAGE_ALIGN(f->fss_file_size)); + else + free(f->fsprg_state); + + free(f->fsprg_seed); + + if (f->hmac) + gcry_md_close(f->hmac); +#endif + + free(f); + return NULL; +} + +void journal_file_close_set(Set *s) { + JournalFile *f; + + assert(s); + + while ((f = set_steal_first(s))) + (void) journal_file_close(f); +} + +static int journal_file_init_header(JournalFile *f, JournalFile *template) { + Header h = {}; + ssize_t k; + int r; + + assert(f); + + memcpy(h.signature, HEADER_SIGNATURE, 8); + h.header_size = htole64(ALIGN64(sizeof(h))); + + h.incompatible_flags |= htole32( + f->compress_xz * HEADER_INCOMPATIBLE_COMPRESSED_XZ | + f->compress_lz4 * HEADER_INCOMPATIBLE_COMPRESSED_LZ4); + + h.compatible_flags = htole32( + f->seal * HEADER_COMPATIBLE_SEALED); + + r = sd_id128_randomize(&h.file_id); + if (r < 0) + return r; + + if (template) { + h.seqnum_id = template->header->seqnum_id; + h.tail_entry_seqnum = template->header->tail_entry_seqnum; + } else + h.seqnum_id = h.file_id; + + k = pwrite(f->fd, &h, sizeof(h), 0); + if (k < 0) + return -errno; + + if (k != sizeof(h)) + return -EIO; + + return 0; +} + +static int fsync_directory_of_file(int fd) { + _cleanup_free_ char *path = NULL, *dn = NULL; + _cleanup_close_ int dfd = -1; + struct stat st; + int r; + + if (fstat(fd, &st) < 0) + return -errno; + + if (!S_ISREG(st.st_mode)) + return -EBADFD; + + r = fd_get_path(fd, &path); + if (r < 0) + return r; + + if (!path_is_absolute(path)) + return -EINVAL; + + dn = dirname_malloc(path); + if (!dn) + return -ENOMEM; + + dfd = open(dn, O_RDONLY|O_CLOEXEC|O_DIRECTORY); + if (dfd < 0) + return -errno; + + if (fsync(dfd) < 0) + return -errno; + + return 0; +} + +static int journal_file_refresh_header(JournalFile *f) { + sd_id128_t boot_id; + int r; + + assert(f); + assert(f->header); + + r = sd_id128_get_machine(&f->header->machine_id); + if (r < 0) + return r; + + r = sd_id128_get_boot(&boot_id); + if (r < 0) + return r; + + if (sd_id128_equal(boot_id, f->header->boot_id)) + f->tail_entry_monotonic_valid = true; + + f->header->boot_id = boot_id; + + r = journal_file_set_online(f); + + /* Sync the online state to disk */ + (void) fsync(f->fd); + + /* We likely just created a new file, also sync the directory this file is located in. */ + (void) fsync_directory_of_file(f->fd); + + return r; +} + +static int journal_file_verify_header(JournalFile *f) { + uint32_t flags; + + assert(f); + assert(f->header); + + if (memcmp(f->header->signature, HEADER_SIGNATURE, 8)) + return -EBADMSG; + + /* In both read and write mode we refuse to open files with + * incompatible flags we don't know */ + flags = le32toh(f->header->incompatible_flags); + if (flags & ~HEADER_INCOMPATIBLE_SUPPORTED) { + if (flags & ~HEADER_INCOMPATIBLE_ANY) + log_debug("Journal file %s has unknown incompatible flags %"PRIx32, + f->path, flags & ~HEADER_INCOMPATIBLE_ANY); + flags = (flags & HEADER_INCOMPATIBLE_ANY) & ~HEADER_INCOMPATIBLE_SUPPORTED; + if (flags) + log_debug("Journal file %s uses incompatible flags %"PRIx32 + " disabled at compilation time.", f->path, flags); + return -EPROTONOSUPPORT; + } + + /* When open for writing we refuse to open files with + * compatible flags, too */ + flags = le32toh(f->header->compatible_flags); + if (f->writable && (flags & ~HEADER_COMPATIBLE_SUPPORTED)) { + if (flags & ~HEADER_COMPATIBLE_ANY) + log_debug("Journal file %s has unknown compatible flags %"PRIx32, + f->path, flags & ~HEADER_COMPATIBLE_ANY); + flags = (flags & HEADER_COMPATIBLE_ANY) & ~HEADER_COMPATIBLE_SUPPORTED; + if (flags) + log_debug("Journal file %s uses compatible flags %"PRIx32 + " disabled at compilation time.", f->path, flags); + return -EPROTONOSUPPORT; + } + + if (f->header->state >= _STATE_MAX) + return -EBADMSG; + + /* The first addition was n_data, so check that we are at least this large */ + if (le64toh(f->header->header_size) < HEADER_SIZE_MIN) + return -EBADMSG; + + if (JOURNAL_HEADER_SEALED(f->header) && !JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays)) + return -EBADMSG; + + if ((le64toh(f->header->header_size) + le64toh(f->header->arena_size)) > (uint64_t) f->last_stat.st_size) + return -ENODATA; + + if (le64toh(f->header->tail_object_offset) > (le64toh(f->header->header_size) + le64toh(f->header->arena_size))) + return -ENODATA; + + if (!VALID64(le64toh(f->header->data_hash_table_offset)) || + !VALID64(le64toh(f->header->field_hash_table_offset)) || + !VALID64(le64toh(f->header->tail_object_offset)) || + !VALID64(le64toh(f->header->entry_array_offset))) + return -ENODATA; + + if (f->writable) { + uint8_t state; + sd_id128_t machine_id; + int r; + + r = sd_id128_get_machine(&machine_id); + if (r < 0) + return r; + + if (!sd_id128_equal(machine_id, f->header->machine_id)) + return -EHOSTDOWN; + + state = f->header->state; + + if (state == STATE_ONLINE) { + log_debug("Journal file %s is already online. Assuming unclean closing.", f->path); + return -EBUSY; + } else if (state == STATE_ARCHIVED) + return -ESHUTDOWN; + else if (state != STATE_OFFLINE) { + log_debug("Journal file %s has unknown state %i.", f->path, state); + return -EBUSY; + } + } + + f->compress_xz = JOURNAL_HEADER_COMPRESSED_XZ(f->header); + f->compress_lz4 = JOURNAL_HEADER_COMPRESSED_LZ4(f->header); + + f->seal = JOURNAL_HEADER_SEALED(f->header); + + return 0; +} + +static int journal_file_fstat(JournalFile *f) { + assert(f); + assert(f->fd >= 0); + + if (fstat(f->fd, &f->last_stat) < 0) + return -errno; + + f->last_stat_usec = now(CLOCK_MONOTONIC); + + /* Refuse appending to files that are already deleted */ + if (f->last_stat.st_nlink <= 0) + return -EIDRM; + + return 0; +} + +static int journal_file_allocate(JournalFile *f, uint64_t offset, uint64_t size) { + uint64_t old_size, new_size; + int r; + + assert(f); + assert(f->header); + + /* We assume that this file is not sparse, and we know that + * for sure, since we always call posix_fallocate() + * ourselves */ + + if (mmap_cache_got_sigbus(f->mmap, f->fd)) + return -EIO; + + old_size = + le64toh(f->header->header_size) + + le64toh(f->header->arena_size); + + new_size = PAGE_ALIGN(offset + size); + if (new_size < le64toh(f->header->header_size)) + new_size = le64toh(f->header->header_size); + + if (new_size <= old_size) { + + /* We already pre-allocated enough space, but before + * we write to it, let's check with fstat() if the + * file got deleted, in order make sure we don't throw + * away the data immediately. Don't check fstat() for + * all writes though, but only once ever 10s. */ + + if (f->last_stat_usec + LAST_STAT_REFRESH_USEC > now(CLOCK_MONOTONIC)) + return 0; + + return journal_file_fstat(f); + } + + /* Allocate more space. */ + + if (f->metrics.max_size > 0 && new_size > f->metrics.max_size) + return -E2BIG; + + if (new_size > f->metrics.min_size && f->metrics.keep_free > 0) { + struct statvfs svfs; + + if (fstatvfs(f->fd, &svfs) >= 0) { + uint64_t available; + + available = LESS_BY((uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize, f->metrics.keep_free); + + if (new_size - old_size > available) + return -E2BIG; + } + } + + /* Increase by larger blocks at once */ + new_size = ((new_size+FILE_SIZE_INCREASE-1) / FILE_SIZE_INCREASE) * FILE_SIZE_INCREASE; + if (f->metrics.max_size > 0 && new_size > f->metrics.max_size) + new_size = f->metrics.max_size; + + /* Note that the glibc fallocate() fallback is very + inefficient, hence we try to minimize the allocation area + as we can. */ + r = posix_fallocate(f->fd, old_size, new_size - old_size); + if (r != 0) + return -r; + + f->header->arena_size = htole64(new_size - le64toh(f->header->header_size)); + + return journal_file_fstat(f); +} + +static unsigned type_to_context(ObjectType type) { + /* One context for each type, plus one catch-all for the rest */ + assert_cc(_OBJECT_TYPE_MAX <= MMAP_CACHE_MAX_CONTEXTS); + assert_cc(CONTEXT_HEADER < MMAP_CACHE_MAX_CONTEXTS); + return type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX ? type : 0; +} + +static int journal_file_move_to(JournalFile *f, ObjectType type, bool keep_always, uint64_t offset, uint64_t size, void **ret) { + int r; + + assert(f); + assert(ret); + + if (size <= 0) + return -EINVAL; + + /* Avoid SIGBUS on invalid accesses */ + if (offset + size > (uint64_t) f->last_stat.st_size) { + /* Hmm, out of range? Let's refresh the fstat() data + * first, before we trust that check. */ + + r = journal_file_fstat(f); + if (r < 0) + return r; + + if (offset + size > (uint64_t) f->last_stat.st_size) + return -EADDRNOTAVAIL; + } + + return mmap_cache_get(f->mmap, f->fd, f->prot, type_to_context(type), keep_always, offset, size, &f->last_stat, ret); +} + +static uint64_t minimum_header_size(Object *o) { + + static const uint64_t table[] = { + [OBJECT_DATA] = sizeof(DataObject), + [OBJECT_FIELD] = sizeof(FieldObject), + [OBJECT_ENTRY] = sizeof(EntryObject), + [OBJECT_DATA_HASH_TABLE] = sizeof(HashTableObject), + [OBJECT_FIELD_HASH_TABLE] = sizeof(HashTableObject), + [OBJECT_ENTRY_ARRAY] = sizeof(EntryArrayObject), + [OBJECT_TAG] = sizeof(TagObject), + }; + + if (o->object.type >= ELEMENTSOF(table) || table[o->object.type] <= 0) + return sizeof(ObjectHeader); + + return table[o->object.type]; +} + +int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret) { + int r; + void *t; + Object *o; + uint64_t s; + + assert(f); + assert(ret); + + /* Objects may only be located at multiple of 64 bit */ + if (!VALID64(offset)) + return -EBADMSG; + + /* Object may not be located in the file header */ + if (offset < le64toh(f->header->header_size)) + return -EBADMSG; + + r = journal_file_move_to(f, type, false, offset, sizeof(ObjectHeader), &t); + if (r < 0) + return r; + + o = (Object*) t; + s = le64toh(o->object.size); + + if (s < sizeof(ObjectHeader)) + return -EBADMSG; + + if (o->object.type <= OBJECT_UNUSED) + return -EBADMSG; + + if (s < minimum_header_size(o)) + return -EBADMSG; + + if (type > OBJECT_UNUSED && o->object.type != type) + return -EBADMSG; + + if (s > sizeof(ObjectHeader)) { + r = journal_file_move_to(f, type, false, offset, s, &t); + if (r < 0) + return r; + + o = (Object*) t; + } + + *ret = o; + return 0; +} + +static uint64_t journal_file_entry_seqnum(JournalFile *f, uint64_t *seqnum) { + uint64_t r; + + assert(f); + assert(f->header); + + r = le64toh(f->header->tail_entry_seqnum) + 1; + + if (seqnum) { + /* If an external seqnum counter was passed, we update + * both the local and the external one, and set it to + * the maximum of both */ + + if (*seqnum + 1 > r) + r = *seqnum + 1; + + *seqnum = r; + } + + f->header->tail_entry_seqnum = htole64(r); + + if (f->header->head_entry_seqnum == 0) + f->header->head_entry_seqnum = htole64(r); + + return r; +} + +int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset) { + int r; + uint64_t p; + Object *tail, *o; + void *t; + + assert(f); + assert(f->header); + assert(type > OBJECT_UNUSED && type < _OBJECT_TYPE_MAX); + assert(size >= sizeof(ObjectHeader)); + assert(offset); + assert(ret); + + r = journal_file_set_online(f); + if (r < 0) + return r; + + p = le64toh(f->header->tail_object_offset); + if (p == 0) + p = le64toh(f->header->header_size); + else { + r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &tail); + if (r < 0) + return r; + + p += ALIGN64(le64toh(tail->object.size)); + } + + r = journal_file_allocate(f, p, size); + if (r < 0) + return r; + + r = journal_file_move_to(f, type, false, p, size, &t); + if (r < 0) + return r; + + o = (Object*) t; + + zero(o->object); + o->object.type = type; + o->object.size = htole64(size); + + f->header->tail_object_offset = htole64(p); + f->header->n_objects = htole64(le64toh(f->header->n_objects) + 1); + + *ret = o; + *offset = p; + + return 0; +} + +static int journal_file_setup_data_hash_table(JournalFile *f) { + uint64_t s, p; + Object *o; + int r; + + assert(f); + assert(f->header); + + /* We estimate that we need 1 hash table entry per 768 bytes + of journal file and we want to make sure we never get + beyond 75% fill level. Calculate the hash table size for + the maximum file size based on these metrics. */ + + s = (f->metrics.max_size * 4 / 768 / 3) * sizeof(HashItem); + if (s < DEFAULT_DATA_HASH_TABLE_SIZE) + s = DEFAULT_DATA_HASH_TABLE_SIZE; + + log_debug("Reserving %"PRIu64" entries in hash table.", s / sizeof(HashItem)); + + r = journal_file_append_object(f, + OBJECT_DATA_HASH_TABLE, + offsetof(Object, hash_table.items) + s, + &o, &p); + if (r < 0) + return r; + + memzero(o->hash_table.items, s); + + f->header->data_hash_table_offset = htole64(p + offsetof(Object, hash_table.items)); + f->header->data_hash_table_size = htole64(s); + + return 0; +} + +static int journal_file_setup_field_hash_table(JournalFile *f) { + uint64_t s, p; + Object *o; + int r; + + assert(f); + assert(f->header); + + /* We use a fixed size hash table for the fields as this + * number should grow very slowly only */ + + s = DEFAULT_FIELD_HASH_TABLE_SIZE; + r = journal_file_append_object(f, + OBJECT_FIELD_HASH_TABLE, + offsetof(Object, hash_table.items) + s, + &o, &p); + if (r < 0) + return r; + + memzero(o->hash_table.items, s); + + f->header->field_hash_table_offset = htole64(p + offsetof(Object, hash_table.items)); + f->header->field_hash_table_size = htole64(s); + + return 0; +} + +int journal_file_map_data_hash_table(JournalFile *f) { + uint64_t s, p; + void *t; + int r; + + assert(f); + assert(f->header); + + if (f->data_hash_table) + return 0; + + p = le64toh(f->header->data_hash_table_offset); + s = le64toh(f->header->data_hash_table_size); + + r = journal_file_move_to(f, + OBJECT_DATA_HASH_TABLE, + true, + p, s, + &t); + if (r < 0) + return r; + + f->data_hash_table = t; + return 0; +} + +int journal_file_map_field_hash_table(JournalFile *f) { + uint64_t s, p; + void *t; + int r; + + assert(f); + assert(f->header); + + if (f->field_hash_table) + return 0; + + p = le64toh(f->header->field_hash_table_offset); + s = le64toh(f->header->field_hash_table_size); + + r = journal_file_move_to(f, + OBJECT_FIELD_HASH_TABLE, + true, + p, s, + &t); + if (r < 0) + return r; + + f->field_hash_table = t; + return 0; +} + +static int journal_file_link_field( + JournalFile *f, + Object *o, + uint64_t offset, + uint64_t hash) { + + uint64_t p, h, m; + int r; + + assert(f); + assert(f->header); + assert(f->field_hash_table); + assert(o); + assert(offset > 0); + + if (o->object.type != OBJECT_FIELD) + return -EINVAL; + + m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem); + if (m <= 0) + return -EBADMSG; + + /* This might alter the window we are looking at */ + o->field.next_hash_offset = o->field.head_data_offset = 0; + + h = hash % m; + p = le64toh(f->field_hash_table[h].tail_hash_offset); + if (p == 0) + f->field_hash_table[h].head_hash_offset = htole64(offset); + else { + r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o); + if (r < 0) + return r; + + o->field.next_hash_offset = htole64(offset); + } + + f->field_hash_table[h].tail_hash_offset = htole64(offset); + + if (JOURNAL_HEADER_CONTAINS(f->header, n_fields)) + f->header->n_fields = htole64(le64toh(f->header->n_fields) + 1); + + return 0; +} + +static int journal_file_link_data( + JournalFile *f, + Object *o, + uint64_t offset, + uint64_t hash) { + + uint64_t p, h, m; + int r; + + assert(f); + assert(f->header); + assert(f->data_hash_table); + assert(o); + assert(offset > 0); + + if (o->object.type != OBJECT_DATA) + return -EINVAL; + + m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); + if (m <= 0) + return -EBADMSG; + + /* This might alter the window we are looking at */ + o->data.next_hash_offset = o->data.next_field_offset = 0; + o->data.entry_offset = o->data.entry_array_offset = 0; + o->data.n_entries = 0; + + h = hash % m; + p = le64toh(f->data_hash_table[h].tail_hash_offset); + if (p == 0) + /* Only entry in the hash table is easy */ + f->data_hash_table[h].head_hash_offset = htole64(offset); + else { + /* Move back to the previous data object, to patch in + * pointer */ + + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + o->data.next_hash_offset = htole64(offset); + } + + f->data_hash_table[h].tail_hash_offset = htole64(offset); + + if (JOURNAL_HEADER_CONTAINS(f->header, n_data)) + f->header->n_data = htole64(le64toh(f->header->n_data) + 1); + + return 0; +} + +int journal_file_find_field_object_with_hash( + JournalFile *f, + const void *field, uint64_t size, uint64_t hash, + Object **ret, uint64_t *offset) { + + uint64_t p, osize, h, m; + int r; + + assert(f); + assert(f->header); + assert(field && size > 0); + + /* If the field hash table is empty, we can't find anything */ + if (le64toh(f->header->field_hash_table_size) <= 0) + return 0; + + /* Map the field hash table, if it isn't mapped yet. */ + r = journal_file_map_field_hash_table(f); + if (r < 0) + return r; + + osize = offsetof(Object, field.payload) + size; + + m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem); + if (m <= 0) + return -EBADMSG; + + h = hash % m; + p = le64toh(f->field_hash_table[h].head_hash_offset); + + while (p > 0) { + Object *o; + + r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o); + if (r < 0) + return r; + + if (le64toh(o->field.hash) == hash && + le64toh(o->object.size) == osize && + memcmp(o->field.payload, field, size) == 0) { + + if (ret) + *ret = o; + if (offset) + *offset = p; + + return 1; + } + + p = le64toh(o->field.next_hash_offset); + } + + return 0; +} + +int journal_file_find_field_object( + JournalFile *f, + const void *field, uint64_t size, + Object **ret, uint64_t *offset) { + + uint64_t hash; + + assert(f); + assert(field && size > 0); + + hash = hash64(field, size); + + return journal_file_find_field_object_with_hash(f, + field, size, hash, + ret, offset); +} + +int journal_file_find_data_object_with_hash( + JournalFile *f, + const void *data, uint64_t size, uint64_t hash, + Object **ret, uint64_t *offset) { + + uint64_t p, osize, h, m; + int r; + + assert(f); + assert(f->header); + assert(data || size == 0); + + /* If there's no data hash table, then there's no entry. */ + if (le64toh(f->header->data_hash_table_size) <= 0) + return 0; + + /* Map the data hash table, if it isn't mapped yet. */ + r = journal_file_map_data_hash_table(f); + if (r < 0) + return r; + + osize = offsetof(Object, data.payload) + size; + + m = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); + if (m <= 0) + return -EBADMSG; + + h = hash % m; + p = le64toh(f->data_hash_table[h].head_hash_offset); + + while (p > 0) { + Object *o; + + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + if (le64toh(o->data.hash) != hash) + goto next; + + if (o->object.flags & OBJECT_COMPRESSION_MASK) { +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + uint64_t l; + size_t rsize = 0; + + l = le64toh(o->object.size); + if (l <= offsetof(Object, data.payload)) + return -EBADMSG; + + l -= offsetof(Object, data.payload); + + r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK, + o->data.payload, l, &f->compress_buffer, &f->compress_buffer_size, &rsize, 0); + if (r < 0) + return r; + + if (rsize == size && + memcmp(f->compress_buffer, data, size) == 0) { + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 1; + } +#else + return -EPROTONOSUPPORT; +#endif + } else if (le64toh(o->object.size) == osize && + memcmp(o->data.payload, data, size) == 0) { + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 1; + } + + next: + p = le64toh(o->data.next_hash_offset); + } + + return 0; +} + +int journal_file_find_data_object( + JournalFile *f, + const void *data, uint64_t size, + Object **ret, uint64_t *offset) { + + uint64_t hash; + + assert(f); + assert(data || size == 0); + + hash = hash64(data, size); + + return journal_file_find_data_object_with_hash(f, + data, size, hash, + ret, offset); +} + +static int journal_file_append_field( + JournalFile *f, + const void *field, uint64_t size, + Object **ret, uint64_t *offset) { + + uint64_t hash, p; + uint64_t osize; + Object *o; + int r; + + assert(f); + assert(field && size > 0); + + hash = hash64(field, size); + + r = journal_file_find_field_object_with_hash(f, field, size, hash, &o, &p); + if (r < 0) + return r; + else if (r > 0) { + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 0; + } + + osize = offsetof(Object, field.payload) + size; + r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p); + if (r < 0) + return r; + + o->field.hash = htole64(hash); + memcpy(o->field.payload, field, size); + + r = journal_file_link_field(f, o, p, hash); + if (r < 0) + return r; + + /* The linking might have altered the window, so let's + * refresh our pointer */ + r = journal_file_move_to_object(f, OBJECT_FIELD, p, &o); + if (r < 0) + return r; + +#ifdef HAVE_GCRYPT + r = journal_file_hmac_put_object(f, OBJECT_FIELD, o, p); + if (r < 0) + return r; +#endif + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 0; +} + +static int journal_file_append_data( + JournalFile *f, + const void *data, uint64_t size, + Object **ret, uint64_t *offset) { + + uint64_t hash, p; + uint64_t osize; + Object *o; + int r, compression = 0; + const void *eq; + + assert(f); + assert(data || size == 0); + + hash = hash64(data, size); + + r = journal_file_find_data_object_with_hash(f, data, size, hash, &o, &p); + if (r < 0) + return r; + if (r > 0) { + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 0; + } + + osize = offsetof(Object, data.payload) + size; + r = journal_file_append_object(f, OBJECT_DATA, osize, &o, &p); + if (r < 0) + return r; + + o->data.hash = htole64(hash); + +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + if (JOURNAL_FILE_COMPRESS(f) && size >= COMPRESSION_SIZE_THRESHOLD) { + size_t rsize = 0; + + compression = compress_blob(data, size, o->data.payload, size - 1, &rsize); + + if (compression >= 0) { + o->object.size = htole64(offsetof(Object, data.payload) + rsize); + o->object.flags |= compression; + + log_debug("Compressed data object %"PRIu64" -> %zu using %s", + size, rsize, object_compressed_to_string(compression)); + } else + /* Compression didn't work, we don't really care why, let's continue without compression */ + compression = 0; + } +#endif + + if (compression == 0) + memcpy_safe(o->data.payload, data, size); + + r = journal_file_link_data(f, o, p, hash); + if (r < 0) + return r; + + /* The linking might have altered the window, so let's + * refresh our pointer */ + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + if (!data) + eq = NULL; + else + eq = memchr(data, '=', size); + if (eq && eq > data) { + Object *fo = NULL; + uint64_t fp; + + /* Create field object ... */ + r = journal_file_append_field(f, data, (uint8_t*) eq - (uint8_t*) data, &fo, &fp); + if (r < 0) + return r; + + /* ... and link it in. */ + o->data.next_field_offset = fo->field.head_data_offset; + fo->field.head_data_offset = le64toh(p); + } + +#ifdef HAVE_GCRYPT + r = journal_file_hmac_put_object(f, OBJECT_DATA, o, p); + if (r < 0) + return r; +#endif + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 0; +} + +uint64_t journal_file_entry_n_items(Object *o) { + assert(o); + + if (o->object.type != OBJECT_ENTRY) + return 0; + + return (le64toh(o->object.size) - offsetof(Object, entry.items)) / sizeof(EntryItem); +} + +uint64_t journal_file_entry_array_n_items(Object *o) { + assert(o); + + if (o->object.type != OBJECT_ENTRY_ARRAY) + return 0; + + return (le64toh(o->object.size) - offsetof(Object, entry_array.items)) / sizeof(uint64_t); +} + +uint64_t journal_file_hash_table_n_items(Object *o) { + assert(o); + + if (o->object.type != OBJECT_DATA_HASH_TABLE && + o->object.type != OBJECT_FIELD_HASH_TABLE) + return 0; + + return (le64toh(o->object.size) - offsetof(Object, hash_table.items)) / sizeof(HashItem); +} + +static int link_entry_into_array(JournalFile *f, + le64_t *first, + le64_t *idx, + uint64_t p) { + int r; + uint64_t n = 0, ap = 0, q, i, a, hidx; + Object *o; + + assert(f); + assert(f->header); + assert(first); + assert(idx); + assert(p > 0); + + a = le64toh(*first); + i = hidx = le64toh(*idx); + while (a > 0) { + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + + n = journal_file_entry_array_n_items(o); + if (i < n) { + o->entry_array.items[i] = htole64(p); + *idx = htole64(hidx + 1); + return 0; + } + + i -= n; + ap = a; + a = le64toh(o->entry_array.next_entry_array_offset); + } + + if (hidx > n) + n = (hidx+1) * 2; + else + n = n * 2; + + if (n < 4) + n = 4; + + r = journal_file_append_object(f, OBJECT_ENTRY_ARRAY, + offsetof(Object, entry_array.items) + n * sizeof(uint64_t), + &o, &q); + if (r < 0) + return r; + +#ifdef HAVE_GCRYPT + r = journal_file_hmac_put_object(f, OBJECT_ENTRY_ARRAY, o, q); + if (r < 0) + return r; +#endif + + o->entry_array.items[i] = htole64(p); + + if (ap == 0) + *first = htole64(q); + else { + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, ap, &o); + if (r < 0) + return r; + + o->entry_array.next_entry_array_offset = htole64(q); + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays)) + f->header->n_entry_arrays = htole64(le64toh(f->header->n_entry_arrays) + 1); + + *idx = htole64(hidx + 1); + + return 0; +} + +static int link_entry_into_array_plus_one(JournalFile *f, + le64_t *extra, + le64_t *first, + le64_t *idx, + uint64_t p) { + + int r; + + assert(f); + assert(extra); + assert(first); + assert(idx); + assert(p > 0); + + if (*idx == 0) + *extra = htole64(p); + else { + le64_t i; + + i = htole64(le64toh(*idx) - 1); + r = link_entry_into_array(f, first, &i, p); + if (r < 0) + return r; + } + + *idx = htole64(le64toh(*idx) + 1); + return 0; +} + +static int journal_file_link_entry_item(JournalFile *f, Object *o, uint64_t offset, uint64_t i) { + uint64_t p; + int r; + assert(f); + assert(o); + assert(offset > 0); + + p = le64toh(o->entry.items[i].object_offset); + if (p == 0) + return -EINVAL; + + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + return link_entry_into_array_plus_one(f, + &o->data.entry_offset, + &o->data.entry_array_offset, + &o->data.n_entries, + offset); +} + +static int journal_file_link_entry(JournalFile *f, Object *o, uint64_t offset) { + uint64_t n, i; + int r; + + assert(f); + assert(f->header); + assert(o); + assert(offset > 0); + + if (o->object.type != OBJECT_ENTRY) + return -EINVAL; + + __sync_synchronize(); + + /* Link up the entry itself */ + r = link_entry_into_array(f, + &f->header->entry_array_offset, + &f->header->n_entries, + offset); + if (r < 0) + return r; + + /* log_debug("=> %s seqnr=%"PRIu64" n_entries=%"PRIu64, f->path, o->entry.seqnum, f->header->n_entries); */ + + if (f->header->head_entry_realtime == 0) + f->header->head_entry_realtime = o->entry.realtime; + + f->header->tail_entry_realtime = o->entry.realtime; + f->header->tail_entry_monotonic = o->entry.monotonic; + + f->tail_entry_monotonic_valid = true; + + /* Link up the items */ + n = journal_file_entry_n_items(o); + for (i = 0; i < n; i++) { + r = journal_file_link_entry_item(f, o, offset, i); + if (r < 0) + return r; + } + + return 0; +} + +static int journal_file_append_entry_internal( + JournalFile *f, + const dual_timestamp *ts, + uint64_t xor_hash, + const EntryItem items[], unsigned n_items, + uint64_t *seqnum, + Object **ret, uint64_t *offset) { + uint64_t np; + uint64_t osize; + Object *o; + int r; + + assert(f); + assert(f->header); + assert(items || n_items == 0); + assert(ts); + + osize = offsetof(Object, entry.items) + (n_items * sizeof(EntryItem)); + + r = journal_file_append_object(f, OBJECT_ENTRY, osize, &o, &np); + if (r < 0) + return r; + + o->entry.seqnum = htole64(journal_file_entry_seqnum(f, seqnum)); + memcpy_safe(o->entry.items, items, n_items * sizeof(EntryItem)); + o->entry.realtime = htole64(ts->realtime); + o->entry.monotonic = htole64(ts->monotonic); + o->entry.xor_hash = htole64(xor_hash); + o->entry.boot_id = f->header->boot_id; + +#ifdef HAVE_GCRYPT + r = journal_file_hmac_put_object(f, OBJECT_ENTRY, o, np); + if (r < 0) + return r; +#endif + + r = journal_file_link_entry(f, o, np); + if (r < 0) + return r; + + if (ret) + *ret = o; + + if (offset) + *offset = np; + + return 0; +} + +void journal_file_post_change(JournalFile *f) { + assert(f); + + /* inotify() does not receive IN_MODIFY events from file + * accesses done via mmap(). After each access we hence + * trigger IN_MODIFY by truncating the journal file to its + * current size which triggers IN_MODIFY. */ + + __sync_synchronize(); + + if (ftruncate(f->fd, f->last_stat.st_size) < 0) + log_debug_errno(errno, "Failed to truncate file to its own size: %m"); +} + +static int post_change_thunk(sd_event_source *timer, uint64_t usec, void *userdata) { + assert(userdata); + + journal_file_post_change(userdata); + + return 1; +} + +static void schedule_post_change(JournalFile *f) { + sd_event_source *timer; + int enabled, r; + uint64_t now; + + assert(f); + assert(f->post_change_timer); + + timer = f->post_change_timer; + + r = sd_event_source_get_enabled(timer, &enabled); + if (r < 0) { + log_debug_errno(r, "Failed to get ftruncate timer state: %m"); + goto fail; + } + + if (enabled == SD_EVENT_ONESHOT) + return; + + r = sd_event_now(sd_event_source_get_event(timer), CLOCK_MONOTONIC, &now); + if (r < 0) { + log_debug_errno(r, "Failed to get clock's now for scheduling ftruncate: %m"); + goto fail; + } + + r = sd_event_source_set_time(timer, now+f->post_change_timer_period); + if (r < 0) { + log_debug_errno(r, "Failed to set time for scheduling ftruncate: %m"); + goto fail; + } + + r = sd_event_source_set_enabled(timer, SD_EVENT_ONESHOT); + if (r < 0) { + log_debug_errno(r, "Failed to enable scheduled ftruncate: %m"); + goto fail; + } + + return; + +fail: + /* On failure, let's simply post the change immediately. */ + journal_file_post_change(f); +} + +/* Enable coalesced change posting in a timer on the provided sd_event instance */ +int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t) { + _cleanup_(sd_event_source_unrefp) sd_event_source *timer = NULL; + int r; + + assert(f); + assert_return(!f->post_change_timer, -EINVAL); + assert(e); + assert(t); + + r = sd_event_add_time(e, &timer, CLOCK_MONOTONIC, 0, 0, post_change_thunk, f); + if (r < 0) + return r; + + r = sd_event_source_set_enabled(timer, SD_EVENT_OFF); + if (r < 0) + return r; + + f->post_change_timer = timer; + timer = NULL; + f->post_change_timer_period = t; + + return r; +} + +static int entry_item_cmp(const void *_a, const void *_b) { + const EntryItem *a = _a, *b = _b; + + if (le64toh(a->object_offset) < le64toh(b->object_offset)) + return -1; + if (le64toh(a->object_offset) > le64toh(b->object_offset)) + return 1; + return 0; +} + +int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqnum, Object **ret, uint64_t *offset) { + unsigned i; + EntryItem *items; + int r; + uint64_t xor_hash = 0; + struct dual_timestamp _ts; + + assert(f); + assert(f->header); + assert(iovec || n_iovec == 0); + + if (!ts) { + dual_timestamp_get(&_ts); + ts = &_ts; + } + +#ifdef HAVE_GCRYPT + r = journal_file_maybe_append_tag(f, ts->realtime); + if (r < 0) + return r; +#endif + + /* alloca() can't take 0, hence let's allocate at least one */ + items = alloca(sizeof(EntryItem) * MAX(1u, n_iovec)); + + for (i = 0; i < n_iovec; i++) { + uint64_t p; + Object *o; + + r = journal_file_append_data(f, iovec[i].iov_base, iovec[i].iov_len, &o, &p); + if (r < 0) + return r; + + xor_hash ^= le64toh(o->data.hash); + items[i].object_offset = htole64(p); + items[i].hash = o->data.hash; + } + + /* Order by the position on disk, in order to improve seek + * times for rotating media. */ + qsort_safe(items, n_iovec, sizeof(EntryItem), entry_item_cmp); + + r = journal_file_append_entry_internal(f, ts, xor_hash, items, n_iovec, seqnum, ret, offset); + + /* If the memory mapping triggered a SIGBUS then we return an + * IO error and ignore the error code passed down to us, since + * it is very likely just an effect of a nullified replacement + * mapping page */ + + if (mmap_cache_got_sigbus(f->mmap, f->fd)) + r = -EIO; + + if (f->post_change_timer) + schedule_post_change(f); + else + journal_file_post_change(f); + + return r; +} + +typedef struct ChainCacheItem { + uint64_t first; /* the array at the beginning of the chain */ + uint64_t array; /* the cached array */ + uint64_t begin; /* the first item in the cached array */ + uint64_t total; /* the total number of items in all arrays before this one in the chain */ + uint64_t last_index; /* the last index we looked at, to optimize locality when bisecting */ +} ChainCacheItem; + +static void chain_cache_put( + OrderedHashmap *h, + ChainCacheItem *ci, + uint64_t first, + uint64_t array, + uint64_t begin, + uint64_t total, + uint64_t last_index) { + + if (!ci) { + /* If the chain item to cache for this chain is the + * first one it's not worth caching anything */ + if (array == first) + return; + + if (ordered_hashmap_size(h) >= CHAIN_CACHE_MAX) { + ci = ordered_hashmap_steal_first(h); + assert(ci); + } else { + ci = new(ChainCacheItem, 1); + if (!ci) + return; + } + + ci->first = first; + + if (ordered_hashmap_put(h, &ci->first, ci) < 0) { + free(ci); + return; + } + } else + assert(ci->first == first); + + ci->array = array; + ci->begin = begin; + ci->total = total; + ci->last_index = last_index; +} + +static int generic_array_get( + JournalFile *f, + uint64_t first, + uint64_t i, + Object **ret, uint64_t *offset) { + + Object *o; + uint64_t p = 0, a, t = 0; + int r; + ChainCacheItem *ci; + + assert(f); + + a = first; + + /* Try the chain cache first */ + ci = ordered_hashmap_get(f->chain_cache, &first); + if (ci && i > ci->total) { + a = ci->array; + i -= ci->total; + t = ci->total; + } + + while (a > 0) { + uint64_t k; + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + + k = journal_file_entry_array_n_items(o); + if (i < k) { + p = le64toh(o->entry_array.items[i]); + goto found; + } + + i -= k; + t += k; + a = le64toh(o->entry_array.next_entry_array_offset); + } + + return 0; + +found: + /* Let's cache this item for the next invocation */ + chain_cache_put(f->chain_cache, ci, first, a, le64toh(o->entry_array.items[0]), t, i); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + return 1; +} + +static int generic_array_get_plus_one( + JournalFile *f, + uint64_t extra, + uint64_t first, + uint64_t i, + Object **ret, uint64_t *offset) { + + Object *o; + + assert(f); + + if (i == 0) { + int r; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o); + if (r < 0) + return r; + + if (ret) + *ret = o; + + if (offset) + *offset = extra; + + return 1; + } + + return generic_array_get(f, first, i-1, ret, offset); +} + +enum { + TEST_FOUND, + TEST_LEFT, + TEST_RIGHT +}; + +static int generic_array_bisect( + JournalFile *f, + uint64_t first, + uint64_t n, + uint64_t needle, + int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle), + direction_t direction, + Object **ret, + uint64_t *offset, + uint64_t *idx) { + + uint64_t a, p, t = 0, i = 0, last_p = 0, last_index = (uint64_t) -1; + bool subtract_one = false; + Object *o, *array = NULL; + int r; + ChainCacheItem *ci; + + assert(f); + assert(test_object); + + /* Start with the first array in the chain */ + a = first; + + ci = ordered_hashmap_get(f->chain_cache, &first); + if (ci && n > ci->total) { + /* Ah, we have iterated this bisection array chain + * previously! Let's see if we can skip ahead in the + * chain, as far as the last time. But we can't jump + * backwards in the chain, so let's check that + * first. */ + + r = test_object(f, ci->begin, needle); + if (r < 0) + return r; + + if (r == TEST_LEFT) { + /* OK, what we are looking for is right of the + * begin of this EntryArray, so let's jump + * straight to previously cached array in the + * chain */ + + a = ci->array; + n -= ci->total; + t = ci->total; + last_index = ci->last_index; + } + } + + while (a > 0) { + uint64_t left, right, k, lp; + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &array); + if (r < 0) + return r; + + k = journal_file_entry_array_n_items(array); + right = MIN(k, n); + if (right <= 0) + return 0; + + i = right - 1; + lp = p = le64toh(array->entry_array.items[i]); + if (p <= 0) + r = -EBADMSG; + else + r = test_object(f, p, needle); + if (r == -EBADMSG) { + log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (1)"); + n = i; + continue; + } + if (r < 0) + return r; + + if (r == TEST_FOUND) + r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT; + + if (r == TEST_RIGHT) { + left = 0; + right -= 1; + + if (last_index != (uint64_t) -1) { + assert(last_index <= right); + + /* If we cached the last index we + * looked at, let's try to not to jump + * too wildly around and see if we can + * limit the range to look at early to + * the immediate neighbors of the last + * index we looked at. */ + + if (last_index > 0) { + uint64_t x = last_index - 1; + + p = le64toh(array->entry_array.items[x]); + if (p <= 0) + return -EBADMSG; + + r = test_object(f, p, needle); + if (r < 0) + return r; + + if (r == TEST_FOUND) + r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT; + + if (r == TEST_RIGHT) + right = x; + else + left = x + 1; + } + + if (last_index < right) { + uint64_t y = last_index + 1; + + p = le64toh(array->entry_array.items[y]); + if (p <= 0) + return -EBADMSG; + + r = test_object(f, p, needle); + if (r < 0) + return r; + + if (r == TEST_FOUND) + r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT; + + if (r == TEST_RIGHT) + right = y; + else + left = y + 1; + } + } + + for (;;) { + if (left == right) { + if (direction == DIRECTION_UP) + subtract_one = true; + + i = left; + goto found; + } + + assert(left < right); + i = (left + right) / 2; + + p = le64toh(array->entry_array.items[i]); + if (p <= 0) + r = -EBADMSG; + else + r = test_object(f, p, needle); + if (r == -EBADMSG) { + log_debug_errno(r, "Encountered invalid entry while bisecting, cutting algorithm short. (2)"); + right = n = i; + continue; + } + if (r < 0) + return r; + + if (r == TEST_FOUND) + r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT; + + if (r == TEST_RIGHT) + right = i; + else + left = i + 1; + } + } + + if (k >= n) { + if (direction == DIRECTION_UP) { + i = n; + subtract_one = true; + goto found; + } + + return 0; + } + + last_p = lp; + + n -= k; + t += k; + last_index = (uint64_t) -1; + a = le64toh(array->entry_array.next_entry_array_offset); + } + + return 0; + +found: + if (subtract_one && t == 0 && i == 0) + return 0; + + /* Let's cache this item for the next invocation */ + chain_cache_put(f->chain_cache, ci, first, a, le64toh(array->entry_array.items[0]), t, subtract_one ? (i > 0 ? i-1 : (uint64_t) -1) : i); + + if (subtract_one && i == 0) + p = last_p; + else if (subtract_one) + p = le64toh(array->entry_array.items[i-1]); + else + p = le64toh(array->entry_array.items[i]); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + if (ret) + *ret = o; + + if (offset) + *offset = p; + + if (idx) + *idx = t + i + (subtract_one ? -1 : 0); + + return 1; +} + +static int generic_array_bisect_plus_one( + JournalFile *f, + uint64_t extra, + uint64_t first, + uint64_t n, + uint64_t needle, + int (*test_object)(JournalFile *f, uint64_t p, uint64_t needle), + direction_t direction, + Object **ret, + uint64_t *offset, + uint64_t *idx) { + + int r; + bool step_back = false; + Object *o; + + assert(f); + assert(test_object); + + if (n <= 0) + return 0; + + /* This bisects the array in object 'first', but first checks + * an extra */ + r = test_object(f, extra, needle); + if (r < 0) + return r; + + if (r == TEST_FOUND) + r = direction == DIRECTION_DOWN ? TEST_RIGHT : TEST_LEFT; + + /* if we are looking with DIRECTION_UP then we need to first + see if in the actual array there is a matching entry, and + return the last one of that. But if there isn't any we need + to return this one. Hence remember this, and return it + below. */ + if (r == TEST_LEFT) + step_back = direction == DIRECTION_UP; + + if (r == TEST_RIGHT) { + if (direction == DIRECTION_DOWN) + goto found; + else + return 0; + } + + r = generic_array_bisect(f, first, n-1, needle, test_object, direction, ret, offset, idx); + + if (r == 0 && step_back) + goto found; + + if (r > 0 && idx) + (*idx)++; + + return r; + +found: + r = journal_file_move_to_object(f, OBJECT_ENTRY, extra, &o); + if (r < 0) + return r; + + if (ret) + *ret = o; + + if (offset) + *offset = extra; + + if (idx) + *idx = 0; + + return 1; +} + +_pure_ static int test_object_offset(JournalFile *f, uint64_t p, uint64_t needle) { + assert(f); + assert(p > 0); + + if (p == needle) + return TEST_FOUND; + else if (p < needle) + return TEST_LEFT; + else + return TEST_RIGHT; +} + +static int test_object_seqnum(JournalFile *f, uint64_t p, uint64_t needle) { + Object *o; + int r; + + assert(f); + assert(p > 0); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + if (le64toh(o->entry.seqnum) == needle) + return TEST_FOUND; + else if (le64toh(o->entry.seqnum) < needle) + return TEST_LEFT; + else + return TEST_RIGHT; +} + +int journal_file_move_to_entry_by_seqnum( + JournalFile *f, + uint64_t seqnum, + direction_t direction, + Object **ret, + uint64_t *offset) { + assert(f); + assert(f->header); + + return generic_array_bisect(f, + le64toh(f->header->entry_array_offset), + le64toh(f->header->n_entries), + seqnum, + test_object_seqnum, + direction, + ret, offset, NULL); +} + +static int test_object_realtime(JournalFile *f, uint64_t p, uint64_t needle) { + Object *o; + int r; + + assert(f); + assert(p > 0); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + if (le64toh(o->entry.realtime) == needle) + return TEST_FOUND; + else if (le64toh(o->entry.realtime) < needle) + return TEST_LEFT; + else + return TEST_RIGHT; +} + +int journal_file_move_to_entry_by_realtime( + JournalFile *f, + uint64_t realtime, + direction_t direction, + Object **ret, + uint64_t *offset) { + assert(f); + assert(f->header); + + return generic_array_bisect(f, + le64toh(f->header->entry_array_offset), + le64toh(f->header->n_entries), + realtime, + test_object_realtime, + direction, + ret, offset, NULL); +} + +static int test_object_monotonic(JournalFile *f, uint64_t p, uint64_t needle) { + Object *o; + int r; + + assert(f); + assert(p > 0); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + if (le64toh(o->entry.monotonic) == needle) + return TEST_FOUND; + else if (le64toh(o->entry.monotonic) < needle) + return TEST_LEFT; + else + return TEST_RIGHT; +} + +static int find_data_object_by_boot_id( + JournalFile *f, + sd_id128_t boot_id, + Object **o, + uint64_t *b) { + + char t[sizeof("_BOOT_ID=")-1 + 32 + 1] = "_BOOT_ID="; + + sd_id128_to_string(boot_id, t + 9); + return journal_file_find_data_object(f, t, sizeof(t) - 1, o, b); +} + +int journal_file_move_to_entry_by_monotonic( + JournalFile *f, + sd_id128_t boot_id, + uint64_t monotonic, + direction_t direction, + Object **ret, + uint64_t *offset) { + + Object *o; + int r; + + assert(f); + + r = find_data_object_by_boot_id(f, boot_id, &o, NULL); + if (r < 0) + return r; + if (r == 0) + return -ENOENT; + + return generic_array_bisect_plus_one(f, + le64toh(o->data.entry_offset), + le64toh(o->data.entry_array_offset), + le64toh(o->data.n_entries), + monotonic, + test_object_monotonic, + direction, + ret, offset, NULL); +} + +void journal_file_reset_location(JournalFile *f) { + f->location_type = LOCATION_HEAD; + f->current_offset = 0; + f->current_seqnum = 0; + f->current_realtime = 0; + f->current_monotonic = 0; + zero(f->current_boot_id); + f->current_xor_hash = 0; +} + +void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset) { + f->location_type = LOCATION_SEEK; + f->current_offset = offset; + f->current_seqnum = le64toh(o->entry.seqnum); + f->current_realtime = le64toh(o->entry.realtime); + f->current_monotonic = le64toh(o->entry.monotonic); + f->current_boot_id = o->entry.boot_id; + f->current_xor_hash = le64toh(o->entry.xor_hash); +} + +int journal_file_compare_locations(JournalFile *af, JournalFile *bf) { + assert(af); + assert(af->header); + assert(bf); + assert(bf->header); + assert(af->location_type == LOCATION_SEEK); + assert(bf->location_type == LOCATION_SEEK); + + /* If contents and timestamps match, these entries are + * identical, even if the seqnum does not match */ + if (sd_id128_equal(af->current_boot_id, bf->current_boot_id) && + af->current_monotonic == bf->current_monotonic && + af->current_realtime == bf->current_realtime && + af->current_xor_hash == bf->current_xor_hash) + return 0; + + if (sd_id128_equal(af->header->seqnum_id, bf->header->seqnum_id)) { + + /* If this is from the same seqnum source, compare + * seqnums */ + if (af->current_seqnum < bf->current_seqnum) + return -1; + if (af->current_seqnum > bf->current_seqnum) + return 1; + + /* Wow! This is weird, different data but the same + * seqnums? Something is borked, but let's make the + * best of it and compare by time. */ + } + + if (sd_id128_equal(af->current_boot_id, bf->current_boot_id)) { + + /* If the boot id matches, compare monotonic time */ + if (af->current_monotonic < bf->current_monotonic) + return -1; + if (af->current_monotonic > bf->current_monotonic) + return 1; + } + + /* Otherwise, compare UTC time */ + if (af->current_realtime < bf->current_realtime) + return -1; + if (af->current_realtime > bf->current_realtime) + return 1; + + /* Finally, compare by contents */ + if (af->current_xor_hash < bf->current_xor_hash) + return -1; + if (af->current_xor_hash > bf->current_xor_hash) + return 1; + + return 0; +} + +int journal_file_next_entry( + JournalFile *f, + uint64_t p, + direction_t direction, + Object **ret, uint64_t *offset) { + + uint64_t i, n, ofs; + int r; + + assert(f); + assert(f->header); + + n = le64toh(f->header->n_entries); + if (n <= 0) + return 0; + + if (p == 0) + i = direction == DIRECTION_DOWN ? 0 : n - 1; + else { + r = generic_array_bisect(f, + le64toh(f->header->entry_array_offset), + le64toh(f->header->n_entries), + p, + test_object_offset, + DIRECTION_DOWN, + NULL, NULL, + &i); + if (r <= 0) + return r; + + if (direction == DIRECTION_DOWN) { + if (i >= n - 1) + return 0; + + i++; + } else { + if (i <= 0) + return 0; + + i--; + } + } + + /* And jump to it */ + r = generic_array_get(f, + le64toh(f->header->entry_array_offset), + i, + ret, &ofs); + if (r == -EBADMSG && direction == DIRECTION_DOWN) { + /* Special case: when we iterate throught the journal file linearly, and hit an entry we can't read, + * consider this the end of the journal file. */ + log_debug_errno(r, "Encountered entry we can't read while iterating through journal file. Considering this the end of the file."); + return 0; + } + if (r <= 0) + return r; + + if (p > 0 && + (direction == DIRECTION_DOWN ? ofs <= p : ofs >= p)) { + log_debug("%s: entry array corrupted at entry %" PRIu64, f->path, i); + return -EBADMSG; + } + + if (offset) + *offset = ofs; + + return 1; +} + +int journal_file_next_entry_for_data( + JournalFile *f, + Object *o, uint64_t p, + uint64_t data_offset, + direction_t direction, + Object **ret, uint64_t *offset) { + + uint64_t n, i; + int r; + Object *d; + + assert(f); + assert(p > 0 || !o); + + r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d); + if (r < 0) + return r; + + n = le64toh(d->data.n_entries); + if (n <= 0) + return n; + + if (!o) + i = direction == DIRECTION_DOWN ? 0 : n - 1; + else { + if (o->object.type != OBJECT_ENTRY) + return -EINVAL; + + r = generic_array_bisect_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + le64toh(d->data.n_entries), + p, + test_object_offset, + DIRECTION_DOWN, + NULL, NULL, + &i); + + if (r <= 0) + return r; + + if (direction == DIRECTION_DOWN) { + if (i >= n - 1) + return 0; + + i++; + } else { + if (i <= 0) + return 0; + + i--; + } + + } + + return generic_array_get_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + i, + ret, offset); +} + +int journal_file_move_to_entry_by_offset_for_data( + JournalFile *f, + uint64_t data_offset, + uint64_t p, + direction_t direction, + Object **ret, uint64_t *offset) { + + int r; + Object *d; + + assert(f); + + r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d); + if (r < 0) + return r; + + return generic_array_bisect_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + le64toh(d->data.n_entries), + p, + test_object_offset, + direction, + ret, offset, NULL); +} + +int journal_file_move_to_entry_by_monotonic_for_data( + JournalFile *f, + uint64_t data_offset, + sd_id128_t boot_id, + uint64_t monotonic, + direction_t direction, + Object **ret, uint64_t *offset) { + + Object *o, *d; + int r; + uint64_t b, z; + + assert(f); + + /* First, seek by time */ + r = find_data_object_by_boot_id(f, boot_id, &o, &b); + if (r < 0) + return r; + if (r == 0) + return -ENOENT; + + r = generic_array_bisect_plus_one(f, + le64toh(o->data.entry_offset), + le64toh(o->data.entry_array_offset), + le64toh(o->data.n_entries), + monotonic, + test_object_monotonic, + direction, + NULL, &z, NULL); + if (r <= 0) + return r; + + /* And now, continue seeking until we find an entry that + * exists in both bisection arrays */ + + for (;;) { + Object *qo; + uint64_t p, q; + + r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d); + if (r < 0) + return r; + + r = generic_array_bisect_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + le64toh(d->data.n_entries), + z, + test_object_offset, + direction, + NULL, &p, NULL); + if (r <= 0) + return r; + + r = journal_file_move_to_object(f, OBJECT_DATA, b, &o); + if (r < 0) + return r; + + r = generic_array_bisect_plus_one(f, + le64toh(o->data.entry_offset), + le64toh(o->data.entry_array_offset), + le64toh(o->data.n_entries), + p, + test_object_offset, + direction, + &qo, &q, NULL); + + if (r <= 0) + return r; + + if (p == q) { + if (ret) + *ret = qo; + if (offset) + *offset = q; + + return 1; + } + + z = q; + } +} + +int journal_file_move_to_entry_by_seqnum_for_data( + JournalFile *f, + uint64_t data_offset, + uint64_t seqnum, + direction_t direction, + Object **ret, uint64_t *offset) { + + Object *d; + int r; + + assert(f); + + r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d); + if (r < 0) + return r; + + return generic_array_bisect_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + le64toh(d->data.n_entries), + seqnum, + test_object_seqnum, + direction, + ret, offset, NULL); +} + +int journal_file_move_to_entry_by_realtime_for_data( + JournalFile *f, + uint64_t data_offset, + uint64_t realtime, + direction_t direction, + Object **ret, uint64_t *offset) { + + Object *d; + int r; + + assert(f); + + r = journal_file_move_to_object(f, OBJECT_DATA, data_offset, &d); + if (r < 0) + return r; + + return generic_array_bisect_plus_one(f, + le64toh(d->data.entry_offset), + le64toh(d->data.entry_array_offset), + le64toh(d->data.n_entries), + realtime, + test_object_realtime, + direction, + ret, offset, NULL); +} + +void journal_file_dump(JournalFile *f) { + Object *o; + int r; + uint64_t p; + + assert(f); + assert(f->header); + + journal_file_print_header(f); + + p = le64toh(f->header->header_size); + while (p != 0) { + r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o); + if (r < 0) + goto fail; + + switch (o->object.type) { + + case OBJECT_UNUSED: + printf("Type: OBJECT_UNUSED\n"); + break; + + case OBJECT_DATA: + printf("Type: OBJECT_DATA\n"); + break; + + case OBJECT_FIELD: + printf("Type: OBJECT_FIELD\n"); + break; + + case OBJECT_ENTRY: + printf("Type: OBJECT_ENTRY seqnum=%"PRIu64" monotonic=%"PRIu64" realtime=%"PRIu64"\n", + le64toh(o->entry.seqnum), + le64toh(o->entry.monotonic), + le64toh(o->entry.realtime)); + break; + + case OBJECT_FIELD_HASH_TABLE: + printf("Type: OBJECT_FIELD_HASH_TABLE\n"); + break; + + case OBJECT_DATA_HASH_TABLE: + printf("Type: OBJECT_DATA_HASH_TABLE\n"); + break; + + case OBJECT_ENTRY_ARRAY: + printf("Type: OBJECT_ENTRY_ARRAY\n"); + break; + + case OBJECT_TAG: + printf("Type: OBJECT_TAG seqnum=%"PRIu64" epoch=%"PRIu64"\n", + le64toh(o->tag.seqnum), + le64toh(o->tag.epoch)); + break; + + default: + printf("Type: unknown (%i)\n", o->object.type); + break; + } + + if (o->object.flags & OBJECT_COMPRESSION_MASK) + printf("Flags: %s\n", + object_compressed_to_string(o->object.flags & OBJECT_COMPRESSION_MASK)); + + if (p == le64toh(f->header->tail_object_offset)) + p = 0; + else + p = p + ALIGN64(le64toh(o->object.size)); + } + + return; +fail: + log_error("File corrupt"); +} + +static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) { + const char *x; + + x = format_timestamp(buf, l, t); + if (x) + return x; + return " --- "; +} + +void journal_file_print_header(JournalFile *f) { + char a[33], b[33], c[33], d[33]; + char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX]; + struct stat st; + char bytes[FORMAT_BYTES_MAX]; + + assert(f); + assert(f->header); + + printf("File Path: %s\n" + "File ID: %s\n" + "Machine ID: %s\n" + "Boot ID: %s\n" + "Sequential Number ID: %s\n" + "State: %s\n" + "Compatible Flags:%s%s\n" + "Incompatible Flags:%s%s%s\n" + "Header size: %"PRIu64"\n" + "Arena size: %"PRIu64"\n" + "Data Hash Table Size: %"PRIu64"\n" + "Field Hash Table Size: %"PRIu64"\n" + "Rotate Suggested: %s\n" + "Head Sequential Number: %"PRIu64" (%"PRIx64")\n" + "Tail Sequential Number: %"PRIu64" (%"PRIx64")\n" + "Head Realtime Timestamp: %s (%"PRIx64")\n" + "Tail Realtime Timestamp: %s (%"PRIx64")\n" + "Tail Monotonic Timestamp: %s (%"PRIx64")\n" + "Objects: %"PRIu64"\n" + "Entry Objects: %"PRIu64"\n", + f->path, + sd_id128_to_string(f->header->file_id, a), + sd_id128_to_string(f->header->machine_id, b), + sd_id128_to_string(f->header->boot_id, c), + sd_id128_to_string(f->header->seqnum_id, d), + f->header->state == STATE_OFFLINE ? "OFFLINE" : + f->header->state == STATE_ONLINE ? "ONLINE" : + f->header->state == STATE_ARCHIVED ? "ARCHIVED" : "UNKNOWN", + JOURNAL_HEADER_SEALED(f->header) ? " SEALED" : "", + (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_ANY) ? " ???" : "", + JOURNAL_HEADER_COMPRESSED_XZ(f->header) ? " COMPRESSED-XZ" : "", + JOURNAL_HEADER_COMPRESSED_LZ4(f->header) ? " COMPRESSED-LZ4" : "", + (le32toh(f->header->incompatible_flags) & ~HEADER_INCOMPATIBLE_ANY) ? " ???" : "", + le64toh(f->header->header_size), + le64toh(f->header->arena_size), + le64toh(f->header->data_hash_table_size) / sizeof(HashItem), + le64toh(f->header->field_hash_table_size) / sizeof(HashItem), + yes_no(journal_file_rotate_suggested(f, 0)), + le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum), + le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum), + format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime), + format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime), + format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic), + le64toh(f->header->n_objects), + le64toh(f->header->n_entries)); + + if (JOURNAL_HEADER_CONTAINS(f->header, n_data)) + printf("Data Objects: %"PRIu64"\n" + "Data Hash Table Fill: %.1f%%\n", + le64toh(f->header->n_data), + 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)))); + + if (JOURNAL_HEADER_CONTAINS(f->header, n_fields)) + printf("Field Objects: %"PRIu64"\n" + "Field Hash Table Fill: %.1f%%\n", + le64toh(f->header->n_fields), + 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)))); + + if (JOURNAL_HEADER_CONTAINS(f->header, n_tags)) + printf("Tag Objects: %"PRIu64"\n", + le64toh(f->header->n_tags)); + if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays)) + printf("Entry Array Objects: %"PRIu64"\n", + le64toh(f->header->n_entry_arrays)); + + if (fstat(f->fd, &st) >= 0) + printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL)); +} + +static int journal_file_warn_btrfs(JournalFile *f) { + unsigned attrs; + int r; + + assert(f); + + /* Before we write anything, check if the COW logic is turned + * off on btrfs. Given our write pattern that is quite + * unfriendly to COW file systems this should greatly improve + * performance on COW file systems, such as btrfs, at the + * expense of data integrity features (which shouldn't be too + * bad, given that we do our own checksumming). */ + + r = btrfs_is_filesystem(f->fd); + if (r < 0) + return log_warning_errno(r, "Failed to determine if journal is on btrfs: %m"); + if (!r) + return 0; + + r = read_attr_fd(f->fd, &attrs); + if (r < 0) + return log_warning_errno(r, "Failed to read file attributes: %m"); + + if (attrs & FS_NOCOW_FL) { + log_debug("Detected btrfs file system with copy-on-write disabled, all is good."); + return 0; + } + + log_notice("Creating journal file %s on a btrfs file system, and copy-on-write is enabled. " + "This is likely to slow down journal access substantially, please consider turning " + "off the copy-on-write file attribute on the journal directory, using chattr +C.", f->path); + + return 1; +} + +int journal_file_open( + int fd, + const char *fname, + int flags, + mode_t mode, + bool compress, + bool seal, + JournalMetrics *metrics, + MMapCache *mmap_cache, + Set *deferred_closes, + JournalFile *template, + JournalFile **ret) { + + bool newly_created = false; + JournalFile *f; + void *h; + int r; + + assert(ret); + assert(fd >= 0 || fname); + + if ((flags & O_ACCMODE) != O_RDONLY && + (flags & O_ACCMODE) != O_RDWR) + return -EINVAL; + + if (fname) { + if (!endswith(fname, ".journal") && + !endswith(fname, ".journal~")) + return -EINVAL; + } + + f = new0(JournalFile, 1); + if (!f) + return -ENOMEM; + + f->fd = fd; + f->mode = mode; + + f->flags = flags; + f->prot = prot_from_flags(flags); + f->writable = (flags & O_ACCMODE) != O_RDONLY; +#if defined(HAVE_LZ4) + f->compress_lz4 = compress; +#elif defined(HAVE_XZ) + f->compress_xz = compress; +#endif +#ifdef HAVE_GCRYPT + f->seal = seal; +#endif + + if (mmap_cache) + f->mmap = mmap_cache_ref(mmap_cache); + else { + f->mmap = mmap_cache_new(); + if (!f->mmap) { + r = -ENOMEM; + goto fail; + } + } + + if (fname) + f->path = strdup(fname); + else /* If we don't know the path, fill in something explanatory and vaguely useful */ + asprintf(&f->path, "/proc/self/%i", fd); + if (!f->path) { + r = -ENOMEM; + goto fail; + } + + f->chain_cache = ordered_hashmap_new(&uint64_hash_ops); + if (!f->chain_cache) { + r = -ENOMEM; + goto fail; + } + + if (f->fd < 0) { + f->fd = open(f->path, f->flags|O_CLOEXEC, f->mode); + if (f->fd < 0) { + r = -errno; + goto fail; + } + + /* fds we opened here by us should also be closed by us. */ + f->close_fd = true; + } + + r = journal_file_fstat(f); + if (r < 0) + goto fail; + + if (f->last_stat.st_size == 0 && f->writable) { + + (void) journal_file_warn_btrfs(f); + + /* Let's attach the creation time to the journal file, + * so that the vacuuming code knows the age of this + * file even if the file might end up corrupted one + * day... Ideally we'd just use the creation time many + * file systems maintain for each file, but there is + * currently no usable API to query this, hence let's + * emulate this via extended attributes. If extended + * attributes are not supported we'll just skip this, + * and rely solely on mtime/atime/ctime of the file. */ + + fd_setcrtime(f->fd, 0); + +#ifdef HAVE_GCRYPT + /* Try to load the FSPRG state, and if we can't, then + * just don't do sealing */ + if (f->seal) { + r = journal_file_fss_load(f); + if (r < 0) + f->seal = false; + } +#endif + + r = journal_file_init_header(f, template); + if (r < 0) + goto fail; + + r = journal_file_fstat(f); + if (r < 0) + goto fail; + + newly_created = true; + } + + if (f->last_stat.st_size < (off_t) HEADER_SIZE_MIN) { + r = -ENODATA; + goto fail; + } + + r = mmap_cache_get(f->mmap, f->fd, f->prot, CONTEXT_HEADER, true, 0, PAGE_ALIGN(sizeof(Header)), &f->last_stat, &h); + if (r < 0) + goto fail; + + f->header = h; + + if (!newly_created) { + if (deferred_closes) + journal_file_close_set(deferred_closes); + + r = journal_file_verify_header(f); + if (r < 0) + goto fail; + } + +#ifdef HAVE_GCRYPT + if (!newly_created && f->writable) { + r = journal_file_fss_load(f); + if (r < 0) + goto fail; + } +#endif + + if (f->writable) { + if (metrics) { + journal_default_metrics(metrics, f->fd); + f->metrics = *metrics; + } else if (template) + f->metrics = template->metrics; + + r = journal_file_refresh_header(f); + if (r < 0) + goto fail; + } + +#ifdef HAVE_GCRYPT + r = journal_file_hmac_setup(f); + if (r < 0) + goto fail; +#endif + + if (newly_created) { + r = journal_file_setup_field_hash_table(f); + if (r < 0) + goto fail; + + r = journal_file_setup_data_hash_table(f); + if (r < 0) + goto fail; + +#ifdef HAVE_GCRYPT + r = journal_file_append_first_tag(f); + if (r < 0) + goto fail; +#endif + } + + if (mmap_cache_got_sigbus(f->mmap, f->fd)) { + r = -EIO; + goto fail; + } + + if (template && template->post_change_timer) { + r = journal_file_enable_post_change_timer( + f, + sd_event_source_get_event(template->post_change_timer), + template->post_change_timer_period); + + if (r < 0) + goto fail; + } + + /* The file is opened now successfully, thus we take possession of any passed in fd. */ + f->close_fd = true; + + *ret = f; + return 0; + +fail: + if (f->fd >= 0 && mmap_cache_got_sigbus(f->mmap, f->fd)) + r = -EIO; + + (void) journal_file_close(f); + + return r; +} + +int journal_file_rotate(JournalFile **f, bool compress, bool seal, Set *deferred_closes) { + _cleanup_free_ char *p = NULL; + size_t l; + JournalFile *old_file, *new_file = NULL; + int r; + + assert(f); + assert(*f); + + old_file = *f; + + if (!old_file->writable) + return -EINVAL; + + /* Is this a journal file that was passed to us as fd? If so, we synthesized a path name for it, and we refuse + * rotation, since we don't know the actual path, and couldn't rename the file hence.*/ + if (path_startswith(old_file->path, "/proc/self/fd")) + return -EINVAL; + + if (!endswith(old_file->path, ".journal")) + return -EINVAL; + + l = strlen(old_file->path); + r = asprintf(&p, "%.*s@" SD_ID128_FORMAT_STR "-%016"PRIx64"-%016"PRIx64".journal", + (int) l - 8, old_file->path, + SD_ID128_FORMAT_VAL(old_file->header->seqnum_id), + le64toh((*f)->header->head_entry_seqnum), + le64toh((*f)->header->head_entry_realtime)); + if (r < 0) + return -ENOMEM; + + /* Try to rename the file to the archived version. If the file + * already was deleted, we'll get ENOENT, let's ignore that + * case. */ + r = rename(old_file->path, p); + if (r < 0 && errno != ENOENT) + return -errno; + + /* Sync the rename to disk */ + (void) fsync_directory_of_file(old_file->fd); + + /* Set as archive so offlining commits w/state=STATE_ARCHIVED. + * Previously we would set old_file->header->state to STATE_ARCHIVED directly here, + * but journal_file_set_offline() short-circuits when state != STATE_ONLINE, which + * would result in the rotated journal never getting fsync() called before closing. + * Now we simply queue the archive state by setting an archive bit, leaving the state + * as STATE_ONLINE so proper offlining occurs. */ + old_file->archive = true; + + /* Currently, btrfs is not very good with out write patterns + * and fragments heavily. Let's defrag our journal files when + * we archive them */ + old_file->defrag_on_close = true; + + r = journal_file_open(-1, old_file->path, old_file->flags, old_file->mode, compress, seal, NULL, old_file->mmap, deferred_closes, old_file, &new_file); + + if (deferred_closes && + set_put(deferred_closes, old_file) >= 0) + (void) journal_file_set_offline(old_file, false); + else + (void) journal_file_close(old_file); + + *f = new_file; + return r; +} + +int journal_file_open_reliably( + const char *fname, + int flags, + mode_t mode, + bool compress, + bool seal, + JournalMetrics *metrics, + MMapCache *mmap_cache, + Set *deferred_closes, + JournalFile *template, + JournalFile **ret) { + + int r; + size_t l; + _cleanup_free_ char *p = NULL; + + r = journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret); + if (!IN_SET(r, + -EBADMSG, /* corrupted */ + -ENODATA, /* truncated */ + -EHOSTDOWN, /* other machine */ + -EPROTONOSUPPORT, /* incompatible feature */ + -EBUSY, /* unclean shutdown */ + -ESHUTDOWN, /* already archived */ + -EIO, /* IO error, including SIGBUS on mmap */ + -EIDRM /* File has been deleted */)) + return r; + + if ((flags & O_ACCMODE) == O_RDONLY) + return r; + + if (!(flags & O_CREAT)) + return r; + + if (!endswith(fname, ".journal")) + return r; + + /* The file is corrupted. Rotate it away and try it again (but only once) */ + + l = strlen(fname); + if (asprintf(&p, "%.*s@%016"PRIx64 "-%016"PRIx64 ".journal~", + (int) l - 8, fname, + now(CLOCK_REALTIME), + random_u64()) < 0) + return -ENOMEM; + + if (rename(fname, p) < 0) + return -errno; + + /* btrfs doesn't cope well with our write pattern and + * fragments heavily. Let's defrag all files we rotate */ + + (void) chattr_path(p, 0, FS_NOCOW_FL); + (void) btrfs_defrag(p); + + log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname); + + return journal_file_open(-1, fname, flags, mode, compress, seal, metrics, mmap_cache, deferred_closes, template, ret); +} + +int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset) { + uint64_t i, n; + uint64_t q, xor_hash = 0; + int r; + EntryItem *items; + dual_timestamp ts; + + assert(from); + assert(to); + assert(o); + assert(p); + + if (!to->writable) + return -EPERM; + + ts.monotonic = le64toh(o->entry.monotonic); + ts.realtime = le64toh(o->entry.realtime); + + n = journal_file_entry_n_items(o); + /* alloca() can't take 0, hence let's allocate at least one */ + items = alloca(sizeof(EntryItem) * MAX(1u, n)); + + for (i = 0; i < n; i++) { + uint64_t l, h; + le64_t le_hash; + size_t t; + void *data; + Object *u; + + q = le64toh(o->entry.items[i].object_offset); + le_hash = o->entry.items[i].hash; + + r = journal_file_move_to_object(from, OBJECT_DATA, q, &o); + if (r < 0) + return r; + + if (le_hash != o->data.hash) + return -EBADMSG; + + l = le64toh(o->object.size) - offsetof(Object, data.payload); + t = (size_t) l; + + /* We hit the limit on 32bit machines */ + if ((uint64_t) t != l) + return -E2BIG; + + if (o->object.flags & OBJECT_COMPRESSION_MASK) { +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + size_t rsize = 0; + + r = decompress_blob(o->object.flags & OBJECT_COMPRESSION_MASK, + o->data.payload, l, &from->compress_buffer, &from->compress_buffer_size, &rsize, 0); + if (r < 0) + return r; + + data = from->compress_buffer; + l = rsize; +#else + return -EPROTONOSUPPORT; +#endif + } else + data = o->data.payload; + + r = journal_file_append_data(to, data, l, &u, &h); + if (r < 0) + return r; + + xor_hash ^= le64toh(u->data.hash); + items[i].object_offset = htole64(h); + items[i].hash = u->data.hash; + + r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + } + + r = journal_file_append_entry_internal(to, &ts, xor_hash, items, n, seqnum, ret, offset); + + if (mmap_cache_got_sigbus(to->mmap, to->fd)) + return -EIO; + + return r; +} + +void journal_reset_metrics(JournalMetrics *m) { + assert(m); + + /* Set everything to "pick automatic values". */ + + *m = (JournalMetrics) { + .min_use = (uint64_t) -1, + .max_use = (uint64_t) -1, + .min_size = (uint64_t) -1, + .max_size = (uint64_t) -1, + .keep_free = (uint64_t) -1, + .n_max_files = (uint64_t) -1, + }; +} + +void journal_default_metrics(JournalMetrics *m, int fd) { + char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX]; + struct statvfs ss; + uint64_t fs_size; + + assert(m); + assert(fd >= 0); + + if (fstatvfs(fd, &ss) >= 0) + fs_size = ss.f_frsize * ss.f_blocks; + else { + log_debug_errno(errno, "Failed to detremine disk size: %m"); + fs_size = 0; + } + + if (m->max_use == (uint64_t) -1) { + + if (fs_size > 0) { + m->max_use = PAGE_ALIGN(fs_size / 10); /* 10% of file system size */ + + if (m->max_use > DEFAULT_MAX_USE_UPPER) + m->max_use = DEFAULT_MAX_USE_UPPER; + + if (m->max_use < DEFAULT_MAX_USE_LOWER) + m->max_use = DEFAULT_MAX_USE_LOWER; + } else + m->max_use = DEFAULT_MAX_USE_LOWER; + } else { + m->max_use = PAGE_ALIGN(m->max_use); + + if (m->max_use != 0 && m->max_use < JOURNAL_FILE_SIZE_MIN*2) + m->max_use = JOURNAL_FILE_SIZE_MIN*2; + } + + if (m->min_use == (uint64_t) -1) + m->min_use = DEFAULT_MIN_USE; + + if (m->min_use > m->max_use) + m->min_use = m->max_use; + + if (m->max_size == (uint64_t) -1) { + m->max_size = PAGE_ALIGN(m->max_use / 8); /* 8 chunks */ + + if (m->max_size > DEFAULT_MAX_SIZE_UPPER) + m->max_size = DEFAULT_MAX_SIZE_UPPER; + } else + m->max_size = PAGE_ALIGN(m->max_size); + + if (m->max_size != 0) { + if (m->max_size < JOURNAL_FILE_SIZE_MIN) + m->max_size = JOURNAL_FILE_SIZE_MIN; + + if (m->max_use != 0 && m->max_size*2 > m->max_use) + m->max_use = m->max_size*2; + } + + if (m->min_size == (uint64_t) -1) + m->min_size = JOURNAL_FILE_SIZE_MIN; + else { + m->min_size = PAGE_ALIGN(m->min_size); + + if (m->min_size < JOURNAL_FILE_SIZE_MIN) + m->min_size = JOURNAL_FILE_SIZE_MIN; + + if (m->max_size != 0 && m->min_size > m->max_size) + m->max_size = m->min_size; + } + + if (m->keep_free == (uint64_t) -1) { + + if (fs_size > 0) { + m->keep_free = PAGE_ALIGN(fs_size * 3 / 20); /* 15% of file system size */ + + if (m->keep_free > DEFAULT_KEEP_FREE_UPPER) + m->keep_free = DEFAULT_KEEP_FREE_UPPER; + + } else + m->keep_free = DEFAULT_KEEP_FREE; + } + + if (m->n_max_files == (uint64_t) -1) + m->n_max_files = DEFAULT_N_MAX_FILES; + + log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64, + format_bytes(a, sizeof(a), m->min_use), + format_bytes(b, sizeof(b), m->max_use), + format_bytes(c, sizeof(c), m->max_size), + format_bytes(d, sizeof(d), m->min_size), + format_bytes(e, sizeof(e), m->keep_free), + m->n_max_files); +} + +int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to) { + assert(f); + assert(f->header); + assert(from || to); + + if (from) { + if (f->header->head_entry_realtime == 0) + return -ENOENT; + + *from = le64toh(f->header->head_entry_realtime); + } + + if (to) { + if (f->header->tail_entry_realtime == 0) + return -ENOENT; + + *to = le64toh(f->header->tail_entry_realtime); + } + + return 1; +} + +int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot_id, usec_t *from, usec_t *to) { + Object *o; + uint64_t p; + int r; + + assert(f); + assert(from || to); + + r = find_data_object_by_boot_id(f, boot_id, &o, &p); + if (r <= 0) + return r; + + if (le64toh(o->data.n_entries) <= 0) + return 0; + + if (from) { + r = journal_file_move_to_object(f, OBJECT_ENTRY, le64toh(o->data.entry_offset), &o); + if (r < 0) + return r; + + *from = le64toh(o->entry.monotonic); + } + + if (to) { + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + r = generic_array_get_plus_one(f, + le64toh(o->data.entry_offset), + le64toh(o->data.entry_array_offset), + le64toh(o->data.n_entries)-1, + &o, NULL); + if (r <= 0) + return r; + + *to = le64toh(o->entry.monotonic); + } + + return 1; +} + +bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec) { + assert(f); + assert(f->header); + + /* If we gained new header fields we gained new features, + * hence suggest a rotation */ + if (le64toh(f->header->header_size) < sizeof(Header)) { + log_debug("%s uses an outdated header, suggesting rotation.", f->path); + return true; + } + + /* Let's check if the hash tables grew over a certain fill + * level (75%, borrowing this value from Java's hash table + * implementation), and if so suggest a rotation. To calculate + * the fill level we need the n_data field, which only exists + * in newer versions. */ + + if (JOURNAL_HEADER_CONTAINS(f->header, n_data)) + if (le64toh(f->header->n_data) * 4ULL > (le64toh(f->header->data_hash_table_size) / sizeof(HashItem)) * 3ULL) { + log_debug("Data hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items, %llu file size, %"PRIu64" bytes per hash table item), suggesting rotation.", + f->path, + 100.0 * (double) le64toh(f->header->n_data) / ((double) (le64toh(f->header->data_hash_table_size) / sizeof(HashItem))), + le64toh(f->header->n_data), + le64toh(f->header->data_hash_table_size) / sizeof(HashItem), + (unsigned long long) f->last_stat.st_size, + f->last_stat.st_size / le64toh(f->header->n_data)); + return true; + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_fields)) + if (le64toh(f->header->n_fields) * 4ULL > (le64toh(f->header->field_hash_table_size) / sizeof(HashItem)) * 3ULL) { + log_debug("Field hash table of %s has a fill level at %.1f (%"PRIu64" of %"PRIu64" items), suggesting rotation.", + f->path, + 100.0 * (double) le64toh(f->header->n_fields) / ((double) (le64toh(f->header->field_hash_table_size) / sizeof(HashItem))), + le64toh(f->header->n_fields), + le64toh(f->header->field_hash_table_size) / sizeof(HashItem)); + return true; + } + + /* Are the data objects properly indexed by field objects? */ + if (JOURNAL_HEADER_CONTAINS(f->header, n_data) && + JOURNAL_HEADER_CONTAINS(f->header, n_fields) && + le64toh(f->header->n_data) > 0 && + le64toh(f->header->n_fields) == 0) + return true; + + if (max_file_usec > 0) { + usec_t t, h; + + h = le64toh(f->header->head_entry_realtime); + t = now(CLOCK_REALTIME); + + if (h > 0 && t > h + max_file_usec) + return true; + } + + return false; +} diff --git a/src/libsystemd/src/sd-journal/journal-file.h b/src/libsystemd/src/sd-journal/journal-file.h new file mode 100644 index 0000000000..054fe5794b --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-file.h @@ -0,0 +1,266 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> + +#ifdef HAVE_GCRYPT +#include <gcrypt.h> +#endif + +#include <systemd/sd-event.h> +#include <systemd/sd-id128.h> + +#include "systemd-basic/hashmap.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/sparse-endian.h" + +#include "journal-def.h" +#include "mmap-cache.h" + +typedef struct JournalMetrics { + /* For all these: -1 means "pick automatically", and 0 means "no limit enforced" */ + uint64_t max_size; /* how large journal files grow at max */ + uint64_t min_size; /* how large journal files grow at least */ + uint64_t max_use; /* how much disk space to use in total at max, keep_free permitting */ + uint64_t min_use; /* how much disk space to use in total at least, even if keep_free says not to */ + uint64_t keep_free; /* how much to keep free on disk */ + uint64_t n_max_files; /* how many files to keep around at max */ +} JournalMetrics; + +typedef enum direction { + DIRECTION_UP, + DIRECTION_DOWN +} direction_t; + +typedef enum LocationType { + /* The first and last entries, resp. */ + LOCATION_HEAD, + LOCATION_TAIL, + + /* We already read the entry we currently point to, and the + * next one to read should probably not be this one again. */ + LOCATION_DISCRETE, + + /* We should seek to the precise location specified, and + * return it, as we haven't read it yet. */ + LOCATION_SEEK +} LocationType; + +typedef enum OfflineState { + OFFLINE_JOINED, + OFFLINE_SYNCING, + OFFLINE_OFFLINING, + OFFLINE_CANCEL, + OFFLINE_AGAIN_FROM_SYNCING, + OFFLINE_AGAIN_FROM_OFFLINING, + OFFLINE_DONE +} OfflineState; + +typedef struct JournalFile { + int fd; + + mode_t mode; + + int flags; + int prot; + bool writable:1; + bool compress_xz:1; + bool compress_lz4:1; + bool seal:1; + bool defrag_on_close:1; + bool close_fd:1; + bool archive:1; + + bool tail_entry_monotonic_valid:1; + + direction_t last_direction; + LocationType location_type; + uint64_t last_n_entries; + + char *path; + struct stat last_stat; + usec_t last_stat_usec; + + Header *header; + HashItem *data_hash_table; + HashItem *field_hash_table; + + uint64_t current_offset; + uint64_t current_seqnum; + uint64_t current_realtime; + uint64_t current_monotonic; + sd_id128_t current_boot_id; + uint64_t current_xor_hash; + + JournalMetrics metrics; + MMapCache *mmap; + + sd_event_source *post_change_timer; + usec_t post_change_timer_period; + + OrderedHashmap *chain_cache; + + pthread_t offline_thread; + volatile OfflineState offline_state; + +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + void *compress_buffer; + size_t compress_buffer_size; +#endif + +#ifdef HAVE_GCRYPT + gcry_md_hd_t hmac; + bool hmac_running; + + FSSHeader *fss_file; + size_t fss_file_size; + + uint64_t fss_start_usec; + uint64_t fss_interval_usec; + + void *fsprg_state; + size_t fsprg_state_size; + + void *fsprg_seed; + size_t fsprg_seed_size; +#endif +} JournalFile; + +int journal_file_open( + int fd, + const char *fname, + int flags, + mode_t mode, + bool compress, + bool seal, + JournalMetrics *metrics, + MMapCache *mmap_cache, + Set *deferred_closes, + JournalFile *template, + JournalFile **ret); + +int journal_file_set_offline(JournalFile *f, bool wait); +bool journal_file_is_offlining(JournalFile *f); +JournalFile* journal_file_close(JournalFile *j); +void journal_file_close_set(Set *s); + +int journal_file_open_reliably( + const char *fname, + int flags, + mode_t mode, + bool compress, + bool seal, + JournalMetrics *metrics, + MMapCache *mmap_cache, + Set *deferred_closes, + JournalFile *template, + JournalFile **ret); + +#define ALIGN64(x) (((x) + 7ULL) & ~7ULL) +#define VALID64(x) (((x) & 7ULL) == 0ULL) + +/* Use six characters to cover the offsets common in smallish journal + * files without adding too many zeros. */ +#define OFSfmt "%06"PRIx64 + +static inline bool VALID_REALTIME(uint64_t u) { + /* This considers timestamps until the year 3112 valid. That should be plenty room... */ + return u > 0 && u < (1ULL << 55); +} + +static inline bool VALID_MONOTONIC(uint64_t u) { + /* This considers timestamps until 1142 years of runtime valid. */ + return u < (1ULL << 55); +} + +static inline bool VALID_EPOCH(uint64_t u) { + /* This allows changing the key for 1142 years, every usec. */ + return u < (1ULL << 55); +} + +#define JOURNAL_HEADER_CONTAINS(h, field) \ + (le64toh((h)->header_size) >= offsetof(Header, field) + sizeof((h)->field)) + +#define JOURNAL_HEADER_SEALED(h) \ + (!!(le32toh((h)->compatible_flags) & HEADER_COMPATIBLE_SEALED)) + +#define JOURNAL_HEADER_COMPRESSED_XZ(h) \ + (!!(le32toh((h)->incompatible_flags) & HEADER_INCOMPATIBLE_COMPRESSED_XZ)) + +#define JOURNAL_HEADER_COMPRESSED_LZ4(h) \ + (!!(le32toh((h)->incompatible_flags) & HEADER_INCOMPATIBLE_COMPRESSED_LZ4)) + +int journal_file_move_to_object(JournalFile *f, ObjectType type, uint64_t offset, Object **ret); + +uint64_t journal_file_entry_n_items(Object *o) _pure_; +uint64_t journal_file_entry_array_n_items(Object *o) _pure_; +uint64_t journal_file_hash_table_n_items(Object *o) _pure_; + +int journal_file_append_object(JournalFile *f, ObjectType type, uint64_t size, Object **ret, uint64_t *offset); +int journal_file_append_entry(JournalFile *f, const dual_timestamp *ts, const struct iovec iovec[], unsigned n_iovec, uint64_t *seqno, Object **ret, uint64_t *offset); + +int journal_file_find_data_object(JournalFile *f, const void *data, uint64_t size, Object **ret, uint64_t *offset); +int journal_file_find_data_object_with_hash(JournalFile *f, const void *data, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset); + +int journal_file_find_field_object(JournalFile *f, const void *field, uint64_t size, Object **ret, uint64_t *offset); +int journal_file_find_field_object_with_hash(JournalFile *f, const void *field, uint64_t size, uint64_t hash, Object **ret, uint64_t *offset); + +void journal_file_reset_location(JournalFile *f); +void journal_file_save_location(JournalFile *f, Object *o, uint64_t offset); +int journal_file_compare_locations(JournalFile *af, JournalFile *bf); +int journal_file_next_entry(JournalFile *f, uint64_t p, direction_t direction, Object **ret, uint64_t *offset); + +int journal_file_next_entry_for_data(JournalFile *f, Object *o, uint64_t p, uint64_t data_offset, direction_t direction, Object **ret, uint64_t *offset); + +int journal_file_move_to_entry_by_seqnum(JournalFile *f, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset); +int journal_file_move_to_entry_by_realtime(JournalFile *f, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset); +int journal_file_move_to_entry_by_monotonic(JournalFile *f, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset); + +int journal_file_move_to_entry_by_offset_for_data(JournalFile *f, uint64_t data_offset, uint64_t p, direction_t direction, Object **ret, uint64_t *offset); +int journal_file_move_to_entry_by_seqnum_for_data(JournalFile *f, uint64_t data_offset, uint64_t seqnum, direction_t direction, Object **ret, uint64_t *offset); +int journal_file_move_to_entry_by_realtime_for_data(JournalFile *f, uint64_t data_offset, uint64_t realtime, direction_t direction, Object **ret, uint64_t *offset); +int journal_file_move_to_entry_by_monotonic_for_data(JournalFile *f, uint64_t data_offset, sd_id128_t boot_id, uint64_t monotonic, direction_t direction, Object **ret, uint64_t *offset); + +int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p, uint64_t *seqnum, Object **ret, uint64_t *offset); + +void journal_file_dump(JournalFile *f); +void journal_file_print_header(JournalFile *f); + +int journal_file_rotate(JournalFile **f, bool compress, bool seal, Set *deferred_closes); + +void journal_file_post_change(JournalFile *f); +int journal_file_enable_post_change_timer(JournalFile *f, sd_event *e, usec_t t); + +void journal_reset_metrics(JournalMetrics *m); +void journal_default_metrics(JournalMetrics *m, int fd); + +int journal_file_get_cutoff_realtime_usec(JournalFile *f, usec_t *from, usec_t *to); +int journal_file_get_cutoff_monotonic_usec(JournalFile *f, sd_id128_t boot, usec_t *from, usec_t *to); + +bool journal_file_rotate_suggested(JournalFile *f, usec_t max_file_usec); + +int journal_file_map_data_hash_table(JournalFile *f); +int journal_file_map_field_hash_table(JournalFile *f); + +static inline bool JOURNAL_FILE_COMPRESS(JournalFile *f) { + assert(f); + return f->compress_xz || f->compress_lz4; +} diff --git a/src/libsystemd/src/sd-journal/journal-internal.h b/src/libsystemd/src/sd-journal/journal-internal.h new file mode 100644 index 0000000000..83f38b51ed --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-internal.h @@ -0,0 +1,144 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <stdbool.h> +#include <sys/types.h> + +#include <systemd/sd-id128.h> +#include <systemd/sd-journal.h> + +#include "systemd-basic/hashmap.h" +#include "systemd-basic/list.h" +#include "systemd-basic/set.h" + +#include "journal-def.h" +#include "journal-file.h" + +typedef struct Match Match; +typedef struct Location Location; +typedef struct Directory Directory; + +typedef enum MatchType { + MATCH_DISCRETE, + MATCH_OR_TERM, + MATCH_AND_TERM +} MatchType; + +struct Match { + MatchType type; + Match *parent; + LIST_FIELDS(Match, matches); + + /* For concrete matches */ + char *data; + size_t size; + le64_t le_hash; + + /* For terms */ + LIST_HEAD(Match, matches); +}; + +struct Location { + LocationType type; + + bool seqnum_set; + bool realtime_set; + bool monotonic_set; + bool xor_hash_set; + + uint64_t seqnum; + sd_id128_t seqnum_id; + + uint64_t realtime; + + uint64_t monotonic; + sd_id128_t boot_id; + + uint64_t xor_hash; +}; + +struct Directory { + char *path; + int wd; + bool is_root; +}; + +struct sd_journal { + int toplevel_fd; + + char *path; + char *prefix; + + OrderedHashmap *files; + MMapCache *mmap; + + Location current_location; + + JournalFile *current_file; + uint64_t current_field; + + Match *level0, *level1, *level2; + + pid_t original_pid; + + int inotify_fd; + unsigned current_invalidate_counter, last_invalidate_counter; + usec_t last_process_usec; + + /* Iterating through unique fields and their data values */ + char *unique_field; + JournalFile *unique_file; + uint64_t unique_offset; + + /* Iterating through known fields */ + JournalFile *fields_file; + uint64_t fields_offset; + uint64_t fields_hash_table_index; + char *fields_buffer; + size_t fields_buffer_allocated; + + int flags; + + bool on_network:1; + bool no_new_files:1; + bool no_inotify:1; + bool unique_file_lost:1; /* File we were iterating over got + removed, and there were no more + files, so sd_j_enumerate_unique + will return a value equal to 0. */ + bool fields_file_lost:1; + bool has_runtime_files:1; + bool has_persistent_files:1; + + size_t data_threshold; + + Hashmap *directories_by_path; + Hashmap *directories_by_wd; + + Hashmap *errors; +}; + +char *journal_make_match_string(sd_journal *j); +void journal_print_header(sd_journal *j); + +#define JOURNAL_FOREACH_DATA_RETVAL(j, data, l, retval) \ + for (sd_journal_restart_data(j); ((retval) = sd_journal_enumerate_data((j), &(data), &(l))) > 0; ) diff --git a/src/libsystemd/src/sd-journal/journal-send.c b/src/libsystemd/src/sd-journal/journal-send.c new file mode 100644 index 0000000000..c168902e9a --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-send.c @@ -0,0 +1,575 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <fcntl.h> +#include <printf.h> +#include <stddef.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <unistd.h> + +#define SD_JOURNAL_SUPPRESS_LOCATION + +#include <systemd/sd-journal.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/memfd-util.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" + +#define SNDBUF_SIZE (8*1024*1024) + +#define ALLOCA_CODE_FUNC(f, func) \ + do { \ + size_t _fl; \ + const char *_func = (func); \ + char **_f = &(f); \ + _fl = strlen(_func) + 1; \ + *_f = alloca(_fl + 10); \ + memcpy(*_f, "CODE_FUNC=", 10); \ + memcpy(*_f + 10, _func, _fl); \ + } while (false) + +/* We open a single fd, and we'll share it with the current process, + * all its threads, and all its subprocesses. This means we need to + * initialize it atomically, and need to operate on it atomically + * never assuming we are the only user */ + +static int journal_fd(void) { + int fd; + static int fd_plus_one = 0; + +retry: + if (fd_plus_one > 0) + return fd_plus_one - 1; + + fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0); + if (fd < 0) + return -errno; + + fd_inc_sndbuf(fd, SNDBUF_SIZE); + + if (!__sync_bool_compare_and_swap(&fd_plus_one, 0, fd+1)) { + safe_close(fd); + goto retry; + } + + return fd; +} + +_public_ int sd_journal_print(int priority, const char *format, ...) { + int r; + va_list ap; + + va_start(ap, format); + r = sd_journal_printv(priority, format, ap); + va_end(ap); + + return r; +} + +_public_ int sd_journal_printv(int priority, const char *format, va_list ap) { + + /* FIXME: Instead of limiting things to LINE_MAX we could do a + C99 variable-length array on the stack here in a loop. */ + + char buffer[8 + LINE_MAX], p[sizeof("PRIORITY=")-1 + DECIMAL_STR_MAX(int) + 1]; + struct iovec iov[2]; + + assert_return(priority >= 0, -EINVAL); + assert_return(priority <= 7, -EINVAL); + assert_return(format, -EINVAL); + + xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK); + + memcpy(buffer, "MESSAGE=", 8); + vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap); + + /* Strip trailing whitespace, keep prefix whitespace. */ + (void) strstrip(buffer); + + /* Suppress empty lines */ + if (isempty(buffer+8)) + return 0; + + zero(iov); + IOVEC_SET_STRING(iov[0], buffer); + IOVEC_SET_STRING(iov[1], p); + + return sd_journal_sendv(iov, 2); +} + +_printf_(1, 0) static int fill_iovec_sprintf(const char *format, va_list ap, int extra, struct iovec **_iov) { + PROTECT_ERRNO; + int r, n = 0, i = 0, j; + struct iovec *iov = NULL; + + assert(_iov); + + if (extra > 0) { + n = MAX(extra * 2, extra + 4); + iov = malloc0(n * sizeof(struct iovec)); + if (!iov) { + r = -ENOMEM; + goto fail; + } + + i = extra; + } + + while (format) { + struct iovec *c; + char *buffer; + va_list aq; + + if (i >= n) { + n = MAX(i*2, 4); + c = realloc(iov, n * sizeof(struct iovec)); + if (!c) { + r = -ENOMEM; + goto fail; + } + + iov = c; + } + + va_copy(aq, ap); + if (vasprintf(&buffer, format, aq) < 0) { + va_end(aq); + r = -ENOMEM; + goto fail; + } + va_end(aq); + + VA_FORMAT_ADVANCE(format, ap); + + (void) strstrip(buffer); /* strip trailing whitespace, keep prefixing whitespace */ + + IOVEC_SET_STRING(iov[i++], buffer); + + format = va_arg(ap, char *); + } + + *_iov = iov; + + return i; + +fail: + for (j = 0; j < i; j++) + free(iov[j].iov_base); + + free(iov); + + return r; +} + +_public_ int sd_journal_send(const char *format, ...) { + int r, i, j; + va_list ap; + struct iovec *iov = NULL; + + va_start(ap, format); + i = fill_iovec_sprintf(format, ap, 0, &iov); + va_end(ap); + + if (_unlikely_(i < 0)) { + r = i; + goto finish; + } + + r = sd_journal_sendv(iov, i); + +finish: + for (j = 0; j < i; j++) + free(iov[j].iov_base); + + free(iov); + + return r; +} + +_public_ int sd_journal_sendv(const struct iovec *iov, int n) { + PROTECT_ERRNO; + int fd, r; + _cleanup_close_ int buffer_fd = -1; + struct iovec *w; + uint64_t *l; + int i, j = 0; + static const union sockaddr_union sa = { + .un.sun_family = AF_UNIX, + .un.sun_path = "/run/systemd/journal/socket", + }; + struct msghdr mh = { + .msg_name = (struct sockaddr*) &sa.sa, + .msg_namelen = SOCKADDR_UN_LEN(sa.un), + }; + ssize_t k; + bool have_syslog_identifier = false; + bool seal = true; + + assert_return(iov, -EINVAL); + assert_return(n > 0, -EINVAL); + + w = newa(struct iovec, n * 5 + 3); + l = newa(uint64_t, n); + + for (i = 0; i < n; i++) { + char *c, *nl; + + if (_unlikely_(!iov[i].iov_base || iov[i].iov_len <= 1)) + return -EINVAL; + + c = memchr(iov[i].iov_base, '=', iov[i].iov_len); + if (_unlikely_(!c || c == iov[i].iov_base)) + return -EINVAL; + + have_syslog_identifier = have_syslog_identifier || + (c == (char *) iov[i].iov_base + 17 && + startswith(iov[i].iov_base, "SYSLOG_IDENTIFIER")); + + nl = memchr(iov[i].iov_base, '\n', iov[i].iov_len); + if (nl) { + if (_unlikely_(nl < c)) + return -EINVAL; + + /* Already includes a newline? Bummer, then + * let's write the variable name, then a + * newline, then the size (64bit LE), followed + * by the data and a final newline */ + + w[j].iov_base = iov[i].iov_base; + w[j].iov_len = c - (char*) iov[i].iov_base; + j++; + + IOVEC_SET_STRING(w[j++], "\n"); + + l[i] = htole64(iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1); + w[j].iov_base = &l[i]; + w[j].iov_len = sizeof(uint64_t); + j++; + + w[j].iov_base = c + 1; + w[j].iov_len = iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1; + j++; + + } else + /* Nothing special? Then just add the line and + * append a newline */ + w[j++] = iov[i]; + + IOVEC_SET_STRING(w[j++], "\n"); + } + + if (!have_syslog_identifier && + string_is_safe(program_invocation_short_name)) { + + /* Implicitly add program_invocation_short_name, if it + * is not set explicitly. We only do this for + * program_invocation_short_name, and nothing else + * since everything else is much nicer to retrieve + * from the outside. */ + + IOVEC_SET_STRING(w[j++], "SYSLOG_IDENTIFIER="); + IOVEC_SET_STRING(w[j++], program_invocation_short_name); + IOVEC_SET_STRING(w[j++], "\n"); + } + + fd = journal_fd(); + if (_unlikely_(fd < 0)) + return fd; + + mh.msg_iov = w; + mh.msg_iovlen = j; + + k = sendmsg(fd, &mh, MSG_NOSIGNAL); + if (k >= 0) + return 0; + + /* Fail silently if the journal is not available */ + if (errno == ENOENT) + return 0; + + if (errno != EMSGSIZE && errno != ENOBUFS) + return -errno; + + /* Message doesn't fit... Let's dump the data in a memfd or + * temporary file and just pass a file descriptor of it to the + * other side. + * + * For the temporary files we use /dev/shm instead of /tmp + * here, since we want this to be a tmpfs, and one that is + * available from early boot on and where unprivileged users + * can create files. */ + buffer_fd = memfd_new(NULL); + if (buffer_fd < 0) { + if (buffer_fd == -ENOSYS) { + buffer_fd = open_tmpfile_unlinkable("/dev/shm", O_RDWR | O_CLOEXEC); + if (buffer_fd < 0) + return buffer_fd; + + seal = false; + } else + return buffer_fd; + } + + n = writev(buffer_fd, w, j); + if (n < 0) + return -errno; + + if (seal) { + r = memfd_set_sealed(buffer_fd); + if (r < 0) + return r; + } + + r = send_one_fd_sa(fd, buffer_fd, mh.msg_name, mh.msg_namelen, 0); + if (r == -ENOENT) + /* Fail silently if the journal is not available */ + return 0; + return r; +} + +static int fill_iovec_perror_and_send(const char *message, int skip, struct iovec iov[]) { + PROTECT_ERRNO; + size_t n, k; + + k = isempty(message) ? 0 : strlen(message) + 2; + n = 8 + k + 256 + 1; + + for (;;) { + char buffer[n]; + char* j; + + errno = 0; + j = strerror_r(_saved_errno_, buffer + 8 + k, n - 8 - k); + if (errno == 0) { + char error[sizeof("ERRNO=")-1 + DECIMAL_STR_MAX(int) + 1]; + + if (j != buffer + 8 + k) + memmove(buffer + 8 + k, j, strlen(j)+1); + + memcpy(buffer, "MESSAGE=", 8); + + if (k > 0) { + memcpy(buffer + 8, message, k - 2); + memcpy(buffer + 8 + k - 2, ": ", 2); + } + + xsprintf(error, "ERRNO=%i", _saved_errno_); + + assert_cc(3 == LOG_ERR); + IOVEC_SET_STRING(iov[skip+0], "PRIORITY=3"); + IOVEC_SET_STRING(iov[skip+1], buffer); + IOVEC_SET_STRING(iov[skip+2], error); + + return sd_journal_sendv(iov, skip + 3); + } + + if (errno != ERANGE) + return -errno; + + n *= 2; + } +} + +_public_ int sd_journal_perror(const char *message) { + struct iovec iovec[3]; + + return fill_iovec_perror_and_send(message, 0, iovec); +} + +_public_ int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix) { + static const union sockaddr_union sa = { + .un.sun_family = AF_UNIX, + .un.sun_path = "/run/systemd/journal/stdout", + }; + _cleanup_close_ int fd = -1; + char *header; + size_t l; + int r; + + assert_return(priority >= 0, -EINVAL); + assert_return(priority <= 7, -EINVAL); + + fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); + if (fd < 0) + return -errno; + + r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)); + if (r < 0) + return -errno; + + if (shutdown(fd, SHUT_RD) < 0) + return -errno; + + fd_inc_sndbuf(fd, SNDBUF_SIZE); + + if (!identifier) + identifier = ""; + + l = strlen(identifier); + header = alloca(l + 1 + 1 + 2 + 2 + 2 + 2 + 2); + + memcpy(header, identifier, l); + header[l++] = '\n'; + header[l++] = '\n'; /* unit id */ + header[l++] = '0' + priority; + header[l++] = '\n'; + header[l++] = '0' + !!level_prefix; + header[l++] = '\n'; + header[l++] = '0'; + header[l++] = '\n'; + header[l++] = '0'; + header[l++] = '\n'; + header[l++] = '0'; + header[l++] = '\n'; + + r = loop_write(fd, header, l, false); + if (r < 0) + return r; + + r = fd; + fd = -1; + return r; +} + +_public_ int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) { + int r; + va_list ap; + + va_start(ap, format); + r = sd_journal_printv_with_location(priority, file, line, func, format, ap); + va_end(ap); + + return r; +} + +_public_ int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) { + char buffer[8 + LINE_MAX], p[sizeof("PRIORITY=")-1 + DECIMAL_STR_MAX(int) + 1]; + struct iovec iov[5]; + char *f; + + assert_return(priority >= 0, -EINVAL); + assert_return(priority <= 7, -EINVAL); + assert_return(format, -EINVAL); + + xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK); + + memcpy(buffer, "MESSAGE=", 8); + vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap); + + /* Strip trailing whitespace, keep prefixing whitespace */ + (void) strstrip(buffer); + + /* Suppress empty lines */ + if (isempty(buffer+8)) + return 0; + + /* func is initialized from __func__ which is not a macro, but + * a static const char[], hence cannot easily be prefixed with + * CODE_FUNC=, hence let's do it manually here. */ + ALLOCA_CODE_FUNC(f, func); + + zero(iov); + IOVEC_SET_STRING(iov[0], buffer); + IOVEC_SET_STRING(iov[1], p); + IOVEC_SET_STRING(iov[2], file); + IOVEC_SET_STRING(iov[3], line); + IOVEC_SET_STRING(iov[4], f); + + return sd_journal_sendv(iov, ELEMENTSOF(iov)); +} + +_public_ int sd_journal_send_with_location(const char *file, const char *line, const char *func, const char *format, ...) { + int r, i, j; + va_list ap; + struct iovec *iov = NULL; + char *f; + + va_start(ap, format); + i = fill_iovec_sprintf(format, ap, 3, &iov); + va_end(ap); + + if (_unlikely_(i < 0)) { + r = i; + goto finish; + } + + ALLOCA_CODE_FUNC(f, func); + + IOVEC_SET_STRING(iov[0], file); + IOVEC_SET_STRING(iov[1], line); + IOVEC_SET_STRING(iov[2], f); + + r = sd_journal_sendv(iov, i); + +finish: + for (j = 3; j < i; j++) + free(iov[j].iov_base); + + free(iov); + + return r; +} + +_public_ int sd_journal_sendv_with_location( + const char *file, const char *line, + const char *func, + const struct iovec *iov, int n) { + + struct iovec *niov; + char *f; + + assert_return(iov, -EINVAL); + assert_return(n > 0, -EINVAL); + + niov = alloca(sizeof(struct iovec) * (n + 3)); + memcpy(niov, iov, sizeof(struct iovec) * n); + + ALLOCA_CODE_FUNC(f, func); + + IOVEC_SET_STRING(niov[n++], file); + IOVEC_SET_STRING(niov[n++], line); + IOVEC_SET_STRING(niov[n++], f); + + return sd_journal_sendv(niov, n); +} + +_public_ int sd_journal_perror_with_location( + const char *file, const char *line, + const char *func, + const char *message) { + + struct iovec iov[6]; + char *f; + + ALLOCA_CODE_FUNC(f, func); + + IOVEC_SET_STRING(iov[0], file); + IOVEC_SET_STRING(iov[1], line); + IOVEC_SET_STRING(iov[2], f); + + return fill_iovec_perror_and_send(message, 3, iov); +} diff --git a/src/libsystemd/src/sd-journal/journal-vacuum.c b/src/libsystemd/src/sd-journal/journal-vacuum.c new file mode 100644 index 0000000000..4bbe3ee800 --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-vacuum.c @@ -0,0 +1,350 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <fcntl.h> +#include <sys/stat.h> +#include <unistd.h> + +#include <systemd/sd-id128.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/dirent-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" +#include "systemd-basic/xattr-util.h" + +#include "journal-def.h" +#include "journal-file.h" +#include "journal-vacuum.h" + +struct vacuum_info { + uint64_t usage; + char *filename; + + uint64_t realtime; + + sd_id128_t seqnum_id; + uint64_t seqnum; + bool have_seqnum; +}; + +static int vacuum_compare(const void *_a, const void *_b) { + const struct vacuum_info *a, *b; + + a = _a; + b = _b; + + if (a->have_seqnum && b->have_seqnum && + sd_id128_equal(a->seqnum_id, b->seqnum_id)) { + if (a->seqnum < b->seqnum) + return -1; + else if (a->seqnum > b->seqnum) + return 1; + else + return 0; + } + + if (a->realtime < b->realtime) + return -1; + else if (a->realtime > b->realtime) + return 1; + else if (a->have_seqnum && b->have_seqnum) + return memcmp(&a->seqnum_id, &b->seqnum_id, 16); + else + return strcmp(a->filename, b->filename); +} + +static void patch_realtime( + int fd, + const char *fn, + const struct stat *st, + unsigned long long *realtime) { + + usec_t x, crtime = 0; + + /* The timestamp was determined by the file name, but let's + * see if the file might actually be older than the file name + * suggested... */ + + assert(fd >= 0); + assert(fn); + assert(st); + assert(realtime); + + x = timespec_load(&st->st_ctim); + if (x > 0 && x != USEC_INFINITY && x < *realtime) + *realtime = x; + + x = timespec_load(&st->st_atim); + if (x > 0 && x != USEC_INFINITY && x < *realtime) + *realtime = x; + + x = timespec_load(&st->st_mtim); + if (x > 0 && x != USEC_INFINITY && x < *realtime) + *realtime = x; + + /* Let's read the original creation time, if possible. Ideally + * we'd just query the creation time the FS might provide, but + * unfortunately there's currently no sane API to query + * it. Hence let's implement this manually... */ + + if (fd_getcrtime_at(fd, fn, &crtime, 0) >= 0) { + if (crtime < *realtime) + *realtime = crtime; + } +} + +static int journal_file_empty(int dir_fd, const char *name) { + _cleanup_close_ int fd; + struct stat st; + le64_t n_entries; + ssize_t n; + + fd = openat(dir_fd, name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK|O_NOATIME); + if (fd < 0) { + /* Maybe failed due to O_NOATIME and lack of privileges? */ + fd = openat(dir_fd, name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK); + if (fd < 0) + return -errno; + } + + if (fstat(fd, &st) < 0) + return -errno; + + /* If an offline file doesn't even have a header we consider it empty */ + if (st.st_size < (off_t) sizeof(Header)) + return 1; + + /* If the number of entries is empty, we consider it empty, too */ + n = pread(fd, &n_entries, sizeof(n_entries), offsetof(Header, n_entries)); + if (n < 0) + return -errno; + if (n != sizeof(n_entries)) + return -EIO; + + return le64toh(n_entries) <= 0; +} + +int journal_directory_vacuum( + const char *directory, + uint64_t max_use, + uint64_t n_max_files, + usec_t max_retention_usec, + usec_t *oldest_usec, + bool verbose) { + + _cleanup_closedir_ DIR *d = NULL; + struct vacuum_info *list = NULL; + unsigned n_list = 0, i, n_active_files = 0; + size_t n_allocated = 0; + uint64_t sum = 0, freed = 0; + usec_t retention_limit = 0; + char sbytes[FORMAT_BYTES_MAX]; + struct dirent *de; + int r; + + assert(directory); + + if (max_use <= 0 && max_retention_usec <= 0 && n_max_files <= 0) + return 0; + + if (max_retention_usec > 0) { + retention_limit = now(CLOCK_REALTIME); + if (retention_limit > max_retention_usec) + retention_limit -= max_retention_usec; + else + max_retention_usec = retention_limit = 0; + } + + d = opendir(directory); + if (!d) + return -errno; + + FOREACH_DIRENT_ALL(de, d, r = -errno; goto finish) { + + unsigned long long seqnum = 0, realtime; + _cleanup_free_ char *p = NULL; + sd_id128_t seqnum_id; + bool have_seqnum; + uint64_t size; + struct stat st; + size_t q; + + if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { + log_debug_errno(errno, "Failed to stat file %s while vacuuming, ignoring: %m", de->d_name); + continue; + } + + if (!S_ISREG(st.st_mode)) + continue; + + q = strlen(de->d_name); + + if (endswith(de->d_name, ".journal")) { + + /* Vacuum archived files. Active files are + * left around */ + + if (q < 1 + 32 + 1 + 16 + 1 + 16 + 8) { + n_active_files++; + continue; + } + + if (de->d_name[q-8-16-1] != '-' || + de->d_name[q-8-16-1-16-1] != '-' || + de->d_name[q-8-16-1-16-1-32-1] != '@') { + n_active_files++; + continue; + } + + p = strdup(de->d_name); + if (!p) { + r = -ENOMEM; + goto finish; + } + + de->d_name[q-8-16-1-16-1] = 0; + if (sd_id128_from_string(de->d_name + q-8-16-1-16-1-32, &seqnum_id) < 0) { + n_active_files++; + continue; + } + + if (sscanf(de->d_name + q-8-16-1-16, "%16llx-%16llx.journal", &seqnum, &realtime) != 2) { + n_active_files++; + continue; + } + + have_seqnum = true; + + } else if (endswith(de->d_name, ".journal~")) { + unsigned long long tmp; + + /* Vacuum corrupted files */ + + if (q < 1 + 16 + 1 + 16 + 8 + 1) { + n_active_files++; + continue; + } + + if (de->d_name[q-1-8-16-1] != '-' || + de->d_name[q-1-8-16-1-16-1] != '@') { + n_active_files++; + continue; + } + + p = strdup(de->d_name); + if (!p) { + r = -ENOMEM; + goto finish; + } + + if (sscanf(de->d_name + q-1-8-16-1-16, "%16llx-%16llx.journal~", &realtime, &tmp) != 2) { + n_active_files++; + continue; + } + + have_seqnum = false; + } else { + /* We do not vacuum unknown files! */ + log_debug("Not vacuuming unknown file %s.", de->d_name); + continue; + } + + size = 512UL * (uint64_t) st.st_blocks; + + r = journal_file_empty(dirfd(d), p); + if (r < 0) { + log_debug_errno(r, "Failed check if %s is empty, ignoring: %m", p); + continue; + } + if (r > 0) { + /* Always vacuum empty non-online files. */ + + if (unlinkat(dirfd(d), p, 0) >= 0) { + + log_full(verbose ? LOG_INFO : LOG_DEBUG, + "Deleted empty archived journal %s/%s (%s).", directory, p, format_bytes(sbytes, sizeof(sbytes), size)); + + freed += size; + } else if (errno != ENOENT) + log_warning_errno(errno, "Failed to delete empty archived journal %s/%s: %m", directory, p); + + continue; + } + + patch_realtime(dirfd(d), p, &st, &realtime); + + if (!GREEDY_REALLOC(list, n_allocated, n_list + 1)) { + r = -ENOMEM; + goto finish; + } + + list[n_list].filename = p; + list[n_list].usage = size; + list[n_list].seqnum = seqnum; + list[n_list].realtime = realtime; + list[n_list].seqnum_id = seqnum_id; + list[n_list].have_seqnum = have_seqnum; + n_list++; + + p = NULL; + sum += size; + } + + qsort_safe(list, n_list, sizeof(struct vacuum_info), vacuum_compare); + + for (i = 0; i < n_list; i++) { + unsigned left; + + left = n_active_files + n_list - i; + + if ((max_retention_usec <= 0 || list[i].realtime >= retention_limit) && + (max_use <= 0 || sum <= max_use) && + (n_max_files <= 0 || left <= n_max_files)) + break; + + if (unlinkat(dirfd(d), list[i].filename, 0) >= 0) { + log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).", directory, list[i].filename, format_bytes(sbytes, sizeof(sbytes), list[i].usage)); + freed += list[i].usage; + + if (list[i].usage < sum) + sum -= list[i].usage; + else + sum = 0; + + } else if (errno != ENOENT) + log_warning_errno(errno, "Failed to delete archived journal %s/%s: %m", directory, list[i].filename); + } + + if (oldest_usec && i < n_list && (*oldest_usec == 0 || list[i].realtime < *oldest_usec)) + *oldest_usec = list[i].realtime; + + r = 0; + +finish: + for (i = 0; i < n_list; i++) + free(list[i].filename); + free(list); + + log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals on disk.", format_bytes(sbytes, sizeof(sbytes), freed)); + + return r; +} diff --git a/src/libsystemd/src/sd-journal/journal-vacuum.h b/src/libsystemd/src/sd-journal/journal-vacuum.h new file mode 100644 index 0000000000..1e76aa856d --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-vacuum.h @@ -0,0 +1,27 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include <inttypes.h> +#include <stdbool.h> + +#include "systemd-basic/time-util.h" + +int journal_directory_vacuum(const char *directory, uint64_t max_use, uint64_t n_max_files, usec_t max_retention_usec, usec_t *oldest_usec, bool verbose); diff --git a/src/libsystemd/src/sd-journal/journal-verify.c b/src/libsystemd/src/sd-journal/journal-verify.c new file mode 100644 index 0000000000..de75cc94ef --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-verify.c @@ -0,0 +1,1309 @@ +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <fcntl.h> +#include <stddef.h> +#include <sys/mman.h> +#include <unistd.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/terminal-util.h" +#include "systemd-basic/util.h" + +#include "compress.h" +#include "journal-authenticate.h" +#include "journal-def.h" +#include "journal-file.h" +#include "journal-verify.h" +#include "lookup3.h" + +static void draw_progress(uint64_t p, usec_t *last_usec) { + unsigned n, i, j, k; + usec_t z, x; + + if (!on_tty()) + return; + + z = now(CLOCK_MONOTONIC); + x = *last_usec; + + if (x != 0 && x + 40 * USEC_PER_MSEC > z) + return; + + *last_usec = z; + + n = (3 * columns()) / 4; + j = (n * (unsigned) p) / 65535ULL; + k = n - j; + + fputs("\r", stdout); + if (colors_enabled()) + fputs("\x1B[?25l" ANSI_HIGHLIGHT_GREEN, stdout); + + for (i = 0; i < j; i++) + fputs("\xe2\x96\x88", stdout); + + fputs(ANSI_NORMAL, stdout); + + for (i = 0; i < k; i++) + fputs("\xe2\x96\x91", stdout); + + printf(" %3"PRIu64"%%", 100U * p / 65535U); + + fputs("\r", stdout); + if (colors_enabled()) + fputs("\x1B[?25h", stdout); + + fflush(stdout); +} + +static uint64_t scale_progress(uint64_t scale, uint64_t p, uint64_t m) { + + /* Calculates scale * p / m, but handles m == 0 safely, and saturates */ + + if (p >= m || m == 0) + return scale; + + return scale * p / m; +} + +static void flush_progress(void) { + unsigned n, i; + + if (!on_tty()) + return; + + n = (3 * columns()) / 4; + + putchar('\r'); + + for (i = 0; i < n + 5; i++) + putchar(' '); + + putchar('\r'); + fflush(stdout); +} + +#define debug(_offset, _fmt, ...) do { \ + flush_progress(); \ + log_debug(OFSfmt": " _fmt, _offset, ##__VA_ARGS__); \ + } while (0) + +#define warning(_offset, _fmt, ...) do { \ + flush_progress(); \ + log_warning(OFSfmt": " _fmt, _offset, ##__VA_ARGS__); \ + } while (0) + +#define error(_offset, _fmt, ...) do { \ + flush_progress(); \ + log_error(OFSfmt": " _fmt, (uint64_t)_offset, ##__VA_ARGS__); \ + } while (0) + +static int journal_file_object_verify(JournalFile *f, uint64_t offset, Object *o) { + uint64_t i; + + assert(f); + assert(offset); + assert(o); + + /* This does various superficial tests about the length an + * possible field values. It does not follow any references to + * other objects. */ + + if ((o->object.flags & OBJECT_COMPRESSED_XZ) && + o->object.type != OBJECT_DATA) { + error(offset, "Found compressed object that isn't of type DATA, which is not allowed."); + return -EBADMSG; + } + + switch (o->object.type) { + + case OBJECT_DATA: { + uint64_t h1, h2; + int compression, r; + + if (le64toh(o->data.entry_offset) == 0) + warning(offset, "Unused data (entry_offset==0)"); + + if ((le64toh(o->data.entry_offset) == 0) ^ (le64toh(o->data.n_entries) == 0)) { + error(offset, "Bad n_entries: %"PRIu64, o->data.n_entries); + return -EBADMSG; + } + + if (le64toh(o->object.size) - offsetof(DataObject, payload) <= 0) { + error(offset, "Bad object size (<= %zu): %"PRIu64, + offsetof(DataObject, payload), + le64toh(o->object.size)); + return -EBADMSG; + } + + h1 = le64toh(o->data.hash); + + compression = o->object.flags & OBJECT_COMPRESSION_MASK; + if (compression) { + _cleanup_free_ void *b = NULL; + size_t alloc = 0, b_size; + + r = decompress_blob(compression, + o->data.payload, + le64toh(o->object.size) - offsetof(Object, data.payload), + &b, &alloc, &b_size, 0); + if (r < 0) { + error(offset, "%s decompression failed: %s", + object_compressed_to_string(compression), strerror(-r)); + return r; + } + + h2 = hash64(b, b_size); + } else + h2 = hash64(o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload)); + + if (h1 != h2) { + error(offset, "Invalid hash (%08"PRIx64" vs. %08"PRIx64, h1, h2); + return -EBADMSG; + } + + if (!VALID64(o->data.next_hash_offset) || + !VALID64(o->data.next_field_offset) || + !VALID64(o->data.entry_offset) || + !VALID64(o->data.entry_array_offset)) { + error(offset, "Invalid offset (next_hash_offset="OFSfmt", next_field_offset="OFSfmt", entry_offset="OFSfmt", entry_array_offset="OFSfmt, + o->data.next_hash_offset, + o->data.next_field_offset, + o->data.entry_offset, + o->data.entry_array_offset); + return -EBADMSG; + } + + break; + } + + case OBJECT_FIELD: + if (le64toh(o->object.size) - offsetof(FieldObject, payload) <= 0) { + error(offset, + "Bad field size (<= %zu): %"PRIu64, + offsetof(FieldObject, payload), + le64toh(o->object.size)); + return -EBADMSG; + } + + if (!VALID64(o->field.next_hash_offset) || + !VALID64(o->field.head_data_offset)) { + error(offset, + "Invalid offset (next_hash_offset="OFSfmt", head_data_offset="OFSfmt, + o->field.next_hash_offset, + o->field.head_data_offset); + return -EBADMSG; + } + break; + + case OBJECT_ENTRY: + if ((le64toh(o->object.size) - offsetof(EntryObject, items)) % sizeof(EntryItem) != 0) { + error(offset, + "Bad entry size (<= %zu): %"PRIu64, + offsetof(EntryObject, items), + le64toh(o->object.size)); + return -EBADMSG; + } + + if ((le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem) <= 0) { + error(offset, + "Invalid number items in entry: %"PRIu64, + (le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem)); + return -EBADMSG; + } + + if (le64toh(o->entry.seqnum) <= 0) { + error(offset, + "Invalid entry seqnum: %"PRIx64, + le64toh(o->entry.seqnum)); + return -EBADMSG; + } + + if (!VALID_REALTIME(le64toh(o->entry.realtime))) { + error(offset, + "Invalid entry realtime timestamp: %"PRIu64, + le64toh(o->entry.realtime)); + return -EBADMSG; + } + + if (!VALID_MONOTONIC(le64toh(o->entry.monotonic))) { + error(offset, + "Invalid entry monotonic timestamp: %"PRIu64, + le64toh(o->entry.monotonic)); + return -EBADMSG; + } + + for (i = 0; i < journal_file_entry_n_items(o); i++) { + if (o->entry.items[i].object_offset == 0 || + !VALID64(o->entry.items[i].object_offset)) { + error(offset, + "Invalid entry item (%"PRIu64"/%"PRIu64" offset: "OFSfmt, + i, journal_file_entry_n_items(o), + o->entry.items[i].object_offset); + return -EBADMSG; + } + } + + break; + + case OBJECT_DATA_HASH_TABLE: + case OBJECT_FIELD_HASH_TABLE: + if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) % sizeof(HashItem) != 0 || + (le64toh(o->object.size) - offsetof(HashTableObject, items)) / sizeof(HashItem) <= 0) { + error(offset, + "Invalid %s hash table size: %"PRIu64, + o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", + le64toh(o->object.size)); + return -EBADMSG; + } + + for (i = 0; i < journal_file_hash_table_n_items(o); i++) { + if (o->hash_table.items[i].head_hash_offset != 0 && + !VALID64(le64toh(o->hash_table.items[i].head_hash_offset))) { + error(offset, + "Invalid %s hash table item (%"PRIu64"/%"PRIu64") head_hash_offset: "OFSfmt, + o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", + i, journal_file_hash_table_n_items(o), + le64toh(o->hash_table.items[i].head_hash_offset)); + return -EBADMSG; + } + if (o->hash_table.items[i].tail_hash_offset != 0 && + !VALID64(le64toh(o->hash_table.items[i].tail_hash_offset))) { + error(offset, + "Invalid %s hash table item (%"PRIu64"/%"PRIu64") tail_hash_offset: "OFSfmt, + o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", + i, journal_file_hash_table_n_items(o), + le64toh(o->hash_table.items[i].tail_hash_offset)); + return -EBADMSG; + } + + if ((o->hash_table.items[i].head_hash_offset != 0) != + (o->hash_table.items[i].tail_hash_offset != 0)) { + error(offset, + "Invalid %s hash table item (%"PRIu64"/%"PRIu64"): head_hash_offset="OFSfmt" tail_hash_offset="OFSfmt, + o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", + i, journal_file_hash_table_n_items(o), + le64toh(o->hash_table.items[i].head_hash_offset), + le64toh(o->hash_table.items[i].tail_hash_offset)); + return -EBADMSG; + } + } + + break; + + case OBJECT_ENTRY_ARRAY: + if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) % sizeof(le64_t) != 0 || + (le64toh(o->object.size) - offsetof(EntryArrayObject, items)) / sizeof(le64_t) <= 0) { + error(offset, + "Invalid object entry array size: %"PRIu64, + le64toh(o->object.size)); + return -EBADMSG; + } + + if (!VALID64(o->entry_array.next_entry_array_offset)) { + error(offset, + "Invalid object entry array next_entry_array_offset: "OFSfmt, + o->entry_array.next_entry_array_offset); + return -EBADMSG; + } + + for (i = 0; i < journal_file_entry_array_n_items(o); i++) + if (le64toh(o->entry_array.items[i]) != 0 && + !VALID64(le64toh(o->entry_array.items[i]))) { + error(offset, + "Invalid object entry array item (%"PRIu64"/%"PRIu64"): "OFSfmt, + i, journal_file_entry_array_n_items(o), + le64toh(o->entry_array.items[i])); + return -EBADMSG; + } + + break; + + case OBJECT_TAG: + if (le64toh(o->object.size) != sizeof(TagObject)) { + error(offset, + "Invalid object tag size: %"PRIu64, + le64toh(o->object.size)); + return -EBADMSG; + } + + if (!VALID_EPOCH(o->tag.epoch)) { + error(offset, + "Invalid object tag epoch: %"PRIu64, + o->tag.epoch); + return -EBADMSG; + } + + break; + } + + return 0; +} + +static int write_uint64(int fd, uint64_t p) { + ssize_t k; + + k = write(fd, &p, sizeof(p)); + if (k < 0) + return -errno; + if (k != sizeof(p)) + return -EIO; + + return 0; +} + +static int contains_uint64(MMapCache *m, int fd, uint64_t n, uint64_t p) { + uint64_t a, b; + int r; + + assert(m); + assert(fd >= 0); + + /* Bisection ... */ + + a = 0; b = n; + while (a < b) { + uint64_t c, *z; + + c = (a + b) / 2; + + r = mmap_cache_get(m, fd, PROT_READ|PROT_WRITE, 0, false, c * sizeof(uint64_t), sizeof(uint64_t), NULL, (void **) &z); + if (r < 0) + return r; + + if (*z == p) + return 1; + + if (a + 1 >= b) + return 0; + + if (p < *z) + b = c; + else + a = c; + } + + return 0; +} + +static int entry_points_to_data( + JournalFile *f, + int entry_fd, + uint64_t n_entries, + uint64_t entry_p, + uint64_t data_p) { + + int r; + uint64_t i, n, a; + Object *o; + bool found = false; + + assert(f); + assert(entry_fd >= 0); + + if (!contains_uint64(f->mmap, entry_fd, n_entries, entry_p)) { + error(data_p, "Data object references invalid entry at "OFSfmt, entry_p); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_ENTRY, entry_p, &o); + if (r < 0) + return r; + + n = journal_file_entry_n_items(o); + for (i = 0; i < n; i++) + if (le64toh(o->entry.items[i].object_offset) == data_p) { + found = true; + break; + } + + if (!found) { + error(entry_p, "Data object at "OFSfmt" not referenced by linked entry", data_p); + return -EBADMSG; + } + + /* Check if this entry is also in main entry array. Since the + * main entry array has already been verified we can rely on + * its consistency. */ + + i = 0; + n = le64toh(f->header->n_entries); + a = le64toh(f->header->entry_array_offset); + + while (i < n) { + uint64_t m, u; + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + + m = journal_file_entry_array_n_items(o); + u = MIN(n - i, m); + + if (entry_p <= le64toh(o->entry_array.items[u-1])) { + uint64_t x, y, z; + + x = 0; + y = u; + + while (x < y) { + z = (x + y) / 2; + + if (le64toh(o->entry_array.items[z]) == entry_p) + return 0; + + if (x + 1 >= y) + break; + + if (entry_p < le64toh(o->entry_array.items[z])) + y = z; + else + x = z; + } + + error(entry_p, "Entry object doesn't exist in main entry array"); + return -EBADMSG; + } + + i += u; + a = le64toh(o->entry_array.next_entry_array_offset); + } + + return 0; +} + +static int verify_data( + JournalFile *f, + Object *o, uint64_t p, + int entry_fd, uint64_t n_entries, + int entry_array_fd, uint64_t n_entry_arrays) { + + uint64_t i, n, a, last, q; + int r; + + assert(f); + assert(o); + assert(entry_fd >= 0); + assert(entry_array_fd >= 0); + + n = le64toh(o->data.n_entries); + a = le64toh(o->data.entry_array_offset); + + /* Entry array means at least two objects */ + if (a && n < 2) { + error(p, "Entry array present (entry_array_offset="OFSfmt", but n_entries=%"PRIu64")", a, n); + return -EBADMSG; + } + + if (n == 0) + return 0; + + /* We already checked that earlier */ + assert(o->data.entry_offset); + + last = q = le64toh(o->data.entry_offset); + r = entry_points_to_data(f, entry_fd, n_entries, q, p); + if (r < 0) + return r; + + i = 1; + while (i < n) { + uint64_t next, m, j; + + if (a == 0) { + error(p, "Array chain too short"); + return -EBADMSG; + } + + if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) { + error(p, "Invalid array offset "OFSfmt, a); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + + next = le64toh(o->entry_array.next_entry_array_offset); + if (next != 0 && next <= a) { + error(p, "Array chain has cycle (jumps back from "OFSfmt" to "OFSfmt")", a, next); + return -EBADMSG; + } + + m = journal_file_entry_array_n_items(o); + for (j = 0; i < n && j < m; i++, j++) { + + q = le64toh(o->entry_array.items[j]); + if (q <= last) { + error(p, "Data object's entry array not sorted"); + return -EBADMSG; + } + last = q; + + r = entry_points_to_data(f, entry_fd, n_entries, q, p); + if (r < 0) + return r; + + /* Pointer might have moved, reposition */ + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + } + + a = next; + } + + return 0; +} + +static int verify_hash_table( + JournalFile *f, + int data_fd, uint64_t n_data, + int entry_fd, uint64_t n_entries, + int entry_array_fd, uint64_t n_entry_arrays, + usec_t *last_usec, + bool show_progress) { + + uint64_t i, n; + int r; + + assert(f); + assert(data_fd >= 0); + assert(entry_fd >= 0); + assert(entry_array_fd >= 0); + assert(last_usec); + + n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); + if (n <= 0) + return 0; + + r = journal_file_map_data_hash_table(f); + if (r < 0) + return log_error_errno(r, "Failed to map data hash table: %m"); + + for (i = 0; i < n; i++) { + uint64_t last = 0, p; + + if (show_progress) + draw_progress(0xC000 + scale_progress(0x3FFF, i, n), last_usec); + + p = le64toh(f->data_hash_table[i].head_hash_offset); + while (p != 0) { + Object *o; + uint64_t next; + + if (!contains_uint64(f->mmap, data_fd, n_data, p)) { + error(p, "Invalid data object at hash entry %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + next = le64toh(o->data.next_hash_offset); + if (next != 0 && next <= p) { + error(p, "Hash chain has a cycle in hash entry %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + if (le64toh(o->data.hash) % n != i) { + error(p, "Hash value mismatch in hash entry %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + r = verify_data(f, o, p, entry_fd, n_entries, entry_array_fd, n_entry_arrays); + if (r < 0) + return r; + + last = p; + p = next; + } + + if (last != le64toh(f->data_hash_table[i].tail_hash_offset)) { + error(p, "Tail hash pointer mismatch in hash table"); + return -EBADMSG; + } + } + + return 0; +} + +static int data_object_in_hash_table(JournalFile *f, uint64_t hash, uint64_t p) { + uint64_t n, h, q; + int r; + assert(f); + + n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); + if (n <= 0) + return 0; + + r = journal_file_map_data_hash_table(f); + if (r < 0) + return log_error_errno(r, "Failed to map data hash table: %m"); + + h = hash % n; + + q = le64toh(f->data_hash_table[h].head_hash_offset); + while (q != 0) { + Object *o; + + if (p == q) + return 1; + + r = journal_file_move_to_object(f, OBJECT_DATA, q, &o); + if (r < 0) + return r; + + q = le64toh(o->data.next_hash_offset); + } + + return 0; +} + +static int verify_entry( + JournalFile *f, + Object *o, uint64_t p, + int data_fd, uint64_t n_data) { + + uint64_t i, n; + int r; + + assert(f); + assert(o); + assert(data_fd >= 0); + + n = journal_file_entry_n_items(o); + for (i = 0; i < n; i++) { + uint64_t q, h; + Object *u; + + q = le64toh(o->entry.items[i].object_offset); + h = le64toh(o->entry.items[i].hash); + + if (!contains_uint64(f->mmap, data_fd, n_data, q)) { + error(p, "Invalid data object of entry"); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_DATA, q, &u); + if (r < 0) + return r; + + if (le64toh(u->data.hash) != h) { + error(p, "Hash mismatch for data object of entry"); + return -EBADMSG; + } + + r = data_object_in_hash_table(f, h, q); + if (r < 0) + return r; + if (r == 0) { + error(p, "Data object missing from hash table"); + return -EBADMSG; + } + } + + return 0; +} + +static int verify_entry_array( + JournalFile *f, + int data_fd, uint64_t n_data, + int entry_fd, uint64_t n_entries, + int entry_array_fd, uint64_t n_entry_arrays, + usec_t *last_usec, + bool show_progress) { + + uint64_t i = 0, a, n, last = 0; + int r; + + assert(f); + assert(data_fd >= 0); + assert(entry_fd >= 0); + assert(entry_array_fd >= 0); + assert(last_usec); + + n = le64toh(f->header->n_entries); + a = le64toh(f->header->entry_array_offset); + while (i < n) { + uint64_t next, m, j; + Object *o; + + if (show_progress) + draw_progress(0x8000 + scale_progress(0x3FFF, i, n), last_usec); + + if (a == 0) { + error(a, "Array chain too short at %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + if (!contains_uint64(f->mmap, entry_array_fd, n_entry_arrays, a)) { + error(a, "Invalid array %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + + next = le64toh(o->entry_array.next_entry_array_offset); + if (next != 0 && next <= a) { + error(a, "Array chain has cycle at %"PRIu64" of %"PRIu64" (jumps back from to "OFSfmt")", i, n, next); + return -EBADMSG; + } + + m = journal_file_entry_array_n_items(o); + for (j = 0; i < n && j < m; i++, j++) { + uint64_t p; + + p = le64toh(o->entry_array.items[j]); + if (p <= last) { + error(a, "Entry array not sorted at %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + last = p; + + if (!contains_uint64(f->mmap, entry_fd, n_entries, p)) { + error(a, "Invalid array entry at %"PRIu64" of %"PRIu64, i, n); + return -EBADMSG; + } + + r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); + if (r < 0) + return r; + + r = verify_entry(f, o, p, data_fd, n_data); + if (r < 0) + return r; + + /* Pointer might have moved, reposition */ + r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); + if (r < 0) + return r; + } + + a = next; + } + + return 0; +} + +int journal_file_verify( + JournalFile *f, + const char *key, + usec_t *first_contained, usec_t *last_validated, usec_t *last_contained, + bool show_progress) { + int r; + Object *o; + uint64_t p = 0, last_epoch = 0, last_tag_realtime = 0, last_sealed_realtime = 0; + + uint64_t entry_seqnum = 0, entry_monotonic = 0, entry_realtime = 0; + sd_id128_t entry_boot_id; + bool entry_seqnum_set = false, entry_monotonic_set = false, entry_realtime_set = false, found_main_entry_array = false; + uint64_t n_weird = 0, n_objects = 0, n_entries = 0, n_data = 0, n_fields = 0, n_data_hash_tables = 0, n_field_hash_tables = 0, n_entry_arrays = 0, n_tags = 0; + usec_t last_usec = 0; + int data_fd = -1, entry_fd = -1, entry_array_fd = -1; + unsigned i; + bool found_last = false; + _cleanup_free_ char *tmp_dir = NULL; + +#ifdef HAVE_GCRYPT + uint64_t last_tag = 0; +#endif + assert(f); + + if (key) { +#ifdef HAVE_GCRYPT + r = journal_file_parse_verification_key(f, key); + if (r < 0) { + log_error("Failed to parse seed."); + return r; + } +#else + return -EOPNOTSUPP; +#endif + } else if (f->seal) + return -ENOKEY; + + r = var_tmp(&tmp_dir); + if (r < 0) { + log_error_errno(r, "Failed to determine temporary directory: %m"); + goto fail; + } + + data_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); + if (data_fd < 0) { + r = log_error_errno(data_fd, "Failed to create data file: %m"); + goto fail; + } + + entry_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); + if (entry_fd < 0) { + r = log_error_errno(entry_fd, "Failed to create entry file: %m"); + goto fail; + } + + entry_array_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); + if (entry_array_fd < 0) { + r = log_error_errno(entry_array_fd, + "Failed to create entry array file: %m"); + goto fail; + } + + if (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SUPPORTED) { + log_error("Cannot verify file with unknown extensions."); + r = -EOPNOTSUPP; + goto fail; + } + + for (i = 0; i < sizeof(f->header->reserved); i++) + if (f->header->reserved[i] != 0) { + error(offsetof(Header, reserved[i]), "Reserved field is non-zero"); + r = -EBADMSG; + goto fail; + } + + /* First iteration: we go through all objects, verify the + * superficial structure, headers, hashes. */ + + p = le64toh(f->header->header_size); + for (;;) { + /* Early exit if there are no objects in the file, at all */ + if (le64toh(f->header->tail_object_offset) == 0) + break; + + if (show_progress) + draw_progress(scale_progress(0x7FFF, p, le64toh(f->header->tail_object_offset)), &last_usec); + + r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o); + if (r < 0) { + error(p, "Invalid object"); + goto fail; + } + + if (p > le64toh(f->header->tail_object_offset)) { + error(offsetof(Header, tail_object_offset), "Invalid tail object pointer"); + r = -EBADMSG; + goto fail; + } + + n_objects++; + + r = journal_file_object_verify(f, p, o); + if (r < 0) { + error(p, "Invalid object contents: %s", strerror(-r)); + goto fail; + } + + if ((o->object.flags & OBJECT_COMPRESSED_XZ) && + (o->object.flags & OBJECT_COMPRESSED_LZ4)) { + error(p, "Objected with double compression"); + r = -EINVAL; + goto fail; + } + + if ((o->object.flags & OBJECT_COMPRESSED_XZ) && !JOURNAL_HEADER_COMPRESSED_XZ(f->header)) { + error(p, "XZ compressed object in file without XZ compression"); + r = -EBADMSG; + goto fail; + } + + if ((o->object.flags & OBJECT_COMPRESSED_LZ4) && !JOURNAL_HEADER_COMPRESSED_LZ4(f->header)) { + error(p, "LZ4 compressed object in file without LZ4 compression"); + r = -EBADMSG; + goto fail; + } + + switch (o->object.type) { + + case OBJECT_DATA: + r = write_uint64(data_fd, p); + if (r < 0) + goto fail; + + n_data++; + break; + + case OBJECT_FIELD: + n_fields++; + break; + + case OBJECT_ENTRY: + if (JOURNAL_HEADER_SEALED(f->header) && n_tags <= 0) { + error(p, "First entry before first tag"); + r = -EBADMSG; + goto fail; + } + + r = write_uint64(entry_fd, p); + if (r < 0) + goto fail; + + if (le64toh(o->entry.realtime) < last_tag_realtime) { + error(p, "Older entry after newer tag"); + r = -EBADMSG; + goto fail; + } + + if (!entry_seqnum_set && + le64toh(o->entry.seqnum) != le64toh(f->header->head_entry_seqnum)) { + error(p, "Head entry sequence number incorrect"); + r = -EBADMSG; + goto fail; + } + + if (entry_seqnum_set && + entry_seqnum >= le64toh(o->entry.seqnum)) { + error(p, "Entry sequence number out of synchronization"); + r = -EBADMSG; + goto fail; + } + + entry_seqnum = le64toh(o->entry.seqnum); + entry_seqnum_set = true; + + if (entry_monotonic_set && + sd_id128_equal(entry_boot_id, o->entry.boot_id) && + entry_monotonic > le64toh(o->entry.monotonic)) { + error(p, "Entry timestamp out of synchronization"); + r = -EBADMSG; + goto fail; + } + + entry_monotonic = le64toh(o->entry.monotonic); + entry_boot_id = o->entry.boot_id; + entry_monotonic_set = true; + + if (!entry_realtime_set && + le64toh(o->entry.realtime) != le64toh(f->header->head_entry_realtime)) { + error(p, "Head entry realtime timestamp incorrect"); + r = -EBADMSG; + goto fail; + } + + entry_realtime = le64toh(o->entry.realtime); + entry_realtime_set = true; + + n_entries++; + break; + + case OBJECT_DATA_HASH_TABLE: + if (n_data_hash_tables > 1) { + error(p, "More than one data hash table"); + r = -EBADMSG; + goto fail; + } + + if (le64toh(f->header->data_hash_table_offset) != p + offsetof(HashTableObject, items) || + le64toh(f->header->data_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) { + error(p, "header fields for data hash table invalid"); + r = -EBADMSG; + goto fail; + } + + n_data_hash_tables++; + break; + + case OBJECT_FIELD_HASH_TABLE: + if (n_field_hash_tables > 1) { + error(p, "More than one field hash table"); + r = -EBADMSG; + goto fail; + } + + if (le64toh(f->header->field_hash_table_offset) != p + offsetof(HashTableObject, items) || + le64toh(f->header->field_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) { + error(p, "Header fields for field hash table invalid"); + r = -EBADMSG; + goto fail; + } + + n_field_hash_tables++; + break; + + case OBJECT_ENTRY_ARRAY: + r = write_uint64(entry_array_fd, p); + if (r < 0) + goto fail; + + if (p == le64toh(f->header->entry_array_offset)) { + if (found_main_entry_array) { + error(p, "More than one main entry array"); + r = -EBADMSG; + goto fail; + } + + found_main_entry_array = true; + } + + n_entry_arrays++; + break; + + case OBJECT_TAG: + if (!JOURNAL_HEADER_SEALED(f->header)) { + error(p, "Tag object in file without sealing"); + r = -EBADMSG; + goto fail; + } + + if (le64toh(o->tag.seqnum) != n_tags + 1) { + error(p, "Tag sequence number out of synchronization"); + r = -EBADMSG; + goto fail; + } + + if (le64toh(o->tag.epoch) < last_epoch) { + error(p, "Epoch sequence out of synchronization"); + r = -EBADMSG; + goto fail; + } + +#ifdef HAVE_GCRYPT + if (f->seal) { + uint64_t q, rt; + + debug(p, "Checking tag %"PRIu64"...", le64toh(o->tag.seqnum)); + + rt = f->fss_start_usec + o->tag.epoch * f->fss_interval_usec; + if (entry_realtime_set && entry_realtime >= rt + f->fss_interval_usec) { + error(p, "tag/entry realtime timestamp out of synchronization"); + r = -EBADMSG; + goto fail; + } + + /* OK, now we know the epoch. So let's now set + * it, and calculate the HMAC for everything + * since the last tag. */ + r = journal_file_fsprg_seek(f, le64toh(o->tag.epoch)); + if (r < 0) + goto fail; + + r = journal_file_hmac_start(f); + if (r < 0) + goto fail; + + if (last_tag == 0) { + r = journal_file_hmac_put_header(f); + if (r < 0) + goto fail; + + q = le64toh(f->header->header_size); + } else + q = last_tag; + + while (q <= p) { + r = journal_file_move_to_object(f, OBJECT_UNUSED, q, &o); + if (r < 0) + goto fail; + + r = journal_file_hmac_put_object(f, OBJECT_UNUSED, o, q); + if (r < 0) + goto fail; + + q = q + ALIGN64(le64toh(o->object.size)); + } + + /* Position might have changed, let's reposition things */ + r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o); + if (r < 0) + goto fail; + + if (memcmp(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH) != 0) { + error(p, "Tag failed verification"); + r = -EBADMSG; + goto fail; + } + + f->hmac_running = false; + last_tag_realtime = rt; + last_sealed_realtime = entry_realtime; + } + + last_tag = p + ALIGN64(le64toh(o->object.size)); +#endif + + last_epoch = le64toh(o->tag.epoch); + + n_tags++; + break; + + default: + n_weird++; + } + + if (p == le64toh(f->header->tail_object_offset)) { + found_last = true; + break; + } + + p = p + ALIGN64(le64toh(o->object.size)); + }; + + if (!found_last && le64toh(f->header->tail_object_offset) != 0) { + error(le64toh(f->header->tail_object_offset), "Tail object pointer dead"); + r = -EBADMSG; + goto fail; + } + + if (n_objects != le64toh(f->header->n_objects)) { + error(offsetof(Header, n_objects), "Object number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (n_entries != le64toh(f->header->n_entries)) { + error(offsetof(Header, n_entries), "Entry number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_data) && + n_data != le64toh(f->header->n_data)) { + error(offsetof(Header, n_data), "Data number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_fields) && + n_fields != le64toh(f->header->n_fields)) { + error(offsetof(Header, n_fields), "Field number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_tags) && + n_tags != le64toh(f->header->n_tags)) { + error(offsetof(Header, n_tags), "Tag number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays) && + n_entry_arrays != le64toh(f->header->n_entry_arrays)) { + error(offsetof(Header, n_entry_arrays), "Entry array number mismatch"); + r = -EBADMSG; + goto fail; + } + + if (!found_main_entry_array && le64toh(f->header->entry_array_offset) != 0) { + error(0, "Missing entry array"); + r = -EBADMSG; + goto fail; + } + + if (entry_seqnum_set && + entry_seqnum != le64toh(f->header->tail_entry_seqnum)) { + error(offsetof(Header, tail_entry_seqnum), "Invalid tail seqnum"); + r = -EBADMSG; + goto fail; + } + + if (entry_monotonic_set && + (!sd_id128_equal(entry_boot_id, f->header->boot_id) || + entry_monotonic != le64toh(f->header->tail_entry_monotonic))) { + error(0, "Invalid tail monotonic timestamp"); + r = -EBADMSG; + goto fail; + } + + if (entry_realtime_set && entry_realtime != le64toh(f->header->tail_entry_realtime)) { + error(0, "Invalid tail realtime timestamp"); + r = -EBADMSG; + goto fail; + } + + /* Second iteration: we follow all objects referenced from the + * two entry points: the object hash table and the entry + * array. We also check that everything referenced (directly + * or indirectly) in the data hash table also exists in the + * entry array, and vice versa. Note that we do not care for + * unreferenced objects. We only care that everything that is + * referenced is consistent. */ + + r = verify_entry_array(f, + data_fd, n_data, + entry_fd, n_entries, + entry_array_fd, n_entry_arrays, + &last_usec, + show_progress); + if (r < 0) + goto fail; + + r = verify_hash_table(f, + data_fd, n_data, + entry_fd, n_entries, + entry_array_fd, n_entry_arrays, + &last_usec, + show_progress); + if (r < 0) + goto fail; + + if (show_progress) + flush_progress(); + + mmap_cache_close_fd(f->mmap, data_fd); + mmap_cache_close_fd(f->mmap, entry_fd); + mmap_cache_close_fd(f->mmap, entry_array_fd); + + safe_close(data_fd); + safe_close(entry_fd); + safe_close(entry_array_fd); + + if (first_contained) + *first_contained = le64toh(f->header->head_entry_realtime); + if (last_validated) + *last_validated = last_sealed_realtime; + if (last_contained) + *last_contained = le64toh(f->header->tail_entry_realtime); + + return 0; + +fail: + if (show_progress) + flush_progress(); + + log_error("File corruption detected at %s:"OFSfmt" (of %llu bytes, %"PRIu64"%%).", + f->path, + p, + (unsigned long long) f->last_stat.st_size, + 100 * p / f->last_stat.st_size); + + if (data_fd >= 0) { + mmap_cache_close_fd(f->mmap, data_fd); + safe_close(data_fd); + } + + if (entry_fd >= 0) { + mmap_cache_close_fd(f->mmap, entry_fd); + safe_close(entry_fd); + } + + if (entry_array_fd >= 0) { + mmap_cache_close_fd(f->mmap, entry_array_fd); + safe_close(entry_array_fd); + } + + return r; +} diff --git a/src/libsystemd/src/sd-journal/journal-verify.h b/src/libsystemd/src/sd-journal/journal-verify.h new file mode 100644 index 0000000000..8f0eaf6daa --- /dev/null +++ b/src/libsystemd/src/sd-journal/journal-verify.h @@ -0,0 +1,24 @@ +#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 <http://www.gnu.org/licenses/>. +***/ + +#include "journal-file.h" + +int journal_file_verify(JournalFile *f, const char *key, usec_t *first_contained, usec_t *last_validated, usec_t *last_contained, bool show_progress); diff --git a/src/libsystemd/src/sd-journal/lookup3.c b/src/libsystemd/src/sd-journal/lookup3.c new file mode 100644 index 0000000000..3d791234f4 --- /dev/null +++ b/src/libsystemd/src/sd-journal/lookup3.c @@ -0,0 +1,1009 @@ +/* Slightly modified by Lennart Poettering, to avoid name clashes, and + * unexport a few functions. */ + +#include "lookup3.h" + +/* +------------------------------------------------------------------------------- +lookup3.c, by Bob Jenkins, May 2006, Public Domain. + +These are functions for producing 32-bit hashes for hash table lookup. +hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() +are externally useful functions. Routines to test the hash are included +if SELF_TEST is defined. You can use this free for any purpose. It's in +the public domain. It has no warranty. + +You probably want to use hashlittle(). hashlittle() and hashbig() +hash byte arrays. hashlittle() is faster than hashbig() on +little-endian machines. Intel and AMD are little-endian machines. +On second thought, you probably want hashlittle2(), which is identical to +hashlittle() except it returns two 32-bit hashes for the price of one. +You could implement hashbig2() if you wanted but I haven't bothered here. + +If you want to find a hash of, say, exactly 7 integers, do + a = i1; b = i2; c = i3; + mix(a,b,c); + a += i4; b += i5; c += i6; + mix(a,b,c); + a += i7; + final(a,b,c); +then use c as the hash value. If you have a variable length array of +4-byte integers to hash, use hashword(). If you have a byte array (like +a character string), use hashlittle(). If you have several byte arrays, or +a mix of things, see the comments above hashlittle(). + +Why is this so big? I read 12 bytes at a time into 3 4-byte integers, +then mix those integers. This is fast (you can do a lot more thorough +mixing with 12*3 instructions on 3 integers than you can with 3 instructions +on 1 byte), but shoehorning those bytes into integers efficiently is messy. +------------------------------------------------------------------------------- +*/ +/* #define SELF_TEST 1 */ + +#include <stdint.h> /* defines uint32_t etc */ +#include <stdio.h> /* defines printf for tests */ +#include <sys/param.h> /* attempt to define endianness */ +#include <time.h> /* defines time_t for timings in the test */ +#ifdef linux +# include <endian.h> /* attempt to define endianness */ +#endif + +/* + * My best guess at if you are big-endian or little-endian. This may + * need adjustment. + */ +#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ + __BYTE_ORDER == __LITTLE_ENDIAN) || \ + (defined(i386) || defined(__i386__) || defined(__i486__) || \ + defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL)) +# define HASH_LITTLE_ENDIAN 1 +# define HASH_BIG_ENDIAN 0 +#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ + __BYTE_ORDER == __BIG_ENDIAN) || \ + (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) +# define HASH_LITTLE_ENDIAN 0 +# define HASH_BIG_ENDIAN 1 +#else +# define HASH_LITTLE_ENDIAN 0 +# define HASH_BIG_ENDIAN 0 +#endif + +#define hashsize(n) ((uint32_t)1<<(n)) +#define hashmask(n) (hashsize(n)-1) +#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) + +/* +------------------------------------------------------------------------------- +mix -- mix 3 32-bit values reversibly. + +This is reversible, so any information in (a,b,c) before mix() is +still in (a,b,c) after mix(). + +If four pairs of (a,b,c) inputs are run through mix(), or through +mix() in reverse, there are at least 32 bits of the output that +are sometimes the same for one pair and different for another pair. +This was tested for: +* pairs that differed by one bit, by two bits, in any combination + of top bits of (a,b,c), or in any combination of bottom bits of + (a,b,c). +* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed + the output delta to a Gray code (a^(a>>1)) so a string of 1's (as + is commonly produced by subtraction) look like a single 1-bit + difference. +* the base values were pseudorandom, all zero but one bit set, or + all zero plus a counter that starts at zero. + +Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that +satisfy this are + 4 6 8 16 19 4 + 9 15 3 18 27 15 + 14 9 3 7 17 3 +Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing +for "differ" defined as + with a one-bit base and a two-bit delta. I +used http://burtleburtle.net/bob/hash/avalanche.html to choose +the operations, constants, and arrangements of the variables. + +This does not achieve avalanche. There are input bits of (a,b,c) +that fail to affect some output bits of (a,b,c), especially of a. The +most thoroughly mixed value is c, but it doesn't really even achieve +avalanche in c. + +This allows some parallelism. Read-after-writes are good at doubling +the number of bits affected, so the goal of mixing pulls in the opposite +direction as the goal of parallelism. I did what I could. Rotates +seem to cost as much as shifts on every machine I could lay my hands +on, and rotates are much kinder to the top and bottom bits, so I used +rotates. +------------------------------------------------------------------------------- +*/ +#define mix(a,b,c) \ +{ \ + a -= c; a ^= rot(c, 4); c += b; \ + b -= a; b ^= rot(a, 6); a += c; \ + c -= b; c ^= rot(b, 8); b += a; \ + a -= c; a ^= rot(c,16); c += b; \ + b -= a; b ^= rot(a,19); a += c; \ + c -= b; c ^= rot(b, 4); b += a; \ +} + +/* +------------------------------------------------------------------------------- +final -- final mixing of 3 32-bit values (a,b,c) into c + +Pairs of (a,b,c) values differing in only a few bits will usually +produce values of c that look totally different. This was tested for +* pairs that differed by one bit, by two bits, in any combination + of top bits of (a,b,c), or in any combination of bottom bits of + (a,b,c). +* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed + the output delta to a Gray code (a^(a>>1)) so a string of 1's (as + is commonly produced by subtraction) look like a single 1-bit + difference. +* the base values were pseudorandom, all zero but one bit set, or + all zero plus a counter that starts at zero. + +These constants passed: + 14 11 25 16 4 14 24 + 12 14 25 16 4 14 24 +and these came close: + 4 8 15 26 3 22 24 + 10 8 15 26 3 22 24 + 11 8 15 26 3 22 24 +------------------------------------------------------------------------------- +*/ +#define final(a,b,c) \ +{ \ + c ^= b; c -= rot(b,14); \ + a ^= c; a -= rot(c,11); \ + b ^= a; b -= rot(a,25); \ + c ^= b; c -= rot(b,16); \ + a ^= c; a -= rot(c,4); \ + b ^= a; b -= rot(a,14); \ + c ^= b; c -= rot(b,24); \ +} + +/* +-------------------------------------------------------------------- + This works on all machines. To be useful, it requires + -- that the key be an array of uint32_t's, and + -- that the length be the number of uint32_t's in the key + + The function hashword() is identical to hashlittle() on little-endian + machines, and identical to hashbig() on big-endian machines, + except that the length has to be measured in uint32_ts rather than in + bytes. hashlittle() is more complicated than hashword() only because + hashlittle() has to dance around fitting the key bytes into registers. +-------------------------------------------------------------------- +*/ +uint32_t jenkins_hashword( +const uint32_t *k, /* the key, an array of uint32_t values */ +size_t length, /* the length of the key, in uint32_ts */ +uint32_t initval) /* the previous hash, or an arbitrary value */ +{ + uint32_t a,b,c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 3; + k += 3; + } + + /*------------------------------------------- handle the last 3 uint32_t's */ + switch(length) /* all the case statements fall through */ + { + case 3 : c+=k[2]; + case 2 : b+=k[1]; + case 1 : a+=k[0]; + final(a,b,c); + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + return c; +} + + +/* +-------------------------------------------------------------------- +hashword2() -- same as hashword(), but take two seeds and return two +32-bit values. pc and pb must both be nonnull, and *pc and *pb must +both be initialized with seeds. If you pass in (*pb)==0, the output +(*pc) will be the same as the return value from hashword(). +-------------------------------------------------------------------- +*/ +void jenkins_hashword2 ( +const uint32_t *k, /* the key, an array of uint32_t values */ +size_t length, /* the length of the key, in uint32_ts */ +uint32_t *pc, /* IN: seed OUT: primary hash value */ +uint32_t *pb) /* IN: more seed OUT: secondary hash value */ +{ + uint32_t a,b,c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc; + c += *pb; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 3; + k += 3; + } + + /*------------------------------------------- handle the last 3 uint32_t's */ + switch(length) /* all the case statements fall through */ + { + case 3 : c+=k[2]; + case 2 : b+=k[1]; + case 1 : a+=k[0]; + final(a,b,c); + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + *pc=c; *pb=b; +} + + +/* +------------------------------------------------------------------------------- +hashlittle() -- hash a variable-length key into a 32-bit value + k : the key (the unaligned variable-length array of bytes) + length : the length of the key, counting by bytes + initval : can be any 4-byte value +Returns a 32-bit value. Every bit of the key affects every bit of +the return value. Two keys differing by one or two bits will have +totally different hash values. + +The best hash table sizes are powers of 2. There is no need to do +mod a prime (mod is sooo slow!). If you need less than 32 bits, +use a bitmask. For example, if you need only 10 bits, do + h = (h & hashmask(10)); +In which case, the hash table should have hashsize(10) elements. + +If you are hashing n strings (uint8_t **)k, do it like this: + for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h); + +By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this +code any way you wish, private, educational, or commercial. It's free. + +Use for hash table lookup, or anything where one collision in 2^^32 is +acceptable. Do NOT use for cryptographic purposes. +------------------------------------------------------------------------------- +*/ + +uint32_t jenkins_hashlittle( const void *key, size_t length, uint32_t initval) +{ + uint32_t a,b,c; /* internal state */ + union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff; a+=k[0]; break; + case 6 : b+=k[1]&0xffff; a+=k[0]; break; + case 5 : b+=k[1]&0xff; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff; break; + case 2 : a+=k[0]&0xffff; break; + case 1 : a+=k[0]&0xff; break; + case 0 : return c; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + { + const uint8_t *k8 = (const uint8_t *) k; + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ + case 1 : a+=k8[0]; break; + case 0 : return c; + } + } + +#endif /* !valgrind */ + + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) + { + a += k[0] + (((uint32_t)k[1])<<16); + b += k[2] + (((uint32_t)k[3])<<16); + c += k[4] + (((uint32_t)k[5])<<16); + mix(a,b,c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[4]+(((uint32_t)k[5])<<16); + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=k[4]; + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=k[2]; + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=k[0]; + break; + case 1 : a+=k8[0]; + break; + case 0 : return c; /* zero length requires no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + a += ((uint32_t)k[1])<<8; + a += ((uint32_t)k[2])<<16; + a += ((uint32_t)k[3])<<24; + b += k[4]; + b += ((uint32_t)k[5])<<8; + b += ((uint32_t)k[6])<<16; + b += ((uint32_t)k[7])<<24; + c += k[8]; + c += ((uint32_t)k[9])<<8; + c += ((uint32_t)k[10])<<16; + c += ((uint32_t)k[11])<<24; + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=((uint32_t)k[11])<<24; + case 11: c+=((uint32_t)k[10])<<16; + case 10: c+=((uint32_t)k[9])<<8; + case 9 : c+=k[8]; + case 8 : b+=((uint32_t)k[7])<<24; + case 7 : b+=((uint32_t)k[6])<<16; + case 6 : b+=((uint32_t)k[5])<<8; + case 5 : b+=k[4]; + case 4 : a+=((uint32_t)k[3])<<24; + case 3 : a+=((uint32_t)k[2])<<16; + case 2 : a+=((uint32_t)k[1])<<8; + case 1 : a+=k[0]; + break; + case 0 : return c; + } + } + + final(a,b,c); + return c; +} + + +/* + * hashlittle2: return 2 32-bit hash values + * + * This is identical to hashlittle(), except it returns two 32-bit hash + * values instead of just one. This is good enough for hash table + * lookup with 2^^64 buckets, or if you want a second hash if you're not + * happy with the first, or if you want a probably-unique 64-bit ID for + * the key. *pc is better mixed than *pb, so use *pc first. If you want + * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)". + */ +void jenkins_hashlittle2( + const void *key, /* the key to hash */ + size_t length, /* length of the key */ + uint32_t *pc, /* IN: primary initval, OUT: primary hash */ + uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ +{ + uint32_t a,b,c; /* internal state */ + union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc; + c += *pb; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff; a+=k[0]; break; + case 6 : b+=k[1]&0xffff; a+=k[0]; break; + case 5 : b+=k[1]&0xff; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff; break; + case 2 : a+=k[0]&0xffff; break; + case 1 : a+=k[0]&0xff; break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + + { + const uint8_t *k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ + case 1 : a+=k8[0]; break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + } + +#endif /* !valgrind */ + + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) + { + a += k[0] + (((uint32_t)k[1])<<16); + b += k[2] + (((uint32_t)k[3])<<16); + c += k[4] + (((uint32_t)k[5])<<16); + mix(a,b,c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch(length) + { + case 12: c+=k[4]+(((uint32_t)k[5])<<16); + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ + case 10: c+=k[4]; + b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 9 : c+=k8[8]; /* fall through */ + case 8 : b+=k[2]+(((uint32_t)k[3])<<16); + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ + case 6 : b+=k[2]; + a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 5 : b+=k8[4]; /* fall through */ + case 4 : a+=k[0]+(((uint32_t)k[1])<<16); + break; + case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ + case 2 : a+=k[0]; + break; + case 1 : a+=k8[0]; + break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + a += ((uint32_t)k[1])<<8; + a += ((uint32_t)k[2])<<16; + a += ((uint32_t)k[3])<<24; + b += k[4]; + b += ((uint32_t)k[5])<<8; + b += ((uint32_t)k[6])<<16; + b += ((uint32_t)k[7])<<24; + c += k[8]; + c += ((uint32_t)k[9])<<8; + c += ((uint32_t)k[10])<<16; + c += ((uint32_t)k[11])<<24; + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=((uint32_t)k[11])<<24; + case 11: c+=((uint32_t)k[10])<<16; + case 10: c+=((uint32_t)k[9])<<8; + case 9 : c+=k[8]; + case 8 : b+=((uint32_t)k[7])<<24; + case 7 : b+=((uint32_t)k[6])<<16; + case 6 : b+=((uint32_t)k[5])<<8; + case 5 : b+=k[4]; + case 4 : a+=((uint32_t)k[3])<<24; + case 3 : a+=((uint32_t)k[2])<<16; + case 2 : a+=((uint32_t)k[1])<<8; + case 1 : a+=k[0]; + break; + case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } + } + + final(a,b,c); + *pc=c; *pb=b; +} + + + +/* + * hashbig(): + * This is the same as hashword() on big-endian machines. It is different + * from hashlittle() on all machines. hashbig() takes advantage of + * big-endian byte ordering. + */ +uint32_t jenkins_hashbig( const void *key, size_t length, uint32_t initval) +{ + uint32_t a,b,c; + union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) + { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a,b,c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]<<8" actually reads beyond the end of the string, but + * then shifts out the part it's not allowed to read. Because the + * string is aligned, the illegal read is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ +#ifndef VALGRIND + + switch(length) + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break; + case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break; + case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break; + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=k[1]&0xffffff00; a+=k[0]; break; + case 6 : b+=k[1]&0xffff0000; a+=k[0]; break; + case 5 : b+=k[1]&0xff000000; a+=k[0]; break; + case 4 : a+=k[0]; break; + case 3 : a+=k[0]&0xffffff00; break; + case 2 : a+=k[0]&0xffff0000; break; + case 1 : a+=k[0]&0xff000000; break; + case 0 : return c; /* zero length strings require no mixing */ + } + +#else /* make valgrind happy */ + + { + const uint8_t *k8 = (const uint8_t *)k; + switch(length) /* all the case statements fall through */ + { + case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; + case 11: c+=((uint32_t)k8[10])<<8; /* fall through */ + case 10: c+=((uint32_t)k8[9])<<16; /* fall through */ + case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */ + case 8 : b+=k[1]; a+=k[0]; break; + case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */ + case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */ + case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */ + case 4 : a+=k[0]; break; + case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */ + case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */ + case 1 : a+=((uint32_t)k8[0])<<24; break; + case 0 : return c; + } + } + +#endif /* !VALGRIND */ + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) + { + a += ((uint32_t)k[0])<<24; + a += ((uint32_t)k[1])<<16; + a += ((uint32_t)k[2])<<8; + a += ((uint32_t)k[3]); + b += ((uint32_t)k[4])<<24; + b += ((uint32_t)k[5])<<16; + b += ((uint32_t)k[6])<<8; + b += ((uint32_t)k[7]); + c += ((uint32_t)k[8])<<24; + c += ((uint32_t)k[9])<<16; + c += ((uint32_t)k[10])<<8; + c += ((uint32_t)k[11]); + mix(a,b,c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch(length) /* all the case statements fall through */ + { + case 12: c+=k[11]; + case 11: c+=((uint32_t)k[10])<<8; + case 10: c+=((uint32_t)k[9])<<16; + case 9 : c+=((uint32_t)k[8])<<24; + case 8 : b+=k[7]; + case 7 : b+=((uint32_t)k[6])<<8; + case 6 : b+=((uint32_t)k[5])<<16; + case 5 : b+=((uint32_t)k[4])<<24; + case 4 : a+=k[3]; + case 3 : a+=((uint32_t)k[2])<<8; + case 2 : a+=((uint32_t)k[1])<<16; + case 1 : a+=((uint32_t)k[0])<<24; + break; + case 0 : return c; + } + } + + final(a,b,c); + return c; +} + + +#ifdef SELF_TEST + +/* used for timings */ +void driver1() +{ + uint8_t buf[256]; + uint32_t i; + uint32_t h=0; + time_t a,z; + + time(&a); + for (i=0; i<256; ++i) buf[i] = 'x'; + for (i=0; i<1; ++i) + { + h = hashlittle(&buf[0],1,h); + } + time(&z); + if (z-a > 0) printf("time %d %.8x\n", z-a, h); +} + +/* check that every input bit changes every output bit half the time */ +#define HASHSTATE 1 +#define HASHLEN 1 +#define MAXPAIR 60 +#define MAXLEN 70 +void driver2() +{ + uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1]; + uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z; + uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE]; + uint32_t x[HASHSTATE],y[HASHSTATE]; + uint32_t hlen; + + printf("No more than %d trials should ever be needed \n",MAXPAIR/2); + for (hlen=0; hlen < MAXLEN; ++hlen) + { + z=0; + for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */ + { + for (j=0; j<8; ++j) /*------------------------ for each input bit, */ + { + for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */ + { + for (l=0; l<HASHSTATE; ++l) + e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0); + + /*---- check that every output bit is affected by that input bit */ + for (k=0; k<MAXPAIR; k+=2) + { + uint32_t finished=1; + /* keys have one bit different */ + for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;} + /* have a and b be two keys differing in only one bit */ + a[i] ^= (k<<j); + a[i] ^= (k>>(8-j)); + c[0] = hashlittle(a, hlen, m); + b[i] ^= ((k+1)<<j); + b[i] ^= ((k+1)>>(8-j)); + d[0] = hashlittle(b, hlen, m); + /* check every bit is 1, 0, set, and not set at least once */ + for (l=0; l<HASHSTATE; ++l) + { + e[l] &= (c[l]^d[l]); + f[l] &= ~(c[l]^d[l]); + g[l] &= c[l]; + h[l] &= ~c[l]; + x[l] &= d[l]; + y[l] &= ~d[l]; + if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0; + } + if (finished) break; + } + if (k>z) z=k; + if (k==MAXPAIR) + { + printf("Some bit didn't change: "); + printf("%.8x %.8x %.8x %.8x %.8x %.8x ", + e[0],f[0],g[0],h[0],x[0],y[0]); + printf("i %d j %d m %d len %d\n", i, j, m, hlen); + } + if (z==MAXPAIR) goto done; + } + } + } + done: + if (z < MAXPAIR) + { + printf("Mix success %2d bytes %2d initvals ",i,m); + printf("required %d trials\n", z/2); + } + } + printf("\n"); +} + +/* Check for reading beyond the end of the buffer and alignment problems */ +void driver3() +{ + uint8_t buf[MAXLEN+20], *b; + uint32_t len; + uint8_t q[] = "This is the time for all good men to come to the aid of their country..."; + uint32_t h; + uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country..."; + uint32_t i; + uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country..."; + uint32_t j; + uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country..."; + uint32_t ref,x,y; + uint8_t *p; + + printf("Endianness. These lines should all be the same (for values filled in):\n"); + printf("%.8x %.8x %.8x\n", + hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13), + hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13), + hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13)); + p = q; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qq[1]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qqq[2]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + p = &qqqq[3]; + printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", + hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), + hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), + hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), + hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), + hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), + hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); + printf("\n"); + + /* check that hashlittle2 and hashlittle produce the same results */ + i=47; j=0; + hashlittle2(q, sizeof(q), &i, &j); + if (hashlittle(q, sizeof(q), 47) != i) + printf("hashlittle2 and hashlittle mismatch\n"); + + /* check that hashword2 and hashword produce the same results */ + len = 0xdeadbeef; + i=47, j=0; + hashword2(&len, 1, &i, &j); + if (hashword(&len, 1, 47) != i) + printf("hashword2 and hashword mismatch %x %x\n", + i, hashword(&len, 1, 47)); + + /* check hashlittle doesn't read before or after the ends of the string */ + for (h=0, b=buf+1; h<8; ++h, ++b) + { + for (i=0; i<MAXLEN; ++i) + { + len = i; + for (j=0; j<i; ++j) *(b+j)=0; + + /* these should all be equal */ + ref = hashlittle(b, len, (uint32_t)1); + *(b+i)=(uint8_t)~0; + *(b-1)=(uint8_t)~0; + x = hashlittle(b, len, (uint32_t)1); + y = hashlittle(b, len, (uint32_t)1); + if ((ref != x) || (ref != y)) + { + printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y, + h, i); + } + } + } +} + +/* check for problems with nulls */ + void driver4() +{ + uint8_t buf[1]; + uint32_t h,i,state[HASHSTATE]; + + + buf[0] = ~0; + for (i=0; i<HASHSTATE; ++i) state[i] = 1; + printf("These should all be different\n"); + for (i=0, h=0; i<8; ++i) + { + h = hashlittle(buf, 0, h); + printf("%2ld 0-byte strings, hash is %.8x\n", i, h); + } +} + +void driver5() +{ + uint32_t b,c; + b=0, c=0, hashlittle2("", 0, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* deadbeef deadbeef */ + b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* bd5b7dde deadbeef */ + b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* 9c093ccd bd5b7dde */ + b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* 17770551 ce7226e6 */ + b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* e3607cae bd371de4 */ + b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b); + printf("hash is %.8lx %.8lx\n", c, b); /* cd628161 6cbea4b3 */ + c = hashlittle("Four score and seven years ago", 30, 0); + printf("hash is %.8lx\n", c); /* 17770551 */ + c = hashlittle("Four score and seven years ago", 30, 1); + printf("hash is %.8lx\n", c); /* cd628161 */ +} + + +int main() +{ + driver1(); /* test that the key is hashed: used for timings */ + driver2(); /* test that whole key is hashed thoroughly */ + driver3(); /* test that nothing but the key is hashed */ + driver4(); /* test hashing multiple buffers (all buffers are null) */ + driver5(); /* test the hash against known vectors */ + return 1; +} + +#endif /* SELF_TEST */ diff --git a/src/libsystemd/src/sd-journal/lookup3.h b/src/libsystemd/src/sd-journal/lookup3.h new file mode 100644 index 0000000000..0c8c0b0ae4 --- /dev/null +++ b/src/libsystemd/src/sd-journal/lookup3.h @@ -0,0 +1,22 @@ +#pragma once + +#include <inttypes.h> +#include <sys/types.h> + +#include "systemd-basic/macro.h" + +uint32_t jenkins_hashword(const uint32_t *k, size_t length, uint32_t initval) _pure_; +void jenkins_hashword2(const uint32_t *k, size_t length, uint32_t *pc, uint32_t *pb); + +uint32_t jenkins_hashlittle(const void *key, size_t length, uint32_t initval) _pure_; +void jenkins_hashlittle2(const void *key, size_t length, uint32_t *pc, uint32_t *pb); + +uint32_t jenkins_hashbig(const void *key, size_t length, uint32_t initval) _pure_; + +static inline uint64_t hash64(const void *data, size_t length) { + uint32_t a = 0, b = 0; + + jenkins_hashlittle2(data, length, &a, &b); + + return ((uint64_t) a << 32ULL) | (uint64_t) b; +} diff --git a/src/libsystemd/src/sd-journal/mmap-cache.c b/src/libsystemd/src/sd-journal/mmap-cache.c new file mode 100644 index 0000000000..2fdb445f3f --- /dev/null +++ b/src/libsystemd/src/sd-journal/mmap-cache.c @@ -0,0 +1,726 @@ +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <stdlib.h> +#include <sys/mman.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/list.h" +#include "systemd-basic/log.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/sigbus.h" +#include "systemd-basic/util.h" + +#include "mmap-cache.h" + +typedef struct Window Window; +typedef struct Context Context; +typedef struct FileDescriptor FileDescriptor; + +struct Window { + MMapCache *cache; + + bool invalidated:1; + bool keep_always:1; + bool in_unused:1; + + int prot; + void *ptr; + uint64_t offset; + size_t size; + + FileDescriptor *fd; + + LIST_FIELDS(Window, by_fd); + LIST_FIELDS(Window, unused); + + LIST_HEAD(Context, contexts); +}; + +struct Context { + MMapCache *cache; + unsigned id; + Window *window; + + LIST_FIELDS(Context, by_window); +}; + +struct FileDescriptor { + MMapCache *cache; + int fd; + bool sigbus; + LIST_HEAD(Window, windows); +}; + +struct MMapCache { + int n_ref; + unsigned n_windows; + + unsigned n_hit, n_missed; + + Hashmap *fds; + Context *contexts[MMAP_CACHE_MAX_CONTEXTS]; + + LIST_HEAD(Window, unused); + Window *last_unused; +}; + +#define WINDOWS_MIN 64 + +#ifdef ENABLE_DEBUG_MMAP_CACHE +/* Tiny windows increase mmap activity and the chance of exposing unsafe use. */ +# define WINDOW_SIZE (page_size()) +#else +# define WINDOW_SIZE (8ULL*1024ULL*1024ULL) +#endif + +MMapCache* mmap_cache_new(void) { + MMapCache *m; + + m = new0(MMapCache, 1); + if (!m) + return NULL; + + m->n_ref = 1; + return m; +} + +MMapCache* mmap_cache_ref(MMapCache *m) { + assert(m); + assert(m->n_ref > 0); + + m->n_ref++; + return m; +} + +static void window_unlink(Window *w) { + Context *c; + + assert(w); + + if (w->ptr) + munmap(w->ptr, w->size); + + if (w->fd) + LIST_REMOVE(by_fd, w->fd->windows, w); + + if (w->in_unused) { + if (w->cache->last_unused == w) + w->cache->last_unused = w->unused_prev; + + LIST_REMOVE(unused, w->cache->unused, w); + } + + LIST_FOREACH(by_window, c, w->contexts) { + assert(c->window == w); + c->window = NULL; + } +} + +static void window_invalidate(Window *w) { + assert(w); + + if (w->invalidated) + return; + + /* Replace the window with anonymous pages. This is useful + * when we hit a SIGBUS and want to make sure the file cannot + * trigger any further SIGBUS, possibly overrunning the sigbus + * queue. */ + + assert_se(mmap(w->ptr, w->size, w->prot, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == w->ptr); + w->invalidated = true; +} + +static void window_free(Window *w) { + assert(w); + + window_unlink(w); + w->cache->n_windows--; + free(w); +} + +_pure_ static bool window_matches(Window *w, int fd, int prot, uint64_t offset, size_t size) { + assert(w); + assert(fd >= 0); + assert(size > 0); + + return + w->fd && + fd == w->fd->fd && + prot == w->prot && + offset >= w->offset && + offset + size <= w->offset + w->size; +} + +static Window *window_add(MMapCache *m, FileDescriptor *fd, int prot, bool keep_always, uint64_t offset, size_t size, void *ptr) { + Window *w; + + assert(m); + assert(fd); + + if (!m->last_unused || m->n_windows <= WINDOWS_MIN) { + + /* Allocate a new window */ + w = new0(Window, 1); + if (!w) + return NULL; + m->n_windows++; + } else { + + /* Reuse an existing one */ + w = m->last_unused; + window_unlink(w); + zero(*w); + } + + w->cache = m; + w->fd = fd; + w->prot = prot; + w->keep_always = keep_always; + w->offset = offset; + w->size = size; + w->ptr = ptr; + + LIST_PREPEND(by_fd, fd->windows, w); + + return w; +} + +static void context_detach_window(Context *c) { + Window *w; + + assert(c); + + if (!c->window) + return; + + w = c->window; + c->window = NULL; + LIST_REMOVE(by_window, w->contexts, c); + + if (!w->contexts && !w->keep_always) { + /* Not used anymore? */ +#ifdef ENABLE_DEBUG_MMAP_CACHE + /* Unmap unused windows immediately to expose use-after-unmap + * by SIGSEGV. */ + window_free(w); +#else + LIST_PREPEND(unused, c->cache->unused, w); + if (!c->cache->last_unused) + c->cache->last_unused = w; + + w->in_unused = true; +#endif + } +} + +static void context_attach_window(Context *c, Window *w) { + assert(c); + assert(w); + + if (c->window == w) + return; + + context_detach_window(c); + + if (w->in_unused) { + /* Used again? */ + LIST_REMOVE(unused, c->cache->unused, w); + if (c->cache->last_unused == w) + c->cache->last_unused = w->unused_prev; + + w->in_unused = false; + } + + c->window = w; + LIST_PREPEND(by_window, w->contexts, c); +} + +static Context *context_add(MMapCache *m, unsigned id) { + Context *c; + + assert(m); + + c = m->contexts[id]; + if (c) + return c; + + c = new0(Context, 1); + if (!c) + return NULL; + + c->cache = m; + c->id = id; + + assert(!m->contexts[id]); + m->contexts[id] = c; + + return c; +} + +static void context_free(Context *c) { + assert(c); + + context_detach_window(c); + + if (c->cache) { + assert(c->cache->contexts[c->id] == c); + c->cache->contexts[c->id] = NULL; + } + + free(c); +} + +static void fd_free(FileDescriptor *f) { + assert(f); + + while (f->windows) + window_free(f->windows); + + if (f->cache) + assert_se(hashmap_remove(f->cache->fds, FD_TO_PTR(f->fd))); + + free(f); +} + +static FileDescriptor* fd_add(MMapCache *m, int fd) { + FileDescriptor *f; + int r; + + assert(m); + assert(fd >= 0); + + f = hashmap_get(m->fds, FD_TO_PTR(fd)); + if (f) + return f; + + r = hashmap_ensure_allocated(&m->fds, NULL); + if (r < 0) + return NULL; + + f = new0(FileDescriptor, 1); + if (!f) + return NULL; + + f->cache = m; + f->fd = fd; + + r = hashmap_put(m->fds, FD_TO_PTR(fd), f); + if (r < 0) { + free(f); + return NULL; + } + + return f; +} + +static void mmap_cache_free(MMapCache *m) { + FileDescriptor *f; + int i; + + assert(m); + + for (i = 0; i < MMAP_CACHE_MAX_CONTEXTS; i++) + if (m->contexts[i]) + context_free(m->contexts[i]); + + while ((f = hashmap_first(m->fds))) + fd_free(f); + + hashmap_free(m->fds); + + while (m->unused) + window_free(m->unused); + + free(m); +} + +MMapCache* mmap_cache_unref(MMapCache *m) { + + if (!m) + return NULL; + + assert(m->n_ref > 0); + + m->n_ref--; + if (m->n_ref == 0) + mmap_cache_free(m); + + return NULL; +} + +static int make_room(MMapCache *m) { + assert(m); + + if (!m->last_unused) + return 0; + + window_free(m->last_unused); + return 1; +} + +static int try_context( + MMapCache *m, + int fd, + int prot, + unsigned context, + bool keep_always, + uint64_t offset, + size_t size, + void **ret) { + + Context *c; + + assert(m); + assert(m->n_ref > 0); + assert(fd >= 0); + assert(size > 0); + assert(ret); + + c = m->contexts[context]; + if (!c) + return 0; + + assert(c->id == context); + + if (!c->window) + return 0; + + if (!window_matches(c->window, fd, prot, offset, size)) { + + /* Drop the reference to the window, since it's unnecessary now */ + context_detach_window(c); + return 0; + } + + if (c->window->fd->sigbus) + return -EIO; + + c->window->keep_always = c->window->keep_always || keep_always; + + *ret = (uint8_t*) c->window->ptr + (offset - c->window->offset); + return 1; +} + +static int find_mmap( + MMapCache *m, + int fd, + int prot, + unsigned context, + bool keep_always, + uint64_t offset, + size_t size, + void **ret) { + + FileDescriptor *f; + Window *w; + Context *c; + + assert(m); + assert(m->n_ref > 0); + assert(fd >= 0); + assert(size > 0); + + f = hashmap_get(m->fds, FD_TO_PTR(fd)); + if (!f) + return 0; + + assert(f->fd == fd); + + if (f->sigbus) + return -EIO; + + LIST_FOREACH(by_fd, w, f->windows) + if (window_matches(w, fd, prot, offset, size)) + break; + + if (!w) + return 0; + + c = context_add(m, context); + if (!c) + return -ENOMEM; + + context_attach_window(c, w); + w->keep_always = w->keep_always || keep_always; + + *ret = (uint8_t*) w->ptr + (offset - w->offset); + return 1; +} + +static int mmap_try_harder(MMapCache *m, void *addr, int fd, int prot, int flags, uint64_t offset, size_t size, void **res) { + void *ptr; + + assert(m); + assert(fd >= 0); + assert(res); + + for (;;) { + int r; + + ptr = mmap(addr, size, prot, flags, fd, offset); + if (ptr != MAP_FAILED) + break; + if (errno != ENOMEM) + return negative_errno(); + + r = make_room(m); + if (r < 0) + return r; + if (r == 0) + return -ENOMEM; + } + + *res = ptr; + return 0; +} + +static int add_mmap( + MMapCache *m, + int fd, + int prot, + unsigned context, + bool keep_always, + uint64_t offset, + size_t size, + struct stat *st, + void **ret) { + + uint64_t woffset, wsize; + Context *c; + FileDescriptor *f; + Window *w; + void *d; + int r; + + assert(m); + assert(m->n_ref > 0); + assert(fd >= 0); + assert(size > 0); + assert(ret); + + woffset = offset & ~((uint64_t) page_size() - 1ULL); + wsize = size + (offset - woffset); + wsize = PAGE_ALIGN(wsize); + + if (wsize < WINDOW_SIZE) { + uint64_t delta; + + delta = PAGE_ALIGN((WINDOW_SIZE - wsize) / 2); + + if (delta > offset) + woffset = 0; + else + woffset -= delta; + + wsize = WINDOW_SIZE; + } + + if (st) { + /* Memory maps that are larger then the files + underneath have undefined behavior. Hence, clamp + things to the file size if we know it */ + + if (woffset >= (uint64_t) st->st_size) + return -EADDRNOTAVAIL; + + if (woffset + wsize > (uint64_t) st->st_size) + wsize = PAGE_ALIGN(st->st_size - woffset); + } + + r = mmap_try_harder(m, NULL, fd, prot, MAP_SHARED, woffset, wsize, &d); + if (r < 0) + return r; + + c = context_add(m, context); + if (!c) + goto outofmem; + + f = fd_add(m, fd); + if (!f) + goto outofmem; + + w = window_add(m, f, prot, keep_always, woffset, wsize, d); + if (!w) + goto outofmem; + + context_detach_window(c); + c->window = w; + LIST_PREPEND(by_window, w->contexts, c); + + *ret = (uint8_t*) w->ptr + (offset - w->offset); + return 1; + +outofmem: + (void) munmap(d, wsize); + return -ENOMEM; +} + +int mmap_cache_get( + MMapCache *m, + int fd, + int prot, + unsigned context, + bool keep_always, + uint64_t offset, + size_t size, + struct stat *st, + void **ret) { + + int r; + + assert(m); + assert(m->n_ref > 0); + assert(fd >= 0); + assert(size > 0); + assert(ret); + assert(context < MMAP_CACHE_MAX_CONTEXTS); + + /* Check whether the current context is the right one already */ + r = try_context(m, fd, prot, context, keep_always, offset, size, ret); + if (r != 0) { + m->n_hit++; + return r; + } + + /* Search for a matching mmap */ + r = find_mmap(m, fd, prot, context, keep_always, offset, size, ret); + if (r != 0) { + m->n_hit++; + return r; + } + + m->n_missed++; + + /* Create a new mmap */ + return add_mmap(m, fd, prot, context, keep_always, offset, size, st, ret); +} + +unsigned mmap_cache_get_hit(MMapCache *m) { + assert(m); + + return m->n_hit; +} + +unsigned mmap_cache_get_missed(MMapCache *m) { + assert(m); + + return m->n_missed; +} + +static void mmap_cache_process_sigbus(MMapCache *m) { + bool found = false; + FileDescriptor *f; + Iterator i; + int r; + + assert(m); + + /* Iterate through all triggered pages and mark their files as + * invalidated */ + for (;;) { + bool ours; + void *addr; + + r = sigbus_pop(&addr); + if (_likely_(r == 0)) + break; + if (r < 0) { + log_error_errno(r, "SIGBUS handling failed: %m"); + abort(); + } + + ours = false; + HASHMAP_FOREACH(f, m->fds, i) { + Window *w; + + LIST_FOREACH(by_fd, w, f->windows) { + if ((uint8_t*) addr >= (uint8_t*) w->ptr && + (uint8_t*) addr < (uint8_t*) w->ptr + w->size) { + found = ours = f->sigbus = true; + break; + } + } + + if (ours) + break; + } + + /* Didn't find a matching window, give up */ + if (!ours) { + log_error("Unknown SIGBUS page, aborting."); + abort(); + } + } + + /* The list of triggered pages is now empty. Now, let's remap + * all windows of the triggered file to anonymous maps, so + * that no page of the file in question is triggered again, so + * that we can be sure not to hit the queue size limit. */ + if (_likely_(!found)) + return; + + HASHMAP_FOREACH(f, m->fds, i) { + Window *w; + + if (!f->sigbus) + continue; + + LIST_FOREACH(by_fd, w, f->windows) + window_invalidate(w); + } +} + +bool mmap_cache_got_sigbus(MMapCache *m, int fd) { + FileDescriptor *f; + + assert(m); + assert(fd >= 0); + + mmap_cache_process_sigbus(m); + + f = hashmap_get(m->fds, FD_TO_PTR(fd)); + if (!f) + return false; + + return f->sigbus; +} + +void mmap_cache_close_fd(MMapCache *m, int fd) { + FileDescriptor *f; + + assert(m); + assert(fd >= 0); + + /* Make sure that any queued SIGBUS are first dispatched, so + * that we don't end up with a SIGBUS entry we cannot relate + * to any existing memory map */ + + mmap_cache_process_sigbus(m); + + f = hashmap_get(m->fds, FD_TO_PTR(fd)); + if (!f) + return; + + fd_free(f); +} diff --git a/src/libsystemd/src/sd-journal/mmap-cache.h b/src/libsystemd/src/sd-journal/mmap-cache.h new file mode 100644 index 0000000000..199d944647 --- /dev/null +++ b/src/libsystemd/src/sd-journal/mmap-cache.h @@ -0,0 +1,49 @@ +#pragma once + +/*** + This file is part of systemd. + + Copyright 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 <http://www.gnu.org/licenses/>. +***/ + +#include <stdbool.h> +#include <sys/stat.h> + +/* One context per object type, plus one of the header, plus one "additional" one */ +#define MMAP_CACHE_MAX_CONTEXTS 9 + +typedef struct MMapCache MMapCache; + +MMapCache* mmap_cache_new(void); +MMapCache* mmap_cache_ref(MMapCache *m); +MMapCache* mmap_cache_unref(MMapCache *m); + +int mmap_cache_get( + MMapCache *m, + int fd, + int prot, + unsigned context, + bool keep_always, + uint64_t offset, + size_t size, + struct stat *st, + void **ret); +void mmap_cache_close_fd(MMapCache *m, int fd); + +unsigned mmap_cache_get_hit(MMapCache *m); +unsigned mmap_cache_get_missed(MMapCache *m); + +bool mmap_cache_got_sigbus(MMapCache *m, int fd); diff --git a/src/libsystemd/src/sd-journal/sd-journal.c b/src/libsystemd/src/sd-journal/sd-journal.c new file mode 100644 index 0000000000..58307e1626 --- /dev/null +++ b/src/libsystemd/src/sd-journal/sd-journal.c @@ -0,0 +1,2987 @@ +/*** + 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 <http://www.gnu.org/licenses/>. +***/ + +#include <errno.h> +#include <fcntl.h> +#include <inttypes.h> +#include <poll.h> +#include <stddef.h> +#include <sys/inotify.h> +#include <sys/vfs.h> +#include <unistd.h> + +#include <linux/magic.h> + +#include <systemd/sd-journal.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/dirent-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/hostname-util.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/list.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/replace-var.h" +#include "systemd-basic/stat-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" + +#include "catalog.h" +#include "compress.h" +#include "journal-def.h" +#include "journal-file.h" +#include "journal-internal.h" +#include "lookup3.h" + +#define JOURNAL_FILES_MAX 7168 + +#define JOURNAL_FILES_RECHECK_USEC (2 * USEC_PER_SEC) + +#define REPLACE_VAR_MAX 256 + +#define DEFAULT_DATA_THRESHOLD (64*1024) + +static void remove_file_real(sd_journal *j, JournalFile *f); + +static bool journal_pid_changed(sd_journal *j) { + assert(j); + + /* We don't support people creating a journal object and + * keeping it around over a fork(). Let's complain. */ + + return j->original_pid != getpid(); +} + +static int journal_put_error(sd_journal *j, int r, const char *path) { + char *copy; + int k; + + /* Memorize an error we encountered, and store which + * file/directory it was generated from. Note that we store + * only *one* path per error code, as the error code is the + * key into the hashmap, and the path is the value. This means + * we keep track only of all error kinds, but not of all error + * locations. This has the benefit that the hashmap cannot + * grow beyond bounds. + * + * We return an error here only if we didn't manage to + * memorize the real error. */ + + if (r >= 0) + return r; + + k = hashmap_ensure_allocated(&j->errors, NULL); + if (k < 0) + return k; + + if (path) { + copy = strdup(path); + if (!copy) + return -ENOMEM; + } else + copy = NULL; + + k = hashmap_put(j->errors, INT_TO_PTR(r), copy); + if (k < 0) { + free(copy); + + if (k == -EEXIST) + return 0; + + return k; + } + + return 0; +} + +static void detach_location(sd_journal *j) { + Iterator i; + JournalFile *f; + + assert(j); + + j->current_file = NULL; + j->current_field = 0; + + ORDERED_HASHMAP_FOREACH(f, j->files, i) + journal_file_reset_location(f); +} + +static void reset_location(sd_journal *j) { + assert(j); + + detach_location(j); + zero(j->current_location); +} + +static void init_location(Location *l, LocationType type, JournalFile *f, Object *o) { + assert(l); + assert(type == LOCATION_DISCRETE || type == LOCATION_SEEK); + assert(f); + assert(o->object.type == OBJECT_ENTRY); + + l->type = type; + l->seqnum = le64toh(o->entry.seqnum); + l->seqnum_id = f->header->seqnum_id; + l->realtime = le64toh(o->entry.realtime); + l->monotonic = le64toh(o->entry.monotonic); + l->boot_id = o->entry.boot_id; + l->xor_hash = le64toh(o->entry.xor_hash); + + l->seqnum_set = l->realtime_set = l->monotonic_set = l->xor_hash_set = true; +} + +static void set_location(sd_journal *j, JournalFile *f, Object *o) { + assert(j); + assert(f); + assert(o); + + init_location(&j->current_location, LOCATION_DISCRETE, f, o); + + j->current_file = f; + j->current_field = 0; + + /* Let f know its candidate entry was picked. */ + assert(f->location_type == LOCATION_SEEK); + f->location_type = LOCATION_DISCRETE; +} + +static int match_is_valid(const void *data, size_t size) { + const char *b, *p; + + assert(data); + + if (size < 2) + return false; + + if (startswith(data, "__")) + return false; + + b = data; + for (p = b; p < b + size; p++) { + + if (*p == '=') + return p > b; + + if (*p == '_') + continue; + + if (*p >= 'A' && *p <= 'Z') + continue; + + if (*p >= '0' && *p <= '9') + continue; + + return false; + } + + return false; +} + +static bool same_field(const void *_a, size_t s, const void *_b, size_t t) { + const uint8_t *a = _a, *b = _b; + size_t j; + + for (j = 0; j < s && j < t; j++) { + + if (a[j] != b[j]) + return false; + + if (a[j] == '=') + return true; + } + + assert_not_reached("\"=\" not found"); +} + +static Match *match_new(Match *p, MatchType t) { + Match *m; + + m = new0(Match, 1); + if (!m) + return NULL; + + m->type = t; + + if (p) { + m->parent = p; + LIST_PREPEND(matches, p->matches, m); + } + + return m; +} + +static void match_free(Match *m) { + assert(m); + + while (m->matches) + match_free(m->matches); + + if (m->parent) + LIST_REMOVE(matches, m->parent->matches, m); + + free(m->data); + free(m); +} + +static void match_free_if_empty(Match *m) { + if (!m || m->matches) + return; + + match_free(m); +} + +_public_ int sd_journal_add_match(sd_journal *j, const void *data, size_t size) { + Match *l3, *l4, *add_here = NULL, *m; + le64_t le_hash; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(data, -EINVAL); + + if (size == 0) + size = strlen(data); + + assert_return(match_is_valid(data, size), -EINVAL); + + /* level 0: AND term + * level 1: OR terms + * level 2: AND terms + * level 3: OR terms + * level 4: concrete matches */ + + if (!j->level0) { + j->level0 = match_new(NULL, MATCH_AND_TERM); + if (!j->level0) + return -ENOMEM; + } + + if (!j->level1) { + j->level1 = match_new(j->level0, MATCH_OR_TERM); + if (!j->level1) + return -ENOMEM; + } + + if (!j->level2) { + j->level2 = match_new(j->level1, MATCH_AND_TERM); + if (!j->level2) + return -ENOMEM; + } + + assert(j->level0->type == MATCH_AND_TERM); + assert(j->level1->type == MATCH_OR_TERM); + assert(j->level2->type == MATCH_AND_TERM); + + le_hash = htole64(hash64(data, size)); + + LIST_FOREACH(matches, l3, j->level2->matches) { + assert(l3->type == MATCH_OR_TERM); + + LIST_FOREACH(matches, l4, l3->matches) { + assert(l4->type == MATCH_DISCRETE); + + /* Exactly the same match already? Then ignore + * this addition */ + if (l4->le_hash == le_hash && + l4->size == size && + memcmp(l4->data, data, size) == 0) + return 0; + + /* Same field? Then let's add this to this OR term */ + if (same_field(data, size, l4->data, l4->size)) { + add_here = l3; + break; + } + } + + if (add_here) + break; + } + + if (!add_here) { + add_here = match_new(j->level2, MATCH_OR_TERM); + if (!add_here) + goto fail; + } + + m = match_new(add_here, MATCH_DISCRETE); + if (!m) + goto fail; + + m->le_hash = le_hash; + m->size = size; + m->data = memdup(data, size); + if (!m->data) + goto fail; + + detach_location(j); + + return 0; + +fail: + match_free_if_empty(add_here); + match_free_if_empty(j->level2); + match_free_if_empty(j->level1); + match_free_if_empty(j->level0); + + return -ENOMEM; +} + +_public_ int sd_journal_add_conjunction(sd_journal *j) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + if (!j->level0) + return 0; + + if (!j->level1) + return 0; + + if (!j->level1->matches) + return 0; + + j->level1 = NULL; + j->level2 = NULL; + + return 0; +} + +_public_ int sd_journal_add_disjunction(sd_journal *j) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + if (!j->level0) + return 0; + + if (!j->level1) + return 0; + + if (!j->level2) + return 0; + + if (!j->level2->matches) + return 0; + + j->level2 = NULL; + return 0; +} + +static char *match_make_string(Match *m) { + char *p, *r; + Match *i; + bool enclose = false; + + if (!m) + return strdup("none"); + + if (m->type == MATCH_DISCRETE) + return strndup(m->data, m->size); + + p = NULL; + LIST_FOREACH(matches, i, m->matches) { + char *t, *k; + + t = match_make_string(i); + if (!t) { + free(p); + return NULL; + } + + if (p) { + k = strjoin(p, m->type == MATCH_OR_TERM ? " OR " : " AND ", t, NULL); + free(p); + free(t); + + if (!k) + return NULL; + + p = k; + + enclose = true; + } else + p = t; + } + + if (enclose) { + r = strjoin("(", p, ")", NULL); + free(p); + return r; + } + + return p; +} + +char *journal_make_match_string(sd_journal *j) { + assert(j); + + return match_make_string(j->level0); +} + +_public_ void sd_journal_flush_matches(sd_journal *j) { + if (!j) + return; + + if (j->level0) + match_free(j->level0); + + j->level0 = j->level1 = j->level2 = NULL; + + detach_location(j); +} + +_pure_ static int compare_with_location(JournalFile *f, Location *l) { + assert(f); + assert(l); + assert(f->location_type == LOCATION_SEEK); + assert(l->type == LOCATION_DISCRETE || l->type == LOCATION_SEEK); + + if (l->monotonic_set && + sd_id128_equal(f->current_boot_id, l->boot_id) && + l->realtime_set && + f->current_realtime == l->realtime && + l->xor_hash_set && + f->current_xor_hash == l->xor_hash) + return 0; + + if (l->seqnum_set && + sd_id128_equal(f->header->seqnum_id, l->seqnum_id)) { + + if (f->current_seqnum < l->seqnum) + return -1; + if (f->current_seqnum > l->seqnum) + return 1; + } + + if (l->monotonic_set && + sd_id128_equal(f->current_boot_id, l->boot_id)) { + + if (f->current_monotonic < l->monotonic) + return -1; + if (f->current_monotonic > l->monotonic) + return 1; + } + + if (l->realtime_set) { + + if (f->current_realtime < l->realtime) + return -1; + if (f->current_realtime > l->realtime) + return 1; + } + + if (l->xor_hash_set) { + + if (f->current_xor_hash < l->xor_hash) + return -1; + if (f->current_xor_hash > l->xor_hash) + return 1; + } + + return 0; +} + +static int next_for_match( + sd_journal *j, + Match *m, + JournalFile *f, + uint64_t after_offset, + direction_t direction, + Object **ret, + uint64_t *offset) { + + int r; + uint64_t np = 0; + Object *n; + + assert(j); + assert(m); + assert(f); + + if (m->type == MATCH_DISCRETE) { + uint64_t dp; + + r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp); + if (r <= 0) + return r; + + return journal_file_move_to_entry_by_offset_for_data(f, dp, after_offset, direction, ret, offset); + + } else if (m->type == MATCH_OR_TERM) { + Match *i; + + /* Find the earliest match beyond after_offset */ + + LIST_FOREACH(matches, i, m->matches) { + uint64_t cp; + + r = next_for_match(j, i, f, after_offset, direction, NULL, &cp); + if (r < 0) + return r; + else if (r > 0) { + if (np == 0 || (direction == DIRECTION_DOWN ? cp < np : cp > np)) + np = cp; + } + } + + if (np == 0) + return 0; + + } else if (m->type == MATCH_AND_TERM) { + Match *i, *last_moved; + + /* Always jump to the next matching entry and repeat + * this until we find an offset that matches for all + * matches. */ + + if (!m->matches) + return 0; + + r = next_for_match(j, m->matches, f, after_offset, direction, NULL, &np); + if (r <= 0) + return r; + + assert(direction == DIRECTION_DOWN ? np >= after_offset : np <= after_offset); + last_moved = m->matches; + + LIST_LOOP_BUT_ONE(matches, i, m->matches, last_moved) { + uint64_t cp; + + r = next_for_match(j, i, f, np, direction, NULL, &cp); + if (r <= 0) + return r; + + assert(direction == DIRECTION_DOWN ? cp >= np : cp <= np); + if (direction == DIRECTION_DOWN ? cp > np : cp < np) { + np = cp; + last_moved = i; + } + } + } + + assert(np > 0); + + r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n); + if (r < 0) + return r; + + if (ret) + *ret = n; + if (offset) + *offset = np; + + return 1; +} + +static int find_location_for_match( + sd_journal *j, + Match *m, + JournalFile *f, + direction_t direction, + Object **ret, + uint64_t *offset) { + + int r; + + assert(j); + assert(m); + assert(f); + + if (m->type == MATCH_DISCRETE) { + uint64_t dp; + + r = journal_file_find_data_object_with_hash(f, m->data, m->size, le64toh(m->le_hash), NULL, &dp); + if (r <= 0) + return r; + + /* FIXME: missing: find by monotonic */ + + if (j->current_location.type == LOCATION_HEAD) + return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_DOWN, ret, offset); + if (j->current_location.type == LOCATION_TAIL) + return journal_file_next_entry_for_data(f, NULL, 0, dp, DIRECTION_UP, ret, offset); + if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id)) + return journal_file_move_to_entry_by_seqnum_for_data(f, dp, j->current_location.seqnum, direction, ret, offset); + if (j->current_location.monotonic_set) { + r = journal_file_move_to_entry_by_monotonic_for_data(f, dp, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset); + if (r != -ENOENT) + return r; + } + if (j->current_location.realtime_set) + return journal_file_move_to_entry_by_realtime_for_data(f, dp, j->current_location.realtime, direction, ret, offset); + + return journal_file_next_entry_for_data(f, NULL, 0, dp, direction, ret, offset); + + } else if (m->type == MATCH_OR_TERM) { + uint64_t np = 0; + Object *n; + Match *i; + + /* Find the earliest match */ + + LIST_FOREACH(matches, i, m->matches) { + uint64_t cp; + + r = find_location_for_match(j, i, f, direction, NULL, &cp); + if (r < 0) + return r; + else if (r > 0) { + if (np == 0 || (direction == DIRECTION_DOWN ? np > cp : np < cp)) + np = cp; + } + } + + if (np == 0) + return 0; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, np, &n); + if (r < 0) + return r; + + if (ret) + *ret = n; + if (offset) + *offset = np; + + return 1; + + } else { + Match *i; + uint64_t np = 0; + + assert(m->type == MATCH_AND_TERM); + + /* First jump to the last match, and then find the + * next one where all matches match */ + + if (!m->matches) + return 0; + + LIST_FOREACH(matches, i, m->matches) { + uint64_t cp; + + r = find_location_for_match(j, i, f, direction, NULL, &cp); + if (r <= 0) + return r; + + if (np == 0 || (direction == DIRECTION_DOWN ? cp > np : cp < np)) + np = cp; + } + + return next_for_match(j, m, f, np, direction, ret, offset); + } +} + +static int find_location_with_matches( + sd_journal *j, + JournalFile *f, + direction_t direction, + Object **ret, + uint64_t *offset) { + + int r; + + assert(j); + assert(f); + assert(ret); + assert(offset); + + if (!j->level0) { + /* No matches is simple */ + + if (j->current_location.type == LOCATION_HEAD) + return journal_file_next_entry(f, 0, DIRECTION_DOWN, ret, offset); + if (j->current_location.type == LOCATION_TAIL) + return journal_file_next_entry(f, 0, DIRECTION_UP, ret, offset); + if (j->current_location.seqnum_set && sd_id128_equal(j->current_location.seqnum_id, f->header->seqnum_id)) + return journal_file_move_to_entry_by_seqnum(f, j->current_location.seqnum, direction, ret, offset); + if (j->current_location.monotonic_set) { + r = journal_file_move_to_entry_by_monotonic(f, j->current_location.boot_id, j->current_location.monotonic, direction, ret, offset); + if (r != -ENOENT) + return r; + } + if (j->current_location.realtime_set) + return journal_file_move_to_entry_by_realtime(f, j->current_location.realtime, direction, ret, offset); + + return journal_file_next_entry(f, 0, direction, ret, offset); + } else + return find_location_for_match(j, j->level0, f, direction, ret, offset); +} + +static int next_with_matches( + sd_journal *j, + JournalFile *f, + direction_t direction, + Object **ret, + uint64_t *offset) { + + assert(j); + assert(f); + assert(ret); + assert(offset); + + /* No matches is easy. We simple advance the file + * pointer by one. */ + if (!j->level0) + return journal_file_next_entry(f, f->current_offset, direction, ret, offset); + + /* If we have a match then we look for the next matching entry + * with an offset at least one step larger */ + return next_for_match(j, j->level0, f, + direction == DIRECTION_DOWN ? f->current_offset + 1 + : f->current_offset - 1, + direction, ret, offset); +} + +static int next_beyond_location(sd_journal *j, JournalFile *f, direction_t direction) { + Object *c; + uint64_t cp, n_entries; + int r; + + assert(j); + assert(f); + + n_entries = le64toh(f->header->n_entries); + + /* If we hit EOF before, we don't need to look into this file again + * unless direction changed or new entries appeared. */ + if (f->last_direction == direction && f->location_type == LOCATION_TAIL && + n_entries == f->last_n_entries) + return 0; + + f->last_n_entries = n_entries; + + if (f->last_direction == direction && f->current_offset > 0) { + /* LOCATION_SEEK here means we did the work in a previous + * iteration and the current location already points to a + * candidate entry. */ + if (f->location_type != LOCATION_SEEK) { + r = next_with_matches(j, f, direction, &c, &cp); + if (r <= 0) + return r; + + journal_file_save_location(f, c, cp); + } + } else { + f->last_direction = direction; + + r = find_location_with_matches(j, f, direction, &c, &cp); + if (r <= 0) + return r; + + journal_file_save_location(f, c, cp); + } + + /* OK, we found the spot, now let's advance until an entry + * that is actually different from what we were previously + * looking at. This is necessary to handle entries which exist + * in two (or more) journal files, and which shall all be + * suppressed but one. */ + + for (;;) { + bool found; + + if (j->current_location.type == LOCATION_DISCRETE) { + int k; + + k = compare_with_location(f, &j->current_location); + + found = direction == DIRECTION_DOWN ? k > 0 : k < 0; + } else + found = true; + + if (found) + return 1; + + r = next_with_matches(j, f, direction, &c, &cp); + if (r <= 0) + return r; + + journal_file_save_location(f, c, cp); + } +} + +static int real_journal_next(sd_journal *j, direction_t direction) { + JournalFile *f, *new_file = NULL; + Iterator i; + Object *o; + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + bool found; + + r = next_beyond_location(j, f, direction); + if (r < 0) { + log_debug_errno(r, "Can't iterate through %s, ignoring: %m", f->path); + remove_file_real(j, f); + continue; + } else if (r == 0) { + f->location_type = LOCATION_TAIL; + continue; + } + + if (!new_file) + found = true; + else { + int k; + + k = journal_file_compare_locations(f, new_file); + + found = direction == DIRECTION_DOWN ? k < 0 : k > 0; + } + + if (found) + new_file = f; + } + + if (!new_file) + return 0; + + r = journal_file_move_to_object(new_file, OBJECT_ENTRY, new_file->current_offset, &o); + if (r < 0) + return r; + + set_location(j, new_file, o); + + return 1; +} + +_public_ int sd_journal_next(sd_journal *j) { + return real_journal_next(j, DIRECTION_DOWN); +} + +_public_ int sd_journal_previous(sd_journal *j) { + return real_journal_next(j, DIRECTION_UP); +} + +static int real_journal_next_skip(sd_journal *j, direction_t direction, uint64_t skip) { + int c = 0, r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + if (skip == 0) { + /* If this is not a discrete skip, then at least + * resolve the current location */ + if (j->current_location.type != LOCATION_DISCRETE) + return real_journal_next(j, direction); + + return 0; + } + + do { + r = real_journal_next(j, direction); + if (r < 0) + return r; + + if (r == 0) + return c; + + skip--; + c++; + } while (skip > 0); + + return c; +} + +_public_ int sd_journal_next_skip(sd_journal *j, uint64_t skip) { + return real_journal_next_skip(j, DIRECTION_DOWN, skip); +} + +_public_ int sd_journal_previous_skip(sd_journal *j, uint64_t skip) { + return real_journal_next_skip(j, DIRECTION_UP, skip); +} + +_public_ int sd_journal_get_cursor(sd_journal *j, char **cursor) { + Object *o; + int r; + char bid[33], sid[33]; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(cursor, -EINVAL); + + if (!j->current_file || j->current_file->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o); + if (r < 0) + return r; + + sd_id128_to_string(j->current_file->header->seqnum_id, sid); + sd_id128_to_string(o->entry.boot_id, bid); + + if (asprintf(cursor, + "s=%s;i=%"PRIx64";b=%s;m=%"PRIx64";t=%"PRIx64";x=%"PRIx64, + sid, le64toh(o->entry.seqnum), + bid, le64toh(o->entry.monotonic), + le64toh(o->entry.realtime), + le64toh(o->entry.xor_hash)) < 0) + return -ENOMEM; + + return 0; +} + +_public_ int sd_journal_seek_cursor(sd_journal *j, const char *cursor) { + const char *word, *state; + size_t l; + unsigned long long seqnum, monotonic, realtime, xor_hash; + bool + seqnum_id_set = false, + seqnum_set = false, + boot_id_set = false, + monotonic_set = false, + realtime_set = false, + xor_hash_set = false; + sd_id128_t seqnum_id, boot_id; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(!isempty(cursor), -EINVAL); + + FOREACH_WORD_SEPARATOR(word, l, cursor, ";", state) { + char *item; + int k = 0; + + if (l < 2 || word[1] != '=') + return -EINVAL; + + item = strndup(word, l); + if (!item) + return -ENOMEM; + + switch (word[0]) { + + case 's': + seqnum_id_set = true; + k = sd_id128_from_string(item+2, &seqnum_id); + break; + + case 'i': + seqnum_set = true; + if (sscanf(item+2, "%llx", &seqnum) != 1) + k = -EINVAL; + break; + + case 'b': + boot_id_set = true; + k = sd_id128_from_string(item+2, &boot_id); + break; + + case 'm': + monotonic_set = true; + if (sscanf(item+2, "%llx", &monotonic) != 1) + k = -EINVAL; + break; + + case 't': + realtime_set = true; + if (sscanf(item+2, "%llx", &realtime) != 1) + k = -EINVAL; + break; + + case 'x': + xor_hash_set = true; + if (sscanf(item+2, "%llx", &xor_hash) != 1) + k = -EINVAL; + break; + } + + free(item); + + if (k < 0) + return k; + } + + if ((!seqnum_set || !seqnum_id_set) && + (!monotonic_set || !boot_id_set) && + !realtime_set) + return -EINVAL; + + reset_location(j); + + j->current_location.type = LOCATION_SEEK; + + if (realtime_set) { + j->current_location.realtime = (uint64_t) realtime; + j->current_location.realtime_set = true; + } + + if (seqnum_set && seqnum_id_set) { + j->current_location.seqnum = (uint64_t) seqnum; + j->current_location.seqnum_id = seqnum_id; + j->current_location.seqnum_set = true; + } + + if (monotonic_set && boot_id_set) { + j->current_location.monotonic = (uint64_t) monotonic; + j->current_location.boot_id = boot_id; + j->current_location.monotonic_set = true; + } + + if (xor_hash_set) { + j->current_location.xor_hash = (uint64_t) xor_hash; + j->current_location.xor_hash_set = true; + } + + return 0; +} + +_public_ int sd_journal_test_cursor(sd_journal *j, const char *cursor) { + int r; + Object *o; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(!isempty(cursor), -EINVAL); + + if (!j->current_file || j->current_file->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(j->current_file, OBJECT_ENTRY, j->current_file->current_offset, &o); + if (r < 0) + return r; + + for (;;) { + _cleanup_free_ char *item = NULL; + unsigned long long ll; + sd_id128_t id; + int k = 0; + + r = extract_first_word(&cursor, &item, ";", EXTRACT_DONT_COALESCE_SEPARATORS); + if (r < 0) + return r; + + if (r == 0) + break; + + if (strlen(item) < 2 || item[1] != '=') + return -EINVAL; + + switch (item[0]) { + + case 's': + k = sd_id128_from_string(item+2, &id); + if (k < 0) + return k; + if (!sd_id128_equal(id, j->current_file->header->seqnum_id)) + return 0; + break; + + case 'i': + if (sscanf(item+2, "%llx", &ll) != 1) + return -EINVAL; + if (ll != le64toh(o->entry.seqnum)) + return 0; + break; + + case 'b': + k = sd_id128_from_string(item+2, &id); + if (k < 0) + return k; + if (!sd_id128_equal(id, o->entry.boot_id)) + return 0; + break; + + case 'm': + if (sscanf(item+2, "%llx", &ll) != 1) + return -EINVAL; + if (ll != le64toh(o->entry.monotonic)) + return 0; + break; + + case 't': + if (sscanf(item+2, "%llx", &ll) != 1) + return -EINVAL; + if (ll != le64toh(o->entry.realtime)) + return 0; + break; + + case 'x': + if (sscanf(item+2, "%llx", &ll) != 1) + return -EINVAL; + if (ll != le64toh(o->entry.xor_hash)) + return 0; + break; + } + } + + return 1; +} + + +_public_ int sd_journal_seek_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t usec) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + reset_location(j); + j->current_location.type = LOCATION_SEEK; + j->current_location.boot_id = boot_id; + j->current_location.monotonic = usec; + j->current_location.monotonic_set = true; + + return 0; +} + +_public_ int sd_journal_seek_realtime_usec(sd_journal *j, uint64_t usec) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + reset_location(j); + j->current_location.type = LOCATION_SEEK; + j->current_location.realtime = usec; + j->current_location.realtime_set = true; + + return 0; +} + +_public_ int sd_journal_seek_head(sd_journal *j) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + reset_location(j); + j->current_location.type = LOCATION_HEAD; + + return 0; +} + +_public_ int sd_journal_seek_tail(sd_journal *j) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + reset_location(j); + j->current_location.type = LOCATION_TAIL; + + return 0; +} + +static void check_network(sd_journal *j, int fd) { + struct statfs sfs; + + assert(j); + + if (j->on_network) + return; + + if (fstatfs(fd, &sfs) < 0) + return; + + j->on_network = + F_TYPE_EQUAL(sfs.f_type, CIFS_MAGIC_NUMBER) || + F_TYPE_EQUAL(sfs.f_type, CODA_SUPER_MAGIC) || + F_TYPE_EQUAL(sfs.f_type, NCP_SUPER_MAGIC) || + F_TYPE_EQUAL(sfs.f_type, NFS_SUPER_MAGIC) || + F_TYPE_EQUAL(sfs.f_type, SMB_SUPER_MAGIC); +} + +static bool file_has_type_prefix(const char *prefix, const char *filename) { + const char *full, *tilded, *atted; + + full = strjoina(prefix, ".journal"); + tilded = strjoina(full, "~"); + atted = strjoina(prefix, "@"); + + return streq(filename, full) || + streq(filename, tilded) || + startswith(filename, atted); +} + +static bool file_type_wanted(int flags, const char *filename) { + assert(filename); + + if (!endswith(filename, ".journal") && !endswith(filename, ".journal~")) + return false; + + /* no flags set → every type is OK */ + if (!(flags & (SD_JOURNAL_SYSTEM | SD_JOURNAL_CURRENT_USER))) + return true; + + if (flags & SD_JOURNAL_SYSTEM && file_has_type_prefix("system", filename)) + return true; + + if (flags & SD_JOURNAL_CURRENT_USER) { + char prefix[5 + DECIMAL_STR_MAX(uid_t) + 1]; + + xsprintf(prefix, "user-"UID_FMT, getuid()); + + if (file_has_type_prefix(prefix, filename)) + return true; + } + + return false; +} + +static bool path_has_prefix(sd_journal *j, const char *path, const char *prefix) { + assert(j); + assert(path); + assert(prefix); + + if (j->toplevel_fd >= 0) + return false; + + return path_startswith(path, prefix); +} + +static const char *skip_slash(const char *p) { + + if (!p) + return NULL; + + while (*p == '/') + p++; + + return p; +} + +static int add_any_file(sd_journal *j, int fd, const char *path) { + JournalFile *f = NULL; + bool close_fd = false; + int r, k; + + assert(j); + assert(fd >= 0 || path); + + if (path && ordered_hashmap_get(j->files, path)) + return 0; + + if (ordered_hashmap_size(j->files) >= JOURNAL_FILES_MAX) { + log_debug("Too many open journal files, not adding %s.", path); + r = -ETOOMANYREFS; + goto fail; + } + + if (fd < 0 && j->toplevel_fd >= 0) { + + /* If there's a top-level fd defined, open the file relative to this now. (Make the path relative, + * explicitly, since otherwise openat() ignores the first argument.) */ + + fd = openat(j->toplevel_fd, skip_slash(path), O_RDONLY|O_CLOEXEC); + if (fd < 0) { + r = log_debug_errno(errno, "Failed to open journal file %s: %m", path); + goto fail; + } + + close_fd = true; + } + + r = journal_file_open(fd, path, O_RDONLY, 0, false, false, NULL, j->mmap, NULL, NULL, &f); + if (r < 0) { + if (close_fd) + safe_close(fd); + log_debug_errno(r, "Failed to open journal file %s: %m", path); + goto fail; + } + + /* journal_file_dump(f); */ + + r = ordered_hashmap_put(j->files, f->path, f); + if (r < 0) { + f->close_fd = close_fd; + (void) journal_file_close(f); + goto fail; + } + + if (!j->has_runtime_files && path_has_prefix(j, f->path, "/run")) + j->has_runtime_files = true; + else if (!j->has_persistent_files && path_has_prefix(j, f->path, "/var")) + j->has_persistent_files = true; + + log_debug("File %s added.", f->path); + + check_network(j, f->fd); + + j->current_invalidate_counter++; + + return 0; + +fail: + k = journal_put_error(j, r, path); + if (k < 0) + return k; + + return r; +} + +static int add_file(sd_journal *j, const char *prefix, const char *filename) { + const char *path; + + assert(j); + assert(prefix); + assert(filename); + + if (j->no_new_files) + return 0; + + if (!file_type_wanted(j->flags, filename)) + return 0; + + path = strjoina(prefix, "/", filename); + return add_any_file(j, -1, path); +} + +static void remove_file(sd_journal *j, const char *prefix, const char *filename) { + const char *path; + JournalFile *f; + + assert(j); + assert(prefix); + assert(filename); + + path = strjoina(prefix, "/", filename); + f = ordered_hashmap_get(j->files, path); + if (!f) + return; + + remove_file_real(j, f); +} + +static void remove_file_real(sd_journal *j, JournalFile *f) { + assert(j); + assert(f); + + ordered_hashmap_remove(j->files, f->path); + + log_debug("File %s removed.", f->path); + + if (j->current_file == f) { + j->current_file = NULL; + j->current_field = 0; + } + + if (j->unique_file == f) { + /* Jump to the next unique_file or NULL if that one was last */ + j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path); + j->unique_offset = 0; + if (!j->unique_file) + j->unique_file_lost = true; + } + + if (j->fields_file == f) { + j->fields_file = ordered_hashmap_next(j->files, j->fields_file->path); + j->fields_offset = 0; + if (!j->fields_file) + j->fields_file_lost = true; + } + + (void) journal_file_close(f); + + j->current_invalidate_counter++; +} + +static int dirname_is_machine_id(const char *fn) { + sd_id128_t id, machine; + int r; + + r = sd_id128_get_machine(&machine); + if (r < 0) + return r; + + r = sd_id128_from_string(fn, &id); + if (r < 0) + return r; + + return sd_id128_equal(id, machine); +} + +static int add_directory(sd_journal *j, const char *prefix, const char *dirname) { + _cleanup_free_ char *path = NULL; + _cleanup_closedir_ DIR *d = NULL; + struct dirent *de = NULL; + Directory *m; + int r, k; + + assert(j); + assert(prefix); + + /* Adds a journal file directory to watch. If the directory is already tracked this updates the inotify watch + * and reenumerates directory contents */ + + if (dirname) + path = strjoin(prefix, "/", dirname, NULL); + else + path = strdup(prefix); + if (!path) { + r = -ENOMEM; + goto fail; + } + + log_debug("Considering directory %s.", path); + + /* We consider everything local that is in a directory for the local machine ID, or that is stored in /run */ + if ((j->flags & SD_JOURNAL_LOCAL_ONLY) && + !((dirname && dirname_is_machine_id(dirname) > 0) || path_has_prefix(j, path, "/run"))) + return 0; + + + if (j->toplevel_fd < 0) + d = opendir(path); + else + /* Open the specified directory relative to the toplevel fd. Enforce that the path specified is + * relative, by dropping the initial slash */ + d = xopendirat(j->toplevel_fd, skip_slash(path), 0); + if (!d) { + r = log_debug_errno(errno, "Failed to open directory %s: %m", path); + goto fail; + } + + m = hashmap_get(j->directories_by_path, path); + if (!m) { + m = new0(Directory, 1); + if (!m) { + r = -ENOMEM; + goto fail; + } + + m->is_root = false; + m->path = path; + + if (hashmap_put(j->directories_by_path, m->path, m) < 0) { + free(m); + r = -ENOMEM; + goto fail; + } + + path = NULL; /* avoid freeing in cleanup */ + j->current_invalidate_counter++; + + log_debug("Directory %s added.", m->path); + + } else if (m->is_root) + return 0; + + if (m->wd <= 0 && j->inotify_fd >= 0) { + /* Watch this directory, if it not being watched yet. */ + + m->wd = inotify_add_watch_fd(j->inotify_fd, dirfd(d), + IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE| + IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT|IN_MOVED_FROM| + IN_ONLYDIR); + + if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0) + inotify_rm_watch(j->inotify_fd, m->wd); + } + + FOREACH_DIRENT_ALL(de, d, r = log_debug_errno(errno, "Failed to read directory %s: %m", m->path); goto fail) { + + if (dirent_is_file_with_suffix(de, ".journal") || + dirent_is_file_with_suffix(de, ".journal~")) + (void) add_file(j, m->path, de->d_name); + } + + check_network(j, dirfd(d)); + + return 0; + +fail: + k = journal_put_error(j, r, path ?: prefix); + if (k < 0) + return k; + + return r; +} + +static int add_root_directory(sd_journal *j, const char *p, bool missing_ok) { + + _cleanup_closedir_ DIR *d = NULL; + struct dirent *de; + Directory *m; + int r, k; + + assert(j); + + /* Adds a root directory to our set of directories to use. If the root directory is already in the set, we + * update the inotify logic, and renumerate the directory entries. This call may hence be called to initially + * populate the set, as well as to update it later. */ + + if (p) { + /* If there's a path specified, use it. */ + + if ((j->flags & SD_JOURNAL_RUNTIME_ONLY) && + !path_has_prefix(j, p, "/run")) + return -EINVAL; + + if (j->prefix) + p = strjoina(j->prefix, p); + + if (j->toplevel_fd < 0) + d = opendir(p); + else + d = xopendirat(j->toplevel_fd, skip_slash(p), 0); + + if (!d) { + if (errno == ENOENT && missing_ok) + return 0; + + r = log_debug_errno(errno, "Failed to open root directory %s: %m", p); + goto fail; + } + } else { + int dfd; + + /* If there's no path specified, then we use the top-level fd itself. We duplicate the fd here, since + * opendir() will take possession of the fd, and close it, which we don't want. */ + + p = "."; /* store this as "." in the directories hashmap */ + + dfd = fcntl(j->toplevel_fd, F_DUPFD_CLOEXEC, 3); + if (dfd < 0) { + r = -errno; + goto fail; + } + + d = fdopendir(dfd); + if (!d) { + r = -errno; + safe_close(dfd); + goto fail; + } + + rewinddir(d); + } + + m = hashmap_get(j->directories_by_path, p); + if (!m) { + m = new0(Directory, 1); + if (!m) { + r = -ENOMEM; + goto fail; + } + + m->is_root = true; + + m->path = strdup(p); + if (!m->path) { + free(m); + r = -ENOMEM; + goto fail; + } + + if (hashmap_put(j->directories_by_path, m->path, m) < 0) { + free(m->path); + free(m); + r = -ENOMEM; + goto fail; + } + + j->current_invalidate_counter++; + + log_debug("Root directory %s added.", m->path); + + } else if (!m->is_root) + return 0; + + if (m->wd <= 0 && j->inotify_fd >= 0) { + + m->wd = inotify_add_watch_fd(j->inotify_fd, dirfd(d), + IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB|IN_DELETE| + IN_ONLYDIR); + + if (m->wd > 0 && hashmap_put(j->directories_by_wd, INT_TO_PTR(m->wd), m) < 0) + inotify_rm_watch(j->inotify_fd, m->wd); + } + + if (j->no_new_files) + return 0; + + FOREACH_DIRENT_ALL(de, d, r = log_debug_errno(errno, "Failed to read directory %s: %m", m->path); goto fail) { + sd_id128_t id; + + if (dirent_is_file_with_suffix(de, ".journal") || + dirent_is_file_with_suffix(de, ".journal~")) + (void) add_file(j, m->path, de->d_name); + else if (IN_SET(de->d_type, DT_DIR, DT_LNK, DT_UNKNOWN) && + sd_id128_from_string(de->d_name, &id) >= 0) + (void) add_directory(j, m->path, de->d_name); + } + + check_network(j, dirfd(d)); + + return 0; + +fail: + k = journal_put_error(j, r, p); + if (k < 0) + return k; + + return r; +} + +static void remove_directory(sd_journal *j, Directory *d) { + assert(j); + + if (d->wd > 0) { + hashmap_remove(j->directories_by_wd, INT_TO_PTR(d->wd)); + + if (j->inotify_fd >= 0) + inotify_rm_watch(j->inotify_fd, d->wd); + } + + hashmap_remove(j->directories_by_path, d->path); + + if (d->is_root) + log_debug("Root directory %s removed.", d->path); + else + log_debug("Directory %s removed.", d->path); + + free(d->path); + free(d); +} + +static int add_search_paths(sd_journal *j) { + + static const char search_paths[] = + "/run/log/journal\0" + "/var/log/journal\0"; + const char *p; + + assert(j); + + /* We ignore most errors here, since the idea is to only open + * what's actually accessible, and ignore the rest. */ + + NULSTR_FOREACH(p, search_paths) + (void) add_root_directory(j, p, true); + + return 0; +} + +static int add_current_paths(sd_journal *j) { + Iterator i; + JournalFile *f; + + assert(j); + assert(j->no_new_files); + + /* Simply adds all directories for files we have open as directories. We don't expect errors here, so we + * treat them as fatal. */ + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + _cleanup_free_ char *dir; + int r; + + dir = dirname_malloc(f->path); + if (!dir) + return -ENOMEM; + + r = add_directory(j, dir, NULL); + if (r < 0) + return r; + } + + return 0; +} + +static int allocate_inotify(sd_journal *j) { + assert(j); + + if (j->inotify_fd < 0) { + j->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC); + if (j->inotify_fd < 0) + return -errno; + } + + return hashmap_ensure_allocated(&j->directories_by_wd, NULL); +} + +static sd_journal *journal_new(int flags, const char *path) { + sd_journal *j; + + j = new0(sd_journal, 1); + if (!j) + return NULL; + + j->original_pid = getpid(); + j->toplevel_fd = -1; + j->inotify_fd = -1; + j->flags = flags; + j->data_threshold = DEFAULT_DATA_THRESHOLD; + + if (path) { + j->path = strdup(path); + if (!j->path) + goto fail; + } + + j->files = ordered_hashmap_new(&string_hash_ops); + j->directories_by_path = hashmap_new(&string_hash_ops); + j->mmap = mmap_cache_new(); + if (!j->files || !j->directories_by_path || !j->mmap) + goto fail; + + return j; + +fail: + sd_journal_close(j); + return NULL; +} + +_public_ int sd_journal_open(sd_journal **ret, int flags) { + sd_journal *j; + int r; + + assert_return(ret, -EINVAL); + assert_return((flags & ~(SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_RUNTIME_ONLY|SD_JOURNAL_SYSTEM|SD_JOURNAL_CURRENT_USER)) == 0, -EINVAL); + + j = journal_new(flags, NULL); + if (!j) + return -ENOMEM; + + r = add_search_paths(j); + if (r < 0) + goto fail; + + *ret = j; + return 0; + +fail: + sd_journal_close(j); + + return r; +} + +_public_ int sd_journal_open_container(sd_journal **ret, const char *machine, int flags) { + _cleanup_free_ char *root = NULL, *class = NULL; + sd_journal *j; + char *p; + int r; + + /* This is pretty much deprecated, people should use machined's OpenMachineRootDirectory() call instead in + * combination with sd_journal_open_directory_fd(). */ + + assert_return(machine, -EINVAL); + assert_return(ret, -EINVAL); + assert_return((flags & ~(SD_JOURNAL_LOCAL_ONLY|SD_JOURNAL_SYSTEM)) == 0, -EINVAL); + assert_return(machine_name_is_valid(machine), -EINVAL); + + p = strjoina("/run/systemd/machines/", machine); + r = parse_env_file(p, NEWLINE, "ROOT", &root, "CLASS", &class, NULL); + if (r == -ENOENT) + return -EHOSTDOWN; + if (r < 0) + return r; + if (!root) + return -ENODATA; + + if (!streq_ptr(class, "container")) + return -EIO; + + j = journal_new(flags, NULL); + if (!j) + return -ENOMEM; + + j->prefix = root; + root = NULL; + + r = add_search_paths(j); + if (r < 0) + goto fail; + + *ret = j; + return 0; + +fail: + sd_journal_close(j); + return r; +} + +_public_ int sd_journal_open_directory(sd_journal **ret, const char *path, int flags) { + sd_journal *j; + int r; + + assert_return(ret, -EINVAL); + assert_return(path, -EINVAL); + assert_return((flags & ~SD_JOURNAL_OS_ROOT) == 0, -EINVAL); + + j = journal_new(flags, path); + if (!j) + return -ENOMEM; + + if (flags & SD_JOURNAL_OS_ROOT) + r = add_search_paths(j); + else + r = add_root_directory(j, path, false); + if (r < 0) + goto fail; + + *ret = j; + return 0; + +fail: + sd_journal_close(j); + return r; +} + +_public_ int sd_journal_open_files(sd_journal **ret, const char **paths, int flags) { + sd_journal *j; + const char **path; + int r; + + assert_return(ret, -EINVAL); + assert_return(flags == 0, -EINVAL); + + j = journal_new(flags, NULL); + if (!j) + return -ENOMEM; + + STRV_FOREACH(path, paths) { + r = add_any_file(j, -1, *path); + if (r < 0) + goto fail; + } + + j->no_new_files = true; + + *ret = j; + return 0; + +fail: + sd_journal_close(j); + return r; +} + +_public_ int sd_journal_open_directory_fd(sd_journal **ret, int fd, int flags) { + sd_journal *j; + struct stat st; + int r; + + assert_return(ret, -EINVAL); + assert_return(fd >= 0, -EBADF); + assert_return((flags & ~SD_JOURNAL_OS_ROOT) == 0, -EINVAL); + + if (fstat(fd, &st) < 0) + return -errno; + + if (!S_ISDIR(st.st_mode)) + return -EBADFD; + + j = journal_new(flags, NULL); + if (!j) + return -ENOMEM; + + j->toplevel_fd = fd; + + if (flags & SD_JOURNAL_OS_ROOT) + r = add_search_paths(j); + else + r = add_root_directory(j, NULL, false); + if (r < 0) + goto fail; + + *ret = j; + return 0; + +fail: + sd_journal_close(j); + return r; +} + +_public_ int sd_journal_open_files_fd(sd_journal **ret, int fds[], unsigned n_fds, int flags) { + Iterator iterator; + JournalFile *f; + sd_journal *j; + unsigned i; + int r; + + assert_return(ret, -EINVAL); + assert_return(n_fds > 0, -EBADF); + assert_return(flags == 0, -EINVAL); + + j = journal_new(flags, NULL); + if (!j) + return -ENOMEM; + + for (i = 0; i < n_fds; i++) { + struct stat st; + + if (fds[i] < 0) { + r = -EBADF; + goto fail; + } + + if (fstat(fds[i], &st) < 0) { + r = -errno; + goto fail; + } + + if (!S_ISREG(st.st_mode)) { + r = -EBADFD; + goto fail; + } + + r = add_any_file(j, fds[i], NULL); + if (r < 0) + goto fail; + } + + j->no_new_files = true; + j->no_inotify = true; + + *ret = j; + return 0; + +fail: + /* If we fail, make sure we don't take possession of the files we managed to make use of successfully, and they + * remain open */ + ORDERED_HASHMAP_FOREACH(f, j->files, iterator) + f->close_fd = false; + + sd_journal_close(j); + return r; +} + +_public_ void sd_journal_close(sd_journal *j) { + Directory *d; + JournalFile *f; + char *p; + + if (!j) + return; + + sd_journal_flush_matches(j); + + while ((f = ordered_hashmap_steal_first(j->files))) + (void) journal_file_close(f); + + ordered_hashmap_free(j->files); + + while ((d = hashmap_first(j->directories_by_path))) + remove_directory(j, d); + + while ((d = hashmap_first(j->directories_by_wd))) + remove_directory(j, d); + + hashmap_free(j->directories_by_path); + hashmap_free(j->directories_by_wd); + + safe_close(j->inotify_fd); + + if (j->mmap) { + log_debug("mmap cache statistics: %u hit, %u miss", mmap_cache_get_hit(j->mmap), mmap_cache_get_missed(j->mmap)); + mmap_cache_unref(j->mmap); + } + + while ((p = hashmap_steal_first(j->errors))) + free(p); + hashmap_free(j->errors); + + free(j->path); + free(j->prefix); + free(j->unique_field); + free(j->fields_buffer); + free(j); +} + +_public_ int sd_journal_get_realtime_usec(sd_journal *j, uint64_t *ret) { + Object *o; + JournalFile *f; + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(ret, -EINVAL); + + f = j->current_file; + if (!f) + return -EADDRNOTAVAIL; + + if (f->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); + if (r < 0) + return r; + + *ret = le64toh(o->entry.realtime); + return 0; +} + +_public_ int sd_journal_get_monotonic_usec(sd_journal *j, uint64_t *ret, sd_id128_t *ret_boot_id) { + Object *o; + JournalFile *f; + int r; + sd_id128_t id; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + f = j->current_file; + if (!f) + return -EADDRNOTAVAIL; + + if (f->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); + if (r < 0) + return r; + + if (ret_boot_id) + *ret_boot_id = o->entry.boot_id; + else { + r = sd_id128_get_boot(&id); + if (r < 0) + return r; + + if (!sd_id128_equal(id, o->entry.boot_id)) + return -ESTALE; + } + + if (ret) + *ret = le64toh(o->entry.monotonic); + + return 0; +} + +static bool field_is_valid(const char *field) { + const char *p; + + assert(field); + + if (isempty(field)) + return false; + + if (startswith(field, "__")) + return false; + + for (p = field; *p; p++) { + + if (*p == '_') + continue; + + if (*p >= 'A' && *p <= 'Z') + continue; + + if (*p >= '0' && *p <= '9') + continue; + + return false; + } + + return true; +} + +_public_ int sd_journal_get_data(sd_journal *j, const char *field, const void **data, size_t *size) { + JournalFile *f; + uint64_t i, n; + size_t field_length; + int r; + Object *o; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(field, -EINVAL); + assert_return(data, -EINVAL); + assert_return(size, -EINVAL); + assert_return(field_is_valid(field), -EINVAL); + + f = j->current_file; + if (!f) + return -EADDRNOTAVAIL; + + if (f->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); + if (r < 0) + return r; + + field_length = strlen(field); + + n = journal_file_entry_n_items(o); + for (i = 0; i < n; i++) { + uint64_t p, l; + le64_t le_hash; + size_t t; + int compression; + + p = le64toh(o->entry.items[i].object_offset); + le_hash = o->entry.items[i].hash; + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + if (le_hash != o->data.hash) + return -EBADMSG; + + l = le64toh(o->object.size) - offsetof(Object, data.payload); + + compression = o->object.flags & OBJECT_COMPRESSION_MASK; + if (compression) { +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + r = decompress_startswith(compression, + o->data.payload, l, + &f->compress_buffer, &f->compress_buffer_size, + field, field_length, '='); + if (r < 0) + log_debug_errno(r, "Cannot decompress %s object of length %"PRIu64" at offset "OFSfmt": %m", + object_compressed_to_string(compression), l, p); + else if (r > 0) { + + size_t rsize; + + r = decompress_blob(compression, + o->data.payload, l, + &f->compress_buffer, &f->compress_buffer_size, &rsize, + j->data_threshold); + if (r < 0) + return r; + + *data = f->compress_buffer; + *size = (size_t) rsize; + + return 0; + } +#else + return -EPROTONOSUPPORT; +#endif + } else if (l >= field_length+1 && + memcmp(o->data.payload, field, field_length) == 0 && + o->data.payload[field_length] == '=') { + + t = (size_t) l; + + if ((uint64_t) t != l) + return -E2BIG; + + *data = o->data.payload; + *size = t; + + return 0; + } + + r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); + if (r < 0) + return r; + } + + return -ENOENT; +} + +static int return_data(sd_journal *j, JournalFile *f, Object *o, const void **data, size_t *size) { + size_t t; + uint64_t l; + int compression; + + l = le64toh(o->object.size) - offsetof(Object, data.payload); + t = (size_t) l; + + /* We can't read objects larger than 4G on a 32bit machine */ + if ((uint64_t) t != l) + return -E2BIG; + + compression = o->object.flags & OBJECT_COMPRESSION_MASK; + if (compression) { +#if defined(HAVE_XZ) || defined(HAVE_LZ4) + size_t rsize; + int r; + + r = decompress_blob(compression, + o->data.payload, l, &f->compress_buffer, + &f->compress_buffer_size, &rsize, j->data_threshold); + if (r < 0) + return r; + + *data = f->compress_buffer; + *size = (size_t) rsize; +#else + return -EPROTONOSUPPORT; +#endif + } else { + *data = o->data.payload; + *size = t; + } + + return 0; +} + +_public_ int sd_journal_enumerate_data(sd_journal *j, const void **data, size_t *size) { + JournalFile *f; + uint64_t p, n; + le64_t le_hash; + int r; + Object *o; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(data, -EINVAL); + assert_return(size, -EINVAL); + + f = j->current_file; + if (!f) + return -EADDRNOTAVAIL; + + if (f->current_offset <= 0) + return -EADDRNOTAVAIL; + + r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); + if (r < 0) + return r; + + n = journal_file_entry_n_items(o); + if (j->current_field >= n) + return 0; + + p = le64toh(o->entry.items[j->current_field].object_offset); + le_hash = o->entry.items[j->current_field].hash; + r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); + if (r < 0) + return r; + + if (le_hash != o->data.hash) + return -EBADMSG; + + r = return_data(j, f, o, data, size); + if (r < 0) + return r; + + j->current_field++; + + return 1; +} + +_public_ void sd_journal_restart_data(sd_journal *j) { + if (!j) + return; + + j->current_field = 0; +} + +_public_ int sd_journal_get_fd(sd_journal *j) { + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + if (j->no_inotify) + return -EMEDIUMTYPE; + + if (j->inotify_fd >= 0) + return j->inotify_fd; + + r = allocate_inotify(j); + if (r < 0) + return r; + + log_debug("Reiterating files to get inotify watches established"); + + /* Iterate through all dirs again, to add them to the + * inotify */ + if (j->no_new_files) + r = add_current_paths(j); + else if (j->toplevel_fd >= 0) + r = add_root_directory(j, NULL, false); + else if (j->path) + r = add_root_directory(j, j->path, true); + else + r = add_search_paths(j); + if (r < 0) + return r; + + return j->inotify_fd; +} + +_public_ int sd_journal_get_events(sd_journal *j) { + int fd; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + fd = sd_journal_get_fd(j); + if (fd < 0) + return fd; + + return POLLIN; +} + +_public_ int sd_journal_get_timeout(sd_journal *j, uint64_t *timeout_usec) { + int fd; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(timeout_usec, -EINVAL); + + fd = sd_journal_get_fd(j); + if (fd < 0) + return fd; + + if (!j->on_network) { + *timeout_usec = (uint64_t) -1; + return 0; + } + + /* If we are on the network we need to regularly check for + * changes manually */ + + *timeout_usec = j->last_process_usec + JOURNAL_FILES_RECHECK_USEC; + return 1; +} + +static void process_inotify_event(sd_journal *j, struct inotify_event *e) { + Directory *d; + + assert(j); + assert(e); + + /* Is this a subdirectory we watch? */ + d = hashmap_get(j->directories_by_wd, INT_TO_PTR(e->wd)); + if (d) { + sd_id128_t id; + + if (!(e->mask & IN_ISDIR) && e->len > 0 && + (endswith(e->name, ".journal") || + endswith(e->name, ".journal~"))) { + + /* Event for a journal file */ + + if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) + (void) add_file(j, d->path, e->name); + else if (e->mask & (IN_DELETE|IN_MOVED_FROM|IN_UNMOUNT)) + remove_file(j, d->path, e->name); + + } else if (!d->is_root && e->len == 0) { + + /* Event for a subdirectory */ + + if (e->mask & (IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT)) + remove_directory(j, d); + + } else if (d->is_root && (e->mask & IN_ISDIR) && e->len > 0 && sd_id128_from_string(e->name, &id) >= 0) { + + /* Event for root directory */ + + if (e->mask & (IN_CREATE|IN_MOVED_TO|IN_MODIFY|IN_ATTRIB)) + (void) add_directory(j, d->path, e->name); + } + + return; + } + + if (e->mask & IN_IGNORED) + return; + + log_debug("Unknown inotify event."); +} + +static int determine_change(sd_journal *j) { + bool b; + + assert(j); + + b = j->current_invalidate_counter != j->last_invalidate_counter; + j->last_invalidate_counter = j->current_invalidate_counter; + + return b ? SD_JOURNAL_INVALIDATE : SD_JOURNAL_APPEND; +} + +_public_ int sd_journal_process(sd_journal *j) { + bool got_something = false; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + j->last_process_usec = now(CLOCK_MONOTONIC); + + for (;;) { + union inotify_event_buffer buffer; + struct inotify_event *e; + ssize_t l; + + l = read(j->inotify_fd, &buffer, sizeof(buffer)); + if (l < 0) { + if (errno == EAGAIN || errno == EINTR) + return got_something ? determine_change(j) : SD_JOURNAL_NOP; + + return -errno; + } + + got_something = true; + + FOREACH_INOTIFY_EVENT(e, buffer, l) + process_inotify_event(j, e); + } +} + +_public_ int sd_journal_wait(sd_journal *j, uint64_t timeout_usec) { + int r; + uint64_t t; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + if (j->inotify_fd < 0) { + + /* This is the first invocation, hence create the + * inotify watch */ + r = sd_journal_get_fd(j); + if (r < 0) + return r; + + /* The journal might have changed since the context + * object was created and we weren't watching before, + * hence don't wait for anything, and return + * immediately. */ + return determine_change(j); + } + + r = sd_journal_get_timeout(j, &t); + if (r < 0) + return r; + + if (t != (uint64_t) -1) { + usec_t n; + + n = now(CLOCK_MONOTONIC); + t = t > n ? t - n : 0; + + if (timeout_usec == (uint64_t) -1 || timeout_usec > t) + timeout_usec = t; + } + + do { + r = fd_wait_for_event(j->inotify_fd, POLLIN, timeout_usec); + } while (r == -EINTR); + + if (r < 0) + return r; + + return sd_journal_process(j); +} + +_public_ int sd_journal_get_cutoff_realtime_usec(sd_journal *j, uint64_t *from, uint64_t *to) { + Iterator i; + JournalFile *f; + bool first = true; + uint64_t fmin = 0, tmax = 0; + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(from || to, -EINVAL); + assert_return(from != to, -EINVAL); + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + usec_t fr, t; + + r = journal_file_get_cutoff_realtime_usec(f, &fr, &t); + if (r == -ENOENT) + continue; + if (r < 0) + return r; + if (r == 0) + continue; + + if (first) { + fmin = fr; + tmax = t; + first = false; + } else { + fmin = MIN(fr, fmin); + tmax = MAX(t, tmax); + } + } + + if (from) + *from = fmin; + if (to) + *to = tmax; + + return first ? 0 : 1; +} + +_public_ int sd_journal_get_cutoff_monotonic_usec(sd_journal *j, sd_id128_t boot_id, uint64_t *from, uint64_t *to) { + Iterator i; + JournalFile *f; + bool found = false; + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(from || to, -EINVAL); + assert_return(from != to, -EINVAL); + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + usec_t fr, t; + + r = journal_file_get_cutoff_monotonic_usec(f, boot_id, &fr, &t); + if (r == -ENOENT) + continue; + if (r < 0) + return r; + if (r == 0) + continue; + + if (found) { + if (from) + *from = MIN(fr, *from); + if (to) + *to = MAX(t, *to); + } else { + if (from) + *from = fr; + if (to) + *to = t; + found = true; + } + } + + return found; +} + +void journal_print_header(sd_journal *j) { + Iterator i; + JournalFile *f; + bool newline = false; + + assert(j); + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + if (newline) + putchar('\n'); + else + newline = true; + + journal_file_print_header(f); + } +} + +_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *bytes) { + Iterator i; + JournalFile *f; + uint64_t sum = 0; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(bytes, -EINVAL); + + ORDERED_HASHMAP_FOREACH(f, j->files, i) { + struct stat st; + + if (fstat(f->fd, &st) < 0) + return -errno; + + sum += (uint64_t) st.st_blocks * 512ULL; + } + + *bytes = sum; + return 0; +} + +_public_ int sd_journal_query_unique(sd_journal *j, const char *field) { + char *f; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(!isempty(field), -EINVAL); + assert_return(field_is_valid(field), -EINVAL); + + f = strdup(field); + if (!f) + return -ENOMEM; + + free(j->unique_field); + j->unique_field = f; + j->unique_file = NULL; + j->unique_offset = 0; + j->unique_file_lost = false; + + return 0; +} + +_public_ int sd_journal_enumerate_unique(sd_journal *j, const void **data, size_t *l) { + size_t k; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(data, -EINVAL); + assert_return(l, -EINVAL); + assert_return(j->unique_field, -EINVAL); + + k = strlen(j->unique_field); + + if (!j->unique_file) { + if (j->unique_file_lost) + return 0; + + j->unique_file = ordered_hashmap_first(j->files); + if (!j->unique_file) + return 0; + + j->unique_offset = 0; + } + + for (;;) { + JournalFile *of; + Iterator i; + Object *o; + const void *odata; + size_t ol; + bool found; + int r; + + /* Proceed to next data object in the field's linked list */ + if (j->unique_offset == 0) { + r = journal_file_find_field_object(j->unique_file, j->unique_field, k, &o, NULL); + if (r < 0) + return r; + + j->unique_offset = r > 0 ? le64toh(o->field.head_data_offset) : 0; + } else { + r = journal_file_move_to_object(j->unique_file, OBJECT_DATA, j->unique_offset, &o); + if (r < 0) + return r; + + j->unique_offset = le64toh(o->data.next_field_offset); + } + + /* We reached the end of the list? Then start again, with the next file */ + if (j->unique_offset == 0) { + j->unique_file = ordered_hashmap_next(j->files, j->unique_file->path); + if (!j->unique_file) + return 0; + + continue; + } + + /* We do not use OBJECT_DATA context here, but OBJECT_UNUSED + * instead, so that we can look at this data object at the same + * time as one on another file */ + r = journal_file_move_to_object(j->unique_file, OBJECT_UNUSED, j->unique_offset, &o); + if (r < 0) + return r; + + /* Let's do the type check by hand, since we used 0 context above. */ + if (o->object.type != OBJECT_DATA) { + log_debug("%s:offset " OFSfmt ": object has type %d, expected %d", + j->unique_file->path, j->unique_offset, + o->object.type, OBJECT_DATA); + return -EBADMSG; + } + + r = return_data(j, j->unique_file, o, &odata, &ol); + if (r < 0) + return r; + + /* Check if we have at least the field name and "=". */ + if (ol <= k) { + log_debug("%s:offset " OFSfmt ": object has size %zu, expected at least %zu", + j->unique_file->path, j->unique_offset, + ol, k + 1); + return -EBADMSG; + } + + if (memcmp(odata, j->unique_field, k) || ((const char*) odata)[k] != '=') { + log_debug("%s:offset " OFSfmt ": object does not start with \"%s=\"", + j->unique_file->path, j->unique_offset, + j->unique_field); + return -EBADMSG; + } + + /* OK, now let's see if we already returned this data + * object by checking if it exists in the earlier + * traversed files. */ + found = false; + ORDERED_HASHMAP_FOREACH(of, j->files, i) { + if (of == j->unique_file) + break; + + /* Skip this file it didn't have any fields indexed */ + if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0) + continue; + + r = journal_file_find_data_object_with_hash(of, odata, ol, le64toh(o->data.hash), NULL, NULL); + if (r < 0) + return r; + if (r > 0) { + found = true; + break; + } + } + + if (found) + continue; + + r = return_data(j, j->unique_file, o, data, l); + if (r < 0) + return r; + + return 1; + } +} + +_public_ void sd_journal_restart_unique(sd_journal *j) { + if (!j) + return; + + j->unique_file = NULL; + j->unique_offset = 0; + j->unique_file_lost = false; +} + +_public_ int sd_journal_enumerate_fields(sd_journal *j, const char **field) { + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(field, -EINVAL); + + if (!j->fields_file) { + if (j->fields_file_lost) + return 0; + + j->fields_file = ordered_hashmap_first(j->files); + if (!j->fields_file) + return 0; + + j->fields_hash_table_index = 0; + j->fields_offset = 0; + } + + for (;;) { + JournalFile *f, *of; + Iterator i; + uint64_t m; + Object *o; + size_t sz; + bool found; + + f = j->fields_file; + + if (j->fields_offset == 0) { + bool eof = false; + + /* We are not yet positioned at any field. Let's pick the first one */ + r = journal_file_map_field_hash_table(f); + if (r < 0) + return r; + + m = le64toh(f->header->field_hash_table_size) / sizeof(HashItem); + for (;;) { + if (j->fields_hash_table_index >= m) { + /* Reached the end of the hash table, go to the next file. */ + eof = true; + break; + } + + j->fields_offset = le64toh(f->field_hash_table[j->fields_hash_table_index].head_hash_offset); + + if (j->fields_offset != 0) + break; + + /* Empty hash table bucket, go to next one */ + j->fields_hash_table_index++; + } + + if (eof) { + /* Proceed with next file */ + j->fields_file = ordered_hashmap_next(j->files, f->path); + if (!j->fields_file) { + *field = NULL; + return 0; + } + + j->fields_offset = 0; + j->fields_hash_table_index = 0; + continue; + } + + } else { + /* We are already positioned at a field. If so, let's figure out the next field from it */ + + r = journal_file_move_to_object(f, OBJECT_FIELD, j->fields_offset, &o); + if (r < 0) + return r; + + j->fields_offset = le64toh(o->field.next_hash_offset); + if (j->fields_offset == 0) { + /* Reached the end of the hash table chain */ + j->fields_hash_table_index++; + continue; + } + } + + /* We use OBJECT_UNUSED here, so that the iterator below doesn't remove our mmap window */ + r = journal_file_move_to_object(f, OBJECT_UNUSED, j->fields_offset, &o); + if (r < 0) + return r; + + /* Because we used OBJECT_UNUSED above, we need to do our type check manually */ + if (o->object.type != OBJECT_FIELD) { + log_debug("%s:offset " OFSfmt ": object has type %i, expected %i", f->path, j->fields_offset, o->object.type, OBJECT_FIELD); + return -EBADMSG; + } + + sz = le64toh(o->object.size) - offsetof(Object, field.payload); + + /* Let's see if we already returned this field name before. */ + found = false; + ORDERED_HASHMAP_FOREACH(of, j->files, i) { + if (of == f) + break; + + /* Skip this file it didn't have any fields indexed */ + if (JOURNAL_HEADER_CONTAINS(of->header, n_fields) && le64toh(of->header->n_fields) <= 0) + continue; + + r = journal_file_find_field_object_with_hash(of, o->field.payload, sz, le64toh(o->field.hash), NULL, NULL); + if (r < 0) + return r; + if (r > 0) { + found = true; + break; + } + } + + if (found) + continue; + + /* Check if this is really a valid string containing no NUL byte */ + if (memchr(o->field.payload, 0, sz)) + return -EBADMSG; + + if (sz > j->data_threshold) + sz = j->data_threshold; + + if (!GREEDY_REALLOC(j->fields_buffer, j->fields_buffer_allocated, sz + 1)) + return -ENOMEM; + + memcpy(j->fields_buffer, o->field.payload, sz); + j->fields_buffer[sz] = 0; + + if (!field_is_valid(j->fields_buffer)) + return -EBADMSG; + + *field = j->fields_buffer; + return 1; + } +} + +_public_ void sd_journal_restart_fields(sd_journal *j) { + if (!j) + return; + + j->fields_file = NULL; + j->fields_hash_table_index = 0; + j->fields_offset = 0; + j->fields_file_lost = false; +} + +_public_ int sd_journal_reliable_fd(sd_journal *j) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + return !j->on_network; +} + +static char *lookup_field(const char *field, void *userdata) { + sd_journal *j = userdata; + const void *data; + size_t size, d; + int r; + + assert(field); + assert(j); + + r = sd_journal_get_data(j, field, &data, &size); + if (r < 0 || + size > REPLACE_VAR_MAX) + return strdup(field); + + d = strlen(field) + 1; + + return strndup((const char*) data + d, size - d); +} + +_public_ int sd_journal_get_catalog(sd_journal *j, char **ret) { + const void *data; + size_t size; + sd_id128_t id; + _cleanup_free_ char *text = NULL, *cid = NULL; + char *t; + int r; + + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(ret, -EINVAL); + + r = sd_journal_get_data(j, "MESSAGE_ID", &data, &size); + if (r < 0) + return r; + + cid = strndup((const char*) data + 11, size - 11); + if (!cid) + return -ENOMEM; + + r = sd_id128_from_string(cid, &id); + if (r < 0) + return r; + + r = catalog_get(CATALOG_DATABASE, id, &text); + if (r < 0) + return r; + + t = replace_var(text, lookup_field, j); + if (!t) + return -ENOMEM; + + *ret = t; + return 0; +} + +_public_ int sd_journal_get_catalog_for_message_id(sd_id128_t id, char **ret) { + assert_return(ret, -EINVAL); + + return catalog_get(CATALOG_DATABASE, id, ret); +} + +_public_ int sd_journal_set_data_threshold(sd_journal *j, size_t sz) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + + j->data_threshold = sz; + return 0; +} + +_public_ int sd_journal_get_data_threshold(sd_journal *j, size_t *sz) { + assert_return(j, -EINVAL); + assert_return(!journal_pid_changed(j), -ECHILD); + assert_return(sz, -EINVAL); + + *sz = j->data_threshold; + return 0; +} + +_public_ int sd_journal_has_runtime_files(sd_journal *j) { + assert_return(j, -EINVAL); + + return j->has_runtime_files; +} + +_public_ int sd_journal_has_persistent_files(sd_journal *j) { + assert_return(j, -EINVAL); + + return j->has_persistent_files; +} diff --git a/src/libsystemd/src/sd-login/Makefile b/src/libsystemd/src/sd-login/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-login/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-login/sd-login.c b/src/libsystemd/src/sd-login/sd-login.c index 3fcefada3f..9be4ec6c39 100644 --- a/src/libsystemd/sd-login/sd-login.c +++ b/src/libsystemd/src/sd-login/sd-login.c @@ -23,27 +23,27 @@ #include <sys/inotify.h> #include <unistd.h> -#include "sd-login.h" - -#include "alloc-util.h" -#include "cgroup-util.h" -#include "dirent-util.h" -#include "escape.h" -#include "fd-util.h" -#include "fileio.h" -#include "formats-util.h" -#include "fs-util.h" -#include "hostname-util.h" -#include "io-util.h" -#include "login-util.h" -#include "macro.h" -#include "parse-util.h" -#include "path-util.h" -#include "socket-util.h" -#include "string-util.h" -#include "strv.h" -#include "user-util.h" -#include "util.h" +#include <systemd/sd-login.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/cgroup-util.h" +#include "systemd-basic/dirent-util.h" +#include "systemd-basic/escape.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/hostname-util.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/login-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/path-util.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/user-util.h" +#include "systemd-basic/util.h" /* Error codes: * diff --git a/src/libsystemd/sd-login/test-login.c b/src/libsystemd/src/sd-login/test-login.c index c1fd7dd33e..348ce1e790 100644 --- a/src/libsystemd/sd-login/test-login.c +++ b/src/libsystemd/src/sd-login/test-login.c @@ -20,14 +20,14 @@ #include <poll.h> #include <string.h> -#include "sd-login.h" - -#include "alloc-util.h" -#include "fd-util.h" -#include "formats-util.h" -#include "string-util.h" -#include "strv.h" -#include "util.h" +#include <systemd/sd-login.h> + +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" static void test_login(void) { _cleanup_close_pair_ int pair[2] = { -1, -1 }; diff --git a/src/libsystemd/src/sd-netlink/Makefile b/src/libsystemd/src/sd-netlink/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-netlink/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-netlink/local-addresses.c b/src/libsystemd/src/sd-netlink/local-addresses.c index ed9ee041ab..74e1b2c2bf 100644 --- a/src/libsystemd/sd-netlink/local-addresses.c +++ b/src/libsystemd/src/sd-netlink/local-addresses.c @@ -18,11 +18,11 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-netlink.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/macro.h" +#include "systemd-staging/sd-netlink.h" -#include "alloc-util.h" #include "local-addresses.h" -#include "macro.h" #include "netlink-util.h" static int address_compare(const void *_a, const void *_b) { diff --git a/src/libsystemd/sd-netlink/local-addresses.h b/src/libsystemd/src/sd-netlink/local-addresses.h index 18d71e797e..f1e91ccfd2 100644 --- a/src/libsystemd/sd-netlink/local-addresses.h +++ b/src/libsystemd/src/sd-netlink/local-addresses.h @@ -20,9 +20,8 @@ ***/ -#include "sd-netlink.h" - -#include "in-addr-util.h" +#include "systemd-basic/in-addr-util.h" +#include "systemd-staging/sd-netlink.h" struct local_address { int family, ifindex; diff --git a/src/libsystemd/sd-netlink/netlink-internal.h b/src/libsystemd/src/sd-netlink/netlink-internal.h index dcfb080ad3..0df449a43c 100644 --- a/src/libsystemd/sd-netlink/netlink-internal.h +++ b/src/libsystemd/src/sd-netlink/netlink-internal.h @@ -21,12 +21,12 @@ #include <linux/netlink.h> -#include "sd-netlink.h" +#include "systemd-basic/list.h" +#include "systemd-basic/prioq.h" +#include "systemd-basic/refcnt.h" +#include "systemd-staging/sd-netlink.h" -#include "list.h" #include "netlink-types.h" -#include "prioq.h" -#include "refcnt.h" #define RTNL_DEFAULT_TIMEOUT ((usec_t) (25 * USEC_PER_SEC)) diff --git a/src/libsystemd/sd-netlink/netlink-message.c b/src/libsystemd/src/sd-netlink/netlink-message.c index df3b3c922e..73afe876b6 100644 --- a/src/libsystemd/sd-netlink/netlink-message.c +++ b/src/libsystemd/src/sd-netlink/netlink-message.c @@ -21,17 +21,17 @@ #include <stdbool.h> #include <unistd.h> -#include "sd-netlink.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" -#include "alloc-util.h" -#include "formats-util.h" -#include "missing.h" #include "netlink-internal.h" #include "netlink-types.h" #include "netlink-util.h" -#include "refcnt.h" -#include "socket-util.h" -#include "util.h" #define GET_CONTAINER(m, i) ((i) < (m)->n_containers ? (struct rtattr*)((uint8_t*)(m)->hdr + (m)->containers[i].offset) : NULL) #define PUSH_CONTAINER(m, new) (m)->container_offsets[(m)->n_containers++] = (uint8_t*)(new) - (uint8_t*)(m)->hdr; diff --git a/src/libsystemd/sd-netlink/netlink-socket.c b/src/libsystemd/src/sd-netlink/netlink-socket.c index c165fa3359..f9a0df9f20 100644 --- a/src/libsystemd/sd-netlink/netlink-socket.c +++ b/src/libsystemd/src/sd-netlink/netlink-socket.c @@ -21,17 +21,17 @@ #include <stdbool.h> #include <unistd.h> -#include "sd-netlink.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" -#include "alloc-util.h" -#include "formats-util.h" -#include "missing.h" #include "netlink-internal.h" #include "netlink-types.h" #include "netlink-util.h" -#include "refcnt.h" -#include "socket-util.h" -#include "util.h" int socket_open(int family) { int fd; diff --git a/src/libsystemd/sd-netlink/netlink-types.c b/src/libsystemd/src/sd-netlink/netlink-types.c index 566a050432..c3f3789fe5 100644 --- a/src/libsystemd/sd-netlink/netlink-types.c +++ b/src/libsystemd/src/sd-netlink/netlink-types.c @@ -19,6 +19,7 @@ #include <stdint.h> #include <sys/socket.h> + #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/in6.h> @@ -30,11 +31,12 @@ #include <linux/if_link.h> #include <linux/if_tunnel.h> -#include "macro.h" -#include "missing.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/string-table.h" +#include "systemd-basic/util.h" + #include "netlink-types.h" -#include "string-table.h" -#include "util.h" /* Maximum ARP IP target defined in kernel */ #define BOND_MAX_ARP_TARGETS 16 diff --git a/src/libsystemd/sd-netlink/netlink-types.h b/src/libsystemd/src/sd-netlink/netlink-types.h index 7c0e598b26..3cd57715c3 100644 --- a/src/libsystemd/sd-netlink/netlink-types.h +++ b/src/libsystemd/src/sd-netlink/netlink-types.h @@ -19,7 +19,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "macro.h" +#include "systemd-basic/macro.h" enum { NETLINK_TYPE_UNSPEC, diff --git a/src/libsystemd/sd-netlink/netlink-util.c b/src/libsystemd/src/sd-netlink/netlink-util.c index 73b9ac0258..4bb99b00af 100644 --- a/src/libsystemd/sd-netlink/netlink-util.c +++ b/src/libsystemd/src/sd-netlink/netlink-util.c @@ -17,7 +17,7 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-netlink.h" +#include "systemd-staging/sd-netlink.h" #include "netlink-internal.h" #include "netlink-util.h" diff --git a/src/libsystemd/sd-netlink/netlink-util.h b/src/libsystemd/src/sd-netlink/netlink-util.h index f49bf4eaa6..9fc80af61d 100644 --- a/src/libsystemd/sd-netlink/netlink-util.h +++ b/src/libsystemd/src/sd-netlink/netlink-util.h @@ -19,9 +19,8 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-netlink.h" - -#include "util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" int rtnl_message_new_synthetic_error(int error, uint32_t serial, sd_netlink_message **ret); uint32_t rtnl_message_get_serial(sd_netlink_message *m); diff --git a/src/libsystemd/sd-netlink/rtnl-message.c b/src/libsystemd/src/sd-netlink/rtnl-message.c index 09240c7b2a..315da4f0ca 100644 --- a/src/libsystemd/sd-netlink/rtnl-message.c +++ b/src/libsystemd/src/sd-netlink/rtnl-message.c @@ -21,16 +21,16 @@ #include <stdbool.h> #include <unistd.h> -#include "sd-netlink.h" +#include "systemd-basic/formats-util.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/refcnt.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" -#include "formats-util.h" -#include "missing.h" #include "netlink-internal.h" #include "netlink-types.h" #include "netlink-util.h" -#include "refcnt.h" -#include "socket-util.h" -#include "util.h" int sd_rtnl_message_route_set_dst_prefixlen(sd_netlink_message *m, unsigned char prefixlen) { struct rtmsg *rtm; diff --git a/src/libsystemd/sd-netlink/sd-netlink.c b/src/libsystemd/src/sd-netlink/sd-netlink.c index 43114eb825..4999f59d24 100644 --- a/src/libsystemd/sd-netlink/sd-netlink.c +++ b/src/libsystemd/src/sd-netlink/sd-netlink.c @@ -20,17 +20,17 @@ #include <poll.h> #include <sys/socket.h> -#include "sd-netlink.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/hashmap.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" -#include "alloc-util.h" -#include "fd-util.h" -#include "hashmap.h" -#include "macro.h" -#include "missing.h" #include "netlink-internal.h" #include "netlink-util.h" -#include "socket-util.h" -#include "util.h" static int sd_netlink_new(sd_netlink **ret) { _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL; diff --git a/src/libsystemd/sd-netlink/test-local-addresses.c b/src/libsystemd/src/sd-netlink/test-local-addresses.c index e0e28cc0cc..b08cac9907 100644 --- a/src/libsystemd/sd-netlink/test-local-addresses.c +++ b/src/libsystemd/src/sd-netlink/test-local-addresses.c @@ -17,9 +17,10 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "af-list.h" -#include "alloc-util.h" -#include "in-addr-util.h" +#include "systemd-basic/af-list.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/in-addr-util.h" + #include "local-addresses.h" static void print_local_addresses(struct local_address *a, unsigned n) { diff --git a/src/libsystemd/sd-netlink/test-netlink.c b/src/libsystemd/src/sd-netlink/test-netlink.c index 58c2e892f5..b16419a3ab 100644 --- a/src/libsystemd/sd-netlink/test-netlink.c +++ b/src/libsystemd/src/sd-netlink/test-netlink.c @@ -20,15 +20,15 @@ #include <net/if.h> #include <netinet/ether.h> -#include "sd-netlink.h" +#include "systemd-basic/ether-addr-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-netlink.h" -#include "ether-addr-util.h" -#include "macro.h" -#include "missing.h" #include "netlink-util.h" -#include "socket-util.h" -#include "string-util.h" -#include "util.h" static void test_message_link_bridge(sd_netlink *rtnl) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *message = NULL; diff --git a/src/libsystemd/src/sd-network/Makefile b/src/libsystemd/src/sd-network/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-network/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-network/network-util.c b/src/libsystemd/src/sd-network/network-util.c index a0d9b5f1a4..317a7ac804 100644 --- a/src/libsystemd/sd-network/network-util.c +++ b/src/libsystemd/src/sd-network/network-util.c @@ -17,10 +17,11 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "alloc-util.h" -#include "fd-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/strv.h" + #include "network-util.h" -#include "strv.h" bool network_is_online(void) { _cleanup_free_ char *state = NULL; diff --git a/src/libsystemd/sd-network/network-util.h b/src/libsystemd/src/sd-network/network-util.h index 26780dce28..4527ed7c0f 100644 --- a/src/libsystemd/sd-network/network-util.h +++ b/src/libsystemd/src/sd-network/network-util.h @@ -19,6 +19,6 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-network.h" +#include "systemd-staging/sd-network.h" bool network_is_online(void); diff --git a/src/libsystemd/sd-network/sd-network.c b/src/libsystemd/src/sd-network/sd-network.c index f8e18f23fd..2467fdb7ff 100644 --- a/src/libsystemd/sd-network/sd-network.c +++ b/src/libsystemd/src/sd-network/sd-network.c @@ -23,18 +23,17 @@ #include <string.h> #include <sys/inotify.h> -#include "sd-network.h" - -#include "alloc-util.h" -#include "fd-util.h" -#include "fileio.h" -#include "fs-util.h" -#include "macro.h" -#include "parse-util.h" -#include "stdio-util.h" -#include "string-util.h" -#include "strv.h" -#include "util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/fileio.h" +#include "systemd-basic/fs-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/parse-util.h" +#include "systemd-basic/stdio-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-basic/strv.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-network.h" _public_ int sd_network_get_operational_state(char **state) { _cleanup_free_ char *s = NULL; diff --git a/src/libsystemd/src/sd-resolve/Makefile b/src/libsystemd/src/sd-resolve/Makefile new file mode 120000 index 0000000000..71a1159ce0 --- /dev/null +++ b/src/libsystemd/src/sd-resolve/Makefile @@ -0,0 +1 @@ +../subdir.mk
\ No newline at end of file diff --git a/src/libsystemd/sd-resolve/sd-resolve.c b/src/libsystemd/src/sd-resolve/sd-resolve.c index 60aa55de3b..629eeb7799 100644 --- a/src/libsystemd/sd-resolve/sd-resolve.c +++ b/src/libsystemd/src/sd-resolve/sd-resolve.c @@ -29,15 +29,14 @@ #include <sys/prctl.h> #include <unistd.h> -#include "sd-resolve.h" - -#include "alloc-util.h" -#include "fd-util.h" -#include "io-util.h" -#include "list.h" -#include "missing.h" -#include "socket-util.h" -#include "util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/fd-util.h" +#include "systemd-basic/io-util.h" +#include "systemd-basic/list.h" +#include "systemd-basic/missing.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/util.h" +#include "systemd-staging/sd-resolve.h" #define WORKERS_MIN 1U #define WORKERS_MAX 16U diff --git a/src/libsystemd/sd-resolve/test-resolve.c b/src/libsystemd/src/sd-resolve/test-resolve.c index 1be1a7f8a7..0a5bba81cf 100644 --- a/src/libsystemd/sd-resolve/test-resolve.c +++ b/src/libsystemd/src/sd-resolve/test-resolve.c @@ -26,12 +26,11 @@ #include <string.h> #include <sys/socket.h> -#include "sd-resolve.h" - -#include "alloc-util.h" -#include "macro.h" -#include "socket-util.h" -#include "string-util.h" +#include "systemd-basic/alloc-util.h" +#include "systemd-basic/macro.h" +#include "systemd-basic/socket-util.h" +#include "systemd-basic/string-util.h" +#include "systemd-staging/sd-resolve.h" static int getaddrinfo_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) { const struct addrinfo *i; diff --git a/src/libsystemd/sd-utf8/sd-utf8.c b/src/libsystemd/src/sd-utf8/sd-utf8.c index 33a5a04ea1..e00ec94390 100644 --- a/src/libsystemd/sd-utf8/sd-utf8.c +++ b/src/libsystemd/src/sd-utf8/sd-utf8.c @@ -17,10 +17,10 @@ along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ -#include "sd-utf8.h" +#include <systemd/sd-utf8.h> -#include "utf8.h" -#include "util.h" +#include "systemd-basic/utf8.h" +#include "systemd-basic/util.h" _public_ const char *sd_utf8_is_valid(const char *s) { assert_return(s, NULL); diff --git a/src/libsystemd/src/subdir.mk b/src/libsystemd/src/subdir.mk new file mode 100644 index 0000000000..605b592401 --- /dev/null +++ b/src/libsystemd/src/subdir.mk @@ -0,0 +1,29 @@ +# -*- Mode: makefile; indent-tabs-mode: t -*- +# +# This file is part of systemd. +# +# Copyright 2010-2012 Lennart Poettering +# Copyright 2010-2012 Kay Sievers +# Copyright 2013 Zbigniew Jędrzejewski-Szmek +# Copyright 2013 David Strauss +# Copyright 2016 Luke Shumaker +# +# 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 <http://www.gnu.org/licenses/>. +include $(dir $(lastword $(MAKEFILE_LIST)))/../../config.mk +include $(topsrcdir)/build-aux/Makefile.head.mk + +sd.CPPFLAGS += -DLIBDIR=\"$(libdir)\" +sd.CPPFLAGS += -DUDEVLIBEXECDIR=\"$(udevlibexecdir)\" + +include $(topsrcdir)/build-aux/Makefile.tail.mk diff --git a/src/libsystemd/src/test.mk b/src/libsystemd/src/test.mk new file mode 100644 index 0000000000..81df4ca83d --- /dev/null +++ b/src/libsystemd/src/test.mk @@ -0,0 +1,155 @@ +# -*- Mode: makefile; indent-tabs-mode: t -*- +# +# This file is part of systemd. +# +# Copyright 2010-2012 Lennart Poettering +# Copyright 2010-2012 Kay Sievers +# Copyright 2013 Zbigniew Jędrzejewski-Szmek +# Copyright 2013 David Strauss +# Copyright 2016 Luke Shumaker +# +# 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 <http://www.gnu.org/licenses/>. +include $(dir $(lastword $(MAKEFILE_LIST)))/../../config.mk +include $(topsrcdir)/build-aux/Makefile.head.mk + +test_bus_marshal_SOURCES = \ + src/libsystemd/sd-bus/test-bus-marshal.c + +test_bus_marshal_LDADD = \ + libsystemd-shared.la \ + $(GLIB_LIBS) \ + $(DBUS_LIBS) + +test_bus_marshal_CFLAGS = \ + $(GLIB_CFLAGS) \ + $(DBUS_CFLAGS) + +test_bus_signature_SOURCES = \ + src/libsystemd/sd-bus/test-bus-signature.c + +test_bus_signature_LDADD = \ + libsystemd-shared.la + +test_bus_chat_SOURCES = \ + src/libsystemd/sd-bus/test-bus-chat.c + +test_bus_chat_LDADD = \ + libsystemd-shared.la + +test_bus_cleanup_SOURCES = \ + src/libsystemd/sd-bus/test-bus-cleanup.c + +test_bus_cleanup_CFLAGS = \ + $(SECCOMP_CFLAGS) + +test_bus_cleanup_LDADD = \ + libsystemd-shared.la + +test_bus_server_SOURCES = \ + src/libsystemd/sd-bus/test-bus-server.c + +test_bus_server_LDADD = \ + libsystemd-shared.la + +test_bus_objects_SOURCES = \ + src/libsystemd/sd-bus/test-bus-objects.c + +test_bus_objects_LDADD = \ + libsystemd-shared.la + +test_bus_error_SOURCES = \ + src/libsystemd/sd-bus/test-bus-error.c + +# Link statically because this test uses BUS_ERROR_MAP_ELF_REGISTER +test_bus_error_LDADD = \ + libsystemd-shared.la + +test_bus_gvariant_SOURCES = \ + src/libsystemd/sd-bus/test-bus-gvariant.c + +test_bus_gvariant_LDADD = \ + libsystemd-shared.la \ + $(GLIB_LIBS) + +test_bus_gvariant_CFLAGS = \ + $(GLIB_CFLAGS) + +test_bus_creds_SOURCES = \ + src/libsystemd/sd-bus/test-bus-creds.c + +test_bus_creds_LDADD = \ + libsystemd-shared.la + +test_bus_match_SOURCES = \ + src/libsystemd/sd-bus/test-bus-match.c + +test_bus_match_LDADD = \ + libsystemd-shared.la + +test_bus_kernel_SOURCES = \ + src/libsystemd/sd-bus/test-bus-kernel.c + +test_bus_kernel_LDADD = \ + libsystemd-shared.la + +test_bus_kernel_bloom_SOURCES = \ + src/libsystemd/sd-bus/test-bus-kernel-bloom.c + +test_bus_kernel_bloom_LDADD = \ + libsystemd-shared.la + +test_bus_benchmark_SOURCES = \ + src/libsystemd/sd-bus/test-bus-benchmark.c + +test_bus_benchmark_LDADD = \ + libsystemd-shared.la + +test_bus_zero_copy_SOURCES = \ + src/libsystemd/sd-bus/test-bus-zero-copy.c + +test_bus_zero_copy_LDADD = \ + libsystemd-shared.la + +test_bus_introspect_SOURCES = \ + src/libsystemd/sd-bus/test-bus-introspect.c + +test_bus_introspect_LDADD = \ + libsystemd-shared.la + +test_event_SOURCES = \ + src/libsystemd/sd-event/test-event.c + +test_event_LDADD = \ + libsystemd-shared.la + +test_netlink_SOURCES = \ + src/libsystemd/sd-netlink/test-netlink.c + +test_netlink_LDADD = \ + libsystemd-shared.la + +test_local_addresses_SOURCES = \ + src/libsystemd/sd-netlink/test-local-addresses.c + +test_local_addresses_LDADD = \ + libsystemd-shared.la + +test_resolve_SOURCES = \ + src/libsystemd/sd-resolve/test-resolve.c + +test_resolve_LDADD = \ + libsystemd-shared.la + + +include $(topsrcdir)/build-aux/Makefile.tail.mk |