Commit Graph

53 Commits

Author SHA1 Message Date
Lennart Poettering ae2a15bc14 macro: introduce TAKE_PTR() macro
This macro will read a pointer of any type, return it, and set the
pointer to NULL. This is useful as an explicit concept of passing
ownership of a memory area between pointers.

This takes inspiration from Rust:

https://doc.rust-lang.org/std/option/enum.Option.html#method.take

and was suggested by Alan Jenkins (@sourcejedi).

It drops ~160 lines of code from our codebase, which makes me like it.
Also, I think it clarifies passing of ownership, and thus helps
readability a bit (at least for the initiated who know the new macro)
2018-03-22 20:21:42 +01:00
Nathaniel McCallum 45b1f410ba Add support for SD_BUS_DEFAULT*
Currently, sd-bus supports the ability to have thread-local default busses.
However, this is less useful than it can be since all functions which
require an sd_bus* as input require the caller to pass it. This patch adds
a new macro which allows the developer to pass a constant SD_BUS_DEFAULT,
SD_BUS_DEFAULT_USER or SD_BUS_DEFAULT_SYSTEM instead. This reduces work for
the caller.

For example:

    r = sd_bus_default(&bus);
    r = sd_bus_call_method(bus, ...);
    sd_bus_unref(bus);

Becomes:

    r = sd_bus_call_method(SD_BUS_DEFAULT, ...);

If the specified thread-local default bus does not exist, the function
calls will return -ENOPKG. No bus will ever be implicitly created.
2018-01-23 09:40:25 -05:00
Lennart Poettering c7db1984d0 sd-bus: get rid of kdbus flags cruft
We only need three bits from the old kdbus flags cruft, hence let's make
them proper booleans.
2018-01-05 13:55:08 +01:00
Lennart Poettering 0d53667334 tree-wide: use __fsetlocking() instead of fxyz_unlocked()
Let's replace usage of fputc_unlocked() and friends by __fsetlocking(f,
FSETLOCKING_BYCALLER). This turns off locking for the entire FILE*,
instead of doing individual per-call decision whether to use normal
calls or _unlocked() calls.

This has various benefits:

1. It's easier to read and easier not to forget

2. It's more comprehensive, as fprintf() and friends are covered too
   (as these functions have no _unlocked() counterpart)

3. Philosophically, it's a bit more correct, because it's more a
   property of the file handle really whether we ever pass it on to another
   thread, not of the operations we then apply to it.

This patch reworks all pieces of codes that so far used fxyz_unlocked()
calls to use __fsetlocking() instead. It also reworks all places that
use open_memstream(), i.e. use stdio FILE* for string manipulations.

Note that this in some way a revert of 4b61c87511.
2017-12-14 10:42:25 +01:00
Daniel Lockyer 5fecf46d76 Replace free and return NULL with return mfree 2017-11-24 10:31:49 +00:00
Shawn Landden 4831981d89 tree-wide: adjust fall through comments so that gcc is happy
Distcc removes comments, making the comment silencing
not work.

