1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "errno-util.h"
9 #include "glyph-util.h"
13 #include "process-util.h"
14 #include "selinux-util.h"
15 #include "serialize.h"
17 #include "socket-util.h"
18 #include "string-table.h"
19 #include "string-util.h"
21 #include "time-util.h"
22 #include "umask-util.h"
23 #include "user-util.h"
25 #include "varlink-internal.h"
27 #define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
28 #define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
30 #define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
31 #define VARLINK_BUFFER_MAX (16U*1024U*1024U)
32 #define VARLINK_READ_SIZE (64U*1024U)
34 typedef enum VarlinkState
{
35 /* Client side states */
37 VARLINK_AWAITING_REPLY
,
38 VARLINK_AWAITING_REPLY_MORE
,
41 VARLINK_PROCESSING_REPLY
,
43 /* Server side states */
45 VARLINK_PROCESSING_METHOD
,
46 VARLINK_PROCESSING_METHOD_MORE
,
47 VARLINK_PROCESSING_METHOD_ONEWAY
,
48 VARLINK_PROCESSED_METHOD
,
49 VARLINK_PENDING_METHOD
,
50 VARLINK_PENDING_METHOD_MORE
,
52 /* Common states (only during shutdown) */
53 VARLINK_PENDING_DISCONNECT
,
54 VARLINK_PENDING_TIMEOUT
,
55 VARLINK_PROCESSING_DISCONNECT
,
56 VARLINK_PROCESSING_TIMEOUT
,
57 VARLINK_PROCESSING_FAILURE
,
61 _VARLINK_STATE_INVALID
= -EINVAL
,
64 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
65 * is still good for something, and false only when it's dead for good. This means: when we are
66 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
67 * the connection is still good, and we are likely to be able to properly operate on it soon. */
68 #define VARLINK_STATE_IS_ALIVE(state) \
70 VARLINK_IDLE_CLIENT, \
71 VARLINK_AWAITING_REPLY, \
72 VARLINK_AWAITING_REPLY_MORE, \
75 VARLINK_PROCESSING_REPLY, \
76 VARLINK_IDLE_SERVER, \
77 VARLINK_PROCESSING_METHOD, \
78 VARLINK_PROCESSING_METHOD_MORE, \
79 VARLINK_PROCESSING_METHOD_ONEWAY, \
80 VARLINK_PROCESSED_METHOD, \
81 VARLINK_PENDING_METHOD, \
82 VARLINK_PENDING_METHOD_MORE)
84 typedef struct VarlinkJsonQueueItem VarlinkJsonQueueItem
;
86 /* A queued message we shall write into the socket, along with the file descriptors to send at the same
87 * time. This queue item binds them together so that message/fd boundaries are maintained throughout the
89 struct VarlinkJsonQueueItem
{
90 LIST_FIELDS(VarlinkJsonQueueItem
, queue
);
99 VarlinkServer
*server
;
102 bool connecting
; /* This boolean indicates whether the socket fd we are operating on is currently
103 * processing an asynchronous connect(). In that state we watch the socket for
104 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
105 * will trigger ENOTCONN. Note that this boolean is kept separate from the
106 * VarlinkState above on purpose: while the connect() is still not complete we
107 * already want to allow queuing of messages and similar. Thus it's nice to keep
108 * these two state concepts separate: the VarlinkState encodes what our own view of
109 * the connection is, i.e. whether we think it's a server, a client, and has
110 * something queued already, while 'connecting' tells us a detail about the
111 * transport used below, that should have no effect on how we otherwise accept and
112 * process operations from the user.
114 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
115 * connection is good to use, even if it might not be fully connected
116 * yet. connecting=true then informs you that actually we are still connecting, and
117 * the connection is actually not established yet and thus any requests you enqueue
118 * now will still work fine but will be queued only, not sent yet, but that
119 * shouldn't stop you from using the connection, since eventually whatever you queue
122 * Or to say this even differently: 'state' is a high-level ("application layer"
123 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
124 * low, if you so will) state, and while they are not entirely unrelated and
125 * sometimes propagate effects to each other they are only asynchronously connected
131 char *input_buffer
; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
132 size_t input_buffer_index
;
133 size_t input_buffer_size
;
134 size_t input_buffer_unscanned
;
136 char *output_buffer
; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
137 size_t output_buffer_index
;
138 size_t output_buffer_size
;
140 int *input_fds
; /* file descriptors associated with the data in input_buffer (for fd passing) */
143 int *output_fds
; /* file descriptors associated with the data in output_buffer (for fd passing) */
146 /* Further messages to output not yet formatted into text, and thus not included in output_buffer
147 * yet. We keep them separate from output_buffer, to not violate fd message boundaries: we want that
148 * each fd that is sent is associated with its fds, and that fds cannot be accidentally associated
149 * with preceding or following messages. */
150 LIST_HEAD(VarlinkJsonQueueItem
, output_queue
);
151 VarlinkJsonQueueItem
*output_queue_tail
;
153 /* The fds to associate with the next message that is about to be enqueued. The user first pushes the
154 * fds it intends to send via varlink_push_fd() into this queue, and then once the message data is
155 * submitted we'll combine the fds and the message data into one. */
159 VarlinkReply reply_callback
;
161 JsonVariant
*current
;
164 bool ucred_acquired
:1;
166 bool write_disconnected
:1;
167 bool read_disconnected
:1;
168 bool prefer_read_write
:1;
171 bool allow_fd_passing_input
:1;
172 bool allow_fd_passing_output
:1;
174 bool output_buffer_sensitive
:1; /* whether to erase the output buffer after writing it to the socket */
176 int af
; /* address family if socket; AF_UNSPEC if not socket; negative if not known */
185 sd_event_source
*io_event_source
;
186 sd_event_source
*time_event_source
;
187 sd_event_source
*quit_event_source
;
188 sd_event_source
*defer_event_source
;
191 typedef struct VarlinkServerSocket VarlinkServerSocket
;
193 struct VarlinkServerSocket
{
194 VarlinkServer
*server
;
199 sd_event_source
*event_source
;
201 LIST_FIELDS(VarlinkServerSocket
, sockets
);
204 struct VarlinkServer
{
206 VarlinkServerFlags flags
;
208 LIST_HEAD(VarlinkServerSocket
, sockets
);
211 VarlinkConnect connect_callback
;
212 VarlinkDisconnect disconnect_callback
;
215 int64_t event_priority
;
217 unsigned n_connections
;
223 unsigned connections_max
;
224 unsigned connections_per_uid_max
;
227 static const char* const varlink_state_table
[_VARLINK_STATE_MAX
] = {
228 [VARLINK_IDLE_CLIENT
] = "idle-client",
229 [VARLINK_AWAITING_REPLY
] = "awaiting-reply",
230 [VARLINK_AWAITING_REPLY_MORE
] = "awaiting-reply-more",
231 [VARLINK_CALLING
] = "calling",
232 [VARLINK_CALLED
] = "called",
233 [VARLINK_PROCESSING_REPLY
] = "processing-reply",
234 [VARLINK_IDLE_SERVER
] = "idle-server",
235 [VARLINK_PROCESSING_METHOD
] = "processing-method",
236 [VARLINK_PROCESSING_METHOD_MORE
] = "processing-method-more",
237 [VARLINK_PROCESSING_METHOD_ONEWAY
] = "processing-method-oneway",
238 [VARLINK_PROCESSED_METHOD
] = "processed-method",
239 [VARLINK_PENDING_METHOD
] = "pending-method",
240 [VARLINK_PENDING_METHOD_MORE
] = "pending-method-more",
241 [VARLINK_PENDING_DISCONNECT
] = "pending-disconnect",
242 [VARLINK_PENDING_TIMEOUT
] = "pending-timeout",
243 [VARLINK_PROCESSING_DISCONNECT
] = "processing-disconnect",
244 [VARLINK_PROCESSING_TIMEOUT
] = "processing-timeout",
245 [VARLINK_PROCESSING_FAILURE
] = "processing-failure",
246 [VARLINK_DISCONNECTED
] = "disconnected",
249 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state
, VarlinkState
);
251 #define varlink_log_errno(v, error, fmt, ...) \
252 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
254 #define varlink_log(v, fmt, ...) \
255 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
257 #define varlink_server_log_errno(s, error, fmt, ...) \
258 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
260 #define varlink_server_log(s, fmt, ...) \
261 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
263 static int varlink_format_queue(Varlink
*v
);
265 static inline const char *varlink_description(Varlink
*v
) {
266 return (v
? v
->description
: NULL
) ?: "varlink";
269 static inline const char *varlink_server_description(VarlinkServer
*s
) {
270 return (s
? s
->description
: NULL
) ?: "varlink";
273 static VarlinkJsonQueueItem
*varlink_json_queue_item_free(VarlinkJsonQueueItem
*q
) {
277 json_variant_unref(q
->data
);
278 close_many(q
->fds
, q
->n_fds
);
283 static VarlinkJsonQueueItem
*varlink_json_queue_item_new(JsonVariant
*m
, const int fds
[], size_t n_fds
) {
284 VarlinkJsonQueueItem
*q
;
287 assert(fds
|| n_fds
== 0);
289 q
= malloc(offsetof(VarlinkJsonQueueItem
, fds
) + sizeof(int) * n_fds
);
293 *q
= (VarlinkJsonQueueItem
) {
294 .data
= json_variant_ref(m
),
298 memcpy_safe(q
->fds
, fds
, n_fds
* sizeof(int));
303 static void varlink_set_state(Varlink
*v
, VarlinkState state
) {
305 assert(state
>= 0 && state
< _VARLINK_STATE_MAX
);
308 varlink_log(v
, "Setting state %s",
309 varlink_state_to_string(state
));
311 varlink_log(v
, "Changing state %s %s %s",
312 varlink_state_to_string(v
->state
),
313 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
),
314 varlink_state_to_string(state
));
319 static int varlink_new(Varlink
**ret
) {
332 .state
= _VARLINK_STATE_INVALID
,
334 .ucred
= UCRED_INVALID
,
336 .timestamp
= USEC_INFINITY
,
337 .timeout
= VARLINK_DEFAULT_TIMEOUT_USEC
,
346 int varlink_connect_address(Varlink
**ret
, const char *address
) {
347 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
348 union sockaddr_union sockaddr
;
351 assert_return(ret
, -EINVAL
);
352 assert_return(address
, -EINVAL
);
356 return log_debug_errno(r
, "Failed to create varlink object: %m");
358 v
->fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
360 return log_debug_errno(errno
, "Failed to create AF_UNIX socket: %m");
362 v
->fd
= fd_move_above_stdio(v
->fd
);
365 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
367 if (r
!= -ENAMETOOLONG
)
368 return log_debug_errno(r
, "Failed to set socket address '%s': %m", address
);
370 /* This is a file system path, and too long to fit into sockaddr_un. Let's connect via O_PATH
373 r
= connect_unix_path(v
->fd
, AT_FDCWD
, address
);
375 r
= RET_NERRNO(connect(v
->fd
, &sockaddr
.sa
, r
));
378 if (!IN_SET(r
, -EAGAIN
, -EINPROGRESS
))
379 return log_debug_errno(r
, "Failed to connect to %s: %m", address
);
381 v
->connecting
= true; /* We are asynchronously connecting, i.e. the connect() is being
382 * processed in the background. As long as that's the case the socket
383 * is in a special state: it's there, we can poll it for EPOLLOUT, but
384 * if we attempt to write() to it before we see EPOLLOUT we'll get
385 * ENOTCONN (and not EAGAIN, like we would for a normal connected
386 * socket that isn't writable at the moment). Since ENOTCONN on write()
387 * hence can mean two different things (i.e. connection not complete
388 * yet vs. already disconnected again), we store as a boolean whether
389 * we are still in connect(). */
392 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
398 int varlink_connect_fd(Varlink
**ret
, int fd
) {
402 assert_return(ret
, -EINVAL
);
403 assert_return(fd
>= 0, -EBADF
);
405 r
= fd_nonblock(fd
, true);
407 return log_debug_errno(r
, "Failed to make fd %d nonblocking: %m", fd
);
411 return log_debug_errno(r
, "Failed to create varlink object: %m");
415 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
417 /* Note that if this function is called we assume the passed socket (if it is one) is already
418 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
419 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
420 * until the connection is fully set up. Behaviour here is hence a bit different from
421 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
422 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
428 static void varlink_detach_event_sources(Varlink
*v
) {
431 v
->io_event_source
= sd_event_source_disable_unref(v
->io_event_source
);
432 v
->time_event_source
= sd_event_source_disable_unref(v
->time_event_source
);
433 v
->quit_event_source
= sd_event_source_disable_unref(v
->quit_event_source
);
434 v
->defer_event_source
= sd_event_source_disable_unref(v
->defer_event_source
);
437 static void varlink_clear_current(Varlink
*v
) {
440 /* Clears the currently processed incoming message */
441 v
->current
= json_variant_unref(v
->current
);
443 close_many(v
->input_fds
, v
->n_input_fds
);
444 v
->input_fds
= mfree(v
->input_fds
);
448 static void varlink_clear(Varlink
*v
) {
451 varlink_detach_event_sources(v
);
453 v
->fd
= safe_close(v
->fd
);
455 varlink_clear_current(v
);
457 v
->input_buffer
= mfree(v
->input_buffer
);
458 v
->output_buffer
= v
->output_buffer_sensitive
? erase_and_free(v
->output_buffer
) : mfree(v
->output_buffer
);
460 varlink_clear_current(v
);
462 close_many(v
->output_fds
, v
->n_output_fds
);
463 v
->output_fds
= mfree(v
->output_fds
);
466 close_many(v
->pushed_fds
, v
->n_pushed_fds
);
467 v
->pushed_fds
= mfree(v
->pushed_fds
);
470 while (v
->output_queue
) {
471 VarlinkJsonQueueItem
*q
= v
->output_queue
;
473 LIST_REMOVE(queue
, v
->output_queue
, q
);
474 varlink_json_queue_item_free(q
);
476 v
->output_queue_tail
= NULL
;
478 v
->event
= sd_event_unref(v
->event
);
481 static Varlink
* varlink_destroy(Varlink
*v
) {
485 /* If this is called the server object must already been unreffed here. Why that? because when we
486 * linked up the varlink connection with the server object we took one ref in each direction */
491 free(v
->description
);
495 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink
, varlink
, varlink_destroy
);
497 static int varlink_test_disconnect(Varlink
*v
) {
500 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
501 * prematurely, since we want to handle half-open connections as well as possible and want to flush
502 * out and read data before we close down if we can. */
504 /* Already disconnected? */
505 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
508 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
512 /* Still something to write and we can write? Stay around */
513 if (v
->output_buffer_size
> 0 && !v
->write_disconnected
)
516 /* Both sides gone already? Then there's no need to stick around */
517 if (v
->read_disconnected
&& v
->write_disconnected
)
520 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
521 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) && v
->read_disconnected
)
524 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
525 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
526 * being down if we never wrote anything. */
527 if (v
->state
== VARLINK_IDLE_CLIENT
&& (v
->write_disconnected
|| v
->got_pollhup
))
530 /* We are on the server side and still want to send out more replies, but we saw POLLHUP already, and
531 * either got no buffered bytes to write anymore or already saw a write error. In that case we should
532 * shut down the varlink link. */
533 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
) && (v
->write_disconnected
|| v
->output_buffer_size
== 0) && v
->got_pollhup
)
539 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
543 static int varlink_write(Varlink
*v
) {
549 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
551 if (v
->connecting
) /* Writing while we are still wait for a non-blocking connect() to complete will
552 * result in ENOTCONN, hence exit early here */
554 if (v
->write_disconnected
)
557 /* If needed let's convert some output queue json variants into text form */
558 r
= varlink_format_queue(v
);
562 if (v
->output_buffer_size
== 0)
567 if (v
->n_output_fds
> 0) { /* If we shall send fds along, we must use sendmsg() */
569 .iov_base
= v
->output_buffer
+ v
->output_buffer_index
,
570 .iov_len
= v
->output_buffer_size
,
575 .msg_controllen
= CMSG_SPACE(sizeof(int) * v
->n_output_fds
),
578 mh
.msg_control
= alloca0(mh
.msg_controllen
);
580 struct cmsghdr
*control
= CMSG_FIRSTHDR(&mh
);
581 control
->cmsg_len
= CMSG_LEN(sizeof(int) * v
->n_output_fds
);
582 control
->cmsg_level
= SOL_SOCKET
;
583 control
->cmsg_type
= SCM_RIGHTS
;
584 memcpy(CMSG_DATA(control
), v
->output_fds
, sizeof(int) * v
->n_output_fds
);
586 n
= sendmsg(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
588 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
589 * with non-socket IO, hence fall back automatically.
591 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
592 bool prefer_write
= v
->prefer_read_write
;
594 n
= send(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
595 if (n
< 0 && errno
== ENOTSOCK
)
596 prefer_write
= v
->prefer_read_write
= true;
599 n
= write(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
);
605 if (ERRNO_IS_DISCONNECT(errno
)) {
606 /* If we get informed about a disconnect on write, then let's remember that, but not
607 * act on it just yet. Let's wait for read() to report the issue first. */
608 v
->write_disconnected
= true;
615 if (v
->output_buffer_sensitive
)
616 explicit_bzero_safe(v
->output_buffer
+ v
->output_buffer_index
, n
);
618 v
->output_buffer_size
-= n
;
620 if (v
->output_buffer_size
== 0) {
621 v
->output_buffer_index
= 0;
622 v
->output_buffer_sensitive
= false; /* We can reset the sensitive flag once the buffer is empty */
624 v
->output_buffer_index
+= n
;
626 close_many(v
->output_fds
, v
->n_output_fds
);
629 v
->timestamp
= now(CLOCK_MONOTONIC
);
633 #define VARLINK_FDS_MAX (16U*1024U)
635 static int varlink_read(Varlink
*v
) {
636 _cleanup_free_
struct cmsghdr
*cmsg_fds
= NULL
;
645 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
))
647 if (v
->connecting
) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
651 if (v
->input_buffer_unscanned
> 0)
653 if (v
->read_disconnected
)
656 if (v
->input_buffer_size
>= VARLINK_BUFFER_MAX
)
661 if (MALLOC_SIZEOF_SAFE(v
->input_buffer
) <= v
->input_buffer_index
+ v
->input_buffer_size
) {
664 add
= MIN(VARLINK_BUFFER_MAX
- v
->input_buffer_size
, VARLINK_READ_SIZE
);
666 if (v
->input_buffer_index
== 0) {
668 if (!GREEDY_REALLOC(v
->input_buffer
, v
->input_buffer_size
+ add
))
674 b
= new(char, v
->input_buffer_size
+ add
);
678 memcpy(b
, v
->input_buffer
+ v
->input_buffer_index
, v
->input_buffer_size
);
680 free_and_replace(v
->input_buffer
, b
);
681 v
->input_buffer_index
= 0;
685 p
= v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
;
686 rs
= MALLOC_SIZEOF_SAFE(v
->input_buffer
) - (v
->input_buffer_index
+ v
->input_buffer_size
);
688 if (v
->allow_fd_passing_input
) {
689 iov
= IOVEC_MAKE(p
, rs
);
690 mh
= (struct msghdr
) {
695 mh
.msg_controllen
= CMSG_SPACE(sizeof(int) * VARLINK_FDS_MAX
);
696 mh
.msg_control
= cmsg_fds
= malloc(mh
.msg_controllen
);
700 n
= recvmsg_safe(v
->fd
, &mh
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
702 bool prefer_read
= v
->prefer_read_write
;
704 n
= recv(v
->fd
, p
, rs
, MSG_DONTWAIT
);
705 if (n
< 0 && errno
== ENOTSOCK
)
706 prefer_read
= v
->prefer_read_write
= true;
709 n
= read(v
->fd
, p
, rs
);
715 if (ERRNO_IS_DISCONNECT(errno
)) {
716 v
->read_disconnected
= true;
722 if (n
== 0) { /* EOF */
724 if (v
->allow_fd_passing_input
)
727 v
->read_disconnected
= true;
731 if (v
->allow_fd_passing_input
) {
732 struct cmsghdr
* cmsg
;
734 cmsg
= cmsg_find(&mh
, SOL_SOCKET
, SCM_RIGHTS
, (socklen_t
) -1);
738 /* We only allow file descriptors to be passed along with the first byte of a
739 * message. If they are passed with any other byte this is a protocol violation. */
740 if (v
->input_buffer_size
!= 0) {
745 add
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(int);
746 if (add
> INT_MAX
- v
->n_input_fds
) {
751 if (!GREEDY_REALLOC(v
->input_fds
, v
->n_input_fds
+ add
)) {
756 memcpy_safe(v
->input_fds
+ v
->n_input_fds
, CMSG_TYPED_DATA(cmsg
, int), add
* sizeof(int));
757 v
->n_input_fds
+= add
;
761 v
->input_buffer_size
+= n
;
762 v
->input_buffer_unscanned
+= n
;
767 static int varlink_parse_message(Varlink
*v
) {
768 const char *e
, *begin
;
776 if (v
->input_buffer_unscanned
<= 0)
779 assert(v
->input_buffer_unscanned
<= v
->input_buffer_size
);
780 assert(v
->input_buffer_index
+ v
->input_buffer_size
<= MALLOC_SIZEOF_SAFE(v
->input_buffer
));
782 begin
= v
->input_buffer
+ v
->input_buffer_index
;
784 e
= memchr(begin
+ v
->input_buffer_size
- v
->input_buffer_unscanned
, 0, v
->input_buffer_unscanned
);
786 v
->input_buffer_unscanned
= 0;
792 varlink_log(v
, "New incoming message: %s", begin
); /* FIXME: should we output the whole message here before validation?
793 * This may produce a non-printable journal entry if the message
794 * is invalid. We may also expose privileged information. */
796 r
= json_parse(begin
, 0, &v
->current
, NULL
, NULL
);
798 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
799 * hence drop all buffered data now. */
800 v
->input_buffer_index
= v
->input_buffer_size
= v
->input_buffer_unscanned
= 0;
801 return varlink_log_errno(v
, r
, "Failed to parse JSON: %m");
804 v
->input_buffer_size
-= sz
;
806 if (v
->input_buffer_size
== 0)
807 v
->input_buffer_index
= 0;
809 v
->input_buffer_index
+= sz
;
811 v
->input_buffer_unscanned
= v
->input_buffer_size
;
815 static int varlink_test_timeout(Varlink
*v
) {
818 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
820 if (v
->timeout
== USEC_INFINITY
)
823 if (now(CLOCK_MONOTONIC
) < usec_add(v
->timestamp
, v
->timeout
))
826 varlink_set_state(v
, VARLINK_PENDING_TIMEOUT
);
831 static int varlink_dispatch_local_error(Varlink
*v
, const char *error
) {
837 if (!v
->reply_callback
)
840 r
= v
->reply_callback(v
, NULL
, error
, VARLINK_REPLY_ERROR
|VARLINK_REPLY_LOCAL
, v
->userdata
);
842 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
847 static int varlink_dispatch_timeout(Varlink
*v
) {
850 if (v
->state
!= VARLINK_PENDING_TIMEOUT
)
853 varlink_set_state(v
, VARLINK_PROCESSING_TIMEOUT
);
854 varlink_dispatch_local_error(v
, VARLINK_ERROR_TIMEOUT
);
860 static int varlink_dispatch_disconnect(Varlink
*v
) {
863 if (v
->state
!= VARLINK_PENDING_DISCONNECT
)
866 varlink_set_state(v
, VARLINK_PROCESSING_DISCONNECT
);
867 varlink_dispatch_local_error(v
, VARLINK_ERROR_DISCONNECTED
);
873 static int varlink_sanitize_parameters(JsonVariant
**v
) {
876 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
878 return json_variant_new_object(v
, NULL
, 0);
879 else if (!json_variant_is_object(*v
))
885 static int varlink_dispatch_reply(Varlink
*v
) {
886 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
887 VarlinkReplyFlags flags
= 0;
888 const char *error
= NULL
;
895 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
900 assert(v
->n_pending
> 0);
902 if (!json_variant_is_object(v
->current
))
905 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
907 if (streq(k
, "error")) {
910 if (!json_variant_is_string(e
))
913 error
= json_variant_string(e
);
914 flags
|= VARLINK_REPLY_ERROR
;
916 } else if (streq(k
, "parameters")) {
919 if (!json_variant_is_object(e
))
922 parameters
= json_variant_ref(e
);
924 } else if (streq(k
, "continues")) {
925 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
928 if (!json_variant_is_boolean(e
))
931 if (json_variant_boolean(e
))
932 flags
|= VARLINK_REPLY_CONTINUES
;
937 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
938 if (v
->state
!= VARLINK_AWAITING_REPLY_MORE
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
941 /* An error is final */
942 if (error
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
945 r
= varlink_sanitize_parameters(¶meters
);
949 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
)) {
950 varlink_set_state(v
, VARLINK_PROCESSING_REPLY
);
952 if (v
->reply_callback
) {
953 r
= v
->reply_callback(v
, parameters
, error
, flags
, v
->userdata
);
955 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
958 varlink_clear_current(v
);
960 if (v
->state
== VARLINK_PROCESSING_REPLY
) {
962 assert(v
->n_pending
> 0);
964 if (!FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
968 FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
) ? VARLINK_AWAITING_REPLY_MORE
:
969 v
->n_pending
== 0 ? VARLINK_IDLE_CLIENT
: VARLINK_AWAITING_REPLY
);
972 assert(v
->state
== VARLINK_CALLING
);
973 varlink_set_state(v
, VARLINK_CALLED
);
979 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
980 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
986 static int varlink_dispatch_method(Varlink
*v
) {
987 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
988 VarlinkMethodFlags flags
= 0;
989 const char *method
= NULL
, *error
;
991 VarlinkMethod callback
;
997 if (v
->state
!= VARLINK_IDLE_SERVER
)
1002 if (!json_variant_is_object(v
->current
))
1005 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
1007 if (streq(k
, "method")) {
1010 if (!json_variant_is_string(e
))
1013 method
= json_variant_string(e
);
1015 } else if (streq(k
, "parameters")) {
1018 if (!json_variant_is_object(e
))
1021 parameters
= json_variant_ref(e
);
1023 } else if (streq(k
, "oneway")) {
1025 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1028 if (!json_variant_is_boolean(e
))
1031 if (json_variant_boolean(e
))
1032 flags
|= VARLINK_METHOD_ONEWAY
;
1034 } else if (streq(k
, "more")) {
1036 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
1039 if (!json_variant_is_boolean(e
))
1042 if (json_variant_boolean(e
))
1043 flags
|= VARLINK_METHOD_MORE
;
1052 r
= varlink_sanitize_parameters(¶meters
);
1056 varlink_set_state(v
, (flags
& VARLINK_METHOD_MORE
) ? VARLINK_PROCESSING_METHOD_MORE
:
1057 (flags
& VARLINK_METHOD_ONEWAY
) ? VARLINK_PROCESSING_METHOD_ONEWAY
:
1058 VARLINK_PROCESSING_METHOD
);
1062 if (STR_IN_SET(method
, "org.varlink.service.GetInfo", "org.varlink.service.GetInterface")) {
1063 /* For now, we don't implement a single of varlink's own methods */
1065 error
= VARLINK_ERROR_METHOD_NOT_IMPLEMENTED
;
1066 } else if (startswith(method
, "org.varlink.service.")) {
1068 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
1070 callback
= hashmap_get(v
->server
->methods
, method
);
1071 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
1075 r
= callback(v
, parameters
, flags
, v
->userdata
);
1077 log_debug_errno(r
, "Callback for %s returned error: %m", method
);
1079 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
1080 if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
1081 r
= varlink_error_errno(v
, r
);
1086 } else if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
1089 r
= varlink_errorb(v
, error
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
))));
1096 case VARLINK_PROCESSED_METHOD
: /* Method call is fully processed */
1097 case VARLINK_PROCESSING_METHOD_ONEWAY
: /* ditto */
1098 varlink_clear_current(v
);
1099 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1102 case VARLINK_PROCESSING_METHOD
: /* Method call wasn't replied to, will be replied to later */
1103 varlink_set_state(v
, VARLINK_PENDING_METHOD
);
1106 case VARLINK_PROCESSING_METHOD_MORE
: /* No reply for a "more" message was sent, more to come */
1107 varlink_set_state(v
, VARLINK_PENDING_METHOD_MORE
);
1111 assert_not_reached();
1121 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
1122 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
1128 int varlink_process(Varlink
*v
) {
1131 assert_return(v
, -EINVAL
);
1133 if (v
->state
== VARLINK_DISCONNECTED
)
1134 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1138 r
= varlink_write(v
);
1140 varlink_log_errno(v
, r
, "Write failed: %m");
1144 r
= varlink_dispatch_reply(v
);
1146 varlink_log_errno(v
, r
, "Reply dispatch failed: %m");
1150 r
= varlink_dispatch_method(v
);
1152 varlink_log_errno(v
, r
, "Method dispatch failed: %m");
1156 r
= varlink_parse_message(v
);
1158 varlink_log_errno(v
, r
, "Message parsing failed: %m");
1162 r
= varlink_read(v
);
1164 varlink_log_errno(v
, r
, "Read failed: %m");
1168 r
= varlink_test_disconnect(v
);
1173 r
= varlink_dispatch_disconnect(v
);
1178 r
= varlink_test_timeout(v
);
1183 r
= varlink_dispatch_timeout(v
);
1189 if (r
>= 0 && v
->defer_event_source
) {
1192 /* If we did some processing, make sure we are called again soon */
1193 q
= sd_event_source_set_enabled(v
->defer_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
1195 r
= varlink_log_errno(v
, q
, "Failed to enable deferred event source: %m");
1199 if (VARLINK_STATE_IS_ALIVE(v
->state
))
1200 /* Initiate disconnection */
1201 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
1203 /* We failed while disconnecting, in that case close right away */
1211 static void handle_revents(Varlink
*v
, int revents
) {
1214 if (v
->connecting
) {
1215 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
1216 * to complete on, we know we are ready. We don't read the connection error here though,
1217 * we'll get the error on the next read() or write(). */
1218 if ((revents
& (POLLOUT
|POLLHUP
)) == 0)
1221 varlink_log(v
, "Asynchronous connection completed.");
1222 v
->connecting
= false;
1224 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1225 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1226 * momentarily don't want to read nor write anything. */
1228 if (!FLAGS_SET(revents
, POLLHUP
))
1231 varlink_log(v
, "Got POLLHUP from socket.");
1232 v
->got_pollhup
= true;
1236 int varlink_wait(Varlink
*v
, usec_t timeout
) {
1240 assert_return(v
, -EINVAL
);
1242 if (v
->state
== VARLINK_DISCONNECTED
)
1243 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1245 r
= varlink_get_timeout(v
, &t
);
1248 if (t
!= USEC_INFINITY
) {
1251 n
= now(CLOCK_MONOTONIC
);
1255 t
= usec_sub_unsigned(t
, n
);
1258 if (timeout
!= USEC_INFINITY
&&
1259 (t
== USEC_INFINITY
|| timeout
< t
))
1262 fd
= varlink_get_fd(v
);
1266 events
= varlink_get_events(v
);
1270 r
= fd_wait_for_event(fd
, events
, t
);
1271 if (r
< 0 && ERRNO_IS_TRANSIENT(r
)) /* Treat EINTR as not a timeout, but also nothing happened, and
1272 * the caller gets a chance to call back into us */
1277 handle_revents(v
, r
);
1281 int varlink_get_fd(Varlink
*v
) {
1283 assert_return(v
, -EINVAL
);
1285 if (v
->state
== VARLINK_DISCONNECTED
)
1286 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1288 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBADF
), "No valid fd.");
1293 int varlink_get_events(Varlink
*v
) {
1296 assert_return(v
, -EINVAL
);
1298 if (v
->state
== VARLINK_DISCONNECTED
)
1299 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1301 if (v
->connecting
) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1302 * tells us that the connection is now complete. Before that we should neither
1303 * write() or read() from the fd. */
1306 if (!v
->read_disconnected
&&
1307 IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) &&
1309 v
->input_buffer_unscanned
<= 0)
1312 if (!v
->write_disconnected
&&
1313 v
->output_buffer_size
> 0)
1319 int varlink_get_timeout(Varlink
*v
, usec_t
*ret
) {
1320 assert_return(v
, -EINVAL
);
1322 if (v
->state
== VARLINK_DISCONNECTED
)
1323 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1325 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
) &&
1326 v
->timeout
!= USEC_INFINITY
) {
1328 *ret
= usec_add(v
->timestamp
, v
->timeout
);
1332 *ret
= USEC_INFINITY
;
1337 int varlink_flush(Varlink
*v
) {
1340 assert_return(v
, -EINVAL
);
1342 if (v
->state
== VARLINK_DISCONNECTED
)
1343 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1346 if (v
->output_buffer_size
== 0)
1348 if (v
->write_disconnected
)
1351 r
= varlink_write(v
);
1359 r
= fd_wait_for_event(v
->fd
, POLLOUT
, USEC_INFINITY
);
1361 if (ERRNO_IS_TRANSIENT(r
))
1364 return varlink_log_errno(v
, r
, "Poll failed on fd: %m");
1369 handle_revents(v
, r
);
1375 static void varlink_detach_server(Varlink
*v
) {
1376 VarlinkServer
*saved_server
;
1382 if (v
->server
->by_uid
&&
1383 v
->ucred_acquired
&&
1384 uid_is_valid(v
->ucred
.uid
)) {
1387 c
= PTR_TO_UINT(hashmap_get(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
)));
1391 (void) hashmap_remove(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
));
1393 (void) hashmap_replace(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
), UINT_TO_PTR(c
- 1));
1396 assert(v
->server
->n_connections
> 0);
1397 v
->server
->n_connections
--;
1399 /* If this is a connection associated to a server, then let's disconnect the server and the
1400 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1401 * before we release the references, let's call the disconnection callback if it is defined. */
1403 saved_server
= TAKE_PTR(v
->server
);
1405 if (saved_server
->disconnect_callback
)
1406 saved_server
->disconnect_callback(saved_server
, v
, saved_server
->userdata
);
1408 varlink_server_unref(saved_server
);
1412 int varlink_close(Varlink
*v
) {
1413 assert_return(v
, -EINVAL
);
1415 if (v
->state
== VARLINK_DISCONNECTED
)
1418 varlink_set_state(v
, VARLINK_DISCONNECTED
);
1420 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1421 * which would destroy us before we can call varlink_clear() */
1423 varlink_detach_server(v
);
1430 Varlink
* varlink_close_unref(Varlink
*v
) {
1434 (void) varlink_close(v
);
1435 return varlink_unref(v
);
1438 Varlink
* varlink_flush_close_unref(Varlink
*v
) {
1442 (void) varlink_flush(v
);
1443 return varlink_close_unref(v
);
1446 static int varlink_format_json(Varlink
*v
, JsonVariant
*m
) {
1447 _cleanup_(erase_and_freep
) char *text
= NULL
;
1453 r
= json_variant_format(m
, 0, &text
);
1456 assert(text
[r
] == '\0');
1458 if (v
->output_buffer_size
+ r
+ 1 > VARLINK_BUFFER_MAX
)
1461 varlink_log(v
, "Sending message: %s", text
);
1463 if (v
->output_buffer_size
== 0) {
1465 free_and_replace(v
->output_buffer
, text
);
1467 v
->output_buffer_size
= r
+ 1;
1468 v
->output_buffer_index
= 0;
1470 } else if (v
->output_buffer_index
== 0) {
1472 if (!GREEDY_REALLOC(v
->output_buffer
, v
->output_buffer_size
+ r
+ 1))
1475 memcpy(v
->output_buffer
+ v
->output_buffer_size
, text
, r
+ 1);
1476 v
->output_buffer_size
+= r
+ 1;
1479 const size_t new_size
= v
->output_buffer_size
+ r
+ 1;
1481 n
= new(char, new_size
);
1485 memcpy(mempcpy(n
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
), text
, r
+ 1);
1487 free_and_replace(v
->output_buffer
, n
);
1488 v
->output_buffer_size
= new_size
;
1489 v
->output_buffer_index
= 0;
1492 if (json_variant_is_sensitive(m
))
1493 v
->output_buffer_sensitive
= true; /* Propagate sensitive flag */
1495 text
= mfree(text
); /* No point in the erase_and_free() destructor declared above */
1500 static int varlink_enqueue_json(Varlink
*v
, JsonVariant
*m
) {
1501 VarlinkJsonQueueItem
*q
;
1506 /* If there are no file descriptors to be queued and no queue entries yet we can shortcut things and
1507 * append this entry directly to the output buffer */
1508 if (v
->n_pushed_fds
== 0 && !v
->output_queue
)
1509 return varlink_format_json(v
, m
);
1511 /* Otherwise add a queue entry for this */
1512 q
= varlink_json_queue_item_new(m
, v
->pushed_fds
, v
->n_pushed_fds
);
1516 v
->n_pushed_fds
= 0; /* fds now belong to the queue entry */
1518 LIST_INSERT_AFTER(queue
, v
->output_queue
, v
->output_queue_tail
, q
);
1519 v
->output_queue_tail
= q
;
1523 static int varlink_format_queue(Varlink
*v
) {
1528 /* Takes entries out of the output queue and formats them into the output buffer. But only if this
1529 * would not corrupt our fd message boundaries */
1531 while (v
->output_queue
) {
1532 _cleanup_free_
int *array
= NULL
;
1533 VarlinkJsonQueueItem
*q
= v
->output_queue
;
1535 if (v
->n_output_fds
> 0) /* unwritten fds? if we'd add more we'd corrupt the fd message boundaries, hence wait */
1539 array
= newdup(int, q
->fds
, q
->n_fds
);
1544 r
= varlink_format_json(v
, q
->data
);
1548 /* Take possession of the queue element's fds */
1549 free(v
->output_fds
);
1550 v
->output_fds
= TAKE_PTR(array
);
1551 v
->n_output_fds
= q
->n_fds
;
1554 LIST_REMOVE(queue
, v
->output_queue
, q
);
1555 if (!v
->output_queue
)
1556 v
->output_queue_tail
= NULL
;
1558 varlink_json_queue_item_free(q
);
1564 int varlink_send(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1565 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1568 assert_return(v
, -EINVAL
);
1569 assert_return(method
, -EINVAL
);
1571 if (v
->state
== VARLINK_DISCONNECTED
)
1572 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1574 /* We allow enqueuing multiple method calls at once! */
1575 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1576 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1578 r
= varlink_sanitize_parameters(¶meters
);
1580 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1582 r
= json_build(&m
, JSON_BUILD_OBJECT(
1583 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1584 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1585 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1587 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1589 r
= varlink_enqueue_json(v
, m
);
1591 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1593 /* No state change here, this is one-way only after all */
1594 v
->timestamp
= now(CLOCK_MONOTONIC
);
1598 int varlink_sendb(Varlink
*v
, const char *method
, ...) {
1599 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1603 assert_return(v
, -EINVAL
);
1605 va_start(ap
, method
);
1606 r
= json_buildv(¶meters
, ap
);
1610 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1612 return varlink_send(v
, method
, parameters
);
1615 int varlink_invoke(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1616 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1619 assert_return(v
, -EINVAL
);
1620 assert_return(method
, -EINVAL
);
1622 if (v
->state
== VARLINK_DISCONNECTED
)
1623 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1625 /* We allow enqueuing multiple method calls at once! */
1626 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1627 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1629 r
= varlink_sanitize_parameters(¶meters
);
1631 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1633 r
= json_build(&m
, JSON_BUILD_OBJECT(
1634 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1635 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1637 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1639 r
= varlink_enqueue_json(v
, m
);
1641 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1643 varlink_set_state(v
, VARLINK_AWAITING_REPLY
);
1645 v
->timestamp
= now(CLOCK_MONOTONIC
);
1650 int varlink_invokeb(Varlink
*v
, const char *method
, ...) {
1651 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1655 assert_return(v
, -EINVAL
);
1657 va_start(ap
, method
);
1658 r
= json_buildv(¶meters
, ap
);
1662 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1664 return varlink_invoke(v
, method
, parameters
);
1667 int varlink_observe(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1668 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1671 assert_return(v
, -EINVAL
);
1672 assert_return(method
, -EINVAL
);
1674 if (v
->state
== VARLINK_DISCONNECTED
)
1675 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1677 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1678 * thus insist on an idle client here. */
1679 if (v
->state
!= VARLINK_IDLE_CLIENT
)
1680 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1682 r
= varlink_sanitize_parameters(¶meters
);
1684 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1686 r
= json_build(&m
, JSON_BUILD_OBJECT(
1687 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1688 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1689 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1691 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1693 r
= varlink_enqueue_json(v
, m
);
1695 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1697 varlink_set_state(v
, VARLINK_AWAITING_REPLY_MORE
);
1699 v
->timestamp
= now(CLOCK_MONOTONIC
);
1704 int varlink_observeb(Varlink
*v
, const char *method
, ...) {
1705 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1709 assert_return(v
, -EINVAL
);
1711 va_start(ap
, method
);
1712 r
= json_buildv(¶meters
, ap
);
1716 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1718 return varlink_observe(v
, method
, parameters
);
1724 JsonVariant
*parameters
,
1725 JsonVariant
**ret_parameters
,
1726 const char **ret_error_id
,
1727 VarlinkReplyFlags
*ret_flags
) {
1729 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1732 assert_return(v
, -EINVAL
);
1733 assert_return(method
, -EINVAL
);
1735 if (v
->state
== VARLINK_DISCONNECTED
)
1736 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1737 if (v
->state
!= VARLINK_IDLE_CLIENT
)
1738 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1740 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1742 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
1743 * that we can assign a new reply shortly. */
1744 varlink_clear_current(v
);
1746 r
= varlink_sanitize_parameters(¶meters
);
1748 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1750 r
= json_build(&m
, JSON_BUILD_OBJECT(
1751 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1752 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1754 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1756 r
= varlink_enqueue_json(v
, m
);
1758 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1760 varlink_set_state(v
, VARLINK_CALLING
);
1762 v
->timestamp
= now(CLOCK_MONOTONIC
);
1764 while (v
->state
== VARLINK_CALLING
) {
1766 r
= varlink_process(v
);
1772 r
= varlink_wait(v
, USEC_INFINITY
);
1779 case VARLINK_CALLED
:
1782 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
1783 assert(v
->n_pending
== 1);
1787 *ret_parameters
= json_variant_by_key(v
->current
, "parameters");
1789 *ret_error_id
= json_variant_string(json_variant_by_key(v
->current
, "error"));
1795 case VARLINK_PENDING_DISCONNECT
:
1796 case VARLINK_DISCONNECTED
:
1797 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ECONNRESET
), "Connection was closed.");
1799 case VARLINK_PENDING_TIMEOUT
:
1800 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ETIME
), "Connection timed out.");
1803 assert_not_reached();
1810 JsonVariant
**ret_parameters
,
1811 const char **ret_error_id
,
1812 VarlinkReplyFlags
*ret_flags
, ...) {
1814 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1818 assert_return(v
, -EINVAL
);
1820 va_start(ap
, ret_flags
);
1821 r
= json_buildv(¶meters
, ap
);
1825 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1827 return varlink_call(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
1830 int varlink_reply(Varlink
*v
, JsonVariant
*parameters
) {
1831 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1834 assert_return(v
, -EINVAL
);
1836 if (v
->state
== VARLINK_DISCONNECTED
)
1838 if (!IN_SET(v
->state
,
1839 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1840 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1843 r
= varlink_sanitize_parameters(¶meters
);
1845 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1847 r
= json_build(&m
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1849 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1851 r
= varlink_enqueue_json(v
, m
);
1853 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1855 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1856 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1857 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1858 * process further messages. */
1859 varlink_clear_current(v
);
1860 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1862 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1863 * means we should it handle the rest of the state engine. */
1864 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1869 int varlink_replyb(Varlink
*v
, ...) {
1870 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1874 assert_return(v
, -EINVAL
);
1877 r
= json_buildv(¶meters
, ap
);
1883 return varlink_reply(v
, parameters
);
1886 int varlink_error(Varlink
*v
, const char *error_id
, JsonVariant
*parameters
) {
1887 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1890 assert_return(v
, -EINVAL
);
1891 assert_return(error_id
, -EINVAL
);
1893 if (v
->state
== VARLINK_DISCONNECTED
)
1894 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
1895 if (!IN_SET(v
->state
,
1896 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1897 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1898 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
1900 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
1901 * simplify code that puts together a complex reply message with fds, and half-way something
1902 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
1903 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
1904 * the callers don't need to do this explicitly. */
1905 varlink_reset_fds(v
);
1907 r
= varlink_sanitize_parameters(¶meters
);
1909 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
1911 r
= json_build(&m
, JSON_BUILD_OBJECT(
1912 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id
)),
1913 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1915 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1917 r
= varlink_enqueue_json(v
, m
);
1919 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
1921 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1922 varlink_clear_current(v
);
1923 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1925 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1930 int varlink_errorb(Varlink
*v
, const char *error_id
, ...) {
1931 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1935 assert_return(v
, -EINVAL
);
1936 assert_return(error_id
, -EINVAL
);
1938 va_start(ap
, error_id
);
1939 r
= json_buildv(¶meters
, ap
);
1943 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
1945 return varlink_error(v
, error_id
, parameters
);
1948 int varlink_error_invalid_parameter(Varlink
*v
, JsonVariant
*parameters
) {
1951 assert_return(v
, -EINVAL
);
1952 assert_return(parameters
, -EINVAL
);
1954 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1955 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1956 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1957 * don't expect any arguments. */
1959 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
1960 * parameter sanitization to fail, and it returns -EINVAL. */
1962 if (json_variant_is_string(parameters
)) {
1963 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
1965 r
= json_build(¶meters_obj
,
1967 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters
))));
1971 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
1974 if (json_variant_is_object(parameters
) &&
1975 json_variant_elements(parameters
) > 0) {
1976 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters_obj
= NULL
;
1978 r
= json_build(¶meters_obj
,
1980 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters
, 0)))));
1984 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters_obj
);
1990 int varlink_error_errno(Varlink
*v
, int error
) {
1991 return varlink_errorb(
1993 VARLINK_ERROR_SYSTEM
,
1994 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error
)))));
1997 int varlink_notify(Varlink
*v
, JsonVariant
*parameters
) {
1998 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
2001 assert_return(v
, -EINVAL
);
2003 if (v
->state
== VARLINK_DISCONNECTED
)
2004 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENOTCONN
), "Not connected.");
2005 if (!IN_SET(v
->state
, VARLINK_PROCESSING_METHOD_MORE
, VARLINK_PENDING_METHOD_MORE
))
2006 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "Connection busy.");
2008 r
= varlink_sanitize_parameters(¶meters
);
2010 return varlink_log_errno(v
, r
, "Failed to sanitize parameters: %m");
2012 r
= json_build(&m
, JSON_BUILD_OBJECT(
2013 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
2014 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2016 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2018 r
= varlink_enqueue_json(v
, m
);
2020 return varlink_log_errno(v
, r
, "Failed to enqueue json message: %m");
2022 /* No state change, as more is coming */
2026 int varlink_notifyb(Varlink
*v
, ...) {
2027 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
2031 assert_return(v
, -EINVAL
);
2034 r
= json_buildv(¶meters
, ap
);
2038 return varlink_log_errno(v
, r
, "Failed to build json message: %m");
2040 return varlink_notify(v
, parameters
);
2043 int varlink_bind_reply(Varlink
*v
, VarlinkReply callback
) {
2044 assert_return(v
, -EINVAL
);
2046 if (callback
&& v
->reply_callback
&& callback
!= v
->reply_callback
)
2047 return varlink_log_errno(v
, SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
2049 v
->reply_callback
= callback
;
2054 void* varlink_set_userdata(Varlink
*v
, void *userdata
) {
2057 assert_return(v
, NULL
);
2060 v
->userdata
= userdata
;
2065 void* varlink_get_userdata(Varlink
*v
) {
2066 assert_return(v
, NULL
);
2071 static int varlink_acquire_ucred(Varlink
*v
) {
2076 if (v
->ucred_acquired
)
2079 r
= getpeercred(v
->fd
, &v
->ucred
);
2083 v
->ucred_acquired
= true;
2087 int varlink_get_peer_uid(Varlink
*v
, uid_t
*ret
) {
2090 assert_return(v
, -EINVAL
);
2091 assert_return(ret
, -EINVAL
);
2093 r
= varlink_acquire_ucred(v
);
2095 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2097 if (!uid_is_valid(v
->ucred
.uid
))
2098 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2100 *ret
= v
->ucred
.uid
;
2104 int varlink_get_peer_pid(Varlink
*v
, pid_t
*ret
) {
2107 assert_return(v
, -EINVAL
);
2108 assert_return(ret
, -EINVAL
);
2110 r
= varlink_acquire_ucred(v
);
2112 return varlink_log_errno(v
, r
, "Failed to acquire credentials: %m");
2114 if (!pid_is_valid(v
->ucred
.pid
))
2115 return varlink_log_errno(v
, SYNTHETIC_ERRNO(ENODATA
), "Peer uid is invalid.");
2117 *ret
= v
->ucred
.pid
;
2121 int varlink_set_relative_timeout(Varlink
*v
, usec_t timeout
) {
2122 assert_return(v
, -EINVAL
);
2123 assert_return(timeout
> 0, -EINVAL
);
2125 v
->timeout
= timeout
;
2129 VarlinkServer
*varlink_get_server(Varlink
*v
) {
2130 assert_return(v
, NULL
);
2135 int varlink_set_description(Varlink
*v
, const char *description
) {
2136 assert_return(v
, -EINVAL
);
2138 return free_and_strdup(&v
->description
, description
);
2141 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2142 Varlink
*v
= ASSERT_PTR(userdata
);
2146 handle_revents(v
, revents
);
2147 (void) varlink_process(v
);
2152 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
2153 Varlink
*v
= ASSERT_PTR(userdata
);
2157 (void) varlink_process(v
);
2161 static int defer_callback(sd_event_source
*s
, void *userdata
) {
2162 Varlink
*v
= ASSERT_PTR(userdata
);
2166 (void) varlink_process(v
);
2170 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
2171 Varlink
*v
= ASSERT_PTR(userdata
);
2178 e
= varlink_get_events(v
);
2182 r
= sd_event_source_set_io_events(v
->io_event_source
, e
);
2184 return varlink_log_errno(v
, r
, "Failed to set source events: %m");
2186 r
= varlink_get_timeout(v
, &until
);
2189 have_timeout
= r
> 0;
2192 r
= sd_event_source_set_time(v
->time_event_source
, until
);
2194 return varlink_log_errno(v
, r
, "Failed to set source time: %m");
2197 r
= sd_event_source_set_enabled(v
->time_event_source
, have_timeout
? SD_EVENT_ON
: SD_EVENT_OFF
);
2199 return varlink_log_errno(v
, r
, "Failed to enable event source: %m");
2204 static int quit_callback(sd_event_source
*event
, void *userdata
) {
2205 Varlink
*v
= ASSERT_PTR(userdata
);
2215 int varlink_attach_event(Varlink
*v
, sd_event
*e
, int64_t priority
) {
2218 assert_return(v
, -EINVAL
);
2219 assert_return(!v
->event
, -EBUSY
);
2222 v
->event
= sd_event_ref(e
);
2224 r
= sd_event_default(&v
->event
);
2226 return varlink_log_errno(v
, r
, "Failed to create event source: %m");
2229 r
= sd_event_add_time(v
->event
, &v
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, v
);
2233 r
= sd_event_source_set_priority(v
->time_event_source
, priority
);
2237 (void) sd_event_source_set_description(v
->time_event_source
, "varlink-time");
2239 r
= sd_event_add_exit(v
->event
, &v
->quit_event_source
, quit_callback
, v
);
2243 r
= sd_event_source_set_priority(v
->quit_event_source
, priority
);
2247 (void) sd_event_source_set_description(v
->quit_event_source
, "varlink-quit");
2249 r
= sd_event_add_io(v
->event
, &v
->io_event_source
, v
->fd
, 0, io_callback
, v
);
2253 r
= sd_event_source_set_prepare(v
->io_event_source
, prepare_callback
);
2257 r
= sd_event_source_set_priority(v
->io_event_source
, priority
);
2261 (void) sd_event_source_set_description(v
->io_event_source
, "varlink-io");
2263 r
= sd_event_add_defer(v
->event
, &v
->defer_event_source
, defer_callback
, v
);
2267 r
= sd_event_source_set_priority(v
->defer_event_source
, priority
);
2271 (void) sd_event_source_set_description(v
->defer_event_source
, "varlink-defer");
2276 varlink_log_errno(v
, r
, "Failed to setup event source: %m");
2277 varlink_detach_event(v
);
2281 void varlink_detach_event(Varlink
*v
) {
2285 varlink_detach_event_sources(v
);
2287 v
->event
= sd_event_unref(v
->event
);
2290 sd_event
*varlink_get_event(Varlink
*v
) {
2291 assert_return(v
, NULL
);
2296 int varlink_push_fd(Varlink
*v
, int fd
) {
2299 assert_return(v
, -EINVAL
);
2300 assert_return(fd
>= 0, -EBADF
);
2302 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
2303 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
2305 if (!v
->allow_fd_passing_output
)
2308 if (v
->n_pushed_fds
>= INT_MAX
)
2311 if (!GREEDY_REALLOC(v
->pushed_fds
, v
->n_pushed_fds
+ 1))
2314 i
= (int) v
->n_pushed_fds
;
2315 v
->pushed_fds
[v
->n_pushed_fds
++] = fd
;
2319 int varlink_dup_fd(Varlink
*v
, int fd
) {
2320 _cleanup_close_
int dp
= -1;
2323 assert_return(v
, -EINVAL
);
2324 assert_return(fd
>= 0, -EBADF
);
2326 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
2328 dp
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
2332 r
= varlink_push_fd(v
, dp
);
2340 int varlink_reset_fds(Varlink
*v
) {
2341 assert_return(v
, -EINVAL
);
2343 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
2344 * of putting together a message with fds, and then eventually something fails and they need to
2345 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
2347 close_many(v
->output_fds
, v
->n_output_fds
);
2348 v
->n_output_fds
= 0;
2352 int varlink_peek_fd(Varlink
*v
, size_t i
) {
2353 assert_return(v
, -EINVAL
);
2355 /* Returns one of the file descriptors that were received along with the current message. This does
2356 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
2358 if (!v
->allow_fd_passing_input
)
2361 if (i
>= v
->n_input_fds
)
2364 return v
->input_fds
[i
];
2367 int varlink_take_fd(Varlink
*v
, size_t i
) {
2368 assert_return(v
, -EINVAL
);
2370 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
2371 * we'll invalidate the reference to it under our possession. If called twice in a row will return
2374 if (!v
->allow_fd_passing_input
)
2377 if (i
>= v
->n_input_fds
)
2380 return TAKE_FD(v
->input_fds
[i
]);
2383 static int verify_unix_socket(Varlink
*v
) {
2389 if (fstat(v
->fd
, &st
) < 0)
2391 if (!S_ISSOCK(st
.st_mode
)) {
2396 v
->af
= socket_get_family(v
->fd
);
2401 return v
->af
== AF_UNIX
? 0 : -ENOMEDIUM
;
2404 int varlink_set_allow_fd_passing_input(Varlink
*v
, bool b
) {
2407 assert_return(v
, -EINVAL
);
2409 if (v
->allow_fd_passing_input
== b
)
2413 v
->allow_fd_passing_input
= false;
2417 r
= verify_unix_socket(v
);
2421 v
->allow_fd_passing_input
= true;
2425 int varlink_set_allow_fd_passing_output(Varlink
*v
, bool b
) {
2428 assert_return(v
, -EINVAL
);
2430 if (v
->allow_fd_passing_output
== b
)
2434 v
->allow_fd_passing_output
= false;
2438 r
= verify_unix_socket(v
);
2442 v
->allow_fd_passing_output
= true;
2446 int varlink_server_new(VarlinkServer
**ret
, VarlinkServerFlags flags
) {
2449 assert_return(ret
, -EINVAL
);
2450 assert_return((flags
& ~_VARLINK_SERVER_FLAGS_ALL
) == 0, -EINVAL
);
2452 s
= new(VarlinkServer
, 1);
2454 return log_oom_debug();
2456 *s
= (VarlinkServer
) {
2459 .connections_max
= varlink_server_connections_max(NULL
),
2460 .connections_per_uid_max
= varlink_server_connections_per_uid_max(NULL
),
2467 static VarlinkServer
* varlink_server_destroy(VarlinkServer
*s
) {
2473 varlink_server_shutdown(s
);
2475 while ((m
= hashmap_steal_first_key(s
->methods
)))
2478 hashmap_free(s
->methods
);
2479 hashmap_free(s
->by_uid
);
2481 sd_event_unref(s
->event
);
2483 free(s
->description
);
2488 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer
, varlink_server
, varlink_server_destroy
);
2490 static int validate_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
2496 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ROOT_ONLY
))
2497 allowed
= ucred
->uid
== 0;
2499 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_MYSELF_ONLY
))
2500 allowed
= allowed
> 0 || ucred
->uid
== getuid();
2502 if (allowed
== 0) { /* Allow access when it is explicitly allowed or when neither
2503 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2504 varlink_server_log(server
, "Unprivileged client attempted connection, refusing.");
2508 if (server
->n_connections
>= server
->connections_max
) {
2509 varlink_server_log(server
, "Connection limit of %u reached, refusing.", server
->connections_max
);
2513 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
2516 if (!uid_is_valid(ucred
->uid
)) {
2517 varlink_server_log(server
, "Client with invalid UID attempted connection, refusing.");
2521 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
2522 if (c
>= server
->connections_per_uid_max
) {
2523 varlink_server_log(server
, "Per-UID connection limit of %u reached, refusing.",
2524 server
->connections_per_uid_max
);
2532 static int count_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
2539 server
->n_connections
++;
2541 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
2542 r
= hashmap_ensure_allocated(&server
->by_uid
, NULL
);
2544 return log_debug_errno(r
, "Failed to allocate UID hash table: %m");
2546 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
2548 varlink_server_log(server
, "Connections of user " UID_FMT
": %u (of %u max)",
2549 ucred
->uid
, c
, server
->connections_per_uid_max
);
2551 r
= hashmap_replace(server
->by_uid
, UID_TO_PTR(ucred
->uid
), UINT_TO_PTR(c
+ 1));
2553 return log_debug_errno(r
, "Failed to increment counter in UID hash table: %m");
2559 int varlink_server_add_connection(VarlinkServer
*server
, int fd
, Varlink
**ret
) {
2560 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
2561 struct ucred ucred
= UCRED_INVALID
;
2562 bool ucred_acquired
;
2565 assert_return(server
, -EINVAL
);
2566 assert_return(fd
>= 0, -EBADF
);
2568 if ((server
->flags
& (VARLINK_SERVER_ROOT_ONLY
|VARLINK_SERVER_ACCOUNT_UID
)) != 0) {
2569 r
= getpeercred(fd
, &ucred
);
2571 return varlink_server_log_errno(server
, r
, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2573 ucred_acquired
= true;
2575 r
= validate_connection(server
, &ucred
);
2581 ucred_acquired
= false;
2583 r
= varlink_new(&v
);
2585 return varlink_server_log_errno(server
, r
, "Failed to allocate connection object: %m");
2587 r
= count_connection(server
, &ucred
);
2592 if (server
->flags
& VARLINK_SERVER_INHERIT_USERDATA
)
2593 v
->userdata
= server
->userdata
;
2595 if (ucred_acquired
) {
2597 v
->ucred_acquired
= true;
2600 _cleanup_free_
char *desc
= NULL
;
2601 if (asprintf(&desc
, "%s-%i", server
->description
?: "varlink", v
->fd
) >= 0)
2602 v
->description
= TAKE_PTR(desc
);
2604 /* Link up the server and the connection, and take reference in both directions. Note that the
2605 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2606 * which happens in varlink_close(), including in the event loop quit callback. */
2607 v
->server
= varlink_server_ref(server
);
2610 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2612 if (server
->event
) {
2613 r
= varlink_attach_event(v
, server
->event
, server
->event_priority
);
2615 varlink_log_errno(v
, r
, "Failed to attach new connection: %m");
2616 v
->fd
= -EBADF
; /* take the fd out of the connection again */
2628 static VarlinkServerSocket
*varlink_server_socket_free(VarlinkServerSocket
*ss
) {
2636 DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket
*, varlink_server_socket_free
);
2638 static int connect_callback(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2639 VarlinkServerSocket
*ss
= ASSERT_PTR(userdata
);
2640 _cleanup_close_
int cfd
= -EBADF
;
2646 varlink_server_log(ss
->server
, "New incoming connection.");
2648 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2650 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
2653 return varlink_server_log_errno(ss
->server
, errno
, "Failed to accept incoming socket: %m");
2656 r
= varlink_server_add_connection(ss
->server
, cfd
, &v
);
2662 if (ss
->server
->connect_callback
) {
2663 r
= ss
->server
->connect_callback(ss
->server
, v
, ss
->server
->userdata
);
2665 varlink_log_errno(v
, r
, "Connection callback returned error, disconnecting client: %m");
2674 static int varlink_server_create_listen_fd_socket(VarlinkServer
*s
, int fd
, VarlinkServerSocket
**ret_ss
) {
2675 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
2682 r
= fd_nonblock(fd
, true);
2686 ss
= new(VarlinkServerSocket
, 1);
2688 return log_oom_debug();
2690 *ss
= (VarlinkServerSocket
) {
2696 r
= sd_event_add_io(s
->event
, &ss
->event_source
, fd
, EPOLLIN
, connect_callback
, ss
);
2700 r
= sd_event_source_set_priority(ss
->event_source
, s
->event_priority
);
2705 *ret_ss
= TAKE_PTR(ss
);
2709 int varlink_server_listen_fd(VarlinkServer
*s
, int fd
) {
2710 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
2713 assert_return(s
, -EINVAL
);
2714 assert_return(fd
>= 0, -EBADF
);
2716 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
2720 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
2724 int varlink_server_listen_address(VarlinkServer
*s
, const char *address
, mode_t m
) {
2725 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
2726 union sockaddr_union sockaddr
;
2727 socklen_t sockaddr_len
;
2728 _cleanup_close_
int fd
= -EBADF
;
2731 assert_return(s
, -EINVAL
);
2732 assert_return(address
, -EINVAL
);
2733 assert_return((m
& ~0777) == 0, -EINVAL
);
2735 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
2740 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2744 fd
= fd_move_above_stdio(fd
);
2746 (void) sockaddr_un_unlink(&sockaddr
.un
);
2748 WITH_UMASK(~m
& 0777) {
2749 r
= mac_selinux_bind(fd
, &sockaddr
.sa
, sockaddr_len
);
2754 if (listen(fd
, SOMAXCONN_DELUXE
) < 0)
2757 r
= varlink_server_create_listen_fd_socket(s
, fd
, &ss
);
2761 r
= free_and_strdup(&ss
->address
, address
);
2765 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
2770 void* varlink_server_set_userdata(VarlinkServer
*s
, void *userdata
) {
2773 assert_return(s
, NULL
);
2776 s
->userdata
= userdata
;
2781 void* varlink_server_get_userdata(VarlinkServer
*s
) {
2782 assert_return(s
, NULL
);
2787 static VarlinkServerSocket
* varlink_server_socket_destroy(VarlinkServerSocket
*ss
) {
2792 LIST_REMOVE(sockets
, ss
->server
->sockets
, ss
);
2794 sd_event_source_disable_unref(ss
->event_source
);
2802 int varlink_server_shutdown(VarlinkServer
*s
) {
2803 assert_return(s
, -EINVAL
);
2806 varlink_server_socket_destroy(s
->sockets
);
2811 static int varlink_server_add_socket_event_source(VarlinkServer
*s
, VarlinkServerSocket
*ss
, int64_t priority
) {
2812 _cleanup_(sd_event_source_unrefp
) sd_event_source
*es
= NULL
;
2819 assert(ss
->fd
>= 0);
2820 assert(!ss
->event_source
);
2822 r
= sd_event_add_io(s
->event
, &es
, ss
->fd
, EPOLLIN
, connect_callback
, ss
);
2826 r
= sd_event_source_set_priority(es
, priority
);
2830 ss
->event_source
= TAKE_PTR(es
);
2834 int varlink_server_attach_event(VarlinkServer
*s
, sd_event
*e
, int64_t priority
) {
2837 assert_return(s
, -EINVAL
);
2838 assert_return(!s
->event
, -EBUSY
);
2841 s
->event
= sd_event_ref(e
);
2843 r
= sd_event_default(&s
->event
);
2848 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
2849 r
= varlink_server_add_socket_event_source(s
, ss
, priority
);
2854 s
->event_priority
= priority
;
2858 varlink_server_detach_event(s
);
2862 int varlink_server_detach_event(VarlinkServer
*s
) {
2863 assert_return(s
, -EINVAL
);
2865 LIST_FOREACH(sockets
, ss
, s
->sockets
)
2866 ss
->event_source
= sd_event_source_disable_unref(ss
->event_source
);
2868 sd_event_unref(s
->event
);
2872 sd_event
*varlink_server_get_event(VarlinkServer
*s
) {
2873 assert_return(s
, NULL
);
2878 int varlink_server_bind_method(VarlinkServer
*s
, const char *method
, VarlinkMethod callback
) {
2879 _cleanup_free_
char *m
= NULL
;
2882 assert_return(s
, -EINVAL
);
2883 assert_return(method
, -EINVAL
);
2884 assert_return(callback
, -EINVAL
);
2886 if (startswith(method
, "org.varlink.service."))
2887 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST
), "Cannot bind server to '%s'.", method
);
2891 return log_oom_debug();
2893 r
= hashmap_ensure_put(&s
->methods
, &string_hash_ops
, m
, callback
);
2895 return log_oom_debug();
2897 return log_debug_errno(r
, "Failed to register callback: %m");
2904 int varlink_server_bind_method_many_internal(VarlinkServer
*s
, ...) {
2908 assert_return(s
, -EINVAL
);
2912 VarlinkMethod callback
;
2915 method
= va_arg(ap
, const char *);
2919 callback
= va_arg(ap
, VarlinkMethod
);
2921 r
= varlink_server_bind_method(s
, method
, callback
);
2930 int varlink_server_bind_connect(VarlinkServer
*s
, VarlinkConnect callback
) {
2931 assert_return(s
, -EINVAL
);
2933 if (callback
&& s
->connect_callback
&& callback
!= s
->connect_callback
)
2934 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
2936 s
->connect_callback
= callback
;
2940 int varlink_server_bind_disconnect(VarlinkServer
*s
, VarlinkDisconnect callback
) {
2941 assert_return(s
, -EINVAL
);
2943 if (callback
&& s
->disconnect_callback
&& callback
!= s
->disconnect_callback
)
2944 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "A different callback was already set.");
2946 s
->disconnect_callback
= callback
;
2950 unsigned varlink_server_connections_max(VarlinkServer
*s
) {
2953 /* If a server is specified, return the setting for that server, otherwise the default value */
2955 return s
->connections_max
;
2957 dts
= getdtablesize();
2960 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
2961 if (VARLINK_DEFAULT_CONNECTIONS_MAX
> (unsigned) dts
/ 4 * 3)
2964 return VARLINK_DEFAULT_CONNECTIONS_MAX
;
2967 unsigned varlink_server_connections_per_uid_max(VarlinkServer
*s
) {
2971 return s
->connections_per_uid_max
;
2973 /* Make sure to never use up more than ¾th of available connections for a single user */
2974 m
= varlink_server_connections_max(NULL
);
2975 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
> m
)
2978 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
;
2981 int varlink_server_set_connections_per_uid_max(VarlinkServer
*s
, unsigned m
) {
2982 assert_return(s
, -EINVAL
);
2983 assert_return(m
> 0, -EINVAL
);
2985 s
->connections_per_uid_max
= m
;
2989 int varlink_server_set_connections_max(VarlinkServer
*s
, unsigned m
) {
2990 assert_return(s
, -EINVAL
);
2991 assert_return(m
> 0, -EINVAL
);
2993 s
->connections_max
= m
;
2997 unsigned varlink_server_current_connections(VarlinkServer
*s
) {
2998 assert_return(s
, UINT_MAX
);
3000 return s
->n_connections
;
3003 int varlink_server_set_description(VarlinkServer
*s
, const char *description
) {
3004 assert_return(s
, -EINVAL
);
3006 return free_and_strdup(&s
->description
, description
);
3009 int varlink_server_serialize(VarlinkServer
*s
, FILE *f
, FDSet
*fds
) {
3016 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
3019 assert(ss
->address
);
3020 assert(ss
->fd
>= 0);
3022 fprintf(f
, "varlink-server-socket-address=%s", ss
->address
);
3024 /* If we fail to serialize the fd, it will be considered an error during deserialization */
3025 copy
= fdset_put_dup(fds
, ss
->fd
);
3029 fprintf(f
, " varlink-server-socket-fd=%i", copy
);
3037 int varlink_server_deserialize_one(VarlinkServer
*s
, const char *value
, FDSet
*fds
) {
3038 _cleanup_(varlink_server_socket_freep
) VarlinkServerSocket
*ss
= NULL
;
3039 _cleanup_free_
char *address
= NULL
;
3040 const char *v
= ASSERT_PTR(value
);
3048 n
= strcspn(v
, " ");
3049 address
= strndup(v
, n
);
3051 return log_oom_debug();
3054 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
3055 "Failed to deserialize VarlinkServerSocket: %s: %m", value
);
3056 v
= startswith(v
+ n
+ 1, "varlink-server-socket-fd=");
3058 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
3059 "Failed to deserialize VarlinkServerSocket fd %s: %m", value
);
3061 n
= strcspn(v
, " ");
3062 buf
= strndupa_safe(v
, n
);
3066 return log_debug_errno(fd
, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf
);
3067 if (!fdset_contains(fds
, fd
))
3068 return log_debug_errno(SYNTHETIC_ERRNO(EBADF
),
3069 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd
);
3071 ss
= new(VarlinkServerSocket
, 1);
3073 return log_oom_debug();
3075 *ss
= (VarlinkServerSocket
) {
3077 .address
= TAKE_PTR(address
),
3078 .fd
= fdset_remove(fds
, fd
),
3081 r
= varlink_server_add_socket_event_source(s
, ss
, SD_EVENT_PRIORITY_NORMAL
);
3083 return log_debug_errno(r
, "Failed to add VarlinkServerSocket event source to the event loop: %m");
3085 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));