1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include "alloc-util.h"
9 #include "errno-util.h"
11 #include "glyph-util.h"
14 #include "iovec-util.h"
16 #include "path-util.h"
17 #include "process-util.h"
18 #include "selinux-util.h"
19 #include "serialize.h"
21 #include "socket-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
25 #include "time-util.h"
26 #include "umask-util.h"
27 #include "user-util.h"
29 #include "varlink-internal.h"
30 #include "varlink-org.varlink.service.h"
31 #include "varlink-io.systemd.h"
34 #define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
35 #define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
37 #define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
38 #define VARLINK_BUFFER_MAX (16U*1024U*1024U)
39 #define VARLINK_READ_SIZE (64U*1024U)
40 #define VARLINK_COLLECT_MAX 1024U
42 typedef enum VarlinkState
{
43 /* Client side states */
45 VARLINK_AWAITING_REPLY
,
46 VARLINK_AWAITING_REPLY_MORE
,
49 VARLINK_PROCESSING_REPLY
,
51 /* Server side states */
53 VARLINK_PROCESSING_METHOD
,
54 VARLINK_PROCESSING_METHOD_MORE
,
55 VARLINK_PROCESSING_METHOD_ONEWAY
,
56 VARLINK_PROCESSED_METHOD
,
57 VARLINK_PENDING_METHOD
,
58 VARLINK_PENDING_METHOD_MORE
,
60 /* Common states (only during shutdown) */
61 VARLINK_PENDING_DISCONNECT
,
62 VARLINK_PENDING_TIMEOUT
,
63 VARLINK_PROCESSING_DISCONNECT
,
64 VARLINK_PROCESSING_TIMEOUT
,
65 VARLINK_PROCESSING_FAILURE
,
69 _VARLINK_STATE_INVALID
= -EINVAL
,
72 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
73 * is still good for something, and false only when it's dead for good. This means: when we are
74 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
75 * the connection is still good, and we are likely to be able to properly operate on it soon. */
76 #define VARLINK_STATE_IS_ALIVE(state) \
78 VARLINK_IDLE_CLIENT, \
79 VARLINK_AWAITING_REPLY, \
80 VARLINK_AWAITING_REPLY_MORE, \
83 VARLINK_PROCESSING_REPLY, \
84 VARLINK_IDLE_SERVER, \
85 VARLINK_PROCESSING_METHOD, \
86 VARLINK_PROCESSING_METHOD_MORE, \
87 VARLINK_PROCESSING_METHOD_ONEWAY, \
88 VARLINK_PROCESSED_METHOD, \
89 VARLINK_PENDING_METHOD, \
90 VARLINK_PENDING_METHOD_MORE)
92 typedef struct VarlinkJsonQueueItem VarlinkJsonQueueItem
;
94 /* A queued message we shall write into the socket, along with the file descriptors to send at the same
95 * time. This queue item binds them together so that message/fd boundaries are maintained throughout the
97 struct VarlinkJsonQueueItem
{
98 LIST_FIELDS(VarlinkJsonQueueItem
, queue
);
107 VarlinkServer
*server
;
110 bool connecting
; /* This boolean indicates whether the socket fd we are operating on is currently
111 * processing an asynchronous connect(). In that state we watch the socket for
112 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
113 * will trigger ENOTCONN. Note that this boolean is kept separate from the
114 * VarlinkState above on purpose: while the connect() is still not complete we
115 * already want to allow queuing of messages and similar. Thus it's nice to keep
116 * these two state concepts separate: the VarlinkState encodes what our own view of
117 * the connection is, i.e. whether we think it's a server, a client, and has
118 * something queued already, while 'connecting' tells us a detail about the
119 * transport used below, that should have no effect on how we otherwise accept and
120 * process operations from the user.
122 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
123 * connection is good to use, even if it might not be fully connected
124 * yet. connecting=true then informs you that actually we are still connecting, and
125 * the connection is actually not established yet and thus any requests you enqueue
126 * now will still work fine but will be queued only, not sent yet, but that
127 * shouldn't stop you from using the connection, since eventually whatever you queue
130 * Or to say this even differently: 'state' is a high-level ("application layer"
131 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
132 * low, if you so will) state, and while they are not entirely unrelated and
133 * sometimes propagate effects to each other they are only asynchronously connected
139 char *input_buffer
; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
140 size_t input_buffer_index
;
141 size_t input_buffer_size
;
142 size_t input_buffer_unscanned
;
144 void *input_control_buffer
;
145 size_t input_control_buffer_size
;
147 char *output_buffer
; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
148 size_t output_buffer_index
;
149 size_t output_buffer_size
;
151 int *input_fds
; /* file descriptors associated with the data in input_buffer (for fd passing) */
154 int *output_fds
; /* file descriptors associated with the data in output_buffer (for fd passing) */
157 /* Further messages to output not yet formatted into text, and thus not included in output_buffer
158 * yet. We keep them separate from output_buffer, to not violate fd message boundaries: we want that
159 * each fd that is sent is associated with its fds, and that fds cannot be accidentally associated
160 * with preceding or following messages. */
161 LIST_HEAD(VarlinkJsonQueueItem
, output_queue
);
162 VarlinkJsonQueueItem
*output_queue_tail
;
164 /* The fds to associate with the next message that is about to be enqueued. The user first pushes the
165 * fds it intends to send via varlink_push_fd() into this queue, and then once the message data is
166 * submitted we'll combine the fds and the message data into one. */
170 VarlinkReply reply_callback
;
172 JsonVariant
*current
;
173 VarlinkReplyFlags current_reply_flags
;
174 VarlinkSymbol
*current_method
;
178 bool ucred_acquired
:1;
180 bool write_disconnected
:1;
181 bool read_disconnected
:1;
182 bool prefer_read_write
:1;
185 bool allow_fd_passing_input
:1;
186 bool allow_fd_passing_output
:1;
188 bool output_buffer_sensitive
:1; /* whether to erase the output buffer after writing it to the socket */
189 bool input_sensitive
:1; /* Whether incoming messages might be sensitive */
191 int af
; /* address family if socket; AF_UNSPEC if not socket; negative if not known */
200 sd_event_source
*io_event_source
;
201 sd_event_source
*time_event_source
;
202 sd_event_source
*quit_event_source
;
203 sd_event_source
*defer_event_source
;
208 typedef struct VarlinkServerSocket VarlinkServerSocket
;
210 struct VarlinkServerSocket
{
211 VarlinkServer
*server
;
216 sd_event_source
*event_source
;
218 LIST_FIELDS(VarlinkServerSocket
, sockets
);
221 struct VarlinkServer
{
223 VarlinkServerFlags flags
;
225 LIST_HEAD(VarlinkServerSocket
, sockets
);
227 Hashmap
*methods
; /* Fully qualified symbol name of a method → VarlinkMethod */
228 Hashmap
*interfaces
; /* Fully qualified interface name → VarlinkInterface* */
229 Hashmap
*symbols
; /* Fully qualified symbol name of method/error → VarlinkSymbol* */
230 VarlinkConnect connect_callback
;
231 VarlinkDisconnect disconnect_callback
;
234 int64_t event_priority
;
236 unsigned n_connections
;
237 Hashmap
*by_uid
; /* UID_TO_PTR(uid) → UINT_TO_PTR(n_connections) */
242 unsigned connections_max
;
243 unsigned connections_per_uid_max
;
248 typedef struct VarlinkCollectContext
{
249 JsonVariant
*parameters
;
250 const char *error_id
;
251 VarlinkReplyFlags flags
;
252 } VarlinkCollectContext
;
254 static const char* const varlink_state_table
[_VARLINK_STATE_MAX
] = {
255 [VARLINK_IDLE_CLIENT
] = "idle-client",
256 [VARLINK_AWAITING_REPLY
] = "awaiting-reply",
257 [VARLINK_AWAITING_REPLY_MORE
] = "awaiting-reply-more",
258 [VARLINK_CALLING
] = "calling",
259 [VARLINK_CALLED
] = "called",
260 [VARLINK_PROCESSING_REPLY
] = "processing-reply",
261 [VARLINK_IDLE_SERVER
] = "idle-server",
262 [VARLINK_PROCESSING_METHOD
] = "processing-method",
263 [VARLINK_PROCESSING_METHOD_MORE
] = "processing-method-more",
264 [VARLINK_PROCESSING_METHOD_ONEWAY
] = "processing-method-oneway",
265 [VARLINK_PROCESSED_METHOD
] = "processed-method",
266 [VARLINK_PENDING_METHOD
] = "pending-method",
267 [VARLINK_PENDING_METHOD_MORE
] = "pending-method-more",
268 [VARLINK_PENDING_DISCONNECT
] = "pending-disconnect",
269 [VARLINK_PENDING_TIMEOUT
] = "pending-timeout",
270 [VARLINK_PROCESSING_DISCONNECT
] = "processing-disconnect",
271 [VARLINK_PROCESSING_TIMEOUT
] = "processing-timeout",
272 [VARLINK_PROCESSING_FAILURE
] = "processing-failure",
273 [VARLINK_DISCONNECTED
] = "disconnected",
276 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state
, VarlinkState
);
278 #define varlink_log_errno(v, error, fmt, ...) \
279 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
281 #define varlink_log(v, fmt, ...) \
282 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
284 #define varlink_server_log_errno(s, error, fmt, ...) \
285 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
287 #define varlink_server_log(s, fmt, ...) \
288 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
290 static int varlink_format_queue(Varlink
*v
);
291 static void varlink_server_test_exit_on_idle(VarlinkServer
*s
);
293 static const char *varlink_description(Varlink
*v
) {
294 return (v
? v
->description
: NULL
) ?: "varlink";
297 static const char *varlink_server_description(VarlinkServer
*s
) {
298 return (s
? s
->description
: NULL
) ?: "varlink";
301 static VarlinkJsonQueueItem
*varlink_json_queue_item_free(VarlinkJsonQueueItem
*q
) {
305 json_variant_unref(q
->data
);
306 close_many(q
->fds
, q
->n_fds
);
311 static VarlinkJsonQueueItem
*varlink_json_queue_item_new(JsonVariant
*m
, const int fds
[], size_t n_fds
) {
312 VarlinkJsonQueueItem
*q
;
315 assert(fds
|| n_fds
== 0);
317 q
= malloc(offsetof(VarlinkJsonQueueItem
, fds
) + sizeof(int) * n_fds
);
321 *q
= (VarlinkJsonQueueItem
) {
322 .data
= json_variant_ref(m
),
326 memcpy_safe(q
->fds
, fds
, n_fds
* sizeof(int));
331 static void varlink_set_state(Varlink
*v
, VarlinkState state
) {
333 assert(state
>= 0 && state
< _VARLINK_STATE_MAX
);
336 varlink_log(v
, "Setting state %s",
337 varlink_state_to_string(state
));
339 varlink_log(v
, "Changing state %s %s %s",
340 varlink_state_to_string(v
->state
),
341 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
342 varlink_state_to_string(state
));
347 static int varlink_new(Varlink
**ret
) {
360 .state
= _VARLINK_STATE_INVALID
,
362 .ucred
= UCRED_INVALID
,
364 .timestamp
= USEC_INFINITY
,
365 .timeout
= VARLINK_DEFAULT_TIMEOUT_USEC
,
369 .peer_pidfd
= -EBADF
,
376 int varlink_connect_address(Varlink
**ret
, const char *address
) {
377 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
378 union sockaddr_union sockaddr
;
381 assert_return(ret
, -EINVAL
);
382 assert_return(address
, -EINVAL
);
386 return log_debug_errno(r
, "Failed to create varlink object: %m");
388 v
->fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
390 return log_debug_errno(errno
, "Failed to create AF_UNIX socket: %m");
392 v
->fd
= fd_move_above_stdio(v
->fd
);
395 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
397 if (r
!= -ENAMETOOLONG
)
398 return log_debug_errno(r
, "Failed to set socket address '%s': %m", address
);
400 /* This is a file system path, and too long to fit into sockaddr_un. Let's connect via O_PATH
403 r
= connect_unix_path(v
->fd
, AT_FDCWD
, address
);
405 r
= RET_NERRNO(connect(v
->fd
, &sockaddr
.sa
, r
));
408 if (!IN_SET(r
, -EAGAIN
, -EINPROGRESS
))
409 return log_debug_errno(r
, "Failed to connect to %s: %m", address
);
411 v
->connecting
= true; /* We are asynchronously connecting, i.e. the connect() is being
412 * processed in the background. As long as that's the case the socket
413 * is in a special state: it's there, we can poll it for EPOLLOUT, but
414 * if we attempt to write() to it before we see EPOLLOUT we'll get
415 * ENOTCONN (and not EAGAIN, like we would for a normal connected
416 * socket that isn't writable at the moment). Since ENOTCONN on write()
417 * hence can mean two different things (i.e. connection not complete
418 * yet vs. already disconnected again), we store as a boolean whether
419 * we are still in connect(). */
422 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
428 int varlink_connect_exec(Varlink
**ret
, const char *_command
, char **_argv
) {
429 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
430 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
431 _cleanup_free_
char *command
= NULL
;
432 _cleanup_strv_free_
char **argv
= NULL
;
435 assert_return(ret
, -EINVAL
);
436 assert_return(_command
, -EINVAL
);
438 /* Copy the strings, in case they point into our own argv[], which we'll invalidate shortly because
439 * we rename the child process */
440 command
= strdup(_command
);
444 if (strv_isempty(_argv
))
445 argv
= strv_new(command
);
447 argv
= strv_copy(_argv
);
451 log_debug("Forking off Varlink child process '%s'.", command
);
453 if (socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0, pair
) < 0)
454 return log_debug_errno(errno
, "Failed to allocate AF_UNIX socket pair: %m");
456 r
= fd_nonblock(pair
[1], false);
458 return log_debug_errno(r
, "Failed to disable O_NONBLOCK for varlink socket: %m");
462 /* stdio_fds= */ NULL
,
463 /* except_fds= */ (int[]) { pair
[1] },
464 /* n_except_fds= */ 1,
465 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG_SIGTERM
|FORK_REOPEN_LOG
|FORK_LOG
|FORK_RLIMIT_NOFILE_SAFE
,
468 return log_debug_errno(r
, "Failed to spawn process: %m");
470 char spid
[DECIMAL_STR_MAX(pid_t
)+1];
471 const char *setenv_list
[] = {
474 "LISTEN_FDNAMES", "varlink",
481 r
= move_fd(pair
[1], 3, /* cloexec= */ false);
483 log_debug_errno(r
, "Failed to move file descriptor to 3: %m");
487 xsprintf(spid
, PID_FMT
, pid
);
489 STRV_FOREACH_PAIR(a
, b
, setenv_list
) {
490 if (setenv(*a
, *b
, /* override= */ true) < 0) {
491 log_debug_errno(errno
, "Failed to set environment variable '%s': %m", *a
);
496 execvp(command
, argv
);
497 log_debug_errno(r
, "Failed to invoke process '%s': %m", command
);
501 pair
[1] = safe_close(pair
[1]);
506 return log_debug_errno(r
, "Failed to create varlink object: %m");
508 v
->fd
= TAKE_FD(pair
[0]);
510 v
->exec_pid
= TAKE_PID(pid
);
511 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
517 static int varlink_connect_ssh(Varlink
**ret
, const char *where
) {
518 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
519 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
522 assert_return(ret
, -EINVAL
);
523 assert_return(where
, -EINVAL
);
525 /* Connects to an SSH server via OpenSSH 9.4's -W switch to connect to a remote AF_UNIX socket. For
526 * now we do not expose this function directly, but only via varlink_connect_url(). */
528 const char *ssh
= secure_getenv("SYSTEMD_SSH") ?: "ssh";
529 if (!path_is_valid(ssh
))
530 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "SSH path is not valid, refusing: %s", ssh
);
532 const char *e
= strchr(where
, ':');
534 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "SSH specification lacks a : separator between host and path, refusing: %s", where
);
536 _cleanup_free_
char *h
= strndup(where
, e
- where
);
538 return log_oom_debug();
540 _cleanup_free_
char *c
= strdup(e
+ 1);
542 return log_oom_debug();
544 if (!path_is_absolute(c
))
545 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Remote AF_UNIX socket path is not absolute, refusing: %s", c
);
547 _cleanup_free_
char *p
= NULL
;
548 r
= path_simplify_alloc(c
, &p
);
552 if (!path_is_normalized(p
))
553 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path is not normalized, refusing: %s", p
);
555 log_debug("Forking off SSH child process '%s -W %s %s'.", ssh
, p
, h
);
557 if (socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0, pair
) < 0)
558 return log_debug_errno(errno
, "Failed to allocate AF_UNIX socket pair: %m");
562 /* stdio_fds= */ (int[]) { pair
[1], pair
[1], STDERR_FILENO
},
563 /* except_fds= */ NULL
,
564 /* n_except_fds= */ 0,
565 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG_SIGTERM
|FORK_REOPEN_LOG
|FORK_LOG
|FORK_RLIMIT_NOFILE_SAFE
|FORK_REARRANGE_STDIO
,
568 return log_debug_errno(r
, "Failed to spawn process: %m");
572 execlp(ssh
, "ssh", "-W", p
, h
, NULL
);
573 log_debug_errno(errno
, "Failed to invoke %s: %m", ssh
);
577 pair
[1] = safe_close(pair
[1]);
582 return log_debug_errno(r
, "Failed to create varlink object: %m");
584 v
->fd
= TAKE_FD(pair
[0]);
586 v
->exec_pid
= TAKE_PID(pid
);
587 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
593 int varlink_connect_url(Varlink
**ret
, const char *url
) {
594 _cleanup_free_
char *c
= NULL
;
603 assert_return(ret
, -EINVAL
);
604 assert_return(url
, -EINVAL
);
606 // FIXME: Maybe add support for vsock: and ssh-exec: URL schemes here.
608 /* The Varlink URL scheme is a bit underdefined. We support only the spec-defined unix: transport for
609 * now, plus exec:, ssh: transports we made up ourselves. Strictly speaking this shouldn't even be
610 * called "URL", since it has nothing to do with Internet URLs by RFC. */
612 p
= startswith(url
, "unix:");
614 scheme
= SCHEME_UNIX
;
615 else if ((p
= startswith(url
, "exec:")))
616 scheme
= SCHEME_EXEC
;
617 else if ((p
= startswith(url
, "ssh:")))
620 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "URL scheme not supported.");
622 /* The varlink.org reference C library supports more than just file system paths. We might want to
623 * support that one day too. For now simply refuse that. */
624 if (p
[strcspn(p
, ";?#")] != '\0')
625 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "URL parameterization with ';', '?', '#' not supported.");
627 if (scheme
== SCHEME_SSH
)
628 return varlink_connect_ssh(ret
, p
);
630 if (scheme
== SCHEME_EXEC
|| p
[0] != '@') { /* no path validity checks for abstract namespace sockets */
632 if (!path_is_absolute(p
))
633 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path not absolute, refusing.");
635 r
= path_simplify_alloc(p
, &c
);
639 if (!path_is_normalized(c
))
640 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path is not normalized, refusing.");
643 if (scheme
== SCHEME_EXEC
)
644 return varlink_connect_exec(ret
, c
, NULL
);
646 return varlink_connect_address(ret
, c
?: p
);
649 int varlink_connect_fd(Varlink
**ret
, int fd
) {
653 assert_return(ret
, -EINVAL
);
654 assert_return(fd
>= 0, -EBADF
);
656 r
= fd_nonblock(fd
, true);
658 return log_debug_errno(r
, "Failed to make fd %d nonblocking: %m", fd
);
662 return log_debug_errno(r
, "Failed to create varlink object: %m");
666 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
668 /* Note that if this function is called we assume the passed socket (if it is one) is already
669 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
670 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
671 * until the connection is fully set up. Behaviour here is hence a bit different from
672 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
673 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
679 static void varlink_detach_event_sources(Varlink
*v
) {
682 v
->io_event_source
= sd_event_source_disable_unref(v
->io_event_source
);
683 v
->time_event_source
= sd_event_source_disable_unref(v
->time_event_source
);
684 v
->quit_event_source
= sd_event_source_disable_unref(v
->quit_event_source
);
685 v
->defer_event_source
= sd_event_source_disable_unref(v
->defer_event_source
);
688 static void varlink_clear_current(Varlink
*v
) {
691 /* Clears the currently processed incoming message */
692 v
->current
= json_variant_unref(v
->current
);
693 v
->current_method
= NULL
;
694 v
->current_reply_flags
= 0;
696 close_many(v
->input_fds
, v
->n_input_fds
);
697 v
->input_fds
= mfree(v
->input_fds
);
701 static void varlink_clear(Varlink
*v
) {
704 varlink_detach_event_sources(v
);
706 v
->fd
= safe_close(v
->fd
);
708 varlink_clear_current(v
);
710 v
->input_buffer
= v
->input_sensitive
? erase_and_free(v
->input_buffer
) : mfree(v
->input_buffer
);
711 v
->output_buffer
= v
->output_buffer_sensitive
? erase_and_free(v
->output_buffer
) : mfree(v
->output_buffer
);
713 v
->input_control_buffer
= mfree(v
->input_control_buffer
);
714 v
->input_control_buffer_size
= 0;
716 close_many(v
->output_fds
, v
->n_output_fds
);
717 v
->output_fds
= mfree(v
->output_fds
);
720 close_many(v
->pushed_fds
, v
->n_pushed_fds
);
721 v
->pushed_fds
= mfree(v
->pushed_fds
);
724 LIST_CLEAR(queue
, v
->output_queue
, varlink_json_queue_item_free
);
725 v
->output_queue_tail
= NULL
;
727 v
->event
= sd_event_unref(v
->event
);
729 if (v
->exec_pid
> 0) {
730 sigterm_wait(v
->exec_pid
);
734 v
->peer_pidfd
= safe_close(v
->peer_pidfd
);
737 static Varlink
* varlink_destroy(Varlink
*v
) {
741 /* If this is called the server object must already been unreffed here. Why that? because when we
742 * linked up the varlink connection with the server object we took one ref in each direction */
747 free(v
->description
);
751 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink
, varlink
, varlink_destroy
);
753 static int varlink_test_disconnect(Varlink
*v
) {
756 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
757 * prematurely, since we want to handle half-open connections as well as possible and want to flush
758 * out and read data before we close down if we can. */
760 /* Already disconnected? */
761 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
764 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
768 /* Still something to write and we can write? Stay around */
769 if (v
->output_buffer_size
> 0 && !v
->write_disconnected
)
772 /* Both sides gone already? Then there's no need to stick around */
773 if (v
->read_disconnected
&& v
->write_disconnected
)
776 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
777 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) && v
->read_disconnected
)
780 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
781 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
782 * being down if we never wrote anything. */
783 if (v
->state
== VARLINK_IDLE_CLIENT
&& (v
->write_disconnected
|| v
->got_pollhup
))
786 /* We are on the server side and still want to send out more replies, but we saw POLLHUP already, and
787 * either got no buffered bytes to write anymore or already saw a write error. In that case we should
788 * shut down the varlink link. */
789 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
) && (v
->write_disconnected
|| v
->output_buffer_size
== 0) && v
->got_pollhup
)
795 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
799 static int varlink_write(Varlink
*v
) {
805 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
807 if (v
->connecting
) /* Writing while we are still wait for a non-blocking connect() to complete will
808 * result in ENOTCONN, hence exit early here */
810 if (v
->write_disconnected
)
813 /* If needed let's convert some output queue json variants into text form */
814 r
= varlink_format_queue(v
);
818 if (v
->output_buffer_size
== 0)
823 if (v
->n_output_fds
> 0) { /* If we shall send fds along, we must use sendmsg() */
825 .iov_base
= v
->output_buffer
+ v
->output_buffer_index
,
826 .iov_len
= v
->output_buffer_size
,
831 .msg_controllen
= CMSG_SPACE(sizeof(int) * v
->n_output_fds
),
834 mh
.msg_control
= alloca0(mh
.msg_controllen
);
836 struct cmsghdr
*control
= CMSG_FIRSTHDR(&mh
);
837 control
->cmsg_len
= CMSG_LEN(sizeof(int) * v
->n_output_fds
);
838 control
->cmsg_level
= SOL_SOCKET
;
839 control
->cmsg_type
= SCM_RIGHTS
;
840 memcpy(CMSG_DATA(control
), v
->output_fds
, sizeof(int) * v
->n_output_fds
);
842 n
= sendmsg(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
844 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
845 * with non-socket IO, hence fall back automatically.
847 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
848 bool prefer_write
= v
->prefer_read_write
;
850 n
= send(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
851 if (n
< 0 && errno
== ENOTSOCK
)
852 prefer_write
= v
->prefer_read_write
= true;
855 n
= write(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
);
861 if (ERRNO_IS_DISCONNECT(errno
)) {
862 /* If we get informed about a disconnect on write, then let's remember that, but not
863 * act on it just yet. Let's wait for read() to report the issue first. */
864 v
->write_disconnected
= true;
871 if (v
->output_buffer_sensitive
)
872 explicit_bzero_safe(v
->output_buffer
+ v
->output_buffer_index
, n
);
874 v
->output_buffer_size
-= n
;
876 if (v
->output_buffer_size
== 0) {
877 v
->output_buffer_index
= 0;
878 v
->output_buffer_sensitive
= false; /* We can reset the sensitive flag once the buffer is empty */
880 v
->output_buffer_index
+= n
;
882 close_many(v
->output_fds
, v
->n_output_fds
);
885 v
->timestamp
= now(CLOCK_MONOTONIC
);
889 #define VARLINK_FDS_MAX (16U*1024U)
891 static int varlink_read(Varlink
*v
) {
900 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
))
902 if (v
->connecting
) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
906 if (v
->input_buffer_unscanned
> 0)
908 if (v
->read_disconnected
)
911 if (v
->input_buffer_size
>= VARLINK_BUFFER_MAX
)
916 if (MALLOC_SIZEOF_SAFE(v
->input_buffer
) <= v
->input_buffer_index
+ v
->input_buffer_size
) {
919 add
= MIN(VARLINK_BUFFER_MAX
- v
->input_buffer_size
, VARLINK_READ_SIZE
);
921 if (v
->input_buffer_index
== 0) {
923 if (!GREEDY_REALLOC(v
->input_buffer
, v
->input_buffer_size
+ add
))
929 b
= new(char, v
->input_buffer_size
+ add
);
933 memcpy(b
, v
->input_buffer
+ v
->input_buffer_index
, v
->input_buffer_size
);
935 free_and_replace(v
->input_buffer
, b
);
936 v
->input_buffer_index
= 0;
940 p
= v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
;
941 rs
= MALLOC_SIZEOF_SAFE(v
->input_buffer
) - (v
->input_buffer_index
+ v
->input_buffer_size
);
943 if (v
->allow_fd_passing_input
) {
944 iov
= IOVEC_MAKE(p
, rs
);
946 /* Allocate the fd buffer on the heap, since we need a lot of space potentially */
947 if (!v
->input_control_buffer
) {
948 v
->input_control_buffer_size
= CMSG_SPACE(sizeof(int) * VARLINK_FDS_MAX
);
949 v
->input_control_buffer
= malloc(v
->input_control_buffer_size
);
950 if (!v
->input_control_buffer
)
954 mh
= (struct msghdr
) {
957 .msg_control
= v
->input_control_buffer
,
958 .msg_controllen
= v
->input_control_buffer_size
,
961 n
= recvmsg_safe(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
963 bool prefer_read
= v
->prefer_read_write
;
965 n
= recv(v
->fd
, p
, rs
, MSG_DONTWAIT
);
966 if (n
< 0 && errno
== ENOTSOCK
)
967 prefer_read
= v
->prefer_read_write
= true;
970 n
= read(v
->fd
, p
, rs
);
976 if (ERRNO_IS_DISCONNECT(errno
)) {
977 v
->read_disconnected
= true;
983 if (n
== 0) { /* EOF */
985 if (v
->allow_fd_passing_input
)
988 v
->read_disconnected
= true;
992 if (v
->allow_fd_passing_input
) {
993 struct cmsghdr
* cmsg
;
995 cmsg
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, (socklen_t
) -1);
999 /* We only allow file descriptors to be passed along with the first byte of a
1000 * message. If they are passed with any other byte this is a protocol violation. */
1001 if (v
->input_buffer_size
!= 0) {
1002 cmsg_close_all(&mh
);
1006 add
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
1007 if (add
> INT_MAX
- v
->n_input_fds
) {
1008 cmsg_close_all(&mh
);
1012 if (!GREEDY_REALLOC(v
->input_fds
, v
->n_input_fds
+ add
)) {
1013 cmsg_close_all(&mh
);
1017 memcpy_safe(v
->input_fds
+ v
->n_input_fds
, CMSG_TYPED_DATA(cmsg
, int), add
* sizeof(int));
1018 v
->n_input_fds
+= add
;
1022 v
->input_buffer_size
+= n
;
1023 v
->input_buffer_unscanned
+= n
;
1028 static int varlink_parse_message(Varlink
*v
) {
1038 if (v
->input_buffer_unscanned
<= 0)
1041 assert(v
->input_buffer_unscanned
<= v
->input_buffer_size
);
1042 assert(v
->input_buffer_index
+ v
->input_buffer_size
<= MALLOC_SIZEOF_SAFE(v
->input_buffer
));
1044 begin
= v
->input_buffer
+ v
->input_buffer_index
;
1046 e
= memchr(begin
+ v
->input_buffer_size
- v
->input_buffer_unscanned
, 0, v
->input_buffer_unscanned
);
1048 v
->input_buffer_unscanned
= 0;
1054 r
= json_parse(begin
, 0, &v
->current
, NULL
, NULL
);
1055 if (v
->input_sensitive
)
1056 explicit_bzero_safe(begin
, sz
);
1058 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
1059 * hence drop all buffered data now. */
1060 v
->input_buffer_index
= v
->input_buffer_size
= v
->input_buffer_unscanned
= 0;
1061 return varlink_log_errno(v
, r
, "Failed to parse JSON: %m");
1064 if (v
->input_sensitive
) {
1065 /* Mark the parameters subfield as sensitive right-away, if that's requested */
1066 JsonVariant
*parameters
= json_variant_by_key(v
->current
, "parameters");
1068 json_variant_sensitive(parameters
);
1071 if (DEBUG_LOGGING
) {
1072 _cleanup_(erase_and_freep
) char *censored_text
= NULL
;
1074 /* Suppress sensitive fields in the debug output */
1075 r
= json_variant_format(v
->current
, /* flags= */ JSON_FORMAT_CENSOR_SENSITIVE
, &censored_text
);
1079 varlink_log(v
, "Received message: %s", censored_text
);
1082 v
->input_buffer_size
-= sz
;
1084 if (v
->input_buffer_size
== 0)
1085 v
->input_buffer_index
= 0;
1087 v
->input_buffer_index
+= sz
;
1089 v
->input_buffer_unscanned
= v
->input_buffer_size
;
1093 static int varlink_test_timeout(Varlink
*v
) {
1096 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
1098 if (v
->timeout
== USEC_INFINITY
)
1101 if (now(CLOCK_MONOTONIC
) < usec_add(v
->timestamp
, v
->timeout
))
1104 varlink_set_state(v
, VARLINK_PENDING_TIMEOUT
);
1109 static int varlink_dispatch_local_error(Varlink
*v
, const char *error
) {
1115 if (!v
->reply_callback
)
1118 r
= v
->reply_callback(v
, NULL
, error
, VARLINK_REPLY_ERROR
|VARLINK_REPLY_LOCAL
, v
->userdata
);
1120 varlink_log_errno(v
, r
, "Reply callback returned error, ignoring: %m");
1125 static int varlink_dispatch_timeout(Varlink
*v
) {
1128 if (v
->state
!= VARLINK_PENDING_TIMEOUT
)
1131 varlink_set_state(v
, VARLINK_PROCESSING_TIMEOUT
);
1132 varlink_dispatch_local_error(v
, VARLINK_ERROR_TIMEOUT
);
1138 static int varlink_dispatch_disconnect(Varlink
*v
) {
1141 if (v
->state
!= VARLINK_PENDING_DISCONNECT
)
1144 varlink_set_state(v
, VARLINK_PROCESSING_DISCONNECT
);
1145 varlink_dispatch_local_error(v
, VARLINK_ERROR_DISCONNECTED
);
1151 static int varlink_sanitize_parameters(JsonVariant
**v
) {
1156 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
1158 return json_variant_new_object(v
, NULL
, 0);
1159 if (json_variant_is_null(*v
)) {
1162 r
= json_variant_new_object(&empty
, NULL
, 0);
1166 json_variant_unref(*v
);
1170 if (!json_variant_is_object(*v
))
1176 static int varlink_dispatch_reply(Varlink
*v
) {
1177 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1178 VarlinkReplyFlags flags
= 0;
1179 const char *error
= NULL
;
1186 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
1191 assert(v
->n_pending
> 0);
1193 if (!json_variant_is_object(v
->current
))
1196 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
1198 if (streq(k
, "error")) {
1201 if (!json_variant_is_string(e
))
1204 error
= json_variant_string(e
);
1205 flags
|= VARLINK_REPLY_ERROR
;
1207 } else if (streq(k
, "parameters")) {
1210 if (!json_variant_is_object(e
) && !json_variant_is_null(e
))
1213 parameters
= json_variant_ref(e
);
1215 } else if (streq(k
, "continues")) {
1216 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1219 if (!json_variant_is_boolean(e
))
1222 if (json_variant_boolean(e
))
1223 flags
|= VARLINK_REPLY_CONTINUES
;
1228 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
1229 if (v
->state
!= VARLINK_AWAITING_REPLY_MORE
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1232 /* An error is final */
1233 if (error
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1236 r
= varlink_sanitize_parameters(¶meters
);
1240 v
->current_reply_flags
= flags
;
1242 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
)) {
1243 varlink_set_state(v
, VARLINK_PROCESSING_REPLY
);
1245 if (v
->reply_callback
) {
1246 r
= v
->reply_callback(v
, parameters
, error
, flags
, v
->userdata
);
1248 varlink_log_errno(v
, r
, "Reply callback returned error, ignoring: %m");
1251 varlink_clear_current(v
);
1253 if (v
->state
== VARLINK_PROCESSING_REPLY
) {
1254 assert(v
->n_pending
> 0);
1256 if (!FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1259 varlink_set_state(v
,
1260 FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
) ? VARLINK_AWAITING_REPLY_MORE
:
1261 v
->n_pending
== 0 ? VARLINK_IDLE_CLIENT
: VARLINK_AWAITING_REPLY
);
1264 assert(v
->state
== VARLINK_CALLING
);
1265 varlink_set_state(v
, VARLINK_CALLED
);
1271 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
1272 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
1278 static int generic_method_get_info(
1280 JsonVariant
*parameters
,
1281 VarlinkMethodFlags flags
,
1284 _cleanup_strv_free_
char **interfaces
= NULL
;
1285 _cleanup_free_
char *product
= NULL
;
1290 if (json_variant_elements(parameters
) != 0)
1291 return varlink_error_invalid_parameter(link
, parameters
);
1293 product
= strjoin("systemd (", program_invocation_short_name
, ")");
1297 VarlinkInterface
*interface
;
1298 HASHMAP_FOREACH(interface
, ASSERT_PTR(link
->server
)->interfaces
) {
1299 r
= strv_extend(&interfaces
, interface
->name
);
1304 strv_sort(interfaces
);
1306 return varlink_replyb(link
, JSON_BUILD_OBJECT(
1307 JSON_BUILD_PAIR_STRING("vendor", "The systemd Project"),
1308 JSON_BUILD_PAIR_STRING("product", product
),
1309 JSON_BUILD_PAIR_STRING("version", STRINGIFY(PROJECT_VERSION
) " (" GIT_VERSION
")"),
1310 JSON_BUILD_PAIR_STRING("url", "https://systemd.io/"),
1311 JSON_BUILD_PAIR_STRV("interfaces", interfaces
)));
1314 static int generic_method_get_interface_description(
1316 JsonVariant
*parameters
,
1317 VarlinkMethodFlags flags
,
1320 static const struct JsonDispatch dispatch_table
[] = {
1321 { "interface", JSON_VARIANT_STRING
, json_dispatch_const_string
, 0, JSON_MANDATORY
},
1324 _cleanup_free_
char *text
= NULL
;
1325 const VarlinkInterface
*interface
;
1326 const char *name
= NULL
;
1331 r
= json_dispatch(parameters
, dispatch_table
, 0, &name
);
1335 interface
= hashmap_get(ASSERT_PTR(link
->server
)->interfaces
, name
);
1337 return varlink_errorb(link
, VARLINK_ERROR_INTERFACE_NOT_FOUND
,
1339 JSON_BUILD_PAIR_STRING("interface", name
)));
1341 r
= varlink_idl_format(interface
, &text
);
1345 return varlink_replyb(link
,
1347 JSON_BUILD_PAIR_STRING("description", text
)));
1350 static int varlink_dispatch_method(Varlink
*v
) {
1351 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1352 VarlinkMethodFlags flags
= 0;
1353 const char *method
= NULL
;
1355 VarlinkMethod callback
;
1361 if (v
->state
!= VARLINK_IDLE_SERVER
)
1366 if (!json_variant_is_object(v
->current
))
1369 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
1371 if (streq(k
, "method")) {
1374 if (!json_variant_is_string(e
))
1377 method
= json_variant_string(e
);
1379 } else if (streq(k
, "parameters")) {
1382 if (!json_variant_is_object(e
) && !json_variant_is_null(e
))
1385 parameters
= json_variant_ref(e
);
1387 } else if (streq(k
, "oneway")) {
1389 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1392 if (!json_variant_is_boolean(e
))
1395 if (json_variant_boolean(e
))
1396 flags
|= VARLINK_METHOD_ONEWAY
;
1398 } else if (streq(k
, "more")) {
1400 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1403 if (!json_variant_is_boolean(e
))
1406 if (json_variant_boolean(e
))
1407 flags
|= VARLINK_METHOD_MORE
;
1416 r
= varlink_sanitize_parameters(¶meters
);
1420 varlink_set_state(v
, (flags
& VARLINK_METHOD_MORE
) ? VARLINK_PROCESSING_METHOD_MORE
:
1421 (flags
& VARLINK_METHOD_ONEWAY
) ? VARLINK_PROCESSING_METHOD_ONEWAY
:
1422 VARLINK_PROCESSING_METHOD
);
1426 /* First consult user supplied method implementations */
1427 callback
= hashmap_get(v
->server
->methods
, method
);
1429 if (streq(method
, "org.varlink.service.GetInfo"))
1430 callback
= generic_method_get_info
;
1431 else if (streq(method
, "org.varlink.service.GetInterfaceDescription"))
1432 callback
= generic_method_get_interface_description
;
1436 bool invalid
= false;
1438 v
->current_method
= hashmap_get(v
->server
->symbols
, method
);
1439 if (!v
->current_method
)
1440 varlink_log(v
, "No interface description defined for method '%s', not validating.", method
);
1442 const char *bad_field
;
1444 r
= varlink_idl_validate_method_call(v
->current_method
, parameters
, &bad_field
);
1446 /* Please adjust test/units/end.sh when updating the log message. */
1447 varlink_log_errno(v
, r
, "Parameters for method %s() didn't pass validation on field '%s': %m",
1448 method
, strna(bad_field
));
1450 if (IN_SET(v
->state
, VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
)) {
1451 r
= varlink_error_invalid_parameter_name(v
, bad_field
);
1460 r
= callback(v
, parameters
, flags
, v
->userdata
);
1462 varlink_log_errno(v
, r
, "Callback for %s returned error: %m", method
);
1464 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
1465 if (IN_SET(v
->state
, VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
)) {
1466 r
= varlink_error_errno(v
, r
);
1472 } else if (IN_SET(v
->state
, VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
)) {
1473 r
= varlink_errorb(v
, VARLINK_ERROR_METHOD_NOT_FOUND
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
))));
1480 case VARLINK_PROCESSED_METHOD
: /* Method call is fully processed */
1481 case VARLINK_PROCESSING_METHOD_ONEWAY
: /* ditto */
1482 varlink_clear_current(v
);
1483 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1486 case VARLINK_PROCESSING_METHOD
: /* Method call wasn't replied to, will be replied to later */
1487 varlink_set_state(v
, VARLINK_PENDING_METHOD
);
1490 case VARLINK_PROCESSING_METHOD_MORE
: /* No reply for a "more" message was sent, more to come */
1491 varlink_set_state(v
, VARLINK_PENDING_METHOD_MORE
);
1495 assert_not_reached();
1504 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
1505 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
1511 int varlink_process(Varlink
*v
) {
1514 assert_return(v
, -EINVAL
);
1516 if (v
->state
== VARLINK_DISCONNECTED
)
1517 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1521 r
= varlink_write(v
);
1523 varlink_log_errno(v
, r
, "Write failed: %m");
1527 r
= varlink_dispatch_reply(v
);
1529 varlink_log_errno(v
, r
, "Reply dispatch failed: %m");
1533 r
= varlink_dispatch_method(v
);
1535 varlink_log_errno(v
, r
, "Method dispatch failed: %m");
1539 r
= varlink_parse_message(v
);
1541 varlink_log_errno(v
, r
, "Message parsing failed: %m");
1545 r
= varlink_read(v
);
1547 varlink_log_errno(v
, r
, "Read failed: %m");
1551 r
= varlink_test_disconnect(v
);
1556 r
= varlink_dispatch_disconnect(v
);
1561 r
= varlink_test_timeout(v
);
1566 r
= varlink_dispatch_timeout(v
);
1572 if (r
>= 0 && v
->defer_event_source
) {
1575 /* If we did some processing, make sure we are called again soon */
1576 q
= sd_event_source_set_enabled(v
->defer_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
1578 r
= varlink_log_errno(v
, q
, "Failed to enable deferred event source: %m");
1582 if (VARLINK_STATE_IS_ALIVE(v
->state
))
1583 /* Initiate disconnection */
1584 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
1586 /* We failed while disconnecting, in that case close right away */
1594 int varlink_dispatch_again(Varlink
*v
) {
1597 assert_return(v
, -EINVAL
);
1599 /* If a method call handler could not process the method call just yet (for example because it needed
1600 * some Polkit authentication first), then it can leave the call unanswered, do its thing, and then
1601 * ask to be dispatched a second time, via this call. It will then be called again, for the same
1604 if (v
->state
== VARLINK_DISCONNECTED
)
1605 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1606 if (v
->state
!= VARLINK_PENDING_METHOD
)
1607 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection has no pending method.");
1609 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1611 r
= sd_event_source_set_enabled(v
->defer_event_source
, SD_EVENT_ON
);
1613 return varlink_log_errno(v
, r
, "Failed to enable deferred event source: %m");
1618 int varlink_get_current_parameters(Varlink
*v
, JsonVariant
**ret
) {
1621 assert_return(v
, -EINVAL
);
1626 p
= json_variant_by_key(v
->current
, "parameters");
1631 *ret
= json_variant_ref(p
);
1636 static void handle_revents(Varlink
*v
, int revents
) {
1639 if (v
->connecting
) {
1640 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
1641 * to complete on, we know we are ready. We don't read the connection error here though,
1642 * we'll get the error on the next read() or write(). */
1643 if ((revents
& (POLLOUT
|POLLHUP
)) == 0)
1646 varlink_log(v
, "Asynchronous connection completed.");
1647 v
->connecting
= false;
1649 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1650 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1651 * momentarily don't want to read nor write anything. */
1653 if (!FLAGS_SET(revents
, POLLHUP
))
1656 varlink_log(v
, "Got POLLHUP from socket.");
1657 v
->got_pollhup
= true;
1661 int varlink_wait(Varlink
*v
, usec_t timeout
) {
1665 assert_return(v
, -EINVAL
);
1667 if (v
->state
== VARLINK_DISCONNECTED
)
1668 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1670 r
= varlink_get_timeout(v
, &t
);
1673 if (t
!= USEC_INFINITY
) {
1676 n
= now(CLOCK_MONOTONIC
);
1680 t
= usec_sub_unsigned(t
, n
);
1683 if (timeout
!= USEC_INFINITY
&&
1684 (t
== USEC_INFINITY
|| timeout
< t
))
1687 fd
= varlink_get_fd(v
);
1691 events
= varlink_get_events(v
);
1695 r
= fd_wait_for_event(fd
, events
, t
);
1696 if (ERRNO_IS_NEG_TRANSIENT(r
)) /* Treat EINTR as not a timeout, but also nothing happened, and
1697 * the caller gets a chance to call back into us */
1702 handle_revents(v
, r
);
1706 int varlink_is_idle(Varlink
*v
) {
1707 assert_return(v
, -EINVAL
);
1709 /* Returns true if there's nothing pending on the connection anymore, i.e. we processed all incoming
1710 * or outgoing messages fully, or finished disconnection */
1712 return IN_SET(v
->state
, VARLINK_DISCONNECTED
, VARLINK_IDLE_CLIENT
, VARLINK_IDLE_SERVER
);
1715 int varlink_get_fd(Varlink
*v
) {
1717 assert_return(v
, -EINVAL
);
1719 if (v
->state
== VARLINK_DISCONNECTED
)
1720 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1722 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBADF
), "No valid fd.");
1727 int varlink_get_events(Varlink
*v
) {
1730 assert_return(v
, -EINVAL
);
1732 if (v
->state
== VARLINK_DISCONNECTED
)
1733 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1735 if (v
->connecting
) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1736 * tells us that the connection is now complete. Before that we should neither
1737 * write() or read() from the fd. */
1740 if (!v
->read_disconnected
&&
1741 IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) &&
1743 v
->input_buffer_unscanned
<= 0)
1746 if (!v
->write_disconnected
&&
1747 v
->output_buffer_size
> 0)
1753 int varlink_get_timeout(Varlink
*v
, usec_t
*ret
) {
1754 assert_return(v
, -EINVAL
);
1756 if (v
->state
== VARLINK_DISCONNECTED
)
1757 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1759 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
) &&
1760 v
->timeout
!= USEC_INFINITY
) {
1762 *ret
= usec_add(v
->timestamp
, v
->timeout
);
1766 *ret
= USEC_INFINITY
;
1771 int varlink_flush(Varlink
*v
) {
1774 assert_return(v
, -EINVAL
);
1776 if (v
->state
== VARLINK_DISCONNECTED
)
1777 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1780 if (v
->output_buffer_size
== 0)
1782 if (v
->write_disconnected
)
1785 r
= varlink_write(v
);
1793 r
= fd_wait_for_event(v
->fd
, POLLOUT
, USEC_INFINITY
);
1794 if (ERRNO_IS_NEG_TRANSIENT(r
))
1797 return varlink_log_errno(v
, r
, "Poll failed on fd: %m");
1800 handle_revents(v
, r
);
1806 static void varlink_detach_server(Varlink
*v
) {
1807 VarlinkServer
*saved_server
;
1813 if (v
->server
->by_uid
&&
1814 v
->ucred_acquired
&&
1815 uid_is_valid(v
->ucred
.uid
)) {
1818 c
= PTR_TO_UINT(hashmap_get(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
)));
1822 (void) hashmap_remove(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
));
1824 (void) hashmap_replace(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
), UINT_TO_PTR(c
- 1));
1827 assert(v
->server
->n_connections
> 0);
1828 v
->server
->n_connections
--;
1830 /* If this is a connection associated to a server, then let's disconnect the server and the
1831 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1832 * before we release the references, let's call the disconnection callback if it is defined. */
1834 saved_server
= TAKE_PTR(v
->server
);
1836 if (saved_server
->disconnect_callback
)
1837 saved_server
->disconnect_callback(saved_server
, v
, saved_server
->userdata
);
1839 varlink_server_test_exit_on_idle(saved_server
);
1840 varlink_server_unref(saved_server
);
1844 int varlink_close(Varlink
*v
) {
1845 assert_return(v
, -EINVAL
);
1847 if (v
->state
== VARLINK_DISCONNECTED
)
1850 varlink_set_state(v
, VARLINK_DISCONNECTED
);
1852 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1853 * which would destroy us before we can call varlink_clear() */
1855 varlink_detach_server(v
);
1862 Varlink
* varlink_close_unref(Varlink
*v
) {
1866 (void) varlink_close(v
);
1867 return varlink_unref(v
);
1870 Varlink
* varlink_flush_close_unref(Varlink
*v
) {
1874 (void) varlink_flush(v
);
1875 return varlink_close_unref(v
);
1878 static int varlink_format_json(Varlink
*v
, JsonVariant
*m
) {
1879 _cleanup_(erase_and_freep
) char *text
= NULL
;
1885 sz
= json_variant_format(m
, /* flags= */ 0, &text
);
1888 assert(text
[sz
] == '\0');
1890 if (v
->output_buffer_size
+ sz
+ 1 > VARLINK_BUFFER_MAX
)
1893 if (DEBUG_LOGGING
) {
1894 _cleanup_(erase_and_freep
) char *censored_text
= NULL
;
1896 /* Suppress sensitive fields in the debug output */
1897 r
= json_variant_format(m
, /* flags= */ JSON_FORMAT_CENSOR_SENSITIVE
, &censored_text
);
1901 varlink_log(v
, "Sending message: %s", censored_text
);
1904 if (v
->output_buffer_size
== 0) {
1906 free_and_replace(v
->output_buffer
, text
);
1908 v
->output_buffer_size
= sz
+ 1;
1909 v
->output_buffer_index
= 0;
1911 } else if (v
->output_buffer_index
== 0) {
1913 if (!GREEDY_REALLOC(v
->output_buffer
, v
->output_buffer_size
+ sz
+ 1))
1916 memcpy(v
->output_buffer
+ v
->output_buffer_size
, text
, sz
+ 1);
1917 v
->output_buffer_size
+= sz
+ 1;
1920 const size_t new_size
= v
->output_buffer_size
+ sz
+ 1;
1922 n
= new(char, new_size
);
1926 memcpy(mempcpy(n
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
), text
, sz
+ 1);
1928 free_and_replace(v
->output_buffer
, n
);
1929 v
->output_buffer_size
= new_size
;
1930 v
->output_buffer_index
= 0;
1933 if (json_variant_is_sensitive_recursive(m
))
1934 v
->output_buffer_sensitive
= true; /* Propagate sensitive flag */
1936 text
= mfree(text
); /* No point in the erase_and_free() destructor declared above */
1941 static int varlink_enqueue_json(Varlink
*v
, JsonVariant
*m
) {
1942 VarlinkJsonQueueItem
*q
;
1947 /* If there are no file descriptors to be queued and no queue entries yet we can shortcut things and
1948 * append this entry directly to the output buffer */
1949 if (v
->n_pushed_fds
== 0 && !v
->output_queue
)
1950 return varlink_format_json(v
, m
);
1952 /* Otherwise add a queue entry for this */
1953 q
= varlink_json_queue_item_new(m
, v
->pushed_fds
, v
->n_pushed_fds
);
1957 v
->n_pushed_fds
= 0; /* fds now belong to the queue entry */
1959 LIST_INSERT_AFTER(queue
, v
->output_queue
, v
->output_queue_tail
, q
);
1960 v
->output_queue_tail
= q
;
1964 static int varlink_format_queue(Varlink
*v
) {
1969 /* Takes entries out of the output queue and formats them into the output buffer. But only if this
1970 * would not corrupt our fd message boundaries */
1972 while (v
->output_queue
) {
1973 _cleanup_free_
int *array
= NULL
;
1974 VarlinkJsonQueueItem
*q
= v
->output_queue
;
1976 if (v
->n_output_fds
> 0) /* unwritten fds? if we'd add more we'd corrupt the fd message boundaries, hence wait */
1980 array
= newdup(int, q
->fds
, q
->n_fds
);
1985 r
= varlink_format_json(v
, q
->data
);
1989 /* Take possession of the queue element's fds */
1990 free(v
->output_fds
);
1991 v
->output_fds
= TAKE_PTR(array
);
1992 v
->n_output_fds
= q
->n_fds
;
1995 LIST_REMOVE(queue
, v
->output_queue
, q
);
1996 if (!v
->output_queue
)
1997 v
->output_queue_tail
= NULL
;
1999 varlink_json_queue_item_free(q
);
2005 int varlink_send(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
2006 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2009 assert_return(v
, -EINVAL
);
2010 assert_return(method
, -EINVAL
);
2012 if (v
->state
== VARLINK_DISCONNECTED
)
2013 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2015 /* We allow enqueuing multiple method calls at once! */
2016 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
2017 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2019 r
= varlink_sanitize_parameters(¶meters
);
2021 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2023 r
= json_build(&m
, JSON_BUILD_OBJECT(
2024 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
2025 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
2026 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
2028 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2030 r
= varlink_enqueue_json(v
, m
);
2032 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2034 /* No state change here, this is one-way only after all */
2035 v
->timestamp
= now(CLOCK_MONOTONIC
);
2039 int varlink_sendb(Varlink
*v
, const char *method
, ...) {
2040 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2044 assert_return(v
, -EINVAL
);
2046 va_start(ap
, method
);
2047 r
= json_buildv(¶meters
, ap
);
2051 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2053 return varlink_send(v
, method
, parameters
);
2056 int varlink_invoke(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
2057 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2060 assert_return(v
, -EINVAL
);
2061 assert_return(method
, -EINVAL
);
2063 if (v
->state
== VARLINK_DISCONNECTED
)
2064 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2066 /* We allow enqueuing multiple method calls at once! */
2067 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
2068 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2070 r
= varlink_sanitize_parameters(¶meters
);
2072 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2074 r
= json_build(&m
, JSON_BUILD_OBJECT(
2075 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
2076 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2078 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2080 r
= varlink_enqueue_json(v
, m
);
2082 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2084 varlink_set_state(v
, VARLINK_AWAITING_REPLY
);
2086 v
->timestamp
= now(CLOCK_MONOTONIC
);
2091 int varlink_invokeb(Varlink
*v
, const char *method
, ...) {
2092 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2096 assert_return(v
, -EINVAL
);
2098 va_start(ap
, method
);
2099 r
= json_buildv(¶meters
, ap
);
2103 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2105 return varlink_invoke(v
, method
, parameters
);
2108 int varlink_observe(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
2109 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2112 assert_return(v
, -EINVAL
);
2113 assert_return(method
, -EINVAL
);
2115 if (v
->state
== VARLINK_DISCONNECTED
)
2116 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2118 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
2119 * thus insist on an idle client here. */
2120 if (v
->state
!= VARLINK_IDLE_CLIENT
)
2121 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2123 r
= varlink_sanitize_parameters(¶meters
);
2125 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2127 r
= json_build(&m
, JSON_BUILD_OBJECT(
2128 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
2129 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
2130 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
2132 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2134 r
= varlink_enqueue_json(v
, m
);
2136 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2138 varlink_set_state(v
, VARLINK_AWAITING_REPLY_MORE
);
2140 v
->timestamp
= now(CLOCK_MONOTONIC
);
2145 int varlink_observeb(Varlink
*v
, const char *method
, ...) {
2146 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2150 assert_return(v
, -EINVAL
);
2152 va_start(ap
, method
);
2153 r
= json_buildv(¶meters
, ap
);
2157 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2159 return varlink_observe(v
, method
, parameters
);
2162 int varlink_call_full(
2165 JsonVariant
*parameters
,
2166 JsonVariant
**ret_parameters
,
2167 const char **ret_error_id
,
2168 VarlinkReplyFlags
*ret_flags
) {
2170 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2173 assert_return(v
, -EINVAL
);
2174 assert_return(method
, -EINVAL
);
2176 if (v
->state
== VARLINK_DISCONNECTED
)
2177 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2178 if (v
->state
!= VARLINK_IDLE_CLIENT
)
2179 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2181 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2183 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2184 * that we can assign a new reply shortly. */
2185 varlink_clear_current(v
);
2187 r
= varlink_sanitize_parameters(¶meters
);
2189 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2191 r
= json_build(&m
, JSON_BUILD_OBJECT(
2192 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
2193 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2195 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2197 r
= varlink_enqueue_json(v
, m
);
2199 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2201 varlink_set_state(v
, VARLINK_CALLING
);
2203 v
->timestamp
= now(CLOCK_MONOTONIC
);
2205 while (v
->state
== VARLINK_CALLING
) {
2206 r
= varlink_process(v
);
2212 r
= varlink_wait(v
, USEC_INFINITY
);
2219 case VARLINK_CALLED
: {
2222 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
2223 assert(v
->n_pending
== 1);
2226 JsonVariant
*e
= json_variant_by_key(v
->current
, "error"),
2227 *p
= json_variant_by_key(v
->current
, "parameters");
2229 /* If caller doesn't ask for the error string, then let's return an error code in case of failure */
2230 if (!ret_error_id
&& e
)
2231 return varlink_error_to_errno(json_variant_string(e
), p
);
2234 *ret_parameters
= p
;
2236 *ret_error_id
= e
? json_variant_string(e
) : NULL
;
2238 *ret_flags
= v
->current_reply_flags
;
2243 case VARLINK_PENDING_DISCONNECT
:
2244 case VARLINK_DISCONNECTED
:
2245 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ECONNRESET
), "Connection was closed.");
2247 case VARLINK_PENDING_TIMEOUT
:
2248 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ETIME
), "Connection timed out.");
2251 assert_not_reached();
2255 int varlink_callb_ap(
2258 JsonVariant
**ret_parameters
,
2259 const char **ret_error_id
,
2260 VarlinkReplyFlags
*ret_flags
,
2263 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2266 assert_return(v
, -EINVAL
);
2267 assert_return(method
, -EINVAL
);
2269 r
= json_buildv(¶meters
, ap
);
2271 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2273 return varlink_call_full(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
2276 int varlink_call_and_log(
2279 JsonVariant
*parameters
,
2280 JsonVariant
**ret_parameters
) {
2282 JsonVariant
*reply
= NULL
;
2283 const char *error_id
= NULL
;
2286 assert_return(v
, -EINVAL
);
2287 assert_return(method
, -EINVAL
);
2289 r
= varlink_call(v
, method
, parameters
, &reply
, &error_id
);
2291 return log_error_errno(r
, "Failed to issue %s() varlink call: %m", method
);
2293 return log_error_errno(varlink_error_to_errno(error_id
, reply
),
2294 "Failed to issue %s() varlink call: %s", method
, error_id
);
2297 *ret_parameters
= TAKE_PTR(reply
);
2302 int varlink_callb_and_log(
2305 JsonVariant
**ret_parameters
,
2308 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2312 assert_return(v
, -EINVAL
);
2313 assert_return(method
, -EINVAL
);
2315 va_start(ap
, ret_parameters
);
2316 r
= json_buildv(¶meters
, ap
);
2319 return log_error_errno(r
, "Failed to build JSON message: %m");
2321 return varlink_call_and_log(v
, method
, parameters
, ret_parameters
);
2324 static void varlink_collect_context_free(VarlinkCollectContext
*cc
) {
2327 json_variant_unref(cc
->parameters
);
2328 free((char *)cc
->error_id
);
2331 static int collect_callback(
2333 JsonVariant
*parameters
,
2334 const char *error_id
,
2335 VarlinkReplyFlags flags
,
2338 VarlinkCollectContext
*context
= ASSERT_PTR(userdata
);
2343 context
->flags
= flags
;
2344 /* If we hit an error, we will drop all collected replies and just return the error_id and flags in varlink_collect() */
2346 context
->error_id
= error_id
;
2348 json_variant_unref(context
->parameters
);
2349 context
->parameters
= json_variant_ref(parameters
);
2354 if (json_variant_elements(context
->parameters
) >= VARLINK_COLLECT_MAX
)
2355 return varlink_log_errno(v
, SYNTHETIC_ERRNO(E2BIG
), "Number of reply messages grew too large (%zu) while collecting.", json_variant_elements(context
->parameters
));
2357 r
= json_variant_append_array(&context
->parameters
, parameters
);
2359 return varlink_log_errno(v
, r
, "Failed to append JSON object to array: %m");
2364 int varlink_collect(
2367 JsonVariant
*parameters
,
2368 JsonVariant
**ret_parameters
,
2369 const char **ret_error_id
,
2370 VarlinkReplyFlags
*ret_flags
) {
2372 _cleanup_(varlink_collect_context_free
) VarlinkCollectContext context
= {};
2375 assert_return(v
, -EINVAL
);
2376 assert_return(method
, -EINVAL
);
2378 if (v
->state
== VARLINK_DISCONNECTED
)
2379 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2380 if (v
->state
!= VARLINK_IDLE_CLIENT
)
2381 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2383 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2385 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2386 * that we can assign a new reply shortly. */
2387 varlink_clear_current(v
);
2389 r
= varlink_bind_reply(v
, collect_callback
);
2391 return varlink_log_errno(v
, r
, "Failed to bind collect callback");
2393 varlink_set_userdata(v
, &context
);
2394 r
= varlink_observe(v
, method
, parameters
);
2396 return varlink_log_errno(v
, r
, "Failed to collect varlink method: %m");
2398 while (v
->state
== VARLINK_AWAITING_REPLY_MORE
) {
2400 r
= varlink_process(v
);
2404 /* If we get an error from any of the replies, return immediately with just the error_id and flags*/
2405 if (context
.error_id
) {
2407 /* If caller doesn't ask for the error string, then let's return an error code in case of failure */
2409 return varlink_error_to_errno(context
.error_id
, context
.parameters
);
2412 *ret_parameters
= TAKE_PTR(context
.parameters
);
2414 *ret_error_id
= TAKE_PTR(context
.error_id
);
2416 *ret_flags
= context
.flags
;
2423 r
= varlink_wait(v
, USEC_INFINITY
);
2430 case VARLINK_IDLE_CLIENT
:
2433 case VARLINK_PENDING_DISCONNECT
:
2434 case VARLINK_DISCONNECTED
:
2435 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ECONNRESET
), "Connection was closed.");
2437 case VARLINK_PENDING_TIMEOUT
:
2438 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ETIME
), "Connection timed out.");
2441 assert_not_reached();
2444 if (!ret_error_id
&& context
.error_id
)
2445 return varlink_error_to_errno(context
.error_id
, context
.parameters
);
2448 *ret_parameters
= TAKE_PTR(context
.parameters
);
2450 *ret_error_id
= TAKE_PTR(context
.error_id
);
2452 *ret_flags
= context
.flags
;
2456 int varlink_collectb(
2459 JsonVariant
**ret_parameters
,
2460 const char **ret_error_id
,
2461 VarlinkReplyFlags
*ret_flags
, ...) {
2463 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2467 assert_return(v
, -EINVAL
);
2469 va_start(ap
, ret_flags
);
2470 r
= json_buildv(¶meters
, ap
);
2474 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2476 return varlink_collect(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
2479 int varlink_reply(Varlink
*v
, JsonVariant
*parameters
) {
2480 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2483 assert_return(v
, -EINVAL
);
2485 if (v
->state
== VARLINK_DISCONNECTED
)
2487 if (!IN_SET(v
->state
,
2488 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
2489 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
2492 r
= varlink_sanitize_parameters(¶meters
);
2494 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2496 r
= json_build(&m
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2498 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2500 if (v
->current_method
) {
2501 const char *bad_field
= NULL
;
2503 r
= varlink_idl_validate_method_reply(v
->current_method
, parameters
, &bad_field
);
2505 /* Please adjust test/units/end.sh when updating the log message. */
2506 varlink_log_errno(v
, r
, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2507 v
->current_method
->name
, strna(bad_field
));
2510 r
= varlink_enqueue_json(v
, m
);
2512 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2514 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
2515 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
2516 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
2517 * process further messages. */
2518 varlink_clear_current(v
);
2519 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2521 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
2522 * means we should it handle the rest of the state engine. */
2523 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
2528 int varlink_replyb(Varlink
*v
, ...) {
2529 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2533 assert_return(v
, -EINVAL
);
2536 r
= json_buildv(¶meters
, ap
);
2542 return varlink_reply(v
, parameters
);
2545 int varlink_error(Varlink
*v
, const char *error_id
, JsonVariant
*parameters
) {
2546 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2549 assert_return(v
, -EINVAL
);
2550 assert_return(error_id
, -EINVAL
);
2552 if (v
->state
== VARLINK_DISCONNECTED
)
2553 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2554 if (!IN_SET(v
->state
,
2555 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
2556 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
2557 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2559 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
2560 * simplify code that puts together a complex reply message with fds, and half-way something
2561 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
2562 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
2563 * the callers don't need to do this explicitly. */
2564 varlink_reset_fds(v
);
2566 r
= varlink_sanitize_parameters(¶meters
);
2568 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2570 r
= json_build(&m
, JSON_BUILD_OBJECT(
2571 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id
)),
2572 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2574 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2576 VarlinkSymbol
*symbol
= hashmap_get(v
->server
->symbols
, error_id
);
2578 varlink_log(v
, "No interface description defined for error '%s', not validating.", error_id
);
2580 const char *bad_field
= NULL
;
2582 r
= varlink_idl_validate_error(symbol
, parameters
, &bad_field
);
2584 /* Please adjust test/units/end.sh when updating the log message. */
2585 varlink_log_errno(v
, r
, "Parameters for error %s didn't pass validation on field '%s', ignoring: %m",
2586 error_id
, strna(bad_field
));
2589 r
= varlink_enqueue_json(v
, m
);
2591 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2593 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
2594 varlink_clear_current(v
);
2595 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2597 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
2602 int varlink_errorb(Varlink
*v
, const char *error_id
, ...) {
2603 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2607 assert_return(v
, -EINVAL
);
2608 assert_return(error_id
, -EINVAL
);
2610 va_start(ap
, error_id
);
2611 r
= json_buildv(¶meters
, ap
);
2615 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2617 return varlink_error(v
, error_id
, parameters
);
2620 int varlink_error_invalid_parameter(Varlink
*v
, JsonVariant
*parameters
) {
2623 assert_return(v
, -EINVAL
);
2624 assert_return(parameters
, -EINVAL
);
2626 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
2627 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
2628 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
2629 * don't expect any arguments. */
2631 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
2632 * parameter sanitization to fail, and it returns -EINVAL. */
2634 if (json_variant_is_string(parameters
)) {
2635 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
2637 r
= json_build(¶meters_obj
,
2639 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters
))));
2643 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
2646 if (json_variant_is_object(parameters
) &&
2647 json_variant_elements(parameters
) > 0) {
2648 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
2650 r
= json_build(¶meters_obj
,
2652 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters
, 0)))));
2656 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
2662 int varlink_error_invalid_parameter_name(Varlink
*v
, const char *name
) {
2663 return varlink_errorb(
2665 VARLINK_ERROR_INVALID_PARAMETER
,
2666 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameter", JSON_BUILD_STRING(name
))));
2669 int varlink_error_errno(Varlink
*v
, int error
) {
2670 return varlink_errorb(
2672 VARLINK_ERROR_SYSTEM
,
2673 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error
)))));
2676 int varlink_notify(Varlink
*v
, JsonVariant
*parameters
) {
2677 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2680 assert_return(v
, -EINVAL
);
2682 if (v
->state
== VARLINK_DISCONNECTED
)
2683 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2685 /* If we want to reply with a notify connection but the caller didn't set "more", then return an
2686 * error indicating that we expected to be called with "more" set */
2687 if (IN_SET(v
->state
, VARLINK_PROCESSING_METHOD
, VARLINK_PENDING_METHOD
))
2688 return varlink_error(v
, VARLINK_ERROR_EXPECTED_MORE
, NULL
);
2690 if (!IN_SET(v
->state
, VARLINK_PROCESSING_METHOD_MORE
, VARLINK_PENDING_METHOD_MORE
))
2691 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2693 r
= varlink_sanitize_parameters(¶meters
);
2695 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2697 r
= json_build(&m
, JSON_BUILD_OBJECT(
2698 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
2699 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2701 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2703 if (v
->current_method
) {
2704 const char *bad_field
= NULL
;
2706 r
= varlink_idl_validate_method_reply(v
->current_method
, parameters
, &bad_field
);
2708 /* Please adjust test/units/end.sh when updating the log message. */
2709 varlink_log_errno(v
, r
, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2710 v
->current_method
->name
, strna(bad_field
));
2713 r
= varlink_enqueue_json(v
, m
);
2715 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2717 /* No state change, as more is coming */
2721 int varlink_notifyb(Varlink
*v
, ...) {
2722 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2726 assert_return(v
, -EINVAL
);
2729 r
= json_buildv(¶meters
, ap
);
2733 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2735 return varlink_notify(v
, parameters
);
2738 int varlink_dispatch(Varlink
*v
, JsonVariant
*parameters
, const JsonDispatch table
[], void *userdata
) {
2739 const char *bad_field
= NULL
;
2742 assert_return(v
, -EINVAL
);
2743 assert_return(table
, -EINVAL
);
2745 /* A wrapper around json_dispatch_full() that returns a nice InvalidParameter error if we hit a problem with some field. */
2747 r
= json_dispatch_full(parameters
, table
, /* bad= */ NULL
, /* flags= */ 0, userdata
, &bad_field
);
2750 return varlink_error_invalid_parameter_name(v
, bad_field
);
2757 int varlink_bind_reply(Varlink
*v
, VarlinkReply callback
) {
2758 assert_return(v
, -EINVAL
);
2760 if (callback
&& v
->reply_callback
&& callback
!= v
->reply_callback
)
2761 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
2763 v
->reply_callback
= callback
;
2768 void* varlink_set_userdata(Varlink
*v
, void *userdata
) {
2771 assert_return(v
, NULL
);
2774 v
->userdata
= userdata
;
2779 void* varlink_get_userdata(Varlink
*v
) {
2780 assert_return(v
, NULL
);
2785 static int varlink_acquire_ucred(Varlink
*v
) {
2790 if (v
->ucred_acquired
)
2793 r
= getpeercred(v
->fd
, &v
->ucred
);
2797 v
->ucred_acquired
= true;
2801 int varlink_get_peer_uid(Varlink
*v
, uid_t
*ret
) {
2804 assert_return(v
, -EINVAL
);
2805 assert_return(ret
, -EINVAL
);
2807 r
= varlink_acquire_ucred(v
);
2809 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2811 if (!uid_is_valid(v
->ucred
.uid
))
2812 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2814 *ret
= v
->ucred
.uid
;
2818 int varlink_get_peer_pid(Varlink
*v
, pid_t
*ret
) {
2821 assert_return(v
, -EINVAL
);
2822 assert_return(ret
, -EINVAL
);
2824 r
= varlink_acquire_ucred(v
);
2826 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2828 if (!pid_is_valid(v
->ucred
.pid
))
2829 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2831 *ret
= v
->ucred
.pid
;
2835 static int varlink_acquire_pidfd(Varlink
*v
) {
2838 if (v
->peer_pidfd
>= 0)
2841 v
->peer_pidfd
= getpeerpidfd(v
->fd
);
2842 if (v
->peer_pidfd
< 0)
2843 return v
->peer_pidfd
;
2848 int varlink_get_peer_pidref(Varlink
*v
, PidRef
*ret
) {
2851 assert_return(v
, -EINVAL
);
2852 assert_return(ret
, -EINVAL
);
2854 /* Returns r > 0 if we acquired the pidref via SO_PEERPIDFD (i.e. if we can use it for
2855 * authentication). Returns == 0 if we didn't, and the pidref should not be used for
2856 * authentication. */
2858 r
= varlink_acquire_pidfd(v
);
2862 if (v
->peer_pidfd
< 0) {
2865 r
= varlink_get_peer_pid(v
, &pid
);
2869 r
= pidref_set_pid(ret
, pid
);
2873 return 0; /* didn't get pidfd securely */
2876 r
= pidref_set_pidfd(ret
, v
->peer_pidfd
);
2880 return 1; /* got pidfd securely */
2883 int varlink_set_relative_timeout(Varlink
*v
, usec_t timeout
) {
2884 assert_return(v
, -EINVAL
);
2885 assert_return(timeout
> 0, -EINVAL
);
2887 v
->timeout
= timeout
;
2891 VarlinkServer
*varlink_get_server(Varlink
*v
) {
2892 assert_return(v
, NULL
);
2897 int varlink_set_description(Varlink
*v
, const char *description
) {
2898 assert_return(v
, -EINVAL
);
2900 return free_and_strdup(&v
->description
, description
);
2903 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2904 Varlink
*v
= ASSERT_PTR(userdata
);
2908 handle_revents(v
, revents
);
2909 (void) varlink_process(v
);
2914 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
2915 Varlink
*v
= ASSERT_PTR(userdata
);
2919 (void) varlink_process(v
);
2923 static int defer_callback(sd_event_source
*s
, void *userdata
) {
2924 Varlink
*v
= ASSERT_PTR(userdata
);
2928 (void) varlink_process(v
);
2932 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
2933 Varlink
*v
= ASSERT_PTR(userdata
);
2940 e
= varlink_get_events(v
);
2944 r
= sd_event_source_set_io_events(v
->io_event_source
, e
);
2946 return varlink_log_errno(v
, r
, "Failed to set source events: %m");
2948 r
= varlink_get_timeout(v
, &until
);
2951 have_timeout
= r
> 0;
2954 r
= sd_event_source_set_time(v
->time_event_source
, until
);
2956 return varlink_log_errno(v
, r
, "Failed to set source time: %m");
2959 r
= sd_event_source_set_enabled(v
->time_event_source
, have_timeout
? SD_EVENT_ON
: SD_EVENT_OFF
);
2961 return varlink_log_errno(v
, r
, "Failed to enable event source: %m");
2966 static int quit_callback(sd_event_source
*event
, void *userdata
) {
2967 Varlink
*v
= ASSERT_PTR(userdata
);
2977 int varlink_attach_event(Varlink
*v
, sd_event
*e
, int64_t priority
) {
2980 assert_return(v
, -EINVAL
);
2981 assert_return(!v
->event
, -EBUSY
);
2984 v
->event
= sd_event_ref(e
);
2986 r
= sd_event_default(&v
->event
);
2988 return varlink_log_errno(v
, r
, "Failed to create event source: %m");
2991 r
= sd_event_add_time(v
->event
, &v
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, v
);
2995 r
= sd_event_source_set_priority(v
->time_event_source
, priority
);
2999 (void) sd_event_source_set_description(v
->time_event_source
, "varlink-time");
3001 r
= sd_event_add_exit(v
->event
, &v
->quit_event_source
, quit_callback
, v
);
3005 r
= sd_event_source_set_priority(v
->quit_event_source
, priority
);
3009 (void) sd_event_source_set_description(v
->quit_event_source
, "varlink-quit");
3011 r
= sd_event_add_io(v
->event
, &v
->io_event_source
, v
->fd
, 0, io_callback
, v
);
3015 r
= sd_event_source_set_prepare(v
->io_event_source
, prepare_callback
);
3019 r
= sd_event_source_set_priority(v
->io_event_source
, priority
);
3023 (void) sd_event_source_set_description(v
->io_event_source
, "varlink-io");
3025 r
= sd_event_add_defer(v
->event
, &v
->defer_event_source
, defer_callback
, v
);
3029 r
= sd_event_source_set_priority(v
->defer_event_source
, priority
);
3033 (void) sd_event_source_set_description(v
->defer_event_source
, "varlink-defer");
3038 varlink_log_errno(v
, r
, "Failed to setup event source: %m");
3039 varlink_detach_event(v
);
3043 void varlink_detach_event(Varlink
*v
) {
3047 varlink_detach_event_sources(v
);
3049 v
->event
= sd_event_unref(v
->event
);
3052 sd_event
*varlink_get_event(Varlink
*v
) {
3053 assert_return(v
, NULL
);
3058 int varlink_push_fd(Varlink
*v
, int fd
) {
3061 assert_return(v
, -EINVAL
);
3062 assert_return(fd
>= 0, -EBADF
);
3064 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
3065 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
3067 if (!v
->allow_fd_passing_output
)
3070 if (v
->n_pushed_fds
>= INT_MAX
)
3073 if (!GREEDY_REALLOC(v
->pushed_fds
, v
->n_pushed_fds
+ 1))
3076 i
= (int) v
->n_pushed_fds
;
3077 v
->pushed_fds
[v
->n_pushed_fds
++] = fd
;
3081 int varlink_dup_fd(Varlink
*v
, int fd
) {
3082 _cleanup_close_
int dp
= -1;
3085 assert_return(v
, -EINVAL
);
3086 assert_return(fd
>= 0, -EBADF
);
3088 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
3090 dp
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
3094 r
= varlink_push_fd(v
, dp
);
3102 int varlink_reset_fds(Varlink
*v
) {
3103 assert_return(v
, -EINVAL
);
3105 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
3106 * of putting together a message with fds, and then eventually something fails and they need to
3107 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
3109 close_many(v
->output_fds
, v
->n_output_fds
);
3110 v
->n_output_fds
= 0;
3114 int varlink_peek_fd(Varlink
*v
, size_t i
) {
3115 assert_return(v
, -EINVAL
);
3117 /* Returns one of the file descriptors that were received along with the current message. This does
3118 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
3120 if (!v
->allow_fd_passing_input
)
3123 if (i
>= v
->n_input_fds
)
3126 return v
->input_fds
[i
];
3129 int varlink_take_fd(Varlink
*v
, size_t i
) {
3130 assert_return(v
, -EINVAL
);
3132 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
3133 * we'll invalidate the reference to it under our possession. If called twice in a row will return
3136 if (!v
->allow_fd_passing_input
)
3139 if (i
>= v
->n_input_fds
)
3142 return TAKE_FD(v
->input_fds
[i
]);
3145 static int verify_unix_socket(Varlink
*v
) {
3151 if (fstat(v
->fd
, &st
) < 0)
3153 if (!S_ISSOCK(st
.st_mode
)) {
3158 v
->af
= socket_get_family(v
->fd
);
3163 return v
->af
== AF_UNIX
? 0 : -ENOMEDIUM
;
3166 int varlink_set_allow_fd_passing_input(Varlink
*v
, bool b
) {
3169 assert_return(v
, -EINVAL
);
3171 if (v
->allow_fd_passing_input
== b
)
3175 v
->allow_fd_passing_input
= false;
3179 r
= verify_unix_socket(v
);
3183 v
->allow_fd_passing_input
= true;
3187 int varlink_set_allow_fd_passing_output(Varlink
*v
, bool b
) {
3190 assert_return(v
, -EINVAL
);
3192 if (v
->allow_fd_passing_output
== b
)
3196 v
->allow_fd_passing_output
= false;
3200 r
= verify_unix_socket(v
);
3204 v
->allow_fd_passing_output
= true;
3208 int varlink_set_input_sensitive(Varlink
*v
) {
3209 assert_return(v
, -EINVAL
);
3211 v
->input_sensitive
= true;
3215 int varlink_server_new(VarlinkServer
**ret
, VarlinkServerFlags flags
) {
3216 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
3219 assert_return(ret
, -EINVAL
);
3220 assert_return((flags
& ~_VARLINK_SERVER_FLAGS_ALL
) == 0, -EINVAL
);
3222 s
= new(VarlinkServer
, 1);
3224 return log_oom_debug();
3226 *s
= (VarlinkServer
) {
3229 .connections_max
= varlink_server_connections_max(NULL
),
3230 .connections_per_uid_max
= varlink_server_connections_per_uid_max(NULL
),
3233 r
= varlink_server_add_interface_many(
3235 &vl_interface_io_systemd
,
3236 &vl_interface_org_varlink_service
);
3244 static VarlinkServer
* varlink_server_destroy(VarlinkServer
*s
) {
3250 varlink_server_shutdown(s
);
3252 while ((m
= hashmap_steal_first_key(s
->methods
)))
3255 hashmap_free(s
->methods
);
3256 hashmap_free(s
->interfaces
);
3257 hashmap_free(s
->symbols
);
3258 hashmap_free(s
->by_uid
);
3260 sd_event_unref(s
->event
);
3262 free(s
->description
);
3267 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer
, varlink_server
, varlink_server_destroy
);
3269 static int validate_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
3275 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ROOT_ONLY
))
3276 allowed
= ucred
->uid
== 0;
3278 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_MYSELF_ONLY
))
3279 allowed
= allowed
> 0 || ucred
->uid
== getuid();
3281 if (allowed
== 0) { /* Allow access when it is explicitly allowed or when neither
3282 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
3283 varlink_server_log(server
, "Unprivileged client attempted connection, refusing.");
3287 if (server
->n_connections
>= server
->connections_max
) {
3288 varlink_server_log(server
, "Connection limit of %u reached, refusing.", server
->connections_max
);
3292 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
3295 if (!uid_is_valid(ucred
->uid
)) {
3296 varlink_server_log(server
, "Client with invalid UID attempted connection, refusing.");
3300 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
3301 if (c
>= server
->connections_per_uid_max
) {
3302 varlink_server_log(server
, "Per-UID connection limit of %u reached, refusing.",
3303 server
->connections_per_uid_max
);
3311 static int count_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
3318 server
->n_connections
++;
3320 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
3321 assert(uid_is_valid(ucred
->uid
));
3323 r
= hashmap_ensure_allocated(&server
->by_uid
, NULL
);
3325 return varlink_server_log_errno(server
, r
, "Failed to allocate UID hash table: %m");
3327 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
3329 varlink_server_log(server
, "Connections of user " UID_FMT
": %u (of %u max)",
3330 ucred
->uid
, c
, server
->connections_per_uid_max
);
3332 r
= hashmap_replace(server
->by_uid
, UID_TO_PTR(ucred
->uid
), UINT_TO_PTR(c
+ 1));
3334 return varlink_server_log_errno(server
, r
, "Failed to increment counter in UID hash table: %m");
3340 int varlink_server_add_connection(VarlinkServer
*server
, int fd
, Varlink
**ret
) {
3341 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
3342 struct ucred ucred
= UCRED_INVALID
;
3343 bool ucred_acquired
;
3346 assert_return(server
, -EINVAL
);
3347 assert_return(fd
>= 0, -EBADF
);
3349 if ((server
->flags
& (VARLINK_SERVER_ROOT_ONLY
|VARLINK_SERVER_ACCOUNT_UID
)) != 0) {
3350 r
= getpeercred(fd
, &ucred
);
3352 return varlink_server_log_errno(server
, r
, "Failed to acquire peer credentials of incoming socket, refusing: %m");
3354 ucred_acquired
= true;
3356 r
= validate_connection(server
, &ucred
);
3362 ucred_acquired
= false;
3364 r
= varlink_new(&v
);
3366 return varlink_server_log_errno(server
, r
, "Failed to allocate connection object: %m");
3368 r
= count_connection(server
, &ucred
);
3373 if (server
->flags
& VARLINK_SERVER_INHERIT_USERDATA
)
3374 v
->userdata
= server
->userdata
;
3376 if (ucred_acquired
) {
3378 v
->ucred_acquired
= true;
3381 _cleanup_free_
char *desc
= NULL
;
3382 if (asprintf(&desc
, "%s-%i", server
->description
?: "varlink", v
->fd
) >= 0)
3383 v
->description
= TAKE_PTR(desc
);
3385 /* Link up the server and the connection, and take reference in both directions. Note that the
3386 * reference on the connection is left dangling. It will be dropped when the connection is closed,
3387 * which happens in varlink_close(), including in the event loop quit callback. */
3388 v
->server
= varlink_server_ref(server
);
3391 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
3393 if (server
->event
) {
3394 r
= varlink_attach_event(v
, server
->event
, server
->event_priority
);
3396 varlink_log_errno(v
, r
, "Failed to attach new connection: %m");
3397 v
->fd
= -EBADF
; /* take the fd out of the connection again */
3409 static VarlinkServerSocket
*varlink_server_socket_free(VarlinkServerSocket
*ss
) {
3417 DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket
*, varlink_server_socket_free
);
3419 static int connect_callback(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3420 VarlinkServerSocket
*ss
= ASSERT_PTR(userdata
);
3421 _cleanup_close_
int cfd
= -EBADF
;
3427 varlink_server_log(ss
->server
, "New incoming connection.");
3429 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
3431 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
3434 return varlink_server_log_errno(ss
->server
, errno
, "Failed to accept incoming socket: %m");
3437 r
= varlink_server_add_connection(ss
->server
, cfd
, &v
);
3443 if (FLAGS_SET(ss
->server
->flags
, VARLINK_SERVER_INPUT_SENSITIVE
))
3444 varlink_set_input_sensitive(v
);
3446 if (ss
->server
->connect_callback
) {
3447 r
= ss
->server
->connect_callback(ss
->server
, v
, ss
->server
->userdata
);
3449 varlink_log_errno(v
, r
, "Connection callback returned error, disconnecting client: %m");
3458 static int varlink_server_create_listen_fd_socket(VarlinkServer
*s
, int fd
, VarlinkServerSocket
**ret_ss
) {
3459 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3466 ss
= new(VarlinkServerSocket
, 1);
3468 return log_oom_debug();
3470 *ss
= (VarlinkServerSocket
) {
3476 r
= sd_event_add_io(s
->event
, &ss
->event_source
, fd
, EPOLLIN
, connect_callback
, ss
);
3480 r
= sd_event_source_set_priority(ss
->event_source
, s
->event_priority
);
3485 *ret_ss
= TAKE_PTR(ss
);
3489 int varlink_server_listen_fd(VarlinkServer
*s
, int fd
) {
3490 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3493 assert_return(s
, -EINVAL
);
3494 assert_return(fd
>= 0, -EBADF
);
3496 r
= fd_nonblock(fd
, true);
3500 r
= fd_cloexec(fd
, true);
3504 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
3508 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
3512 int varlink_server_listen_address(VarlinkServer
*s
, const char *address
, mode_t m
) {
3513 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3514 union sockaddr_union sockaddr
;
3515 socklen_t sockaddr_len
;
3516 _cleanup_close_
int fd
= -EBADF
;
3519 assert_return(s
, -EINVAL
);
3520 assert_return(address
, -EINVAL
);
3521 assert_return((m
& ~0777) == 0, -EINVAL
);
3523 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
3528 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
3532 fd
= fd_move_above_stdio(fd
);
3534 (void) sockaddr_un_unlink(&sockaddr
.un
);
3536 WITH_UMASK(~m
& 0777) {
3537 r
= mac_selinux_bind(fd
, &sockaddr
.sa
, sockaddr_len
);
3542 if (listen(fd
, SOMAXCONN_DELUXE
) < 0)
3545 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
3549 r
= free_and_strdup(&ss
->address
, address
);
3553 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
3558 int varlink_server_listen_auto(VarlinkServer
*s
) {
3559 _cleanup_strv_free_
char **names
= NULL
;
3562 assert_return(s
, -EINVAL
);
3564 /* Adds all passed fds marked as "varlink" to our varlink server. These fds can either refer to a
3565 * listening socket or to a connection socket.
3567 * See https://varlink.org/#activation for the environment variables this is backed by and the
3568 * recommended "varlink" identifier in $LISTEN_FDNAMES. */
3570 r
= sd_listen_fds_with_names(/* unset_environment= */ false, &names
);
3574 for (int i
= 0; i
< r
; i
++) {
3576 socklen_t l
= sizeof(b
);
3578 if (!streq(names
[i
], "varlink"))
3581 fd
= SD_LISTEN_FDS_START
+ i
;
3583 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
3586 assert(l
== sizeof(b
));
3588 if (b
) /* Listening socket? */
3589 r
= varlink_server_listen_fd(s
, fd
);
3590 else /* Otherwise assume connection socket */
3591 r
= varlink_server_add_connection(s
, fd
, NULL
);
3598 /* For debug purposes let's listen on an explicitly specified address */
3599 const char *e
= secure_getenv("SYSTEMD_VARLINK_LISTEN");
3601 r
= varlink_server_listen_address(s
, e
, FLAGS_SET(s
->flags
, VARLINK_SERVER_ROOT_ONLY
) ? 0600 : 0666);
3609 void* varlink_server_set_userdata(VarlinkServer
*s
, void *userdata
) {
3612 assert_return(s
, NULL
);
3615 s
->userdata
= userdata
;
3620 void* varlink_server_get_userdata(VarlinkServer
*s
) {
3621 assert_return(s
, NULL
);
3626 int varlink_server_loop_auto(VarlinkServer
*server
) {
3627 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
3630 assert_return(server
, -EINVAL
);
3631 assert_return(!server
->event
, -EBUSY
);
3633 /* Runs a Varlink service event loop populated with a passed fd. Exits on the last connection. */
3635 r
= sd_event_new(&event
);
3639 r
= varlink_server_set_exit_on_idle(server
, true);
3643 r
= varlink_server_attach_event(server
, event
, 0);
3647 r
= varlink_server_listen_auto(server
);
3651 return sd_event_loop(event
);
3654 static VarlinkServerSocket
* varlink_server_socket_destroy(VarlinkServerSocket
*ss
) {
3659 LIST_REMOVE(sockets
, ss
->server
->sockets
, ss
);
3661 sd_event_source_disable_unref(ss
->event_source
);
3669 int varlink_server_shutdown(VarlinkServer
*s
) {
3670 assert_return(s
, -EINVAL
);
3673 varlink_server_socket_destroy(s
->sockets
);
3678 static void varlink_server_test_exit_on_idle(VarlinkServer
*s
) {
3681 if (s
->exit_on_idle
&& s
->event
&& s
->n_connections
== 0)
3682 (void) sd_event_exit(s
->event
, 0);
3685 int varlink_server_set_exit_on_idle(VarlinkServer
*s
, bool b
) {
3686 assert_return(s
, -EINVAL
);
3688 s
->exit_on_idle
= b
;
3689 varlink_server_test_exit_on_idle(s
);
3693 static int varlink_server_add_socket_event_source(VarlinkServer
*s
, VarlinkServerSocket
*ss
, int64_t priority
) {
3694 _cleanup_(sd_event_source_unrefp
) sd_event_source
*es
= NULL
;
3700 assert(ss
->fd
>= 0);
3701 assert(!ss
->event_source
);
3703 r
= sd_event_add_io(s
->event
, &es
, ss
->fd
, EPOLLIN
, connect_callback
, ss
);
3707 r
= sd_event_source_set_priority(es
, priority
);
3711 ss
->event_source
= TAKE_PTR(es
);
3715 int varlink_server_attach_event(VarlinkServer
*s
, sd_event
*e
, int64_t priority
) {
3718 assert_return(s
, -EINVAL
);
3719 assert_return(!s
->event
, -EBUSY
);
3722 s
->event
= sd_event_ref(e
);
3724 r
= sd_event_default(&s
->event
);
3729 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
3730 r
= varlink_server_add_socket_event_source(s
, ss
, priority
);
3735 s
->event_priority
= priority
;
3739 varlink_server_detach_event(s
);
3743 int varlink_server_detach_event(VarlinkServer
*s
) {
3744 assert_return(s
, -EINVAL
);
3746 LIST_FOREACH(sockets
, ss
, s
->sockets
)
3747 ss
->event_source
= sd_event_source_disable_unref(ss
->event_source
);
3749 s
->event
= sd_event_unref(s
->event
);
3753 sd_event
*varlink_server_get_event(VarlinkServer
*s
) {
3754 assert_return(s
, NULL
);
3759 static bool varlink_symbol_in_interface(const char *method
, const char *interface
) {
3765 p
= startswith(method
, interface
);
3772 return !strchr(p
+1, '.');
3775 int varlink_server_bind_method(VarlinkServer
*s
, const char *method
, VarlinkMethod callback
) {
3776 _cleanup_free_
char *m
= NULL
;
3779 assert_return(s
, -EINVAL
);
3780 assert_return(method
, -EINVAL
);
3781 assert_return(callback
, -EINVAL
);
3783 if (varlink_symbol_in_interface(method
, "org.varlink.service") ||
3784 varlink_symbol_in_interface(method
, "io.systemd"))
3785 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EEXIST
), "Cannot bind server to '%s'.", method
);
3789 return log_oom_debug();
3791 r
= hashmap_ensure_put(&s
->methods
, &string_hash_ops
, m
, callback
);
3793 return log_oom_debug();
3795 return varlink_server_log_errno(s
, r
, "Failed to register callback: %m");
3802 int varlink_server_bind_method_many_internal(VarlinkServer
*s
, ...) {
3806 assert_return(s
, -EINVAL
);
3810 VarlinkMethod callback
;
3813 method
= va_arg(ap
, const char *);
3817 callback
= va_arg(ap
, VarlinkMethod
);
3819 r
= varlink_server_bind_method(s
, method
, callback
);
3828 int varlink_server_bind_connect(VarlinkServer
*s
, VarlinkConnect callback
) {
3829 assert_return(s
, -EINVAL
);
3831 if (callback
&& s
->connect_callback
&& callback
!= s
->connect_callback
)
3832 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
3834 s
->connect_callback
= callback
;
3838 int varlink_server_bind_disconnect(VarlinkServer
*s
, VarlinkDisconnect callback
) {
3839 assert_return(s
, -EINVAL
);
3841 if (callback
&& s
->disconnect_callback
&& callback
!= s
->disconnect_callback
)
3842 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
3844 s
->disconnect_callback
= callback
;
3848 int varlink_server_add_interface(VarlinkServer
*s
, const VarlinkInterface
*interface
) {
3851 assert_return(s
, -EINVAL
);
3852 assert_return(interface
, -EINVAL
);
3853 assert_return(interface
->name
, -EINVAL
);
3855 if (hashmap_contains(s
->interfaces
, interface
->name
))
3856 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EEXIST
), "Duplicate registration of interface '%s'.", interface
->name
);
3858 r
= hashmap_ensure_put(&s
->interfaces
, &string_hash_ops
, interface
->name
, (void*) interface
);
3862 for (const VarlinkSymbol
*const*symbol
= interface
->symbols
; *symbol
; symbol
++) {
3863 _cleanup_free_
char *j
= NULL
;
3865 /* We only ever want to validate method calls/replies and errors against the interface
3866 * definitions, hence don't bother with the type symbols */
3867 if (!IN_SET((*symbol
)->symbol_type
, VARLINK_METHOD
, VARLINK_ERROR
))
3870 j
= strjoin(interface
->name
, ".", (*symbol
)->name
);
3874 r
= hashmap_ensure_put(&s
->symbols
, &string_hash_ops_free
, j
, (void*) *symbol
);
3884 int varlink_server_add_interface_many_internal(VarlinkServer
*s
, ...) {
3888 assert_return(s
, -EINVAL
);
3892 const VarlinkInterface
*interface
= va_arg(ap
, const VarlinkInterface
*);
3896 r
= varlink_server_add_interface(s
, interface
);
3905 unsigned varlink_server_connections_max(VarlinkServer
*s
) {
3908 /* If a server is specified, return the setting for that server, otherwise the default value */
3910 return s
->connections_max
;
3912 dts
= getdtablesize();
3915 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
3916 if (VARLINK_DEFAULT_CONNECTIONS_MAX
> (unsigned) dts
/ 4 * 3)
3919 return VARLINK_DEFAULT_CONNECTIONS_MAX
;
3922 unsigned varlink_server_connections_per_uid_max(VarlinkServer
*s
) {
3926 return s
->connections_per_uid_max
;
3928 /* Make sure to never use up more than ¾th of available connections for a single user */
3929 m
= varlink_server_connections_max(NULL
);
3930 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
> m
)
3933 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
;
3936 int varlink_server_set_connections_per_uid_max(VarlinkServer
*s
, unsigned m
) {
3937 assert_return(s
, -EINVAL
);
3938 assert_return(m
> 0, -EINVAL
);
3940 s
->connections_per_uid_max
= m
;
3944 int varlink_server_set_connections_max(VarlinkServer
*s
, unsigned m
) {
3945 assert_return(s
, -EINVAL
);
3946 assert_return(m
> 0, -EINVAL
);
3948 s
->connections_max
= m
;
3952 unsigned varlink_server_current_connections(VarlinkServer
*s
) {
3953 assert_return(s
, UINT_MAX
);
3955 return s
->n_connections
;
3958 int varlink_server_set_description(VarlinkServer
*s
, const char *description
) {
3959 assert_return(s
, -EINVAL
);
3961 return free_and_strdup(&s
->description
, description
);
3964 int varlink_server_serialize(VarlinkServer
*s
, FILE *f
, FDSet
*fds
) {
3971 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
3974 assert(ss
->address
);
3975 assert(ss
->fd
>= 0);
3977 fprintf(f
, "varlink-server-socket-address=%s", ss
->address
);
3979 /* If we fail to serialize the fd, it will be considered an error during deserialization */
3980 copy
= fdset_put_dup(fds
, ss
->fd
);
3984 fprintf(f
, " varlink-server-socket-fd=%i", copy
);
3992 int varlink_server_deserialize_one(VarlinkServer
*s
, const char *value
, FDSet
*fds
) {
3993 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3994 _cleanup_free_
char *address
= NULL
;
3995 const char *v
= ASSERT_PTR(value
);
4003 n
= strcspn(v
, " ");
4004 address
= strndup(v
, n
);
4006 return log_oom_debug();
4009 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EINVAL
),
4010 "Failed to deserialize VarlinkServerSocket: %s: %m", value
);
4011 v
= startswith(v
+ n
+ 1, "varlink-server-socket-fd=");
4013 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EINVAL
),
4014 "Failed to deserialize VarlinkServerSocket fd %s: %m", value
);
4016 n
= strcspn(v
, " ");
4017 buf
= strndupa_safe(v
, n
);
4021 return varlink_server_log_errno(s
, fd
, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf
);
4022 if (!fdset_contains(fds
, fd
))
4023 return varlink_server_log_errno(s
, SYNTHETIC_ERRNO(EBADF
),
4024 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd
);
4026 ss
= new(VarlinkServerSocket
, 1);
4028 return log_oom_debug();
4030 *ss
= (VarlinkServerSocket
) {
4032 .address
= TAKE_PTR(address
),
4033 .fd
= fdset_remove(fds
, fd
),
4036 r
= varlink_server_add_socket_event_source(s
, ss
, SD_EVENT_PRIORITY_NORMAL
);
4038 return varlink_server_log_errno(s
, r
, "Failed to add VarlinkServerSocket event source to the event loop: %m");
4040 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
4044 int varlink_invocation(VarlinkInvocationFlags flags
) {
4045 _cleanup_strv_free_
char **names
= NULL
;
4047 socklen_t l
= sizeof(b
);
4049 /* Returns true if this is a "pure" varlink server invocation, i.e. with one fd passed. */
4051 const char *e
= secure_getenv("SYSTEMD_VARLINK_LISTEN"); /* Permit a manual override for testing purposes */
4055 r
= sd_listen_fds_with_names(/* unset_environment= */ false, &names
);
4061 return -ETOOMANYREFS
;
4063 if (!strv_equal(names
, STRV_MAKE("varlink")))
4066 if (FLAGS_SET(flags
, VARLINK_ALLOW_LISTEN
|VARLINK_ALLOW_ACCEPT
)) /* Both flags set? Then allow everything */
4069 if ((flags
& (VARLINK_ALLOW_LISTEN
|VARLINK_ALLOW_ACCEPT
)) == 0) /* Neither is set, then fail */
4072 if (getsockopt(SD_LISTEN_FDS_START
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
4075 assert(l
== sizeof(b
));
4077 if (!FLAGS_SET(flags
, b
? VARLINK_ALLOW_LISTEN
: VARLINK_ALLOW_ACCEPT
))
4083 int varlink_error_to_errno(const char *error
, JsonVariant
*parameters
) {
4084 static const struct {
4088 { VARLINK_ERROR_DISCONNECTED
, -ECONNRESET
},
4089 { VARLINK_ERROR_TIMEOUT
, -ETIMEDOUT
},
4090 { VARLINK_ERROR_PROTOCOL
, -EPROTO
},
4091 { VARLINK_ERROR_INTERFACE_NOT_FOUND
, -EADDRNOTAVAIL
},
4092 { VARLINK_ERROR_METHOD_NOT_FOUND
, -ENXIO
},
4093 { VARLINK_ERROR_METHOD_NOT_IMPLEMENTED
, -ENOTTY
},
4094 { VARLINK_ERROR_INVALID_PARAMETER
, -EINVAL
},
4095 { VARLINK_ERROR_PERMISSION_DENIED
, -EACCES
},
4096 { VARLINK_ERROR_EXPECTED_MORE
, -EBADE
},
4102 FOREACH_ARRAY(t
, table
, ELEMENTSOF(table
))
4103 if (streq(error
, t
->error
))
4106 if (streq(error
, VARLINK_ERROR_SYSTEM
) && parameters
) {
4109 e
= json_variant_by_key(parameters
, "errno");
4110 if (json_variant_is_integer(e
)) {
4113 i
= json_variant_integer(e
);
4114 if (i
> 0 && i
< ERRNO_MAX
)
4119 return -EBADR
; /* Catch-all */