I know there was a decision against a macro in commit
ec251fe7d5
2017-11-20 13:06:25 -08:00
Zbigniew Jędrzejewski-Szmek 53e1b68390 Add SPDX license identifiers to source files under the LGPL
This follows what the kernel is doing, c.f.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5fd54ace4721fc5ce2bb5aef6318fcf17f421460.
2017-11-19 19:08:15 +01:00
Yu Watanabe 85e55d14de tree-wide: do not work in assert() (#7271)
Fixes #7270.
2017-11-07 16:04:20 +03:00
Yu Watanabe 945c2931bb libsystemd: use IN_SET macro 2017-09-28 17:37:59 +09:00
Alan Jenkins 00590f8268 sd-bus: style nitpick node_vtable_get_userdata()
It's confusing to use a single void* to store data with two different
types, i.e. a userdata value which is safe to pass to ->find(), and a
userdata value which identifies the found object.

Name the latter `found_u`.  This naming treats (!c->find) as a degenerate
case.  (I.e. at that point, we know the object has already been found :).
2017-09-17 17:55:01 +01:00
Alan Jenkins 733e792bc6 sd-bus: fix response for GetAll on non-existent objects
Before this commit, if you run `loginctl user-status` from
debug-shell.service (and you have no login sessions for root), you always
see this output:

0
	Linger: no

because Properties.GetAll is returning success but without any properties,
when the only find() callback had returned 0 to mean "no object found".

After:

Could not get properties: Unknown object:
'/org/freedesktop/login1/user/self'


BTW I have a fix for more user-friendly messages from logind in this case.
It is pending in my local branch for #6829 "fix `loginctl enable-linger`".
2017-09-17 17:54:54 +01:00
Lennart Poettering 4b61c87511 tree-wide: fput[cs]() → fput[cs]_unlocked() wherever that makes sense (#6396)
As a follow-up for db3f45e2d2 let's do the
same for all other cases where we create a FILE* with local scope and
know that no other threads hence can have access to it.

For most cases this shouldn't change much really, but this should speed
dbus introspection and calender time formatting up a bit.
2017-07-21 10:35:45 +02:00
Lennart Poettering f2bfc6ba45 sd-bus: make sure propagate all errors with vtable callbacks back to clients
Previously we'd propagate errors returned by user callbacks configured
in vtables back to the users only for method handlers and property
get/set handlers. This does the same for child enumeration and when we
check whether a fallback unit exists.

Without this the failure will be treated as a non-recoverable connection
error and result in connection termination.

Fixes: #6059
2017-06-21 20:42:28 +02:00
David Herrmann c0e7906d20 bus: report builtins in GetManagedObjects() (#5799)
We already report builtin interfaces with InterfacesAdded and InterfacesRemoved. However,
we never reported them in GetManagedObjects(). This might end up confusing callers that
want to use those interfaces (or simply rely on the interface count to be coherent).

Report the builtins for all objects that are queried.
2017-04-25 20:36:30 -04:00
Vito Caputo 9ed794a32d tree-wide: minor formatting inconsistency cleanups 2016-02-23 14:20:34 -08:00
Vito Caputo 313cefa1d9 tree-wide: make ++/-- usage consistent WRT spacing
Throughout the tree there's spurious use of spaces separating ++ and --
operators from their respective operands.  Make ++ and -- operator
consistent with the majority of existing uses; discard the spaces.
2016-02-22 20:32:04 -08:00
Daniel Mack b26fa1a2fb tree-wide: remove Emacs lines from all files
This should be handled fine now by .dir-locals.el, so need to carry that
stuff in every file.
2016-02-10 13:41:57 +01:00
Lennart Poettering 4afd3348c7 tree-wide: expose "p"-suffix unref calls in public APIs to make gcc cleanup easy
GLIB has recently started to officially support the gcc cleanup
attribute in its public API, hence let's do the same for our APIs.

With this patch we'll define an xyz_unrefp() call for each public
xyz_unref() call, to make it easy to use inside a
__attribute__((cleanup())) expression. Then, all code is ported over to
make use of this.

The new calls are also documented in the man pages, with examples how to
use them (well, I only added docs where the _unref() call itself already
had docs, and the examples, only cover sd_bus_unrefp() and
sd_event_unrefp()).

This also renames sd_lldp_free() to sd_lldp_unref(), since that's how we
tend to call our destructors these days.

Note that this defines no public macro that wraps gcc's attribute and
makes it easier to use. While I think it's our duty in the library to
make our stuff easy to use, I figure it's not our duty to make gcc's own
features easy to use on its own. Most likely, client code which wants to
make use of this should define its own:

       #define _cleanup_(function) __attribute__((cleanup(function)))

Or similar, to make the gcc feature easier to use.

Making this logic public has the benefit that we can remove three header
files whose only purpose was to define these functions internally.

See #2008.
2015-11-27 19:19:36 +01:00
Thomas Hindoe Paaboel Andersen cf0fbc49e6 tree-wide: sort includes
Sort the includes accoding to the new coding style.
2015-11-16 22:09:36 +01:00
Lennart Poettering b5efdb8af4 util-lib: split out allocation calls into alloc-util.[ch] 2015-10-27 13:45:53 +01:00
Lennart Poettering 07630cea1f util-lib: split our string related calls from util.[ch] into its own file string-util.[ch]
There are more than enough calls doing string manipulations to deserve
its own files, hence do something about it.

This patch also sorts the #include blocks of all files that needed to be
updated, according to the sorting suggestions from CODING_STYLE. Since
pretty much every file needs our string manipulation functions this
effectively means that most files have sorted #include blocks now.

Also touches a few unrelated include files.
2015-10-24 23:05:02 +02:00
Tom Gundersen b826ab586c hashmap: refactor hash_func
All our hash functions are based on siphash24(), factor out
siphash_init() and siphash24_finalize() and pass the siphash
state to the hash functions rather than the hash key.

This simplifies the hash functions, and in particular makes
composition simpler as calling siphash24_compress() repeatedly
on separate chunks of input has the same effect as first
concatenating the input and then calling siphash23_compress()
on the result.
2015-10-05 18:22:10 +02:00
David Herrmann 44eb1adda9 sd-bus: make introspection data non-recursive
Currently, our introspection data looks like this:

        <node>
         <interface name="org.freedesktop.DBus.Peer">
           ...
         </interface>
         <interface name="org.freedesktop.DBus.Introspectable">
           ...
         </interface>
         <interface name="org.freedesktop.DBus.Properties">
           ...
         </interface>
         <node name="org"/>
         <node name="org/freedesktop"/>
         <node name="org/freedesktop/login1"/>
         <node name="org/freedesktop/login1/user"/>
         <node name="org/freedesktop/login1/user/self"/>
         <node name="org/freedesktop/login1/user/_1000"/>
         <node name="org/freedesktop/login1/seat"/>
         <node name="org/freedesktop/login1/seat/self"/>
         <node name="org/freedesktop/login1/seat/seat0"/>
         <node name="org/freedesktop/login1/session"/>
         <node name="org/freedesktop/login1/session/self"/>
         <node name="org/freedesktop/login1/session/c1"/>
        </node>

(ordered alphabetically for better visibility)

This is grossly incorrect. The spec says that we're allowed to return
non-directed children, however, it does not allow us to return data
recursively in multiple parents. If we return "org", then we must not
return anything else that starts with "org/".

It is unclear, whether we can include child-nodes as a tree. Moreover, it
is usually not what the caller wants. Hence, this patch changes sd-bus to
never return introspection data recursively. Instead, only a single
child-layer is returned.

This patch relies on enumerators to never return hierarchies. If someone
registers an enumerator via sd_bus_add_enumerator, they better register
sub-enumerators if they support *TRUE* hierarchies. Each enumerator is
treated as a single layer and not filtered.
Enumerators are still allowed to return nested data. However, that data
is still required to be a single hierarchy. For instance, returning
"/org/foo" and "/com/bar" is fine, but including "/com" or "/org" in that
dataset is not.
This should be the default for enumerators and I see no reason to filter
in sd-bus. Moreover, filtering that data-set would require to sort the
strv by path and then do prefix-filtering. This is O(n log n), which
would be fine, but still better to avoid.

Fixes #664.
2015-09-05 19:43:29 +02:00
David Herrmann 057171efc1 Revert "sd-bus: do not connect to dbus-1 socket when kdbus is available"
This reverts commit d4d00020d6. The idea of
the commit is broken and needs to be reworked. We really cannot reduce
the bus-addresses to a single address. We always will have systemd with
native clients and legacy clients at the same time, so we also need both
addresses at the same time.
2015-08-27 16:32:22 +02:00
Lennart Poettering 337020515d sd-bus: introduce new SD_BUS_VTABLE_PROPERTY_EXPLICIT flag
This allows marking properties as "explicit". Properties marked like
this are included in the introspection, but are avoided in GetAll()
property queries, PropertiesChanged() signals and in in GetManaged()
object manager calls and InterfacesAdded() signals.

Expensive properties may be marked that way, and they will be
retrievable when explicitly being requested, but never in "blanket"
all-property queries and signals.

This flag may be combined with the flags for "const" and
"emit-validation" properties, but not with "emit-validation", as that
is only useful for properties whose value shall be sent in "blanket"
all-property signals.

The "explicit" flag is also exposed in the introspection data via a new
annotation.
2015-08-25 01:50:59 +02:00
David Herrmann f2196cf2e2 Revert "sd-bus: include queried path in GetManagedObjects"
This reverts commit 92d16a53e3. As it turns
out, this is not how ObjectManager is supposed to work. It is just a
special behavior of BlueZ, but no-one else implements it this way.

Revert the patch as discussed on github, and as such revert to the
previous behavior (as described in the spec).
2015-08-24 12:56:37 +02:00
Kay Sievers d4d00020d6 sd-bus: do not connect to dbus-1 socket when kdbus is available
We should not fall back to dbus-1 and connect to the proxy when kdbus
returns an error that indicates that kdbus is running but just does not
accept new connections because of quota limits or something similar.

Using is_kdbus_available() in libsystemd/ requires it to move from
shared/ to libsystemd/.

Based on a patch from David Herrmann:
  https://github.com/systemd/systemd/pull/886
2015-08-11 20:49:36 +02:00
David Herrmann 2d5c8a2756 sd-bus: fix path of object-manager signals
Each signal of the ObjectManager interface carries the path of the object
in question as an argument. Therefore, a caller will deduce the object
this signal is generated for, by parsing the _argument_. A caller will
*not* use the object-path of the message itself (i.e., message->path).
This is done on purpose, so the caller can rely on message->path to be
the path of the actual object-manager that generated this signal, instead
of the path of the object that triggered this signal.

This commit fixes all InterfacesAdded/Removed signals to use the path of
the closest object-manager as message->path. 'closest' in this case means
closest parent with at least one object-manager registered.

This fix raises the question what happens if we stack object-managers in
a hierarchy. Two implementations are possible: First, we report each
object only on the nearest object-manager. Second, we report it on each
parent object-manager. This patch chooses the former. This is compatible
with other existing ObjectManager implementations, which are required to
call GetManagedObjects() recursively on each object they find, which
implements the ObjectManager interface.
2015-07-27 19:15:08 +02:00
daurnimator 09c8a7c63c sd-bus: add 'offset' member for vtable methods
Defaults to zero, which retains the current behaviour.
Fixes #577
2015-07-24 22:22:54 +10:00
David Herrmann 7d67077f78 sd-bus: fix object tree to be deeper than 2 levels
So right now our object-tree is limited to 2 levels at most
('/' and '/foo/...../bar'). We never link any intermediate levels, even
though that was clearly the plan. Fix the bus_node_allocate() helper to
actually link all intermediate nodes, too, not just the root node.

This fixes a simple inverse ptr-diff bug.

The downside of this fix is that we clearly never tested (nor used) the
object tree in any way. The only reason that the introspection works is
that our enumerators shortcut the object tree.

Lets see whether that code actually works..

Thanks to: Nathaniel McCallum <nathaniel@themccallums.org>
..for reporting this. See #524 for an actual example code.
2015-07-15 14:39:12 +02:00
David Herrmann 92d16a53e3 sd-bus: include queried path in GetManagedObjects
If GetManagedObjects is called on /foo/bar, then it should also include
the object /foo/bar, if it exists. Right now, we only include objects
underneath /foo/bar/.

This follows the behavior of existing dbus implementations.

Obsoletes #527 and fixes #525. Reported by: Nathaniel McCallum
2015-07-09 13:30:16 +02:00
Geert Jansen 969a9685d9 export sd_bus_object_added() / _removed()
Fixes #306.
2015-06-21 22:21:38 -04:00
Lennart Poettering 190700621f sd-bus: drop bus parameter from message callback prototype
This should simplify the prototype a bit. The bus parameter is redundant
in most cases, and in the few where it matters it can be derived from
the message via sd_bus_message_get_bus().
2015-04-29 18:36:25 +02:00
David Herrmann d95eb43e90 bus: add sd_bus_emit_object_{added/removed}()
This implements two new helpers, discussed on systemd-devel about 1 year
ago:
    sd_bus_emit_object_added()
    sd_bus_emit_object_removed()

Both calls are equivalent to their respective counterpart
sd_bus_emit_interfaces_{added/removed}(), but can figure out the list of
interfaces themselves, instead of requiring the caller to provide them.
Furthermore, both calls properly deal with builtin interfaces provided via
org.freedesktop.DBus.* and alike.

Both calls simply traverse a node and all its parent nodes to figure out a
list of all interfaces registered as vtable or fallback. It then appends
each of them, similar to the interfaces_{added/removed}() helpers.

Note that interfaces_{added/removed}() runs a parent traversal for *each*
passed interface. Therefore, it can simply bail out, once it found a
parent node that implements a given interface.
With object_{added/removed}() we cannot know the registered interfaces in
advance, thus, we cannot run one traversal per node. Instead, we run a
single traversal and remember all interfaces that we added. Therefore, a
child-interface overrides all conflicting parent-interfaces. We keep a
"Set *s" context to track those while climbing up the tree.
2014-12-30 11:37:35 +01:00
Filipe Brandenburger 946be29c98 bus: remove spurious include of <sys/capability.h>
They do not use any functions from libcap directly. The CAP_SYS_ADMIN constant
in use by bus-objects.c comes from <linux/capability.h> imported through
"missing.h". The "missing.h" header is imported through "util.h" which gets
imported in "bus-util.h".

Tested that everything builds cleanly after this change.
2014-12-25 10:56:42 -05:00
Lennart Poettering 0ca454d474 sd-bus: create clean error when a property Set() call with incorrect signature is passed in 2014-11-21 00:32:02 +01:00
Lennart Poettering 9b772efb41 sd-bus: refuse properties that claim to be both writable and constant at the same time 2014-11-20 00:01:05 +01:00
David Herrmann ff02f101cb bus: fix error leak in bus_node_exists()
If we call into user callbacks, we must always propagate possible errors.
Fix bus_node_exists() to do that and adjust the callers (which already
partially propagated the error).

Also speed up that function by first checking for registered enumerators
and/or object-managers.
2014-09-17 11:01:56 +02:00
David Herrmann 943c3f94e2 bus: never respond to GetManagedObjects() on sub-paths
The dbus-spec clearly specifies that GetManagedObjects() should only work
on the root-path of an object-tree. But on that path, it works regardless
whether there are any objects available or not.

We could, technically, define all sub-paths as a root-path of its own
sub-tree. However, if we do that, we enter undefined territory:

    Imagine only a fallback vtable is registered. We want
    GetManagedObjects() to *NOT* fail with UNKNOWN_METHOD if it is called
    on a valid sub-tree of the fallback. On the other hand, we don't want
    it to work on arbitrary sub-tree. Something like:
        /path/to/fallback/foobar/foobar/foobar/invalid/foobar
    should not work.
    However, there is no way to know which paths on a fallback are valid
    without looking at there registered objects. If no objects are
    registered, we have no way to figure it out.

Therefore, we now try to follow the dbus spec by only returning valid data
on registered root-paths. We treat each path as root which was registered
an object-manager on via add_object_manager(). So applications can now
directly control which paths to place an object-manager on.

We also fix the introspection to not return object-manager interfaces on
non-root paths.

Also fixes some dead-code paths initially reported by Philippe De Swert.
2014-09-17 11:01:52 +02:00
Michal Schmidt d5099efc47 hashmap: introduce hash_ops to make struct Hashmap smaller
It is redundant to store 'hash' and 'compare' function pointers in
struct Hashmap separately. The functions always comprise a pair.
Store a single pointer to struct hash_ops instead.

systemd keeps hundreds of hashmaps, so this saves a little bit of
memory.
2014-09-15 16:08:50 +02:00
Lennart Poettering 630a4d9ea7 Merge remote-tracking branch 'origin/master' 2014-08-18 18:12:55 +02:00
Lennart Poettering caa829849d sd-bus: add API to query which handler/callback is currently being dispatched 2014-08-18 17:49:53 +02:00
Thomas Hindoe Paaboel Andersen f1e3bee216 sd-bus,log: remove unused variables 2014-08-16 00:32:21 +02:00
Lennart Poettering def9a7aa01 sd-bus: add API to check if a client has privileges
This is a generalization of the vtable privilege check we already have,
but exported, and hence useful when preparing for a polkit change.

This will deal with the complexity that on dbus1 one cannot trust the
capability field we retrieve via the bus, since it is read via
/proc/$$/stat (and thus might be out-of-date) rather than directly from
the message (like on kdbus) or bus connection (as for uid creds on
dbus1).

Also, port over all code to this new API.
2014-08-15 20:08:51 +02:00
Zbigniew Jędrzejewski-Szmek 2915234da0 bus: fix unitialized variable access in error path 2014-05-16 18:03:00 -04:00
Lennart Poettering 1b64f83829 sd-bus: always keep slot reference while dispatching callback
Also, make sure we automatically destroy reply callbacks that are
floating.
2014-05-15 17:13:05 +02:00
Lennart Poettering 19befb2d5f sd-bus: introduce sd_bus_slot objects encapsulating callbacks or vtables attached to a bus connection
This makes callback behaviour more like sd-event or sd-resolve, and
creates proper object for unregistering callbacks.

Taking the refernce to the slot is optional. If not taken life time of
the slot will be bound to the underlying bus object (or in the case of
an async call until the reply has been recieved).
2014-05-15 01:15:30 +02:00
Lennart Poettering 1b02f30183 bus: simplification 2014-04-23 19:06:38 +02:00
Lennart Poettering a3d59cd1b0 sd-bus: don't use assert_return() to check for disconnected bus connections
A terminated connection is a runtime error and not a developer mistake,
hence don't use assert_return() to check for it.
2014-03-19 21:41:21 +01:00
Lennart Poettering 0936559234 sd-bus: add proper monitoring API 2014-03-19 04:17:00 +01:00