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)
41 typedef enum VarlinkState
{
42 /* Client side states */
44 VARLINK_AWAITING_REPLY
,
45 VARLINK_AWAITING_REPLY_MORE
,
48 VARLINK_PROCESSING_REPLY
,
50 /* Server side states */
52 VARLINK_PROCESSING_METHOD
,
53 VARLINK_PROCESSING_METHOD_MORE
,
54 VARLINK_PROCESSING_METHOD_ONEWAY
,
55 VARLINK_PROCESSED_METHOD
,
56 VARLINK_PENDING_METHOD
,
57 VARLINK_PENDING_METHOD_MORE
,
59 /* Common states (only during shutdown) */
60 VARLINK_PENDING_DISCONNECT
,
61 VARLINK_PENDING_TIMEOUT
,
62 VARLINK_PROCESSING_DISCONNECT
,
63 VARLINK_PROCESSING_TIMEOUT
,
64 VARLINK_PROCESSING_FAILURE
,
68 _VARLINK_STATE_INVALID
= -EINVAL
,
71 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
72 * is still good for something, and false only when it's dead for good. This means: when we are
73 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
74 * the connection is still good, and we are likely to be able to properly operate on it soon. */
75 #define VARLINK_STATE_IS_ALIVE(state) \
77 VARLINK_IDLE_CLIENT, \
78 VARLINK_AWAITING_REPLY, \
79 VARLINK_AWAITING_REPLY_MORE, \
82 VARLINK_PROCESSING_REPLY, \
83 VARLINK_IDLE_SERVER, \
84 VARLINK_PROCESSING_METHOD, \
85 VARLINK_PROCESSING_METHOD_MORE, \
86 VARLINK_PROCESSING_METHOD_ONEWAY, \
87 VARLINK_PROCESSED_METHOD, \
88 VARLINK_PENDING_METHOD, \
89 VARLINK_PENDING_METHOD_MORE)
91 typedef struct VarlinkJsonQueueItem VarlinkJsonQueueItem
;
93 /* A queued message we shall write into the socket, along with the file descriptors to send at the same
94 * time. This queue item binds them together so that message/fd boundaries are maintained throughout the
96 struct VarlinkJsonQueueItem
{
97 LIST_FIELDS(VarlinkJsonQueueItem
, queue
);
106 VarlinkServer
*server
;
109 bool connecting
; /* This boolean indicates whether the socket fd we are operating on is currently
110 * processing an asynchronous connect(). In that state we watch the socket for
111 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
112 * will trigger ENOTCONN. Note that this boolean is kept separate from the
113 * VarlinkState above on purpose: while the connect() is still not complete we
114 * already want to allow queuing of messages and similar. Thus it's nice to keep
115 * these two state concepts separate: the VarlinkState encodes what our own view of
116 * the connection is, i.e. whether we think it's a server, a client, and has
117 * something queued already, while 'connecting' tells us a detail about the
118 * transport used below, that should have no effect on how we otherwise accept and
119 * process operations from the user.
121 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
122 * connection is good to use, even if it might not be fully connected
123 * yet. connecting=true then informs you that actually we are still connecting, and
124 * the connection is actually not established yet and thus any requests you enqueue
125 * now will still work fine but will be queued only, not sent yet, but that
126 * shouldn't stop you from using the connection, since eventually whatever you queue
129 * Or to say this even differently: 'state' is a high-level ("application layer"
130 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
131 * low, if you so will) state, and while they are not entirely unrelated and
132 * sometimes propagate effects to each other they are only asynchronously connected
138 char *input_buffer
; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
139 size_t input_buffer_index
;
140 size_t input_buffer_size
;
141 size_t input_buffer_unscanned
;
143 void *input_control_buffer
;
144 size_t input_control_buffer_size
;
146 char *output_buffer
; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
147 size_t output_buffer_index
;
148 size_t output_buffer_size
;
150 int *input_fds
; /* file descriptors associated with the data in input_buffer (for fd passing) */
153 int *output_fds
; /* file descriptors associated with the data in output_buffer (for fd passing) */
156 /* Further messages to output not yet formatted into text, and thus not included in output_buffer
157 * yet. We keep them separate from output_buffer, to not violate fd message boundaries: we want that
158 * each fd that is sent is associated with its fds, and that fds cannot be accidentally associated
159 * with preceding or following messages. */
160 LIST_HEAD(VarlinkJsonQueueItem
, output_queue
);
161 VarlinkJsonQueueItem
*output_queue_tail
;
163 /* The fds to associate with the next message that is about to be enqueued. The user first pushes the
164 * fds it intends to send via varlink_push_fd() into this queue, and then once the message data is
165 * submitted we'll combine the fds and the message data into one. */
169 VarlinkReply reply_callback
;
171 JsonVariant
*current
;
172 VarlinkSymbol
*current_method
;
175 bool ucred_acquired
:1;
177 bool write_disconnected
:1;
178 bool read_disconnected
:1;
179 bool prefer_read_write
:1;
182 bool allow_fd_passing_input
:1;
183 bool allow_fd_passing_output
:1;
185 bool output_buffer_sensitive
:1; /* whether to erase the output buffer after writing it to the socket */
187 int af
; /* address family if socket; AF_UNSPEC if not socket; negative if not known */
196 sd_event_source
*io_event_source
;
197 sd_event_source
*time_event_source
;
198 sd_event_source
*quit_event_source
;
199 sd_event_source
*defer_event_source
;
204 typedef struct VarlinkServerSocket VarlinkServerSocket
;
206 struct VarlinkServerSocket
{
207 VarlinkServer
*server
;
212 sd_event_source
*event_source
;
214 LIST_FIELDS(VarlinkServerSocket
, sockets
);
217 struct VarlinkServer
{
219 VarlinkServerFlags flags
;
221 LIST_HEAD(VarlinkServerSocket
, sockets
);
223 Hashmap
*methods
; /* Fully qualified symbol name of a method → VarlinkMethod */
224 Hashmap
*interfaces
; /* Fully qualified interface name → VarlinkInterface* */
225 Hashmap
*symbols
; /* Fully qualified symbol name of method/error → VarlinkSymbol* */
226 VarlinkConnect connect_callback
;
227 VarlinkDisconnect disconnect_callback
;
230 int64_t event_priority
;
232 unsigned n_connections
;
233 Hashmap
*by_uid
; /* UID_TO_PTR(uid) → UINT_TO_PTR(n_connections) */
238 unsigned connections_max
;
239 unsigned connections_per_uid_max
;
244 typedef struct VarlinkCollectContext
{
245 JsonVariant
*parameters
;
246 const char *error_id
;
247 VarlinkReplyFlags flags
;
248 } VarlinkCollectContext
;
250 static const char* const varlink_state_table
[_VARLINK_STATE_MAX
] = {
251 [VARLINK_IDLE_CLIENT
] = "idle-client",
252 [VARLINK_AWAITING_REPLY
] = "awaiting-reply",
253 [VARLINK_AWAITING_REPLY_MORE
] = "awaiting-reply-more",
254 [VARLINK_CALLING
] = "calling",
255 [VARLINK_CALLED
] = "called",
256 [VARLINK_PROCESSING_REPLY
] = "processing-reply",
257 [VARLINK_IDLE_SERVER
] = "idle-server",
258 [VARLINK_PROCESSING_METHOD
] = "processing-method",
259 [VARLINK_PROCESSING_METHOD_MORE
] = "processing-method-more",
260 [VARLINK_PROCESSING_METHOD_ONEWAY
] = "processing-method-oneway",
261 [VARLINK_PROCESSED_METHOD
] = "processed-method",
262 [VARLINK_PENDING_METHOD
] = "pending-method",
263 [VARLINK_PENDING_METHOD_MORE
] = "pending-method-more",
264 [VARLINK_PENDING_DISCONNECT
] = "pending-disconnect",
265 [VARLINK_PENDING_TIMEOUT
] = "pending-timeout",
266 [VARLINK_PROCESSING_DISCONNECT
] = "processing-disconnect",
267 [VARLINK_PROCESSING_TIMEOUT
] = "processing-timeout",
268 [VARLINK_PROCESSING_FAILURE
] = "processing-failure",
269 [VARLINK_DISCONNECTED
] = "disconnected",
272 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state
, VarlinkState
);
274 #define varlink_log_errno(v, error, fmt, ...) \
275 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
277 #define varlink_log(v, fmt, ...) \
278 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
280 #define varlink_server_log_errno(s, error, fmt, ...) \
281 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
283 #define varlink_server_log(s, fmt, ...) \
284 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
286 static int varlink_format_queue(Varlink
*v
);
287 static void varlink_server_test_exit_on_idle(VarlinkServer
*s
);
289 static const char *varlink_description(Varlink
*v
) {
290 return (v
? v
->description
: NULL
) ?: "varlink";
293 static const char *varlink_server_description(VarlinkServer
*s
) {
294 return (s
? s
->description
: NULL
) ?: "varlink";
297 static VarlinkJsonQueueItem
*varlink_json_queue_item_free(VarlinkJsonQueueItem
*q
) {
301 json_variant_unref(q
->data
);
302 close_many(q
->fds
, q
->n_fds
);
307 static VarlinkJsonQueueItem
*varlink_json_queue_item_new(JsonVariant
*m
, const int fds
[], size_t n_fds
) {
308 VarlinkJsonQueueItem
*q
;
311 assert(fds
|| n_fds
== 0);
313 q
= malloc(offsetof(VarlinkJsonQueueItem
, fds
) + sizeof(int) * n_fds
);
317 *q
= (VarlinkJsonQueueItem
) {
318 .data
= json_variant_ref(m
),
322 memcpy_safe(q
->fds
, fds
, n_fds
* sizeof(int));
327 static void varlink_set_state(Varlink
*v
, VarlinkState state
) {
329 assert(state
>= 0 && state
< _VARLINK_STATE_MAX
);
332 varlink_log(v
, "Setting state %s",
333 varlink_state_to_string(state
));
335 varlink_log(v
, "Changing state %s %s %s",
336 varlink_state_to_string(v
->state
),
337 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
338 varlink_state_to_string(state
));
343 static int varlink_new(Varlink
**ret
) {
356 .state
= _VARLINK_STATE_INVALID
,
358 .ucred
= UCRED_INVALID
,
360 .timestamp
= USEC_INFINITY
,
361 .timeout
= VARLINK_DEFAULT_TIMEOUT_USEC
,
370 int varlink_connect_address(Varlink
**ret
, const char *address
) {
371 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
372 union sockaddr_union sockaddr
;
375 assert_return(ret
, -EINVAL
);
376 assert_return(address
, -EINVAL
);
380 return log_debug_errno(r
, "Failed to create varlink object: %m");
382 v
->fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
384 return log_debug_errno(errno
, "Failed to create AF_UNIX socket: %m");
386 v
->fd
= fd_move_above_stdio(v
->fd
);
389 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
391 if (r
!= -ENAMETOOLONG
)
392 return log_debug_errno(r
, "Failed to set socket address '%s': %m", address
);
394 /* This is a file system path, and too long to fit into sockaddr_un. Let's connect via O_PATH
397 r
= connect_unix_path(v
->fd
, AT_FDCWD
, address
);
399 r
= RET_NERRNO(connect(v
->fd
, &sockaddr
.sa
, r
));
402 if (!IN_SET(r
, -EAGAIN
, -EINPROGRESS
))
403 return log_debug_errno(r
, "Failed to connect to %s: %m", address
);
405 v
->connecting
= true; /* We are asynchronously connecting, i.e. the connect() is being
406 * processed in the background. As long as that's the case the socket
407 * is in a special state: it's there, we can poll it for EPOLLOUT, but
408 * if we attempt to write() to it before we see EPOLLOUT we'll get
409 * ENOTCONN (and not EAGAIN, like we would for a normal connected
410 * socket that isn't writable at the moment). Since ENOTCONN on write()
411 * hence can mean two different things (i.e. connection not complete
412 * yet vs. already disconnected again), we store as a boolean whether
413 * we are still in connect(). */
416 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
422 int varlink_connect_exec(Varlink
**ret
, const char *_command
, char **_argv
) {
423 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
424 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
425 _cleanup_free_
char *command
= NULL
;
426 _cleanup_strv_free_
char **argv
= NULL
;
429 assert_return(ret
, -EINVAL
);
430 assert_return(_command
, -EINVAL
);
432 /* Copy the strings, in case they point into our own argv[], which we'll invalidate shortly because
433 * we rename the child process */
434 command
= strdup(_command
);
438 if (strv_isempty(_argv
))
439 argv
= strv_new(command
);
441 argv
= strv_copy(_argv
);
445 log_debug("Forking off Varlink child process '%s'.", command
);
447 if (socketpair(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0, pair
) < 0)
448 return log_debug_errno(errno
, "Failed to allocate AF_UNIX socket pair: %m");
452 /* stdio_fds= */ NULL
,
453 /* except_fds= */ (int[]) { pair
[1] },
454 /* n_except_fds= */ 1,
455 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_REOPEN_LOG
|FORK_LOG
|FORK_RLIMIT_NOFILE_SAFE
,
458 return log_debug_errno(r
, "Failed to spawn process: %m");
460 char spid
[DECIMAL_STR_MAX(pid_t
)+1];
461 const char *setenv_list
[] = {
464 "LISTEN_FDNAMES", "varlink",
471 r
= move_fd(pair
[1], 3, /* cloexec= */ false);
473 log_debug_errno(r
, "Failed to move file descriptor to 3: %m");
477 xsprintf(spid
, PID_FMT
, pid
);
479 STRV_FOREACH_PAIR(a
, b
, setenv_list
) {
480 if (setenv(*a
, *b
, /* override= */ true) < 0) {
481 log_debug_errno(errno
, "Failed to set environment variable '%s': %m", *a
);
486 execvp(command
, argv
);
487 log_debug_errno(r
, "Failed to invoke process '%s': %m", command
);
491 pair
[1] = safe_close(pair
[1]);
496 return log_debug_errno(r
, "Failed to create varlink object: %m");
498 v
->fd
= TAKE_FD(pair
[0]);
500 v
->exec_pid
= TAKE_PID(pid
);
501 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
507 int varlink_connect_url(Varlink
**ret
, const char *url
) {
508 _cleanup_free_
char *c
= NULL
;
513 assert_return(ret
, -EINVAL
);
514 assert_return(url
, -EINVAL
);
516 // FIXME: Add support for vsock:, ssh-exec:, ssh-unix: URL schemes here. (The latter with OpenSSH
517 // 9.4's -W switch for referencing remote AF_UNIX sockets.)
519 /* The Varlink URL scheme is a bit underdefined. We support only the unix: transport for now, plus an
520 * exec: transport we made up ourselves. Strictly speaking this shouldn't even be called URL, since
521 * it has nothing to do with Internet URLs by RFC. */
523 p
= startswith(url
, "unix:");
527 p
= startswith(url
, "exec:");
529 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "URL scheme not supported.");
534 /* The varlink.org reference C library supports more than just file system paths. We might want to
535 * support that one day too. For now simply refuse that. */
536 if (p
[strcspn(p
, ";?#")] != '\0')
537 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT
), "URL parameterization with ';', '?', '#' not supported.");
539 if (exec
|| p
[0] != '@') { /* no validity checks for abstract namespace */
541 if (!path_is_absolute(p
))
542 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path not absolute, refusing.");
544 r
= path_simplify_alloc(p
, &c
);
548 if (!path_is_normalized(c
))
549 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Specified path is not normalized, refusing.");
553 return varlink_connect_exec(ret
, c
, NULL
);
555 return varlink_connect_address(ret
, c
?: p
);
558 int varlink_connect_fd(Varlink
**ret
, int fd
) {
562 assert_return(ret
, -EINVAL
);
563 assert_return(fd
>= 0, -EBADF
);
565 r
= fd_nonblock(fd
, true);
567 return log_debug_errno(r
, "Failed to make fd %d nonblocking: %m", fd
);
571 return log_debug_errno(r
, "Failed to create varlink object: %m");
575 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
577 /* Note that if this function is called we assume the passed socket (if it is one) is already
578 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
579 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
580 * until the connection is fully set up. Behaviour here is hence a bit different from
581 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
582 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
588 static void varlink_detach_event_sources(Varlink
*v
) {
591 v
->io_event_source
= sd_event_source_disable_unref(v
->io_event_source
);
592 v
->time_event_source
= sd_event_source_disable_unref(v
->time_event_source
);
593 v
->quit_event_source
= sd_event_source_disable_unref(v
->quit_event_source
);
594 v
->defer_event_source
= sd_event_source_disable_unref(v
->defer_event_source
);
597 static void varlink_clear_current(Varlink
*v
) {
600 /* Clears the currently processed incoming message */
601 v
->current
= json_variant_unref(v
->current
);
602 v
->current_method
= NULL
;
604 close_many(v
->input_fds
, v
->n_input_fds
);
605 v
->input_fds
= mfree(v
->input_fds
);
609 static void varlink_clear(Varlink
*v
) {
612 varlink_detach_event_sources(v
);
614 v
->fd
= safe_close(v
->fd
);
616 varlink_clear_current(v
);
618 v
->input_buffer
= mfree(v
->input_buffer
);
619 v
->output_buffer
= v
->output_buffer_sensitive
? erase_and_free(v
->output_buffer
) : mfree(v
->output_buffer
);
621 v
->input_control_buffer
= mfree(v
->input_control_buffer
);
622 v
->input_control_buffer_size
= 0;
624 close_many(v
->output_fds
, v
->n_output_fds
);
625 v
->output_fds
= mfree(v
->output_fds
);
628 close_many(v
->pushed_fds
, v
->n_pushed_fds
);
629 v
->pushed_fds
= mfree(v
->pushed_fds
);
632 LIST_CLEAR(queue
, v
->output_queue
, varlink_json_queue_item_free
);
633 v
->output_queue_tail
= NULL
;
635 v
->event
= sd_event_unref(v
->event
);
637 if (v
->exec_pid
> 0) {
638 sigterm_wait(v
->exec_pid
);
643 static Varlink
* varlink_destroy(Varlink
*v
) {
647 /* If this is called the server object must already been unreffed here. Why that? because when we
648 * linked up the varlink connection with the server object we took one ref in each direction */
653 free(v
->description
);
657 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink
, varlink
, varlink_destroy
);
659 static int varlink_test_disconnect(Varlink
*v
) {
662 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
663 * prematurely, since we want to handle half-open connections as well as possible and want to flush
664 * out and read data before we close down if we can. */
666 /* Already disconnected? */
667 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
670 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
674 /* Still something to write and we can write? Stay around */
675 if (v
->output_buffer_size
> 0 && !v
->write_disconnected
)
678 /* Both sides gone already? Then there's no need to stick around */
679 if (v
->read_disconnected
&& v
->write_disconnected
)
682 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
683 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) && v
->read_disconnected
)
686 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
687 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
688 * being down if we never wrote anything. */
689 if (v
->state
== VARLINK_IDLE_CLIENT
&& (v
->write_disconnected
|| v
->got_pollhup
))
692 /* We are on the server side and still want to send out more replies, but we saw POLLHUP already, and
693 * either got no buffered bytes to write anymore or already saw a write error. In that case we should
694 * shut down the varlink link. */
695 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
) && (v
->write_disconnected
|| v
->output_buffer_size
== 0) && v
->got_pollhup
)
701 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
705 static int varlink_write(Varlink
*v
) {
711 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
713 if (v
->connecting
) /* Writing while we are still wait for a non-blocking connect() to complete will
714 * result in ENOTCONN, hence exit early here */
716 if (v
->write_disconnected
)
719 /* If needed let's convert some output queue json variants into text form */
720 r
= varlink_format_queue(v
);
724 if (v
->output_buffer_size
== 0)
729 if (v
->n_output_fds
> 0) { /* If we shall send fds along, we must use sendmsg() */
731 .iov_base
= v
->output_buffer
+ v
->output_buffer_index
,
732 .iov_len
= v
->output_buffer_size
,
737 .msg_controllen
= CMSG_SPACE(sizeof(int) * v
->n_output_fds
),
740 mh
.msg_control
= alloca0(mh
.msg_controllen
);
742 struct cmsghdr
*control
= CMSG_FIRSTHDR(&mh
);
743 control
->cmsg_len
= CMSG_LEN(sizeof(int) * v
->n_output_fds
);
744 control
->cmsg_level
= SOL_SOCKET
;
745 control
->cmsg_type
= SCM_RIGHTS
;
746 memcpy(CMSG_DATA(control
), v
->output_fds
, sizeof(int) * v
->n_output_fds
);
748 n
= sendmsg(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
750 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
751 * with non-socket IO, hence fall back automatically.
753 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
754 bool prefer_write
= v
->prefer_read_write
;
756 n
= send(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
757 if (n
< 0 && errno
== ENOTSOCK
)
758 prefer_write
= v
->prefer_read_write
= true;
761 n
= write(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
);
767 if (ERRNO_IS_DISCONNECT(errno
)) {
768 /* If we get informed about a disconnect on write, then let's remember that, but not
769 * act on it just yet. Let's wait for read() to report the issue first. */
770 v
->write_disconnected
= true;
777 if (v
->output_buffer_sensitive
)
778 explicit_bzero_safe(v
->output_buffer
+ v
->output_buffer_index
, n
);
780 v
->output_buffer_size
-= n
;
782 if (v
->output_buffer_size
== 0) {
783 v
->output_buffer_index
= 0;
784 v
->output_buffer_sensitive
= false; /* We can reset the sensitive flag once the buffer is empty */
786 v
->output_buffer_index
+= n
;
788 close_many(v
->output_fds
, v
->n_output_fds
);
791 v
->timestamp
= now(CLOCK_MONOTONIC
);
795 #define VARLINK_FDS_MAX (16U*1024U)
797 static int varlink_read(Varlink
*v
) {
806 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
))
808 if (v
->connecting
) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
812 if (v
->input_buffer_unscanned
> 0)
814 if (v
->read_disconnected
)
817 if (v
->input_buffer_size
>= VARLINK_BUFFER_MAX
)
822 if (MALLOC_SIZEOF_SAFE(v
->input_buffer
) <= v
->input_buffer_index
+ v
->input_buffer_size
) {
825 add
= MIN(VARLINK_BUFFER_MAX
- v
->input_buffer_size
, VARLINK_READ_SIZE
);
827 if (v
->input_buffer_index
== 0) {
829 if (!GREEDY_REALLOC(v
->input_buffer
, v
->input_buffer_size
+ add
))
835 b
= new(char, v
->input_buffer_size
+ add
);
839 memcpy(b
, v
->input_buffer
+ v
->input_buffer_index
, v
->input_buffer_size
);
841 free_and_replace(v
->input_buffer
, b
);
842 v
->input_buffer_index
= 0;
846 p
= v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
;
847 rs
= MALLOC_SIZEOF_SAFE(v
->input_buffer
) - (v
->input_buffer_index
+ v
->input_buffer_size
);
849 if (v
->allow_fd_passing_input
) {
850 iov
= IOVEC_MAKE(p
, rs
);
852 /* Allocate the fd buffer on the heap, since we need a lot of space potentially */
853 if (!v
->input_control_buffer
) {
854 v
->input_control_buffer_size
= CMSG_SPACE(sizeof(int) * VARLINK_FDS_MAX
);
855 v
->input_control_buffer
= malloc(v
->input_control_buffer_size
);
856 if (!v
->input_control_buffer
)
860 mh
= (struct msghdr
) {
863 .msg_control
= v
->input_control_buffer
,
864 .msg_controllen
= v
->input_control_buffer_size
,
867 n
= recvmsg_safe(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
869 bool prefer_read
= v
->prefer_read_write
;
871 n
= recv(v
->fd
, p
, rs
, MSG_DONTWAIT
);
872 if (n
< 0 && errno
== ENOTSOCK
)
873 prefer_read
= v
->prefer_read_write
= true;
876 n
= read(v
->fd
, p
, rs
);
882 if (ERRNO_IS_DISCONNECT(errno
)) {
883 v
->read_disconnected
= true;
889 if (n
== 0) { /* EOF */
891 if (v
->allow_fd_passing_input
)
894 v
->read_disconnected
= true;
898 if (v
->allow_fd_passing_input
) {
899 struct cmsghdr
* cmsg
;
901 cmsg
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, (socklen_t
) -1);
905 /* We only allow file descriptors to be passed along with the first byte of a
906 * message. If they are passed with any other byte this is a protocol violation. */
907 if (v
->input_buffer_size
!= 0) {
912 add
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
913 if (add
> INT_MAX
- v
->n_input_fds
) {
918 if (!GREEDY_REALLOC(v
->input_fds
, v
->n_input_fds
+ add
)) {
923 memcpy_safe(v
->input_fds
+ v
->n_input_fds
, CMSG_TYPED_DATA(cmsg
, int), add
* sizeof(int));
924 v
->n_input_fds
+= add
;
928 v
->input_buffer_size
+= n
;
929 v
->input_buffer_unscanned
+= n
;
934 static int varlink_parse_message(Varlink
*v
) {
935 const char *e
, *begin
;
943 if (v
->input_buffer_unscanned
<= 0)
946 assert(v
->input_buffer_unscanned
<= v
->input_buffer_size
);
947 assert(v
->input_buffer_index
+ v
->input_buffer_size
<= MALLOC_SIZEOF_SAFE(v
->input_buffer
));
949 begin
= v
->input_buffer
+ v
->input_buffer_index
;
951 e
= memchr(begin
+ v
->input_buffer_size
- v
->input_buffer_unscanned
, 0, v
->input_buffer_unscanned
);
953 v
->input_buffer_unscanned
= 0;
959 varlink_log(v
, "New incoming message: %s", begin
); /* FIXME: should we output the whole message here before validation?
960 * This may produce a non-printable journal entry if the message
961 * is invalid. We may also expose privileged information. */
963 r
= json_parse(begin
, 0, &v
->current
, NULL
, NULL
);
965 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
966 * hence drop all buffered data now. */
967 v
->input_buffer_index
= v
->input_buffer_size
= v
->input_buffer_unscanned
= 0;
968 return varlink_log_errno(v
, r
, "Failed to parse JSON: %m");
971 v
->input_buffer_size
-= sz
;
973 if (v
->input_buffer_size
== 0)
974 v
->input_buffer_index
= 0;
976 v
->input_buffer_index
+= sz
;
978 v
->input_buffer_unscanned
= v
->input_buffer_size
;
982 static int varlink_test_timeout(Varlink
*v
) {
985 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
987 if (v
->timeout
== USEC_INFINITY
)
990 if (now(CLOCK_MONOTONIC
) < usec_add(v
->timestamp
, v
->timeout
))
993 varlink_set_state(v
, VARLINK_PENDING_TIMEOUT
);
998 static int varlink_dispatch_local_error(Varlink
*v
, const char *error
) {
1004 if (!v
->reply_callback
)
1007 r
= v
->reply_callback(v
, NULL
, error
, VARLINK_REPLY_ERROR
|VARLINK_REPLY_LOCAL
, v
->userdata
);
1009 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
1014 static int varlink_dispatch_timeout(Varlink
*v
) {
1017 if (v
->state
!= VARLINK_PENDING_TIMEOUT
)
1020 varlink_set_state(v
, VARLINK_PROCESSING_TIMEOUT
);
1021 varlink_dispatch_local_error(v
, VARLINK_ERROR_TIMEOUT
);
1027 static int varlink_dispatch_disconnect(Varlink
*v
) {
1030 if (v
->state
!= VARLINK_PENDING_DISCONNECT
)
1033 varlink_set_state(v
, VARLINK_PROCESSING_DISCONNECT
);
1034 varlink_dispatch_local_error(v
, VARLINK_ERROR_DISCONNECTED
);
1040 static int varlink_sanitize_parameters(JsonVariant
**v
) {
1043 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
1045 return json_variant_new_object(v
, NULL
, 0);
1046 else if (!json_variant_is_object(*v
))
1052 static int varlink_dispatch_reply(Varlink
*v
) {
1053 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1054 VarlinkReplyFlags flags
= 0;
1055 const char *error
= NULL
;
1062 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
1067 assert(v
->n_pending
> 0);
1069 if (!json_variant_is_object(v
->current
))
1072 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
1074 if (streq(k
, "error")) {
1077 if (!json_variant_is_string(e
))
1080 error
= json_variant_string(e
);
1081 flags
|= VARLINK_REPLY_ERROR
;
1083 } else if (streq(k
, "parameters")) {
1086 if (!json_variant_is_object(e
))
1089 parameters
= json_variant_ref(e
);
1091 } else if (streq(k
, "continues")) {
1092 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1095 if (!json_variant_is_boolean(e
))
1098 if (json_variant_boolean(e
))
1099 flags
|= VARLINK_REPLY_CONTINUES
;
1104 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
1105 if (v
->state
!= VARLINK_AWAITING_REPLY_MORE
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1108 /* An error is final */
1109 if (error
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1112 r
= varlink_sanitize_parameters(¶meters
);
1116 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
)) {
1117 varlink_set_state(v
, VARLINK_PROCESSING_REPLY
);
1119 if (v
->reply_callback
) {
1120 r
= v
->reply_callback(v
, parameters
, error
, flags
, v
->userdata
);
1122 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
1125 varlink_clear_current(v
);
1127 if (v
->state
== VARLINK_PROCESSING_REPLY
) {
1129 assert(v
->n_pending
> 0);
1131 if (!FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
1134 varlink_set_state(v
,
1135 FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
) ? VARLINK_AWAITING_REPLY_MORE
:
1136 v
->n_pending
== 0 ? VARLINK_IDLE_CLIENT
: VARLINK_AWAITING_REPLY
);
1139 assert(v
->state
== VARLINK_CALLING
);
1140 varlink_set_state(v
, VARLINK_CALLED
);
1146 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
1147 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
1153 static int generic_method_get_info(
1155 JsonVariant
*parameters
,
1156 VarlinkMethodFlags flags
,
1159 _cleanup_strv_free_
char **interfaces
= NULL
;
1160 _cleanup_free_
char *product
= NULL
;
1165 if (json_variant_elements(parameters
) != 0)
1166 return varlink_errorb(link
, VARLINK_ERROR_INVALID_PARAMETER
,
1168 JSON_BUILD_PAIR_VARIANT("parameter", json_variant_by_index(parameters
, 0))));
1170 product
= strjoin("systemd (", program_invocation_short_name
, ")");
1174 VarlinkInterface
*interface
;
1175 HASHMAP_FOREACH(interface
, ASSERT_PTR(link
->server
)->interfaces
) {
1176 r
= strv_extend(&interfaces
, interface
->name
);
1181 strv_sort(interfaces
);
1183 return varlink_replyb(link
, JSON_BUILD_OBJECT(
1184 JSON_BUILD_PAIR_STRING("vendor", "The systemd Project"),
1185 JSON_BUILD_PAIR_STRING("product", product
),
1186 JSON_BUILD_PAIR_STRING("version", STRINGIFY(PROJECT_VERSION
) " (" GIT_VERSION
")"),
1187 JSON_BUILD_PAIR_STRING("url", "https://systemd.io/"),
1188 JSON_BUILD_PAIR_STRV("interfaces", interfaces
)));
1191 static int generic_method_get_interface_description(
1193 JsonVariant
*parameters
,
1194 VarlinkMethodFlags flags
,
1197 static const struct JsonDispatch dispatch_table
[] = {
1198 { "interface", JSON_VARIANT_STRING
, json_dispatch_const_string
, 0, JSON_MANDATORY
},
1201 _cleanup_free_
char *text
= NULL
;
1202 const VarlinkInterface
*interface
;
1203 const char *name
= NULL
;
1208 r
= json_dispatch(parameters
, dispatch_table
, 0, &name
);
1212 interface
= hashmap_get(ASSERT_PTR(link
->server
)->interfaces
, name
);
1214 return varlink_errorb(link
, VARLINK_ERROR_INTERFACE_NOT_FOUND
,
1216 JSON_BUILD_PAIR_STRING("interface", name
)));
1218 r
= varlink_idl_format(interface
, &text
);
1222 return varlink_replyb(link
,
1224 JSON_BUILD_PAIR_STRING("description", text
)));
1227 static int varlink_dispatch_method(Varlink
*v
) {
1228 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1229 VarlinkMethodFlags flags
= 0;
1230 const char *method
= NULL
;
1232 VarlinkMethod callback
;
1238 if (v
->state
!= VARLINK_IDLE_SERVER
)
1243 if (!json_variant_is_object(v
->current
))
1246 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
1248 if (streq(k
, "method")) {
1251 if (!json_variant_is_string(e
))
1254 method
= json_variant_string(e
);
1256 } else if (streq(k
, "parameters")) {
1259 if (!json_variant_is_object(e
))
1262 parameters
= json_variant_ref(e
);
1264 } else if (streq(k
, "oneway")) {
1266 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1269 if (!json_variant_is_boolean(e
))
1272 if (json_variant_boolean(e
))
1273 flags
|= VARLINK_METHOD_ONEWAY
;
1275 } else if (streq(k
, "more")) {
1277 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1280 if (!json_variant_is_boolean(e
))
1283 if (json_variant_boolean(e
))
1284 flags
|= VARLINK_METHOD_MORE
;
1293 r
= varlink_sanitize_parameters(¶meters
);
1297 varlink_set_state(v
, (flags
& VARLINK_METHOD_MORE
) ? VARLINK_PROCESSING_METHOD_MORE
:
1298 (flags
& VARLINK_METHOD_ONEWAY
) ? VARLINK_PROCESSING_METHOD_ONEWAY
:
1299 VARLINK_PROCESSING_METHOD
);
1303 /* First consult user supplied method implementations */
1304 callback
= hashmap_get(v
->server
->methods
, method
);
1306 if (streq(method
, "org.varlink.service.GetInfo"))
1307 callback
= generic_method_get_info
;
1308 else if (streq(method
, "org.varlink.service.GetInterfaceDescription"))
1309 callback
= generic_method_get_interface_description
;
1313 bool invalid
= false;
1315 v
->current_method
= hashmap_get(v
->server
->symbols
, method
);
1316 if (!v
->current_method
)
1317 log_debug("No interface description defined for method '%s', not validating.", method
);
1319 const char *bad_field
;
1321 r
= varlink_idl_validate_method_call(v
->current_method
, parameters
, &bad_field
);
1323 log_debug_errno(r
, "Parameters for method %s() didn't pass validation on field '%s': %m", method
, strna(bad_field
));
1325 if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
1326 r
= varlink_errorb(v
, VARLINK_ERROR_INVALID_PARAMETER
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR_STRING("parameter", bad_field
)));
1335 r
= callback(v
, parameters
, flags
, v
->userdata
);
1337 log_debug_errno(r
, "Callback for %s returned error: %m", method
);
1339 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
1340 if (v
->state
== VARLINK_PROCESSED_METHOD
)
1341 r
= 0; /* already processed */
1342 else if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
1343 r
= varlink_error_errno(v
, r
);
1349 } else if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
1350 r
= varlink_errorb(v
, VARLINK_ERROR_METHOD_NOT_FOUND
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
))));
1358 case VARLINK_PROCESSED_METHOD
: /* Method call is fully processed */
1359 case VARLINK_PROCESSING_METHOD_ONEWAY
: /* ditto */
1360 varlink_clear_current(v
);
1361 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1364 case VARLINK_PROCESSING_METHOD
: /* Method call wasn't replied to, will be replied to later */
1365 varlink_set_state(v
, VARLINK_PENDING_METHOD
);
1368 case VARLINK_PROCESSING_METHOD_MORE
: /* No reply for a "more" message was sent, more to come */
1369 varlink_set_state(v
, VARLINK_PENDING_METHOD_MORE
);
1373 assert_not_reached();
1382 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
1383 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
1389 int varlink_process(Varlink
*v
) {
1392 assert_return(v
, -EINVAL
);
1394 if (v
->state
== VARLINK_DISCONNECTED
)
1395 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1399 r
= varlink_write(v
);
1401 varlink_log_errno(v
, r
, "Write failed: %m");
1405 r
= varlink_dispatch_reply(v
);
1407 varlink_log_errno(v
, r
, "Reply dispatch failed: %m");
1411 r
= varlink_dispatch_method(v
);
1413 varlink_log_errno(v
, r
, "Method dispatch failed: %m");
1417 r
= varlink_parse_message(v
);
1419 varlink_log_errno(v
, r
, "Message parsing failed: %m");
1423 r
= varlink_read(v
);
1425 varlink_log_errno(v
, r
, "Read failed: %m");
1429 r
= varlink_test_disconnect(v
);
1434 r
= varlink_dispatch_disconnect(v
);
1439 r
= varlink_test_timeout(v
);
1444 r
= varlink_dispatch_timeout(v
);
1450 if (r
>= 0 && v
->defer_event_source
) {
1453 /* If we did some processing, make sure we are called again soon */
1454 q
= sd_event_source_set_enabled(v
->defer_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
1456 r
= varlink_log_errno(v
, q
, "Failed to enable deferred event source: %m");
1460 if (VARLINK_STATE_IS_ALIVE(v
->state
))
1461 /* Initiate disconnection */
1462 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
1464 /* We failed while disconnecting, in that case close right away */
1472 static void handle_revents(Varlink
*v
, int revents
) {
1475 if (v
->connecting
) {
1476 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
1477 * to complete on, we know we are ready. We don't read the connection error here though,
1478 * we'll get the error on the next read() or write(). */
1479 if ((revents
& (POLLOUT
|POLLHUP
)) == 0)
1482 varlink_log(v
, "Asynchronous connection completed.");
1483 v
->connecting
= false;
1485 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1486 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1487 * momentarily don't want to read nor write anything. */
1489 if (!FLAGS_SET(revents
, POLLHUP
))
1492 varlink_log(v
, "Got POLLHUP from socket.");
1493 v
->got_pollhup
= true;
1497 int varlink_wait(Varlink
*v
, usec_t timeout
) {
1501 assert_return(v
, -EINVAL
);
1503 if (v
->state
== VARLINK_DISCONNECTED
)
1504 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1506 r
= varlink_get_timeout(v
, &t
);
1509 if (t
!= USEC_INFINITY
) {
1512 n
= now(CLOCK_MONOTONIC
);
1516 t
= usec_sub_unsigned(t
, n
);
1519 if (timeout
!= USEC_INFINITY
&&
1520 (t
== USEC_INFINITY
|| timeout
< t
))
1523 fd
= varlink_get_fd(v
);
1527 events
= varlink_get_events(v
);
1531 r
= fd_wait_for_event(fd
, events
, t
);
1532 if (ERRNO_IS_NEG_TRANSIENT(r
)) /* Treat EINTR as not a timeout, but also nothing happened, and
1533 * the caller gets a chance to call back into us */
1538 handle_revents(v
, r
);
1542 int varlink_is_idle(Varlink
*v
) {
1543 assert_return(v
, -EINVAL
);
1545 /* Returns true if there's nothing pending on the connection anymore, i.e. we processed all incoming
1546 * or outgoing messages fully, or finished disconnection */
1548 return IN_SET(v
->state
, VARLINK_DISCONNECTED
, VARLINK_IDLE_CLIENT
, VARLINK_IDLE_SERVER
);
1551 int varlink_get_fd(Varlink
*v
) {
1553 assert_return(v
, -EINVAL
);
1555 if (v
->state
== VARLINK_DISCONNECTED
)
1556 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1558 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBADF
), "No valid fd.");
1563 int varlink_get_events(Varlink
*v
) {
1566 assert_return(v
, -EINVAL
);
1568 if (v
->state
== VARLINK_DISCONNECTED
)
1569 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1571 if (v
->connecting
) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1572 * tells us that the connection is now complete. Before that we should neither
1573 * write() or read() from the fd. */
1576 if (!v
->read_disconnected
&&
1577 IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) &&
1579 v
->input_buffer_unscanned
<= 0)
1582 if (!v
->write_disconnected
&&
1583 v
->output_buffer_size
> 0)
1589 int varlink_get_timeout(Varlink
*v
, usec_t
*ret
) {
1590 assert_return(v
, -EINVAL
);
1592 if (v
->state
== VARLINK_DISCONNECTED
)
1593 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1595 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
) &&
1596 v
->timeout
!= USEC_INFINITY
) {
1598 *ret
= usec_add(v
->timestamp
, v
->timeout
);
1602 *ret
= USEC_INFINITY
;
1607 int varlink_flush(Varlink
*v
) {
1610 assert_return(v
, -EINVAL
);
1612 if (v
->state
== VARLINK_DISCONNECTED
)
1613 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1616 if (v
->output_buffer_size
== 0)
1618 if (v
->write_disconnected
)
1621 r
= varlink_write(v
);
1629 r
= fd_wait_for_event(v
->fd
, POLLOUT
, USEC_INFINITY
);
1630 if (ERRNO_IS_NEG_TRANSIENT(r
))
1633 return varlink_log_errno(v
, r
, "Poll failed on fd: %m");
1636 handle_revents(v
, r
);
1642 static void varlink_detach_server(Varlink
*v
) {
1643 VarlinkServer
*saved_server
;
1649 if (v
->server
->by_uid
&&
1650 v
->ucred_acquired
&&
1651 uid_is_valid(v
->ucred
.uid
)) {
1654 c
= PTR_TO_UINT(hashmap_get(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
)));
1658 (void) hashmap_remove(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
));
1660 (void) hashmap_replace(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
), UINT_TO_PTR(c
- 1));
1663 assert(v
->server
->n_connections
> 0);
1664 v
->server
->n_connections
--;
1666 /* If this is a connection associated to a server, then let's disconnect the server and the
1667 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1668 * before we release the references, let's call the disconnection callback if it is defined. */
1670 saved_server
= TAKE_PTR(v
->server
);
1672 if (saved_server
->disconnect_callback
)
1673 saved_server
->disconnect_callback(saved_server
, v
, saved_server
->userdata
);
1675 varlink_server_test_exit_on_idle(saved_server
);
1676 varlink_server_unref(saved_server
);
1680 int varlink_close(Varlink
*v
) {
1681 assert_return(v
, -EINVAL
);
1683 if (v
->state
== VARLINK_DISCONNECTED
)
1686 varlink_set_state(v
, VARLINK_DISCONNECTED
);
1688 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1689 * which would destroy us before we can call varlink_clear() */
1691 varlink_detach_server(v
);
1698 Varlink
* varlink_close_unref(Varlink
*v
) {
1702 (void) varlink_close(v
);
1703 return varlink_unref(v
);
1706 Varlink
* varlink_flush_close_unref(Varlink
*v
) {
1710 (void) varlink_flush(v
);
1711 return varlink_close_unref(v
);
1714 static int varlink_format_json(Varlink
*v
, JsonVariant
*m
) {
1715 _cleanup_(erase_and_freep
) char *text
= NULL
;
1721 r
= json_variant_format(m
, 0, &text
);
1724 assert(text
[r
] == '\0');
1726 if (v
->output_buffer_size
+ r
+ 1 > VARLINK_BUFFER_MAX
)
1729 varlink_log(v
, "Sending message: %s", text
);
1731 if (v
->output_buffer_size
== 0) {
1733 free_and_replace(v
->output_buffer
, text
);
1735 v
->output_buffer_size
= r
+ 1;
1736 v
->output_buffer_index
= 0;
1738 } else if (v
->output_buffer_index
== 0) {
1740 if (!GREEDY_REALLOC(v
->output_buffer
, v
->output_buffer_size
+ r
+ 1))
1743 memcpy(v
->output_buffer
+ v
->output_buffer_size
, text
, r
+ 1);
1744 v
->output_buffer_size
+= r
+ 1;
1747 const size_t new_size
= v
->output_buffer_size
+ r
+ 1;
1749 n
= new(char, new_size
);
1753 memcpy(mempcpy(n
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
), text
, r
+ 1);
1755 free_and_replace(v
->output_buffer
, n
);
1756 v
->output_buffer_size
= new_size
;
1757 v
->output_buffer_index
= 0;
1760 if (json_variant_is_sensitive(m
))
1761 v
->output_buffer_sensitive
= true; /* Propagate sensitive flag */
1763 text
= mfree(text
); /* No point in the erase_and_free() destructor declared above */
1768 static int varlink_enqueue_json(Varlink
*v
, JsonVariant
*m
) {
1769 VarlinkJsonQueueItem
*q
;
1774 /* If there are no file descriptors to be queued and no queue entries yet we can shortcut things and
1775 * append this entry directly to the output buffer */
1776 if (v
->n_pushed_fds
== 0 && !v
->output_queue
)
1777 return varlink_format_json(v
, m
);
1779 /* Otherwise add a queue entry for this */
1780 q
= varlink_json_queue_item_new(m
, v
->pushed_fds
, v
->n_pushed_fds
);
1784 v
->n_pushed_fds
= 0; /* fds now belong to the queue entry */
1786 LIST_INSERT_AFTER(queue
, v
->output_queue
, v
->output_queue_tail
, q
);
1787 v
->output_queue_tail
= q
;
1791 static int varlink_format_queue(Varlink
*v
) {
1796 /* Takes entries out of the output queue and formats them into the output buffer. But only if this
1797 * would not corrupt our fd message boundaries */
1799 while (v
->output_queue
) {
1800 _cleanup_free_
int *array
= NULL
;
1801 VarlinkJsonQueueItem
*q
= v
->output_queue
;
1803 if (v
->n_output_fds
> 0) /* unwritten fds? if we'd add more we'd corrupt the fd message boundaries, hence wait */
1807 array
= newdup(int, q
->fds
, q
->n_fds
);
1812 r
= varlink_format_json(v
, q
->data
);
1816 /* Take possession of the queue element's fds */
1817 free(v
->output_fds
);
1818 v
->output_fds
= TAKE_PTR(array
);
1819 v
->n_output_fds
= q
->n_fds
;
1822 LIST_REMOVE(queue
, v
->output_queue
, q
);
1823 if (!v
->output_queue
)
1824 v
->output_queue_tail
= NULL
;
1826 varlink_json_queue_item_free(q
);
1832 int varlink_send(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1833 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1836 assert_return(v
, -EINVAL
);
1837 assert_return(method
, -EINVAL
);
1839 if (v
->state
== VARLINK_DISCONNECTED
)
1840 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1842 /* We allow enqueuing multiple method calls at once! */
1843 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1844 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1846 r
= varlink_sanitize_parameters(¶meters
);
1848 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1850 r
= json_build(&m
, JSON_BUILD_OBJECT(
1851 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1852 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1853 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1855 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1857 r
= varlink_enqueue_json(v
, m
);
1859 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1861 /* No state change here, this is one-way only after all */
1862 v
->timestamp
= now(CLOCK_MONOTONIC
);
1866 int varlink_sendb(Varlink
*v
, const char *method
, ...) {
1867 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1871 assert_return(v
, -EINVAL
);
1873 va_start(ap
, method
);
1874 r
= json_buildv(¶meters
, ap
);
1878 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1880 return varlink_send(v
, method
, parameters
);
1883 int varlink_invoke(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1884 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1887 assert_return(v
, -EINVAL
);
1888 assert_return(method
, -EINVAL
);
1890 if (v
->state
== VARLINK_DISCONNECTED
)
1891 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1893 /* We allow enqueuing multiple method calls at once! */
1894 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1895 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1897 r
= varlink_sanitize_parameters(¶meters
);
1899 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1901 r
= json_build(&m
, JSON_BUILD_OBJECT(
1902 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1903 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1905 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1907 r
= varlink_enqueue_json(v
, m
);
1909 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1911 varlink_set_state(v
, VARLINK_AWAITING_REPLY
);
1913 v
->timestamp
= now(CLOCK_MONOTONIC
);
1918 int varlink_invokeb(Varlink
*v
, const char *method
, ...) {
1919 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1923 assert_return(v
, -EINVAL
);
1925 va_start(ap
, method
);
1926 r
= json_buildv(¶meters
, ap
);
1930 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1932 return varlink_invoke(v
, method
, parameters
);
1935 int varlink_observe(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1936 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1939 assert_return(v
, -EINVAL
);
1940 assert_return(method
, -EINVAL
);
1942 if (v
->state
== VARLINK_DISCONNECTED
)
1943 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1945 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1946 * thus insist on an idle client here. */
1947 if (v
->state
!= VARLINK_IDLE_CLIENT
)
1948 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1950 r
= varlink_sanitize_parameters(¶meters
);
1952 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1954 r
= json_build(&m
, JSON_BUILD_OBJECT(
1955 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1956 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1957 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1959 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1961 r
= varlink_enqueue_json(v
, m
);
1963 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1965 varlink_set_state(v
, VARLINK_AWAITING_REPLY_MORE
);
1967 v
->timestamp
= now(CLOCK_MONOTONIC
);
1972 int varlink_observeb(Varlink
*v
, const char *method
, ...) {
1973 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1977 assert_return(v
, -EINVAL
);
1979 va_start(ap
, method
);
1980 r
= json_buildv(¶meters
, ap
);
1984 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1986 return varlink_observe(v
, method
, parameters
);
1992 JsonVariant
*parameters
,
1993 JsonVariant
**ret_parameters
,
1994 const char **ret_error_id
,
1995 VarlinkReplyFlags
*ret_flags
) {
1997 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2000 assert_return(v
, -EINVAL
);
2001 assert_return(method
, -EINVAL
);
2003 if (v
->state
== VARLINK_DISCONNECTED
)
2004 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2005 if (v
->state
!= VARLINK_IDLE_CLIENT
)
2006 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2008 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2010 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2011 * that we can assign a new reply shortly. */
2012 varlink_clear_current(v
);
2014 r
= varlink_sanitize_parameters(¶meters
);
2016 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2018 r
= json_build(&m
, JSON_BUILD_OBJECT(
2019 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
2020 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2022 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2024 r
= varlink_enqueue_json(v
, m
);
2026 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2028 varlink_set_state(v
, VARLINK_CALLING
);
2030 v
->timestamp
= now(CLOCK_MONOTONIC
);
2032 while (v
->state
== VARLINK_CALLING
) {
2034 r
= varlink_process(v
);
2040 r
= varlink_wait(v
, USEC_INFINITY
);
2047 case VARLINK_CALLED
:
2050 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
2051 assert(v
->n_pending
== 1);
2055 *ret_parameters
= json_variant_by_key(v
->current
, "parameters");
2057 *ret_error_id
= json_variant_string(json_variant_by_key(v
->current
, "error"));
2063 case VARLINK_PENDING_DISCONNECT
:
2064 case VARLINK_DISCONNECTED
:
2065 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ECONNRESET
), "Connection was closed.");
2067 case VARLINK_PENDING_TIMEOUT
:
2068 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ETIME
), "Connection timed out.");
2071 assert_not_reached();
2078 JsonVariant
**ret_parameters
,
2079 const char **ret_error_id
,
2080 VarlinkReplyFlags
*ret_flags
, ...) {
2082 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2086 assert_return(v
, -EINVAL
);
2088 va_start(ap
, ret_flags
);
2089 r
= json_buildv(¶meters
, ap
);
2093 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2095 return varlink_call(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
2098 static void varlink_collect_context_free(VarlinkCollectContext
*cc
) {
2101 json_variant_unref(cc
->parameters
);
2102 free((char *)cc
->error_id
);
2105 static int collect_callback(
2107 JsonVariant
*parameters
,
2108 const char *error_id
,
2109 VarlinkReplyFlags flags
,
2112 VarlinkCollectContext
*context
= ASSERT_PTR(userdata
);
2117 context
->flags
= flags
;
2118 /* If we hit an error, we will drop all collected replies and just return the error_id and flags in varlink_collect() */
2120 context
->error_id
= error_id
;
2124 r
= json_variant_append_array(&context
->parameters
, parameters
);
2126 return varlink_log_errno(v
, r
, "Failed to append JSON object to array: %m");
2131 int varlink_collect(
2134 JsonVariant
*parameters
,
2135 JsonVariant
**ret_parameters
,
2136 const char **ret_error_id
,
2137 VarlinkReplyFlags
*ret_flags
) {
2139 _cleanup_(varlink_collect_context_free
) VarlinkCollectContext context
= {};
2142 assert_return(v
, -EINVAL
);
2143 assert_return(method
, -EINVAL
);
2145 if (v
->state
== VARLINK_DISCONNECTED
)
2146 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2147 if (v
->state
!= VARLINK_IDLE_CLIENT
)
2148 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2150 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2152 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2153 * that we can assign a new reply shortly. */
2154 varlink_clear_current(v
);
2156 r
= varlink_bind_reply(v
, collect_callback
);
2158 return varlink_log_errno(v
, r
, "Failed to bind collect callback");
2160 varlink_set_userdata(v
, &context
);
2161 r
= varlink_observe(v
, method
, parameters
);
2163 return varlink_log_errno(v
, r
, "Failed to collect varlink method: %m");
2165 while (v
->state
== VARLINK_AWAITING_REPLY_MORE
) {
2167 r
= varlink_process(v
);
2171 /* If we get an error from any of the replies, return immediately with just the error_id and flags*/
2172 if (context
.error_id
) {
2174 *ret_error_id
= TAKE_PTR(context
.error_id
);
2176 *ret_flags
= context
.flags
;
2183 r
= varlink_wait(v
, USEC_INFINITY
);
2190 case VARLINK_IDLE_CLIENT
:
2193 case VARLINK_PENDING_DISCONNECT
:
2194 case VARLINK_DISCONNECTED
:
2195 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ECONNRESET
), "Connection was closed.");
2197 case VARLINK_PENDING_TIMEOUT
:
2198 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ETIME
), "Connection timed out.");
2201 assert_not_reached();
2205 *ret_parameters
= TAKE_PTR(context
.parameters
);
2207 *ret_error_id
= TAKE_PTR(context
.error_id
);
2209 *ret_flags
= context
.flags
;
2213 int varlink_collectb(
2216 JsonVariant
**ret_parameters
,
2217 const char **ret_error_id
,
2218 VarlinkReplyFlags
*ret_flags
, ...) {
2220 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2224 assert_return(v
, -EINVAL
);
2226 va_start(ap
, ret_flags
);
2227 r
= json_buildv(¶meters
, ap
);
2231 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2233 return varlink_collect(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
2236 int varlink_reply(Varlink
*v
, JsonVariant
*parameters
) {
2237 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2240 assert_return(v
, -EINVAL
);
2242 if (v
->state
== VARLINK_DISCONNECTED
)
2244 if (!IN_SET(v
->state
,
2245 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
2246 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
2249 r
= varlink_sanitize_parameters(¶meters
);
2251 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2253 r
= json_build(&m
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2255 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2257 if (v
->current_method
) {
2258 const char *bad_field
= NULL
;
2260 r
= varlink_idl_validate_method_reply(v
->current_method
, parameters
, &bad_field
);
2262 log_debug_errno(r
, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m", v
->current_method
->name
, strna(bad_field
));
2265 r
= varlink_enqueue_json(v
, m
);
2267 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2269 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
2270 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
2271 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
2272 * process further messages. */
2273 varlink_clear_current(v
);
2274 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2276 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
2277 * means we should it handle the rest of the state engine. */
2278 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
2283 int varlink_replyb(Varlink
*v
, ...) {
2284 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2288 assert_return(v
, -EINVAL
);
2291 r
= json_buildv(¶meters
, ap
);
2297 return varlink_reply(v
, parameters
);
2300 int varlink_error(Varlink
*v
, const char *error_id
, JsonVariant
*parameters
) {
2301 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2304 assert_return(v
, -EINVAL
);
2305 assert_return(error_id
, -EINVAL
);
2307 if (v
->state
== VARLINK_DISCONNECTED
)
2308 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2309 if (!IN_SET(v
->state
,
2310 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
2311 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
2312 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2314 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
2315 * simplify code that puts together a complex reply message with fds, and half-way something
2316 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
2317 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
2318 * the callers don't need to do this explicitly. */
2319 varlink_reset_fds(v
);
2321 r
= varlink_sanitize_parameters(¶meters
);
2323 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2325 r
= json_build(&m
, JSON_BUILD_OBJECT(
2326 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id
)),
2327 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
2329 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2331 VarlinkSymbol
*symbol
= hashmap_get(v
->server
->symbols
, error_id
);
2333 log_debug("No interface description defined for error '%s', not validating.", error_id
);
2335 const char *bad_field
= NULL
;
2337 r
= varlink_idl_validate_error(symbol
, parameters
, &bad_field
);
2339 log_debug_errno(r
, "Parameters for error %s didn't pass validation on field '%s', ignoring: %m", error_id
, strna(bad_field
));
2342 r
= varlink_enqueue_json(v
, m
);
2344 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2346 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
2347 varlink_clear_current(v
);
2348 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2350 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
2355 int varlink_errorb(Varlink
*v
, const char *error_id
, ...) {
2356 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2360 assert_return(v
, -EINVAL
);
2361 assert_return(error_id
, -EINVAL
);
2363 va_start(ap
, error_id
);
2364 r
= json_buildv(¶meters
, ap
);
2368 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2370 return varlink_error(v
, error_id
, parameters
);
2373 int varlink_error_invalid_parameter(Varlink
*v
, JsonVariant
*parameters
) {
2376 assert_return(v
, -EINVAL
);
2377 assert_return(parameters
, -EINVAL
);
2379 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
2380 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
2381 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
2382 * don't expect any arguments. */
2384 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
2385 * parameter sanitization to fail, and it returns -EINVAL. */
2387 if (json_variant_is_string(parameters
)) {
2388 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
2390 r
= json_build(¶meters_obj
,
2392 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters
))));
2396 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
2399 if (json_variant_is_object(parameters
) &&
2400 json_variant_elements(parameters
) > 0) {
2401 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
2403 r
= json_build(¶meters_obj
,
2405 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters
, 0)))));
2409 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
2415 int varlink_error_errno(Varlink
*v
, int error
) {
2416 return varlink_errorb(
2418 VARLINK_ERROR_SYSTEM
,
2419 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error
)))));
2422 int varlink_notify(Varlink
*v
, JsonVariant
*parameters
) {
2423 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2426 assert_return(v
, -EINVAL
);
2428 if (v
->state
== VARLINK_DISCONNECTED
)
2429 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2431 /* If we want to reply with a notify connection but the caller didn't set "more", then return an
2432 * error indicating that we expected to be called with "more" set */
2433 if (IN_SET(v
->state
, VARLINK_PROCESSING_METHOD
, VARLINK_PENDING_METHOD
))
2434 return varlink_error(v
, VARLINK_ERROR_EXPECTED_MORE
, NULL
);
2436 if (!IN_SET(v
->state
, VARLINK_PROCESSING_METHOD_MORE
, VARLINK_PENDING_METHOD_MORE
))
2437 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2439 r
= varlink_sanitize_parameters(¶meters
);
2441 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2443 r
= json_build(&m
, JSON_BUILD_OBJECT(
2444 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
2445 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2447 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2449 if (v
->current_method
) {
2450 const char *bad_field
= NULL
;
2452 r
= varlink_idl_validate_method_reply(v
->current_method
, parameters
, &bad_field
);
2454 log_debug_errno(r
, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m", v
->current_method
->name
, strna(bad_field
));
2457 r
= varlink_enqueue_json(v
, m
);
2459 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2461 /* No state change, as more is coming */
2465 int varlink_notifyb(Varlink
*v
, ...) {
2466 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2470 assert_return(v
, -EINVAL
);
2473 r
= json_buildv(¶meters
, ap
);
2477 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2479 return varlink_notify(v
, parameters
);
2482 int varlink_dispatch(Varlink
*v
, JsonVariant
*parameters
, const JsonDispatch table
[], void *userdata
) {
2483 const char *bad_field
= NULL
;
2486 assert_return(v
, -EINVAL
);
2487 assert_return(table
, -EINVAL
);
2489 /* A wrapper around json_dispatch_full() that returns a nice InvalidParameter error if we hit a problem with some field. */
2491 r
= json_dispatch_full(parameters
, table
, /* bad= */ NULL
, /* flags= */ 0, userdata
, &bad_field
);
2494 return varlink_errorb(v
, VARLINK_ERROR_INVALID_PARAMETER
,
2495 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameter", JSON_BUILD_STRING(bad_field
))));
2502 int varlink_bind_reply(Varlink
*v
, VarlinkReply callback
) {
2503 assert_return(v
, -EINVAL
);
2505 if (callback
&& v
->reply_callback
&& callback
!= v
->reply_callback
)
2506 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
2508 v
->reply_callback
= callback
;
2513 void* varlink_set_userdata(Varlink
*v
, void *userdata
) {
2516 assert_return(v
, NULL
);
2519 v
->userdata
= userdata
;
2524 void* varlink_get_userdata(Varlink
*v
) {
2525 assert_return(v
, NULL
);
2530 static int varlink_acquire_ucred(Varlink
*v
) {
2535 if (v
->ucred_acquired
)
2538 r
= getpeercred(v
->fd
, &v
->ucred
);
2542 v
->ucred_acquired
= true;
2546 int varlink_get_peer_uid(Varlink
*v
, uid_t
*ret
) {
2549 assert_return(v
, -EINVAL
);
2550 assert_return(ret
, -EINVAL
);
2552 r
= varlink_acquire_ucred(v
);
2554 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2556 if (!uid_is_valid(v
->ucred
.uid
))
2557 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2559 *ret
= v
->ucred
.uid
;
2563 int varlink_get_peer_pid(Varlink
*v
, pid_t
*ret
) {
2566 assert_return(v
, -EINVAL
);
2567 assert_return(ret
, -EINVAL
);
2569 r
= varlink_acquire_ucred(v
);
2571 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2573 if (!pid_is_valid(v
->ucred
.pid
))
2574 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2576 *ret
= v
->ucred
.pid
;
2580 int varlink_set_relative_timeout(Varlink
*v
, usec_t timeout
) {
2581 assert_return(v
, -EINVAL
);
2582 assert_return(timeout
> 0, -EINVAL
);
2584 v
->timeout
= timeout
;
2588 VarlinkServer
*varlink_get_server(Varlink
*v
) {
2589 assert_return(v
, NULL
);
2594 int varlink_set_description(Varlink
*v
, const char *description
) {
2595 assert_return(v
, -EINVAL
);
2597 return free_and_strdup(&v
->description
, description
);
2600 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2601 Varlink
*v
= ASSERT_PTR(userdata
);
2605 handle_revents(v
, revents
);
2606 (void) varlink_process(v
);
2611 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
2612 Varlink
*v
= ASSERT_PTR(userdata
);
2616 (void) varlink_process(v
);
2620 static int defer_callback(sd_event_source
*s
, void *userdata
) {
2621 Varlink
*v
= ASSERT_PTR(userdata
);
2625 (void) varlink_process(v
);
2629 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
2630 Varlink
*v
= ASSERT_PTR(userdata
);
2637 e
= varlink_get_events(v
);
2641 r
= sd_event_source_set_io_events(v
->io_event_source
, e
);
2643 return varlink_log_errno(v
, r
, "Failed to set source events: %m");
2645 r
= varlink_get_timeout(v
, &until
);
2648 have_timeout
= r
> 0;
2651 r
= sd_event_source_set_time(v
->time_event_source
, until
);
2653 return varlink_log_errno(v
, r
, "Failed to set source time: %m");
2656 r
= sd_event_source_set_enabled(v
->time_event_source
, have_timeout
? SD_EVENT_ON
: SD_EVENT_OFF
);
2658 return varlink_log_errno(v
, r
, "Failed to enable event source: %m");
2663 static int quit_callback(sd_event_source
*event
, void *userdata
) {
2664 Varlink
*v
= ASSERT_PTR(userdata
);
2674 int varlink_attach_event(Varlink
*v
, sd_event
*e
, int64_t priority
) {
2677 assert_return(v
, -EINVAL
);
2678 assert_return(!v
->event
, -EBUSY
);
2681 v
->event
= sd_event_ref(e
);
2683 r
= sd_event_default(&v
->event
);
2685 return varlink_log_errno(v
, r
, "Failed to create event source: %m");
2688 r
= sd_event_add_time(v
->event
, &v
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, v
);
2692 r
= sd_event_source_set_priority(v
->time_event_source
, priority
);
2696 (void) sd_event_source_set_description(v
->time_event_source
, "varlink-time");
2698 r
= sd_event_add_exit(v
->event
, &v
->quit_event_source
, quit_callback
, v
);
2702 r
= sd_event_source_set_priority(v
->quit_event_source
, priority
);
2706 (void) sd_event_source_set_description(v
->quit_event_source
, "varlink-quit");
2708 r
= sd_event_add_io(v
->event
, &v
->io_event_source
, v
->fd
, 0, io_callback
, v
);
2712 r
= sd_event_source_set_prepare(v
->io_event_source
, prepare_callback
);
2716 r
= sd_event_source_set_priority(v
->io_event_source
, priority
);
2720 (void) sd_event_source_set_description(v
->io_event_source
, "varlink-io");
2722 r
= sd_event_add_defer(v
->event
, &v
->defer_event_source
, defer_callback
, v
);
2726 r
= sd_event_source_set_priority(v
->defer_event_source
, priority
);
2730 (void) sd_event_source_set_description(v
->defer_event_source
, "varlink-defer");
2735 varlink_log_errno(v
, r
, "Failed to setup event source: %m");
2736 varlink_detach_event(v
);
2740 void varlink_detach_event(Varlink
*v
) {
2744 varlink_detach_event_sources(v
);
2746 v
->event
= sd_event_unref(v
->event
);
2749 sd_event
*varlink_get_event(Varlink
*v
) {
2750 assert_return(v
, NULL
);
2755 int varlink_push_fd(Varlink
*v
, int fd
) {
2758 assert_return(v
, -EINVAL
);
2759 assert_return(fd
>= 0, -EBADF
);
2761 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
2762 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
2764 if (!v
->allow_fd_passing_output
)
2767 if (v
->n_pushed_fds
>= INT_MAX
)
2770 if (!GREEDY_REALLOC(v
->pushed_fds
, v
->n_pushed_fds
+ 1))
2773 i
= (int) v
->n_pushed_fds
;
2774 v
->pushed_fds
[v
->n_pushed_fds
++] = fd
;
2778 int varlink_dup_fd(Varlink
*v
, int fd
) {
2779 _cleanup_close_
int dp
= -1;
2782 assert_return(v
, -EINVAL
);
2783 assert_return(fd
>= 0, -EBADF
);
2785 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
2787 dp
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
2791 r
= varlink_push_fd(v
, dp
);
2799 int varlink_reset_fds(Varlink
*v
) {
2800 assert_return(v
, -EINVAL
);
2802 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
2803 * of putting together a message with fds, and then eventually something fails and they need to
2804 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
2806 close_many(v
->output_fds
, v
->n_output_fds
);
2807 v
->n_output_fds
= 0;
2811 int varlink_peek_fd(Varlink
*v
, size_t i
) {
2812 assert_return(v
, -EINVAL
);
2814 /* Returns one of the file descriptors that were received along with the current message. This does
2815 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
2817 if (!v
->allow_fd_passing_input
)
2820 if (i
>= v
->n_input_fds
)
2823 return v
->input_fds
[i
];
2826 int varlink_take_fd(Varlink
*v
, size_t i
) {
2827 assert_return(v
, -EINVAL
);
2829 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
2830 * we'll invalidate the reference to it under our possession. If called twice in a row will return
2833 if (!v
->allow_fd_passing_input
)
2836 if (i
>= v
->n_input_fds
)
2839 return TAKE_FD(v
->input_fds
[i
]);
2842 static int verify_unix_socket(Varlink
*v
) {
2848 if (fstat(v
->fd
, &st
) < 0)
2850 if (!S_ISSOCK(st
.st_mode
)) {
2855 v
->af
= socket_get_family(v
->fd
);
2860 return v
->af
== AF_UNIX
? 0 : -ENOMEDIUM
;
2863 int varlink_set_allow_fd_passing_input(Varlink
*v
, bool b
) {
2866 assert_return(v
, -EINVAL
);
2868 if (v
->allow_fd_passing_input
== b
)
2872 v
->allow_fd_passing_input
= false;
2876 r
= verify_unix_socket(v
);
2880 v
->allow_fd_passing_input
= true;
2884 int varlink_set_allow_fd_passing_output(Varlink
*v
, bool b
) {
2887 assert_return(v
, -EINVAL
);
2889 if (v
->allow_fd_passing_output
== b
)
2893 v
->allow_fd_passing_output
= false;
2897 r
= verify_unix_socket(v
);
2901 v
->allow_fd_passing_output
= true;
2905 int varlink_server_new(VarlinkServer
**ret
, VarlinkServerFlags flags
) {
2906 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
2909 assert_return(ret
, -EINVAL
);
2910 assert_return((flags
& ~_VARLINK_SERVER_FLAGS_ALL
) == 0, -EINVAL
);
2912 s
= new(VarlinkServer
, 1);
2914 return log_oom_debug();
2916 *s
= (VarlinkServer
) {
2919 .connections_max
= varlink_server_connections_max(NULL
),
2920 .connections_per_uid_max
= varlink_server_connections_per_uid_max(NULL
),
2923 r
= varlink_server_add_interface_many(
2925 &vl_interface_io_systemd
,
2926 &vl_interface_org_varlink_service
);
2934 static VarlinkServer
* varlink_server_destroy(VarlinkServer
*s
) {
2940 varlink_server_shutdown(s
);
2942 while ((m
= hashmap_steal_first_key(s
->methods
)))
2945 hashmap_free(s
->methods
);
2946 hashmap_free(s
->interfaces
);
2947 hashmap_free(s
->symbols
);
2948 hashmap_free(s
->by_uid
);
2950 sd_event_unref(s
->event
);
2952 free(s
->description
);
2957 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer
, varlink_server
, varlink_server_destroy
);
2959 static int validate_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
2965 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ROOT_ONLY
))
2966 allowed
= ucred
->uid
== 0;
2968 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_MYSELF_ONLY
))
2969 allowed
= allowed
> 0 || ucred
->uid
== getuid();
2971 if (allowed
== 0) { /* Allow access when it is explicitly allowed or when neither
2972 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2973 varlink_server_log(server
, "Unprivileged client attempted connection, refusing.");
2977 if (server
->n_connections
>= server
->connections_max
) {
2978 varlink_server_log(server
, "Connection limit of %u reached, refusing.", server
->connections_max
);
2982 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
2985 if (!uid_is_valid(ucred
->uid
)) {
2986 varlink_server_log(server
, "Client with invalid UID attempted connection, refusing.");
2990 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
2991 if (c
>= server
->connections_per_uid_max
) {
2992 varlink_server_log(server
, "Per-UID connection limit of %u reached, refusing.",
2993 server
->connections_per_uid_max
);
3001 static int count_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
3008 server
->n_connections
++;
3010 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
3011 r
= hashmap_ensure_allocated(&server
->by_uid
, NULL
);
3013 return log_debug_errno(r
, "Failed to allocate UID hash table: %m");
3015 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
3017 varlink_server_log(server
, "Connections of user " UID_FMT
": %u (of %u max)",
3018 ucred
->uid
, c
, server
->connections_per_uid_max
);
3020 r
= hashmap_replace(server
->by_uid
, UID_TO_PTR(ucred
->uid
), UINT_TO_PTR(c
+ 1));
3022 return log_debug_errno(r
, "Failed to increment counter in UID hash table: %m");
3028 int varlink_server_add_connection(VarlinkServer
*server
, int fd
, Varlink
**ret
) {
3029 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
3030 struct ucred ucred
= UCRED_INVALID
;
3031 bool ucred_acquired
;
3034 assert_return(server
, -EINVAL
);
3035 assert_return(fd
>= 0, -EBADF
);
3037 if ((server
->flags
& (VARLINK_SERVER_ROOT_ONLY
|VARLINK_SERVER_ACCOUNT_UID
)) != 0) {
3038 r
= getpeercred(fd
, &ucred
);
3040 return varlink_server_log_errno(server
, r
, "Failed to acquire peer credentials of incoming socket, refusing: %m");
3042 ucred_acquired
= true;
3044 r
= validate_connection(server
, &ucred
);
3050 ucred_acquired
= false;
3052 r
= varlink_new(&v
);
3054 return varlink_server_log_errno(server
, r
, "Failed to allocate connection object: %m");
3056 r
= count_connection(server
, &ucred
);
3061 if (server
->flags
& VARLINK_SERVER_INHERIT_USERDATA
)
3062 v
->userdata
= server
->userdata
;
3064 if (ucred_acquired
) {
3066 v
->ucred_acquired
= true;
3069 _cleanup_free_
char *desc
= NULL
;
3070 if (asprintf(&desc
, "%s-%i", server
->description
?: "varlink", v
->fd
) >= 0)
3071 v
->description
= TAKE_PTR(desc
);
3073 /* Link up the server and the connection, and take reference in both directions. Note that the
3074 * reference on the connection is left dangling. It will be dropped when the connection is closed,
3075 * which happens in varlink_close(), including in the event loop quit callback. */
3076 v
->server
= varlink_server_ref(server
);
3079 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
3081 if (server
->event
) {
3082 r
= varlink_attach_event(v
, server
->event
, server
->event_priority
);
3084 varlink_log_errno(v
, r
, "Failed to attach new connection: %m");
3085 v
->fd
= -EBADF
; /* take the fd out of the connection again */
3097 static VarlinkServerSocket
*varlink_server_socket_free(VarlinkServerSocket
*ss
) {
3105 DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket
*, varlink_server_socket_free
);
3107 static int connect_callback(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3108 VarlinkServerSocket
*ss
= ASSERT_PTR(userdata
);
3109 _cleanup_close_
int cfd
= -EBADF
;
3115 varlink_server_log(ss
->server
, "New incoming connection.");
3117 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
3119 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
3122 return varlink_server_log_errno(ss
->server
, errno
, "Failed to accept incoming socket: %m");
3125 r
= varlink_server_add_connection(ss
->server
, cfd
, &v
);
3131 if (ss
->server
->connect_callback
) {
3132 r
= ss
->server
->connect_callback(ss
->server
, v
, ss
->server
->userdata
);
3134 varlink_log_errno(v
, r
, "Connection callback returned error, disconnecting client: %m");
3143 static int varlink_server_create_listen_fd_socket(VarlinkServer
*s
, int fd
, VarlinkServerSocket
**ret_ss
) {
3144 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3151 ss
= new(VarlinkServerSocket
, 1);
3153 return log_oom_debug();
3155 *ss
= (VarlinkServerSocket
) {
3161 r
= sd_event_add_io(s
->event
, &ss
->event_source
, fd
, EPOLLIN
, connect_callback
, ss
);
3165 r
= sd_event_source_set_priority(ss
->event_source
, s
->event_priority
);
3170 *ret_ss
= TAKE_PTR(ss
);
3174 int varlink_server_listen_fd(VarlinkServer
*s
, int fd
) {
3175 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3178 assert_return(s
, -EINVAL
);
3179 assert_return(fd
>= 0, -EBADF
);
3181 r
= fd_nonblock(fd
, true);
3185 r
= fd_cloexec(fd
, true);
3189 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
3193 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
3197 int varlink_server_listen_address(VarlinkServer
*s
, const char *address
, mode_t m
) {
3198 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3199 union sockaddr_union sockaddr
;
3200 socklen_t sockaddr_len
;
3201 _cleanup_close_
int fd
= -EBADF
;
3204 assert_return(s
, -EINVAL
);
3205 assert_return(address
, -EINVAL
);
3206 assert_return((m
& ~0777) == 0, -EINVAL
);
3208 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
3213 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
3217 fd
= fd_move_above_stdio(fd
);
3219 (void) sockaddr_un_unlink(&sockaddr
.un
);
3221 WITH_UMASK(~m
& 0777) {
3222 r
= mac_selinux_bind(fd
, &sockaddr
.sa
, sockaddr_len
);
3227 if (listen(fd
, SOMAXCONN_DELUXE
) < 0)
3230 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
3234 r
= free_and_strdup(&ss
->address
, address
);
3238 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
3243 int varlink_server_listen_auto(VarlinkServer
*s
) {
3244 _cleanup_strv_free_
char **names
= NULL
;
3247 assert_return(s
, -EINVAL
);
3249 /* Adds all passed fds marked as "varlink" to our varlink server. These fds can either refer to a
3250 * listening socket or to a connection socket.
3252 * See https://varlink.org/#activation for the environment variables this is backed by and the
3253 * recommended "varlink" identifier in $LISTEN_FDNAMES. */
3255 r
= sd_listen_fds_with_names(/* unset_environment= */ false, &names
);
3259 for (int i
= 0; i
< r
; i
++) {
3261 socklen_t l
= sizeof(b
);
3263 if (!streq(names
[i
], "varlink"))
3266 fd
= SD_LISTEN_FDS_START
+ i
;
3268 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
3271 assert(l
== sizeof(b
));
3273 if (b
) /* Listening socket? */
3274 r
= varlink_server_listen_fd(s
, fd
);
3275 else /* Otherwise assume connection socket */
3276 r
= varlink_server_add_connection(s
, fd
, NULL
);
3286 void* varlink_server_set_userdata(VarlinkServer
*s
, void *userdata
) {
3289 assert_return(s
, NULL
);
3292 s
->userdata
= userdata
;
3297 void* varlink_server_get_userdata(VarlinkServer
*s
) {
3298 assert_return(s
, NULL
);
3303 int varlink_server_loop_auto(VarlinkServer
*server
) {
3304 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
3307 assert_return(server
, -EINVAL
);
3308 assert_return(!server
->event
, -EBUSY
);
3310 /* Runs a Varlink service event loop populated with a passed fd. Exits on the last connection. */
3312 r
= sd_event_new(&event
);
3316 r
= varlink_server_set_exit_on_idle(server
, true);
3320 r
= varlink_server_attach_event(server
, event
, 0);
3324 r
= varlink_server_listen_auto(server
);
3328 return sd_event_loop(event
);
3331 static VarlinkServerSocket
* varlink_server_socket_destroy(VarlinkServerSocket
*ss
) {
3336 LIST_REMOVE(sockets
, ss
->server
->sockets
, ss
);
3338 sd_event_source_disable_unref(ss
->event_source
);
3346 int varlink_server_shutdown(VarlinkServer
*s
) {
3347 assert_return(s
, -EINVAL
);
3350 varlink_server_socket_destroy(s
->sockets
);
3355 static void varlink_server_test_exit_on_idle(VarlinkServer
*s
) {
3358 if (s
->exit_on_idle
&& s
->event
&& s
->n_connections
== 0)
3359 (void) sd_event_exit(s
->event
, 0);
3362 int varlink_server_set_exit_on_idle(VarlinkServer
*s
, bool b
) {
3363 assert_return(s
, -EINVAL
);
3365 s
->exit_on_idle
= b
;
3366 varlink_server_test_exit_on_idle(s
);
3370 static int varlink_server_add_socket_event_source(VarlinkServer
*s
, VarlinkServerSocket
*ss
, int64_t priority
) {
3371 _cleanup_(sd_event_source_unrefp
) sd_event_source
*es
= NULL
;
3377 assert(ss
->fd
>= 0);
3378 assert(!ss
->event_source
);
3380 r
= sd_event_add_io(s
->event
, &es
, ss
->fd
, EPOLLIN
, connect_callback
, ss
);
3384 r
= sd_event_source_set_priority(es
, priority
);
3388 ss
->event_source
= TAKE_PTR(es
);
3392 int varlink_server_attach_event(VarlinkServer
*s
, sd_event
*e
, int64_t priority
) {
3395 assert_return(s
, -EINVAL
);
3396 assert_return(!s
->event
, -EBUSY
);
3399 s
->event
= sd_event_ref(e
);
3401 r
= sd_event_default(&s
->event
);
3406 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
3407 r
= varlink_server_add_socket_event_source(s
, ss
, priority
);
3412 s
->event_priority
= priority
;
3416 varlink_server_detach_event(s
);
3420 int varlink_server_detach_event(VarlinkServer
*s
) {
3421 assert_return(s
, -EINVAL
);
3423 LIST_FOREACH(sockets
, ss
, s
->sockets
)
3424 ss
->event_source
= sd_event_source_disable_unref(ss
->event_source
);
3426 sd_event_unref(s
->event
);
3430 sd_event
*varlink_server_get_event(VarlinkServer
*s
) {
3431 assert_return(s
, NULL
);
3436 static bool varlink_symbol_in_interface(const char *method
, const char *interface
) {
3442 p
= startswith(method
, interface
);
3449 return !strchr(p
+1, '.');
3452 int varlink_server_bind_method(VarlinkServer
*s
, const char *method
, VarlinkMethod callback
) {
3453 _cleanup_free_
char *m
= NULL
;
3456 assert_return(s
, -EINVAL
);
3457 assert_return(method
, -EINVAL
);
3458 assert_return(callback
, -EINVAL
);
3460 if (varlink_symbol_in_interface(method
, "org.varlink.service") ||
3461 varlink_symbol_in_interface(method
, "io.systemd"))
3462 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST
), "Cannot bind server to '%s'.", method
);
3466 return log_oom_debug();
3468 r
= hashmap_ensure_put(&s
->methods
, &string_hash_ops
, m
, callback
);
3470 return log_oom_debug();
3472 return log_debug_errno(r
, "Failed to register callback: %m");
3479 int varlink_server_bind_method_many_internal(VarlinkServer
*s
, ...) {
3483 assert_return(s
, -EINVAL
);
3487 VarlinkMethod callback
;
3490 method
= va_arg(ap
, const char *);
3494 callback
= va_arg(ap
, VarlinkMethod
);
3496 r
= varlink_server_bind_method(s
, method
, callback
);
3505 int varlink_server_bind_connect(VarlinkServer
*s
, VarlinkConnect callback
) {
3506 assert_return(s
, -EINVAL
);
3508 if (callback
&& s
->connect_callback
&& callback
!= s
->connect_callback
)
3509 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
3511 s
->connect_callback
= callback
;
3515 int varlink_server_bind_disconnect(VarlinkServer
*s
, VarlinkDisconnect callback
) {
3516 assert_return(s
, -EINVAL
);
3518 if (callback
&& s
->disconnect_callback
&& callback
!= s
->disconnect_callback
)
3519 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
3521 s
->disconnect_callback
= callback
;
3525 int varlink_server_add_interface(VarlinkServer
*s
, const VarlinkInterface
*interface
) {
3528 assert_return(s
, -EINVAL
);
3529 assert_return(interface
, -EINVAL
);
3530 assert_return(interface
->name
, -EINVAL
);
3532 if (hashmap_contains(s
->interfaces
, interface
->name
))
3533 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST
), "Duplicate registration of interface '%s'.", interface
->name
);
3535 r
= hashmap_ensure_put(&s
->interfaces
, &string_hash_ops
, interface
->name
, (void*) interface
);
3539 for (const VarlinkSymbol
*const*symbol
= interface
->symbols
; *symbol
; symbol
++) {
3540 _cleanup_free_
char *j
= NULL
;
3542 /* We only ever want to validate method calls/replies and errors against the interface
3543 * definitions, hence don't bother with the type symbols */
3544 if (!IN_SET((*symbol
)->symbol_type
, VARLINK_METHOD
, VARLINK_ERROR
))
3547 j
= strjoin(interface
->name
, ".", (*symbol
)->name
);
3551 r
= hashmap_ensure_put(&s
->symbols
, &string_hash_ops_free
, j
, (void*) *symbol
);
3561 int varlink_server_add_interface_many_internal(VarlinkServer
*s
, ...) {
3565 assert_return(s
, -EINVAL
);
3569 const VarlinkInterface
*interface
= va_arg(ap
, const VarlinkInterface
*);
3573 r
= varlink_server_add_interface(s
, interface
);
3582 unsigned varlink_server_connections_max(VarlinkServer
*s
) {
3585 /* If a server is specified, return the setting for that server, otherwise the default value */
3587 return s
->connections_max
;
3589 dts
= getdtablesize();
3592 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
3593 if (VARLINK_DEFAULT_CONNECTIONS_MAX
> (unsigned) dts
/ 4 * 3)
3596 return VARLINK_DEFAULT_CONNECTIONS_MAX
;
3599 unsigned varlink_server_connections_per_uid_max(VarlinkServer
*s
) {
3603 return s
->connections_per_uid_max
;
3605 /* Make sure to never use up more than ¾th of available connections for a single user */
3606 m
= varlink_server_connections_max(NULL
);
3607 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
> m
)
3610 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
;
3613 int varlink_server_set_connections_per_uid_max(VarlinkServer
*s
, unsigned m
) {
3614 assert_return(s
, -EINVAL
);
3615 assert_return(m
> 0, -EINVAL
);
3617 s
->connections_per_uid_max
= m
;
3621 int varlink_server_set_connections_max(VarlinkServer
*s
, unsigned m
) {
3622 assert_return(s
, -EINVAL
);
3623 assert_return(m
> 0, -EINVAL
);
3625 s
->connections_max
= m
;
3629 unsigned varlink_server_current_connections(VarlinkServer
*s
) {
3630 assert_return(s
, UINT_MAX
);
3632 return s
->n_connections
;
3635 int varlink_server_set_description(VarlinkServer
*s
, const char *description
) {
3636 assert_return(s
, -EINVAL
);
3638 return free_and_strdup(&s
->description
, description
);
3641 int varlink_server_serialize(VarlinkServer
*s
, FILE *f
, FDSet
*fds
) {
3648 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
3651 assert(ss
->address
);
3652 assert(ss
->fd
>= 0);
3654 fprintf(f
, "varlink-server-socket-address=%s", ss
->address
);
3656 /* If we fail to serialize the fd, it will be considered an error during deserialization */
3657 copy
= fdset_put_dup(fds
, ss
->fd
);
3661 fprintf(f
, " varlink-server-socket-fd=%i", copy
);
3669 int varlink_server_deserialize_one(VarlinkServer
*s
, const char *value
, FDSet
*fds
) {
3670 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3671 _cleanup_free_
char *address
= NULL
;
3672 const char *v
= ASSERT_PTR(value
);
3680 n
= strcspn(v
, " ");
3681 address
= strndup(v
, n
);
3683 return log_oom_debug();
3686 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
3687 "Failed to deserialize VarlinkServerSocket: %s: %m", value
);
3688 v
= startswith(v
+ n
+ 1, "varlink-server-socket-fd=");
3690 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
3691 "Failed to deserialize VarlinkServerSocket fd %s: %m", value
);
3693 n
= strcspn(v
, " ");
3694 buf
= strndupa_safe(v
, n
);
3698 return log_debug_errno(fd
, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf
);
3699 if (!fdset_contains(fds
, fd
))
3700 return log_debug_errno(SYNTHETIC_ERRNO(EBADF
),
3701 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd
);
3703 ss
= new(VarlinkServerSocket
, 1);
3705 return log_oom_debug();
3707 *ss
= (VarlinkServerSocket
) {
3709 .address
= TAKE_PTR(address
),
3710 .fd
= fdset_remove(fds
, fd
),
3713 r
= varlink_server_add_socket_event_source(s
, ss
, SD_EVENT_PRIORITY_NORMAL
);
3715 return log_debug_errno(r
, "Failed to add VarlinkServerSocket event source to the event loop: %m");
3717 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
3721 int varlink_invocation(VarlinkInvocationFlags flags
) {
3722 _cleanup_strv_free_
char **names
= NULL
;
3724 socklen_t l
= sizeof(b
);
3726 /* Returns true if this is a "pure" varlink server invocation, i.e. with one fd passed. */
3728 r
= sd_listen_fds_with_names(/* unset_environment= */ false, &names
);
3734 return -ETOOMANYREFS
;
3736 if (!strv_equal(names
, STRV_MAKE("varlink")))
3739 if (FLAGS_SET(flags
, VARLINK_ALLOW_LISTEN
|VARLINK_ALLOW_ACCEPT
)) /* Both flags set? Then allow everything */
3742 if ((flags
& (VARLINK_ALLOW_LISTEN
|VARLINK_ALLOW_ACCEPT
)) == 0) /* Neither is set, then fail */
3745 if (getsockopt(SD_LISTEN_FDS_START
, SOL_SOCKET
, SO_ACCEPTCONN
, &b
, &l
) < 0)
3748 assert(l
== sizeof(b
));
3750 if (!FLAGS_SET(flags
, b
? VARLINK_ALLOW_LISTEN
: VARLINK_ALLOW_ACCEPT
))