1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include "alloc-util.h"
6 #include "errno-util.h"
11 #include "process-util.h"
12 #include "selinux-util.h"
14 #include "socket-util.h"
15 #include "string-table.h"
16 #include "string-util.h"
18 #include "time-util.h"
19 #include "umask-util.h"
20 #include "user-util.h"
23 #define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
24 #define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
26 #define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
27 #define VARLINK_BUFFER_MAX (16U*1024U*1024U)
28 #define VARLINK_READ_SIZE (64U*1024U)
30 typedef enum VarlinkState
{
31 /* Client side states */
33 VARLINK_AWAITING_REPLY
,
34 VARLINK_AWAITING_REPLY_MORE
,
37 VARLINK_PROCESSING_REPLY
,
39 /* Server side states */
41 VARLINK_PROCESSING_METHOD
,
42 VARLINK_PROCESSING_METHOD_MORE
,
43 VARLINK_PROCESSING_METHOD_ONEWAY
,
44 VARLINK_PROCESSED_METHOD
,
45 VARLINK_PENDING_METHOD
,
46 VARLINK_PENDING_METHOD_MORE
,
48 /* Common states (only during shutdown) */
49 VARLINK_PENDING_DISCONNECT
,
50 VARLINK_PENDING_TIMEOUT
,
51 VARLINK_PROCESSING_DISCONNECT
,
52 VARLINK_PROCESSING_TIMEOUT
,
53 VARLINK_PROCESSING_FAILURE
,
57 _VARLINK_STATE_INVALID
= -1
60 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
61 * is still good for something, and false only when it's dead for good. This means: when we are
62 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
63 * the connection is still good, and we are likely to be able to properly operate on it soon. */
64 #define VARLINK_STATE_IS_ALIVE(state) \
66 VARLINK_IDLE_CLIENT, \
67 VARLINK_AWAITING_REPLY, \
68 VARLINK_AWAITING_REPLY_MORE, \
71 VARLINK_PROCESSING_REPLY, \
72 VARLINK_IDLE_SERVER, \
73 VARLINK_PROCESSING_METHOD, \
74 VARLINK_PROCESSING_METHOD_MORE, \
75 VARLINK_PROCESSING_METHOD_ONEWAY, \
76 VARLINK_PROCESSED_METHOD, \
77 VARLINK_PENDING_METHOD, \
78 VARLINK_PENDING_METHOD_MORE)
83 VarlinkServer
*server
;
86 bool connecting
; /* This boolean indicates whether the socket fd we are operating on is currently
87 * processing an asynchronous connect(). In that state we watch the socket for
88 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
89 * will trigger ENOTCONN. Note that this boolean is kept separate from the
90 * VarlinkState above on purpose: while the connect() is still not complete we
91 * already want to allow queuing of messages and similar. Thus it's nice to keep
92 * these two state concepts separate: the VarlinkState encodes what our own view of
93 * the connection is, i.e. whether we think it's a server, a client, and has
94 * something queued already, while 'connecting' tells us a detail about the
95 * transport used below, that should have no effect on how we otherwise accept and
96 * process operations from the user.
98 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
99 * connection is good to use, even if it might not be fully connected
100 * yet. connecting=true then informs you that actually we are still connecting, and
101 * the connection is actually not established yet and thus any requests you enqueue
102 * now will still work fine but will be queued only, not sent yet, but that
103 * shouldn't stop you from using the connection, since eventually whatever you queue
106 * Or to say this even differently: 'state' is a high-level ("application layer"
107 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
108 * low, if you so will) state, and while they are not entirely unrelated and
109 * sometimes propagate effects to each other they are only asynchronously connected
115 char *input_buffer
; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
116 size_t input_buffer_allocated
;
117 size_t input_buffer_index
;
118 size_t input_buffer_size
;
119 size_t input_buffer_unscanned
;
121 char *output_buffer
; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
122 size_t output_buffer_allocated
;
123 size_t output_buffer_index
;
124 size_t output_buffer_size
;
126 VarlinkReply reply_callback
;
128 JsonVariant
*current
;
132 bool ucred_acquired
:1;
134 bool write_disconnected
:1;
135 bool read_disconnected
:1;
136 bool prefer_read_write
:1;
146 sd_event_source
*io_event_source
;
147 sd_event_source
*time_event_source
;
148 sd_event_source
*quit_event_source
;
149 sd_event_source
*defer_event_source
;
152 typedef struct VarlinkServerSocket VarlinkServerSocket
;
154 struct VarlinkServerSocket
{
155 VarlinkServer
*server
;
160 sd_event_source
*event_source
;
162 LIST_FIELDS(VarlinkServerSocket
, sockets
);
165 struct VarlinkServer
{
167 VarlinkServerFlags flags
;
169 LIST_HEAD(VarlinkServerSocket
, sockets
);
172 VarlinkConnect connect_callback
;
173 VarlinkDisconnect disconnect_callback
;
176 int64_t event_priority
;
178 unsigned n_connections
;
184 unsigned connections_max
;
185 unsigned connections_per_uid_max
;
188 static const char* const varlink_state_table
[_VARLINK_STATE_MAX
] = {
189 [VARLINK_IDLE_CLIENT
] = "idle-client",
190 [VARLINK_AWAITING_REPLY
] = "awaiting-reply",
191 [VARLINK_AWAITING_REPLY_MORE
] = "awaiting-reply-more",
192 [VARLINK_CALLING
] = "calling",
193 [VARLINK_CALLED
] = "called",
194 [VARLINK_PROCESSING_REPLY
] = "processing-reply",
195 [VARLINK_IDLE_SERVER
] = "idle-server",
196 [VARLINK_PROCESSING_METHOD
] = "processing-method",
197 [VARLINK_PROCESSING_METHOD_MORE
] = "processing-method-more",
198 [VARLINK_PROCESSING_METHOD_ONEWAY
] = "processing-method-oneway",
199 [VARLINK_PROCESSED_METHOD
] = "processed-method",
200 [VARLINK_PENDING_METHOD
] = "pending-method",
201 [VARLINK_PENDING_METHOD_MORE
] = "pending-method-more",
202 [VARLINK_PENDING_DISCONNECT
] = "pending-disconnect",
203 [VARLINK_PENDING_TIMEOUT
] = "pending-timeout",
204 [VARLINK_PROCESSING_DISCONNECT
] = "processing-disconnect",
205 [VARLINK_PROCESSING_TIMEOUT
] = "processing-timeout",
206 [VARLINK_PROCESSING_FAILURE
] = "processing-failure",
207 [VARLINK_DISCONNECTED
] = "disconnected",
210 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state
, VarlinkState
);
212 #define varlink_log_errno(v, error, fmt, ...) \
213 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
215 #define varlink_log(v, fmt, ...) \
216 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
218 #define varlink_server_log_errno(s, error, fmt, ...) \
219 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
221 #define varlink_server_log(s, fmt, ...) \
222 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
224 static inline const char *varlink_description(Varlink
*v
) {
225 return strna(v
? v
->description
: NULL
);
228 static inline const char *varlink_server_description(VarlinkServer
*s
) {
229 return strna(s
? s
->description
: NULL
);
232 static void varlink_set_state(Varlink
*v
, VarlinkState state
) {
234 assert(state
>= 0 && state
< _VARLINK_STATE_MAX
);
237 varlink_log(v
, "varlink: setting state %s",
238 varlink_state_to_string(state
));
240 varlink_log(v
, "varlink: changing state %s → %s",
241 varlink_state_to_string(v
->state
),
242 varlink_state_to_string(state
));
247 static int varlink_new(Varlink
**ret
) {
260 .state
= _VARLINK_STATE_INVALID
,
262 .ucred
.uid
= UID_INVALID
,
263 .ucred
.gid
= GID_INVALID
,
265 .timestamp
= USEC_INFINITY
,
266 .timeout
= VARLINK_DEFAULT_TIMEOUT_USEC
273 int varlink_connect_address(Varlink
**ret
, const char *address
) {
274 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
275 union sockaddr_union sockaddr
;
276 socklen_t sockaddr_len
;
279 assert_return(ret
, -EINVAL
);
280 assert_return(address
, -EINVAL
);
282 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
291 v
->fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
295 v
->fd
= fd_move_above_stdio(v
->fd
);
297 if (connect(v
->fd
, &sockaddr
.sa
, sockaddr_len
) < 0) {
298 if (!IN_SET(errno
, EAGAIN
, EINPROGRESS
))
301 v
->connecting
= true; /* We are asynchronously connecting, i.e. the connect() is being
302 * processed in the background. As long as that's the case the socket
303 * is in a special state: it's there, we can poll it for EPOLLOUT, but
304 * if we attempt to write() to it before we see EPOLLOUT we'll get
305 * ENOTCONN (and not EAGAIN, like we would for a normal connected
306 * socket that isn't writable at the moment). Since ENOTCONN on write()
307 * hence can mean two different things (i.e. connection not complete
308 * yet vs. already disconnected again), we store as a boolean whether
309 * we are still in connect(). */
312 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
318 int varlink_connect_fd(Varlink
**ret
, int fd
) {
322 assert_return(ret
, -EINVAL
);
323 assert_return(fd
>= 0, -EBADF
);
325 r
= fd_nonblock(fd
, true);
334 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
336 /* Note that if this function is called we assume the passed socket (if it is one) is already
337 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
338 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
339 * until the connection is fully set up. Behaviour here is hence a bit different from
340 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
341 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
347 static void varlink_detach_event_sources(Varlink
*v
) {
350 v
->io_event_source
= sd_event_source_disable_unref(v
->io_event_source
);
351 v
->time_event_source
= sd_event_source_disable_unref(v
->time_event_source
);
352 v
->quit_event_source
= sd_event_source_disable_unref(v
->quit_event_source
);
353 v
->defer_event_source
= sd_event_source_disable_unref(v
->defer_event_source
);
356 static void varlink_clear(Varlink
*v
) {
359 varlink_detach_event_sources(v
);
361 v
->fd
= safe_close(v
->fd
);
363 v
->input_buffer
= mfree(v
->input_buffer
);
364 v
->output_buffer
= mfree(v
->output_buffer
);
366 v
->current
= json_variant_unref(v
->current
);
367 v
->reply
= json_variant_unref(v
->reply
);
369 v
->event
= sd_event_unref(v
->event
);
372 static Varlink
* varlink_destroy(Varlink
*v
) {
376 /* If this is called the server object must already been unreffed here. Why that? because when we
377 * linked up the varlink connection with the server object we took one ref in each direction */
382 free(v
->description
);
386 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink
, varlink
, varlink_destroy
);
388 static int varlink_test_disconnect(Varlink
*v
) {
391 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
392 * prematurely, since we want to handle half-open connections as well as possible and want to flush
393 * out and read data before we close down if we can. */
395 /* Already disconnected? */
396 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
399 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
403 /* Still something to write and we can write? Stay around */
404 if (v
->output_buffer_size
> 0 && !v
->write_disconnected
)
407 /* Both sides gone already? Then there's no need to stick around */
408 if (v
->read_disconnected
&& v
->write_disconnected
)
411 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
412 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) && v
->read_disconnected
)
415 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
416 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
417 * being down if we never wrote anything. */
418 if (IN_SET(v
->state
, VARLINK_IDLE_CLIENT
) && (v
->write_disconnected
|| v
->got_pollhup
))
421 /* The server is still expecting to write more, but its write end is disconnected and it got a POLLHUP
422 * (i.e. from a disconnected client), so disconnect. */
423 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
) && v
->write_disconnected
&& v
->got_pollhup
)
429 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
433 static int varlink_write(Varlink
*v
) {
438 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
440 if (v
->connecting
) /* Writing while we are still wait for a non-blocking connect() to complete will
441 * result in ENOTCONN, hence exit early here */
443 if (v
->output_buffer_size
== 0)
445 if (v
->write_disconnected
)
450 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
451 * with non-socket IO, hence fall back automatically */
452 if (!v
->prefer_read_write
) {
453 n
= send(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
454 if (n
< 0 && errno
== ENOTSOCK
)
455 v
->prefer_read_write
= true;
457 if (v
->prefer_read_write
)
458 n
= write(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
);
463 if (ERRNO_IS_DISCONNECT(errno
)) {
464 /* If we get informed about a disconnect on write, then let's remember that, but not
465 * act on it just yet. Let's wait for read() to report the issue first. */
466 v
->write_disconnected
= true;
473 v
->output_buffer_size
-= n
;
475 if (v
->output_buffer_size
== 0)
476 v
->output_buffer_index
= 0;
478 v
->output_buffer_index
+= n
;
480 v
->timestamp
= now(CLOCK_MONOTONIC
);
484 static int varlink_read(Varlink
*v
) {
490 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
))
492 if (v
->connecting
) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
496 if (v
->input_buffer_unscanned
> 0)
498 if (v
->read_disconnected
)
501 if (v
->input_buffer_size
>= VARLINK_BUFFER_MAX
)
506 if (v
->input_buffer_allocated
<= v
->input_buffer_index
+ v
->input_buffer_size
) {
509 add
= MIN(VARLINK_BUFFER_MAX
- v
->input_buffer_size
, VARLINK_READ_SIZE
);
511 if (v
->input_buffer_index
== 0) {
513 if (!GREEDY_REALLOC(v
->input_buffer
, v
->input_buffer_allocated
, v
->input_buffer_size
+ add
))
519 b
= new(char, v
->input_buffer_size
+ add
);
523 memcpy(b
, v
->input_buffer
+ v
->input_buffer_index
, v
->input_buffer_size
);
525 free_and_replace(v
->input_buffer
, b
);
527 v
->input_buffer_allocated
= v
->input_buffer_size
+ add
;
528 v
->input_buffer_index
= 0;
532 rs
= v
->input_buffer_allocated
- (v
->input_buffer_index
+ v
->input_buffer_size
);
534 if (!v
->prefer_read_write
) {
535 n
= recv(v
->fd
, v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
, rs
, MSG_DONTWAIT
);
536 if (n
< 0 && errno
== ENOTSOCK
)
537 v
->prefer_read_write
= true;
539 if (v
->prefer_read_write
)
540 n
= read(v
->fd
, v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
, rs
);
545 if (ERRNO_IS_DISCONNECT(errno
)) {
546 v
->read_disconnected
= true;
552 if (n
== 0) { /* EOF */
553 v
->read_disconnected
= true;
557 v
->input_buffer_size
+= n
;
558 v
->input_buffer_unscanned
+= n
;
563 static int varlink_parse_message(Varlink
*v
) {
564 const char *e
, *begin
;
572 if (v
->input_buffer_unscanned
<= 0)
575 assert(v
->input_buffer_unscanned
<= v
->input_buffer_size
);
576 assert(v
->input_buffer_index
+ v
->input_buffer_size
<= v
->input_buffer_allocated
);
578 begin
= v
->input_buffer
+ v
->input_buffer_index
;
580 e
= memchr(begin
+ v
->input_buffer_size
- v
->input_buffer_unscanned
, 0, v
->input_buffer_unscanned
);
582 v
->input_buffer_unscanned
= 0;
588 varlink_log(v
, "New incoming message: %s", begin
); /* FIXME: should we output the whole message here before validation?
589 * This may produce a non-printable journal entry if the message
590 * is invalid. We may also expose privileged information. */
592 r
= json_parse(begin
, 0, &v
->current
, NULL
, NULL
);
594 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
595 * hence drop all buffered data now. */
596 v
->input_buffer_index
= v
->input_buffer_size
= v
->input_buffer_unscanned
= 0;
597 return varlink_log_errno(v
, r
, "Failed to parse JSON: %m");
600 v
->input_buffer_size
-= sz
;
602 if (v
->input_buffer_size
== 0)
603 v
->input_buffer_index
= 0;
605 v
->input_buffer_index
+= sz
;
607 v
->input_buffer_unscanned
= v
->input_buffer_size
;
611 static int varlink_test_timeout(Varlink
*v
) {
614 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
616 if (v
->timeout
== USEC_INFINITY
)
619 if (now(CLOCK_MONOTONIC
) < usec_add(v
->timestamp
, v
->timeout
))
622 varlink_set_state(v
, VARLINK_PENDING_TIMEOUT
);
627 static int varlink_dispatch_local_error(Varlink
*v
, const char *error
) {
633 if (!v
->reply_callback
)
636 r
= v
->reply_callback(v
, NULL
, error
, VARLINK_REPLY_ERROR
|VARLINK_REPLY_LOCAL
, v
->userdata
);
638 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
643 static int varlink_dispatch_timeout(Varlink
*v
) {
646 if (v
->state
!= VARLINK_PENDING_TIMEOUT
)
649 varlink_set_state(v
, VARLINK_PROCESSING_TIMEOUT
);
650 varlink_dispatch_local_error(v
, VARLINK_ERROR_TIMEOUT
);
656 static int varlink_dispatch_disconnect(Varlink
*v
) {
659 if (v
->state
!= VARLINK_PENDING_DISCONNECT
)
662 varlink_set_state(v
, VARLINK_PROCESSING_DISCONNECT
);
663 varlink_dispatch_local_error(v
, VARLINK_ERROR_DISCONNECTED
);
669 static int varlink_sanitize_parameters(JsonVariant
**v
) {
672 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
674 return json_variant_new_object(v
, NULL
, 0);
675 else if (!json_variant_is_object(*v
))
681 static int varlink_dispatch_reply(Varlink
*v
) {
682 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
683 VarlinkReplyFlags flags
= 0;
684 const char *error
= NULL
;
691 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
))
696 assert(v
->n_pending
> 0);
698 if (!json_variant_is_object(v
->current
))
701 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
703 if (streq(k
, "error")) {
706 if (!json_variant_is_string(e
))
709 error
= json_variant_string(e
);
710 flags
|= VARLINK_REPLY_ERROR
;
712 } else if (streq(k
, "parameters")) {
715 if (!json_variant_is_object(e
))
718 parameters
= json_variant_ref(e
);
720 } else if (streq(k
, "continues")) {
721 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
724 if (!json_variant_is_boolean(e
))
727 if (json_variant_boolean(e
))
728 flags
|= VARLINK_REPLY_CONTINUES
;
733 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
734 if (v
->state
!= VARLINK_AWAITING_REPLY_MORE
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
737 /* An error is final */
738 if (error
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
741 r
= varlink_sanitize_parameters(¶meters
);
745 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
)) {
746 varlink_set_state(v
, VARLINK_PROCESSING_REPLY
);
748 if (v
->reply_callback
) {
749 r
= v
->reply_callback(v
, parameters
, error
, flags
, v
->userdata
);
751 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
754 v
->current
= json_variant_unref(v
->current
);
756 if (v
->state
== VARLINK_PROCESSING_REPLY
) {
758 assert(v
->n_pending
> 0);
760 if (!FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
764 FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
) ? VARLINK_AWAITING_REPLY_MORE
:
765 v
->n_pending
== 0 ? VARLINK_IDLE_CLIENT
: VARLINK_AWAITING_REPLY
);
768 assert(v
->state
== VARLINK_CALLING
);
769 varlink_set_state(v
, VARLINK_CALLED
);
775 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
776 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
782 static int varlink_dispatch_method(Varlink
*v
) {
783 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
784 VarlinkMethodFlags flags
= 0;
785 const char *method
= NULL
, *error
;
787 VarlinkMethod callback
;
793 if (v
->state
!= VARLINK_IDLE_SERVER
)
798 if (!json_variant_is_object(v
->current
))
801 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
803 if (streq(k
, "method")) {
806 if (!json_variant_is_string(e
))
809 method
= json_variant_string(e
);
811 } else if (streq(k
, "parameters")) {
814 if (!json_variant_is_object(e
))
817 parameters
= json_variant_ref(e
);
819 } else if (streq(k
, "oneway")) {
821 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
824 if (!json_variant_is_boolean(e
))
827 if (json_variant_boolean(e
))
828 flags
|= VARLINK_METHOD_ONEWAY
;
830 } else if (streq(k
, "more")) {
832 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
835 if (!json_variant_is_boolean(e
))
838 if (json_variant_boolean(e
))
839 flags
|= VARLINK_METHOD_MORE
;
848 r
= varlink_sanitize_parameters(¶meters
);
852 varlink_set_state(v
, (flags
& VARLINK_METHOD_MORE
) ? VARLINK_PROCESSING_METHOD_MORE
:
853 (flags
& VARLINK_METHOD_ONEWAY
) ? VARLINK_PROCESSING_METHOD_ONEWAY
:
854 VARLINK_PROCESSING_METHOD
);
858 if (STR_IN_SET(method
, "org.varlink.service.GetInfo", "org.varlink.service.GetInterface")) {
859 /* For now, we don't implement a single of varlink's own methods */
861 error
= VARLINK_ERROR_METHOD_NOT_IMPLEMENTED
;
862 } else if (startswith(method
, "org.varlink.service.")) {
864 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
866 callback
= hashmap_get(v
->server
->methods
, method
);
867 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
871 r
= callback(v
, parameters
, flags
, v
->userdata
);
873 log_debug_errno(r
, "Callback for %s returned error: %m", method
);
875 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
876 if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
877 r
= varlink_error_errno(v
, r
);
882 } else if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
885 r
= varlink_errorb(v
, error
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
))));
892 case VARLINK_PROCESSED_METHOD
: /* Method call is fully processed */
893 case VARLINK_PROCESSING_METHOD_ONEWAY
: /* ditto */
894 v
->current
= json_variant_unref(v
->current
);
895 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
898 case VARLINK_PROCESSING_METHOD
: /* Method call wasn't replied to, will be replied to later */
899 varlink_set_state(v
, VARLINK_PENDING_METHOD
);
902 case VARLINK_PROCESSING_METHOD_MORE
: /* No reply for a "more" message was sent, more to come */
903 varlink_set_state(v
, VARLINK_PENDING_METHOD_MORE
);
907 assert_not_reached("Unexpected state");
917 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
918 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
924 int varlink_process(Varlink
*v
) {
927 assert_return(v
, -EINVAL
);
929 if (v
->state
== VARLINK_DISCONNECTED
)
934 r
= varlink_write(v
);
938 r
= varlink_dispatch_reply(v
);
942 r
= varlink_dispatch_method(v
);
946 r
= varlink_parse_message(v
);
954 r
= varlink_test_disconnect(v
);
958 r
= varlink_dispatch_disconnect(v
);
962 r
= varlink_test_timeout(v
);
966 r
= varlink_dispatch_timeout(v
);
971 if (r
>= 0 && v
->defer_event_source
) {
974 /* If we did some processing, make sure we are called again soon */
975 q
= sd_event_source_set_enabled(v
->defer_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
981 if (VARLINK_STATE_IS_ALIVE(v
->state
))
982 /* Initiate disconnection */
983 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
985 /* We failed while disconnecting, in that case close right away */
993 static void handle_revents(Varlink
*v
, int revents
) {
997 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
998 * to complete on, we know we are ready. We don't read the connection error here though,
999 * we'll get the error on the next read() or write(). */
1000 if ((revents
& (POLLOUT
|POLLHUP
)) == 0)
1003 varlink_log(v
, "Anynchronous connection completed.");
1004 v
->connecting
= false;
1006 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1007 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1008 * momentarily don't want to read nor write anything. */
1010 if (!FLAGS_SET(revents
, POLLHUP
))
1013 varlink_log(v
, "Got POLLHUP from socket.");
1014 v
->got_pollhup
= true;
1018 int varlink_wait(Varlink
*v
, usec_t timeout
) {
1022 assert_return(v
, -EINVAL
);
1024 if (v
->state
== VARLINK_DISCONNECTED
)
1027 r
= varlink_get_timeout(v
, &t
);
1030 if (t
!= USEC_INFINITY
) {
1033 n
= now(CLOCK_MONOTONIC
);
1037 t
= usec_sub_unsigned(t
, n
);
1040 if (timeout
!= USEC_INFINITY
&&
1041 (t
== USEC_INFINITY
|| timeout
< t
))
1044 fd
= varlink_get_fd(v
);
1048 events
= varlink_get_events(v
);
1052 r
= fd_wait_for_event(fd
, events
, t
);
1056 handle_revents(v
, r
);
1060 int varlink_get_fd(Varlink
*v
) {
1062 assert_return(v
, -EINVAL
);
1064 if (v
->state
== VARLINK_DISCONNECTED
)
1072 int varlink_get_events(Varlink
*v
) {
1075 assert_return(v
, -EINVAL
);
1077 if (v
->state
== VARLINK_DISCONNECTED
)
1080 if (v
->connecting
) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1081 * tells us that the connection is now complete. Before that we should neither
1082 * write() or read() from the fd. */
1085 if (!v
->read_disconnected
&&
1086 IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) &&
1088 v
->input_buffer_unscanned
<= 0)
1091 if (!v
->write_disconnected
&&
1092 v
->output_buffer_size
> 0)
1098 int varlink_get_timeout(Varlink
*v
, usec_t
*ret
) {
1099 assert_return(v
, -EINVAL
);
1101 if (v
->state
== VARLINK_DISCONNECTED
)
1104 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_AWAITING_REPLY_MORE
, VARLINK_CALLING
) &&
1105 v
->timeout
!= USEC_INFINITY
) {
1107 *ret
= usec_add(v
->timestamp
, v
->timeout
);
1111 *ret
= USEC_INFINITY
;
1116 int varlink_flush(Varlink
*v
) {
1119 assert_return(v
, -EINVAL
);
1121 if (v
->state
== VARLINK_DISCONNECTED
)
1125 if (v
->output_buffer_size
== 0)
1127 if (v
->write_disconnected
)
1130 r
= varlink_write(v
);
1138 r
= fd_wait_for_event(v
->fd
, POLLOUT
, USEC_INFINITY
);
1144 handle_revents(v
, r
);
1150 static void varlink_detach_server(Varlink
*v
) {
1151 VarlinkServer
*saved_server
;
1157 if (v
->server
->by_uid
&&
1158 v
->ucred_acquired
&&
1159 uid_is_valid(v
->ucred
.uid
)) {
1162 c
= PTR_TO_UINT(hashmap_get(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
)));
1166 (void) hashmap_remove(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
));
1168 (void) hashmap_replace(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
), UINT_TO_PTR(c
- 1));
1171 assert(v
->server
->n_connections
> 0);
1172 v
->server
->n_connections
--;
1174 /* If this is a connection associated to a server, then let's disconnect the server and the
1175 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1176 * before we release the references, let's call the disconnection callback if it is defined. */
1178 saved_server
= TAKE_PTR(v
->server
);
1180 if (saved_server
->disconnect_callback
)
1181 saved_server
->disconnect_callback(saved_server
, v
, saved_server
->userdata
);
1183 varlink_server_unref(saved_server
);
1187 int varlink_close(Varlink
*v
) {
1189 assert_return(v
, -EINVAL
);
1191 if (v
->state
== VARLINK_DISCONNECTED
)
1194 varlink_set_state(v
, VARLINK_DISCONNECTED
);
1196 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1197 * which would destroy us before we can call varlink_clear() */
1199 varlink_detach_server(v
);
1206 Varlink
* varlink_close_unref(Varlink
*v
) {
1211 (void) varlink_close(v
);
1212 return varlink_unref(v
);
1215 Varlink
* varlink_flush_close_unref(Varlink
*v
) {
1220 (void) varlink_flush(v
);
1221 (void) varlink_close(v
);
1222 return varlink_unref(v
);
1225 static int varlink_enqueue_json(Varlink
*v
, JsonVariant
*m
) {
1226 _cleanup_free_
char *text
= NULL
;
1232 r
= json_variant_format(m
, 0, &text
);
1235 assert(text
[r
] == '\0');
1237 if (v
->output_buffer_size
+ r
+ 1 > VARLINK_BUFFER_MAX
)
1240 varlink_log(v
, "Sending message: %s", text
);
1242 if (v
->output_buffer_size
== 0) {
1244 free_and_replace(v
->output_buffer
, text
);
1246 v
->output_buffer_size
= v
->output_buffer_allocated
= r
+ 1;
1247 v
->output_buffer_index
= 0;
1249 } else if (v
->output_buffer_index
== 0) {
1251 if (!GREEDY_REALLOC(v
->output_buffer
, v
->output_buffer_allocated
, v
->output_buffer_size
+ r
+ 1))
1254 memcpy(v
->output_buffer
+ v
->output_buffer_size
, text
, r
+ 1);
1255 v
->output_buffer_size
+= r
+ 1;
1259 const size_t new_size
= v
->output_buffer_size
+ r
+ 1;
1261 n
= new(char, new_size
);
1265 memcpy(mempcpy(n
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
), text
, r
+ 1);
1267 free_and_replace(v
->output_buffer
, n
);
1268 v
->output_buffer_allocated
= v
->output_buffer_size
= new_size
;
1269 v
->output_buffer_index
= 0;
1275 int varlink_send(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1276 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1279 assert_return(v
, -EINVAL
);
1280 assert_return(method
, -EINVAL
);
1282 if (v
->state
== VARLINK_DISCONNECTED
)
1285 /* We allow enqueuing multiple method calls at once! */
1286 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1289 r
= varlink_sanitize_parameters(¶meters
);
1293 r
= json_build(&m
, JSON_BUILD_OBJECT(
1294 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1295 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1296 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1300 r
= varlink_enqueue_json(v
, m
);
1304 /* No state change here, this is one-way only after all */
1305 v
->timestamp
= now(CLOCK_MONOTONIC
);
1309 int varlink_sendb(Varlink
*v
, const char *method
, ...) {
1310 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1314 assert_return(v
, -EINVAL
);
1316 va_start(ap
, method
);
1317 r
= json_buildv(¶meters
, ap
);
1323 return varlink_send(v
, method
, parameters
);
1326 int varlink_invoke(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1327 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1330 assert_return(v
, -EINVAL
);
1331 assert_return(method
, -EINVAL
);
1333 if (v
->state
== VARLINK_DISCONNECTED
)
1336 /* We allow enqueuing multiple method calls at once! */
1337 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1340 r
= varlink_sanitize_parameters(¶meters
);
1344 r
= json_build(&m
, JSON_BUILD_OBJECT(
1345 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1346 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1350 r
= varlink_enqueue_json(v
, m
);
1354 varlink_set_state(v
, VARLINK_AWAITING_REPLY
);
1356 v
->timestamp
= now(CLOCK_MONOTONIC
);
1361 int varlink_invokeb(Varlink
*v
, const char *method
, ...) {
1362 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1366 assert_return(v
, -EINVAL
);
1368 va_start(ap
, method
);
1369 r
= json_buildv(¶meters
, ap
);
1375 return varlink_invoke(v
, method
, parameters
);
1378 int varlink_observe(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1379 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1382 assert_return(v
, -EINVAL
);
1383 assert_return(method
, -EINVAL
);
1385 if (v
->state
== VARLINK_DISCONNECTED
)
1387 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1388 * thus insist on an idle client here. */
1389 if (v
->state
!= VARLINK_IDLE_CLIENT
)
1392 r
= varlink_sanitize_parameters(¶meters
);
1396 r
= json_build(&m
, JSON_BUILD_OBJECT(
1397 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1398 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1399 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1403 r
= varlink_enqueue_json(v
, m
);
1408 varlink_set_state(v
, VARLINK_AWAITING_REPLY_MORE
);
1410 v
->timestamp
= now(CLOCK_MONOTONIC
);
1415 int varlink_observeb(Varlink
*v
, const char *method
, ...) {
1416 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1420 assert_return(v
, -EINVAL
);
1422 va_start(ap
, method
);
1423 r
= json_buildv(¶meters
, ap
);
1429 return varlink_observe(v
, method
, parameters
);
1435 JsonVariant
*parameters
,
1436 JsonVariant
**ret_parameters
,
1437 const char **ret_error_id
,
1438 VarlinkReplyFlags
*ret_flags
) {
1440 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1443 assert_return(v
, -EINVAL
);
1444 assert_return(method
, -EINVAL
);
1446 if (v
->state
== VARLINK_DISCONNECTED
)
1448 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
))
1451 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1453 r
= varlink_sanitize_parameters(¶meters
);
1457 r
= json_build(&m
, JSON_BUILD_OBJECT(
1458 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1459 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1463 r
= varlink_enqueue_json(v
, m
);
1467 varlink_set_state(v
, VARLINK_CALLING
);
1469 v
->timestamp
= now(CLOCK_MONOTONIC
);
1471 while (v
->state
== VARLINK_CALLING
) {
1473 r
= varlink_process(v
);
1479 r
= varlink_wait(v
, USEC_INFINITY
);
1486 case VARLINK_CALLED
:
1489 json_variant_unref(v
->reply
);
1490 v
->reply
= TAKE_PTR(v
->current
);
1492 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
1493 assert(v
->n_pending
== 1);
1497 *ret_parameters
= json_variant_by_key(v
->reply
, "parameters");
1499 *ret_error_id
= json_variant_string(json_variant_by_key(v
->reply
, "error"));
1505 case VARLINK_PENDING_DISCONNECT
:
1506 case VARLINK_DISCONNECTED
:
1509 case VARLINK_PENDING_TIMEOUT
:
1513 assert_not_reached("Unexpected state after method call.");
1520 JsonVariant
**ret_parameters
,
1521 const char **ret_error_id
,
1522 VarlinkReplyFlags
*ret_flags
, ...) {
1524 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1528 assert_return(v
, -EINVAL
);
1530 va_start(ap
, ret_flags
);
1531 r
= json_buildv(¶meters
, ap
);
1537 return varlink_call(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
1540 int varlink_reply(Varlink
*v
, JsonVariant
*parameters
) {
1541 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1544 assert_return(v
, -EINVAL
);
1546 if (v
->state
== VARLINK_DISCONNECTED
)
1548 if (!IN_SET(v
->state
,
1549 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1550 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1553 r
= varlink_sanitize_parameters(¶meters
);
1557 r
= json_build(&m
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1561 r
= varlink_enqueue_json(v
, m
);
1565 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1566 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1567 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1568 * process further messages. */
1569 v
->current
= json_variant_unref(v
->current
);
1570 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1572 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1573 * means we should it handle the rest of the state engine. */
1574 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1579 int varlink_replyb(Varlink
*v
, ...) {
1580 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1584 assert_return(v
, -EINVAL
);
1587 r
= json_buildv(¶meters
, ap
);
1593 return varlink_reply(v
, parameters
);
1596 int varlink_error(Varlink
*v
, const char *error_id
, JsonVariant
*parameters
) {
1597 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1600 assert_return(v
, -EINVAL
);
1601 assert_return(error_id
, -EINVAL
);
1603 if (v
->state
== VARLINK_DISCONNECTED
)
1605 if (!IN_SET(v
->state
,
1606 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1607 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1610 r
= varlink_sanitize_parameters(¶meters
);
1614 r
= json_build(&m
, JSON_BUILD_OBJECT(
1615 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id
)),
1616 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1620 r
= varlink_enqueue_json(v
, m
);
1624 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1625 v
->current
= json_variant_unref(v
->current
);
1626 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1628 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1633 int varlink_errorb(Varlink
*v
, const char *error_id
, ...) {
1634 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1638 assert_return(v
, -EINVAL
);
1639 assert_return(error_id
, -EINVAL
);
1641 va_start(ap
, error_id
);
1642 r
= json_buildv(¶meters
, ap
);
1648 return varlink_error(v
, error_id
, parameters
);
1651 int varlink_error_invalid_parameter(Varlink
*v
, JsonVariant
*parameters
) {
1653 assert_return(v
, -EINVAL
);
1654 assert_return(parameters
, -EINVAL
);
1656 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1657 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1658 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1659 * don't expect any arguments. */
1661 if (json_variant_is_string(parameters
))
1662 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters
);
1664 if (json_variant_is_object(parameters
) &&
1665 json_variant_elements(parameters
) > 0)
1666 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
,
1667 json_variant_by_index(parameters
, 0));
1672 int varlink_error_errno(Varlink
*v
, int error
) {
1673 return varlink_errorb(
1675 VARLINK_ERROR_SYSTEM
,
1676 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error
)))));
1679 int varlink_notify(Varlink
*v
, JsonVariant
*parameters
) {
1680 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1683 assert_return(v
, -EINVAL
);
1685 if (v
->state
== VARLINK_DISCONNECTED
)
1687 if (!IN_SET(v
->state
, VARLINK_PROCESSING_METHOD_MORE
, VARLINK_PENDING_METHOD_MORE
))
1690 r
= varlink_sanitize_parameters(¶meters
);
1694 r
= json_build(&m
, JSON_BUILD_OBJECT(
1695 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1696 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
1700 r
= varlink_enqueue_json(v
, m
);
1704 /* No state change, as more is coming */
1708 int varlink_notifyb(Varlink
*v
, ...) {
1709 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1713 assert_return(v
, -EINVAL
);
1716 r
= json_buildv(¶meters
, ap
);
1722 return varlink_notify(v
, parameters
);
1725 int varlink_bind_reply(Varlink
*v
, VarlinkReply callback
) {
1726 assert_return(v
, -EINVAL
);
1728 if (callback
&& v
->reply_callback
&& callback
!= v
->reply_callback
)
1731 v
->reply_callback
= callback
;
1736 void* varlink_set_userdata(Varlink
*v
, void *userdata
) {
1739 assert_return(v
, NULL
);
1742 v
->userdata
= userdata
;
1747 void* varlink_get_userdata(Varlink
*v
) {
1748 assert_return(v
, NULL
);
1753 static int varlink_acquire_ucred(Varlink
*v
) {
1758 if (v
->ucred_acquired
)
1761 r
= getpeercred(v
->fd
, &v
->ucred
);
1765 v
->ucred_acquired
= true;
1769 int varlink_get_peer_uid(Varlink
*v
, uid_t
*ret
) {
1772 assert_return(v
, -EINVAL
);
1773 assert_return(ret
, -EINVAL
);
1775 r
= varlink_acquire_ucred(v
);
1779 if (!uid_is_valid(v
->ucred
.uid
))
1782 *ret
= v
->ucred
.uid
;
1786 int varlink_get_peer_pid(Varlink
*v
, pid_t
*ret
) {
1789 assert_return(v
, -EINVAL
);
1790 assert_return(ret
, -EINVAL
);
1792 r
= varlink_acquire_ucred(v
);
1796 if (!pid_is_valid(v
->ucred
.pid
))
1799 *ret
= v
->ucred
.pid
;
1803 int varlink_set_relative_timeout(Varlink
*v
, usec_t timeout
) {
1804 assert_return(v
, -EINVAL
);
1805 assert_return(timeout
> 0, -EINVAL
);
1807 v
->timeout
= timeout
;
1811 VarlinkServer
*varlink_get_server(Varlink
*v
) {
1812 assert_return(v
, NULL
);
1817 int varlink_set_description(Varlink
*v
, const char *description
) {
1818 assert_return(v
, -EINVAL
);
1820 return free_and_strdup(&v
->description
, description
);
1823 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1824 Varlink
*v
= userdata
;
1829 handle_revents(v
, revents
);
1830 (void) varlink_process(v
);
1835 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
1836 Varlink
*v
= userdata
;
1841 (void) varlink_process(v
);
1845 static int defer_callback(sd_event_source
*s
, void *userdata
) {
1846 Varlink
*v
= userdata
;
1851 (void) varlink_process(v
);
1855 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
1856 Varlink
*v
= userdata
;
1864 e
= varlink_get_events(v
);
1868 r
= sd_event_source_set_io_events(v
->io_event_source
, e
);
1872 r
= varlink_get_timeout(v
, &until
);
1875 have_timeout
= r
> 0;
1878 r
= sd_event_source_set_time(v
->time_event_source
, until
);
1883 r
= sd_event_source_set_enabled(v
->time_event_source
, have_timeout
? SD_EVENT_ON
: SD_EVENT_OFF
);
1890 static int quit_callback(sd_event_source
*event
, void *userdata
) {
1891 Varlink
*v
= userdata
;
1902 int varlink_attach_event(Varlink
*v
, sd_event
*e
, int64_t priority
) {
1905 assert_return(v
, -EINVAL
);
1906 assert_return(!v
->event
, -EBUSY
);
1909 v
->event
= sd_event_ref(e
);
1911 r
= sd_event_default(&v
->event
);
1916 r
= sd_event_add_time(v
->event
, &v
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, v
);
1920 r
= sd_event_source_set_priority(v
->time_event_source
, priority
);
1924 (void) sd_event_source_set_description(v
->time_event_source
, "varlink-time");
1926 r
= sd_event_add_exit(v
->event
, &v
->quit_event_source
, quit_callback
, v
);
1930 r
= sd_event_source_set_priority(v
->quit_event_source
, priority
);
1934 (void) sd_event_source_set_description(v
->quit_event_source
, "varlink-quit");
1936 r
= sd_event_add_io(v
->event
, &v
->io_event_source
, v
->fd
, 0, io_callback
, v
);
1940 r
= sd_event_source_set_prepare(v
->io_event_source
, prepare_callback
);
1944 r
= sd_event_source_set_priority(v
->io_event_source
, priority
);
1948 (void) sd_event_source_set_description(v
->io_event_source
, "varlink-io");
1950 r
= sd_event_add_defer(v
->event
, &v
->defer_event_source
, defer_callback
, v
);
1954 r
= sd_event_source_set_priority(v
->defer_event_source
, priority
);
1958 (void) sd_event_source_set_description(v
->defer_event_source
, "varlink-defer");
1963 varlink_detach_event(v
);
1967 void varlink_detach_event(Varlink
*v
) {
1971 varlink_detach_event_sources(v
);
1973 v
->event
= sd_event_unref(v
->event
);
1976 sd_event
*varlink_get_event(Varlink
*v
) {
1977 assert_return(v
, NULL
);
1982 int varlink_server_new(VarlinkServer
**ret
, VarlinkServerFlags flags
) {
1985 assert_return(ret
, -EINVAL
);
1986 assert_return((flags
& ~_VARLINK_SERVER_FLAGS_ALL
) == 0, -EINVAL
);
1988 s
= new(VarlinkServer
, 1);
1992 *s
= (VarlinkServer
) {
1995 .connections_max
= varlink_server_connections_max(NULL
),
1996 .connections_per_uid_max
= varlink_server_connections_per_uid_max(NULL
),
2003 static VarlinkServer
* varlink_server_destroy(VarlinkServer
*s
) {
2009 varlink_server_shutdown(s
);
2011 while ((m
= hashmap_steal_first_key(s
->methods
)))
2014 hashmap_free(s
->methods
);
2015 hashmap_free(s
->by_uid
);
2017 sd_event_unref(s
->event
);
2019 free(s
->description
);
2024 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer
, varlink_server
, varlink_server_destroy
);
2026 static int validate_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
2032 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ROOT_ONLY
))
2033 allowed
= ucred
->uid
== 0;
2035 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_MYSELF_ONLY
))
2036 allowed
= allowed
> 0 || ucred
->uid
== getuid();
2038 if (allowed
== 0) { /* Allow access when it is explicitly allowed or when neither
2039 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2040 varlink_server_log(server
, "Unprivileged client attempted connection, refusing.");
2044 if (server
->n_connections
>= server
->connections_max
) {
2045 varlink_server_log(server
, "Connection limit of %u reached, refusing.", server
->connections_max
);
2049 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
2052 if (!uid_is_valid(ucred
->uid
)) {
2053 varlink_server_log(server
, "Client with invalid UID attempted connection, refusing.");
2057 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
2058 if (c
>= server
->connections_per_uid_max
) {
2059 varlink_server_log(server
, "Per-UID connection limit of %u reached, refusing.",
2060 server
->connections_per_uid_max
);
2068 static int count_connection(VarlinkServer
*server
, struct ucred
*ucred
) {
2075 server
->n_connections
++;
2077 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
2078 r
= hashmap_ensure_allocated(&server
->by_uid
, NULL
);
2080 return log_debug_errno(r
, "Failed to allocate UID hash table: %m");
2082 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
2084 varlink_server_log(server
, "Connections of user " UID_FMT
": %u (of %u max)",
2085 ucred
->uid
, c
, server
->connections_per_uid_max
);
2087 r
= hashmap_replace(server
->by_uid
, UID_TO_PTR(ucred
->uid
), UINT_TO_PTR(c
+ 1));
2089 return log_debug_errno(r
, "Failed to increment counter in UID hash table: %m");
2095 int varlink_server_add_connection(VarlinkServer
*server
, int fd
, Varlink
**ret
) {
2096 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
2097 bool ucred_acquired
;
2101 assert_return(server
, -EINVAL
);
2102 assert_return(fd
>= 0, -EBADF
);
2104 if ((server
->flags
& (VARLINK_SERVER_ROOT_ONLY
|VARLINK_SERVER_ACCOUNT_UID
)) != 0) {
2105 r
= getpeercred(fd
, &ucred
);
2107 return varlink_server_log_errno(server
, r
, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2109 ucred_acquired
= true;
2111 r
= validate_connection(server
, &ucred
);
2117 ucred_acquired
= false;
2119 r
= varlink_new(&v
);
2121 return varlink_server_log_errno(server
, r
, "Failed to allocate connection object: %m");
2123 r
= count_connection(server
, &ucred
);
2128 v
->userdata
= server
->userdata
;
2129 if (ucred_acquired
) {
2131 v
->ucred_acquired
= true;
2134 (void) asprintf(&v
->description
, "%s-%i", server
->description
?: "varlink", v
->fd
);
2136 /* Link up the server and the connection, and take reference in both directions. Note that the
2137 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2138 * which happens in varlink_close(), including in the event loop quit callback. */
2139 v
->server
= varlink_server_ref(server
);
2142 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2144 if (server
->event
) {
2145 r
= varlink_attach_event(v
, server
->event
, server
->event_priority
);
2147 varlink_log_errno(v
, r
, "Failed to attach new connection: %m");
2148 v
->fd
= -1; /* take the fd out of the connection again */
2160 static int connect_callback(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2161 VarlinkServerSocket
*ss
= userdata
;
2162 _cleanup_close_
int cfd
= -1;
2169 varlink_server_log(ss
->server
, "New incoming connection.");
2171 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2173 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
2176 return varlink_server_log_errno(ss
->server
, errno
, "Failed to accept incoming socket: %m");
2179 r
= varlink_server_add_connection(ss
->server
, cfd
, &v
);
2185 if (ss
->server
->connect_callback
) {
2186 r
= ss
->server
->connect_callback(ss
->server
, v
, ss
->server
->userdata
);
2188 varlink_log_errno(v
, r
, "Connection callback returned error, disconnecting client: %m");
2197 int varlink_server_listen_fd(VarlinkServer
*s
, int fd
) {
2198 _cleanup_free_ VarlinkServerSocket
*ss
= NULL
;
2201 assert_return(s
, -EINVAL
);
2202 assert_return(fd
>= 0, -EBADF
);
2204 r
= fd_nonblock(fd
, true);
2208 ss
= new(VarlinkServerSocket
, 1);
2212 *ss
= (VarlinkServerSocket
) {
2218 r
= sd_event_add_io(s
->event
, &ss
->event_source
, fd
, EPOLLIN
, connect_callback
, ss
);
2222 r
= sd_event_source_set_priority(ss
->event_source
, s
->event_priority
);
2227 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
2231 int varlink_server_listen_address(VarlinkServer
*s
, const char *address
, mode_t m
) {
2232 union sockaddr_union sockaddr
;
2233 socklen_t sockaddr_len
;
2234 _cleanup_close_
int fd
= -1;
2237 assert_return(s
, -EINVAL
);
2238 assert_return(address
, -EINVAL
);
2239 assert_return((m
& ~0777) == 0, -EINVAL
);
2241 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
2246 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2250 fd
= fd_move_above_stdio(fd
);
2252 (void) sockaddr_un_unlink(&sockaddr
.un
);
2254 RUN_WITH_UMASK(~m
& 0777) {
2255 r
= mac_selinux_bind(fd
, &sockaddr
.sa
, sockaddr_len
);
2260 if (listen(fd
, SOMAXCONN
) < 0)
2263 r
= varlink_server_listen_fd(s
, fd
);
2271 void* varlink_server_set_userdata(VarlinkServer
*s
, void *userdata
) {
2274 assert_return(s
, NULL
);
2277 s
->userdata
= userdata
;
2282 void* varlink_server_get_userdata(VarlinkServer
*s
) {
2283 assert_return(s
, NULL
);
2288 static VarlinkServerSocket
* varlink_server_socket_destroy(VarlinkServerSocket
*ss
) {
2293 LIST_REMOVE(sockets
, ss
->server
->sockets
, ss
);
2295 sd_event_source_disable_unref(ss
->event_source
);
2303 int varlink_server_shutdown(VarlinkServer
*s
) {
2304 assert_return(s
, -EINVAL
);
2307 varlink_server_socket_destroy(s
->sockets
);
2312 int varlink_server_attach_event(VarlinkServer
*s
, sd_event
*e
, int64_t priority
) {
2313 VarlinkServerSocket
*ss
;
2316 assert_return(s
, -EINVAL
);
2317 assert_return(!s
->event
, -EBUSY
);
2320 s
->event
= sd_event_ref(e
);
2322 r
= sd_event_default(&s
->event
);
2327 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
2328 assert(!ss
->event_source
);
2330 r
= sd_event_add_io(s
->event
, &ss
->event_source
, ss
->fd
, EPOLLIN
, connect_callback
, ss
);
2334 r
= sd_event_source_set_priority(ss
->event_source
, priority
);
2339 s
->event_priority
= priority
;
2343 varlink_server_detach_event(s
);
2347 int varlink_server_detach_event(VarlinkServer
*s
) {
2348 VarlinkServerSocket
*ss
;
2350 assert_return(s
, -EINVAL
);
2352 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
2354 if (!ss
->event_source
)
2357 (void) sd_event_source_set_enabled(ss
->event_source
, SD_EVENT_OFF
);
2358 ss
->event_source
= sd_event_source_unref(ss
->event_source
);
2361 sd_event_unref(s
->event
);
2365 sd_event
*varlink_server_get_event(VarlinkServer
*s
) {
2366 assert_return(s
, NULL
);
2371 int varlink_server_bind_method(VarlinkServer
*s
, const char *method
, VarlinkMethod callback
) {
2375 assert_return(s
, -EINVAL
);
2376 assert_return(method
, -EINVAL
);
2377 assert_return(callback
, -EINVAL
);
2379 if (startswith(method
, "org.varlink.service."))
2382 r
= hashmap_ensure_allocated(&s
->methods
, &string_hash_ops
);
2390 r
= hashmap_put(s
->methods
, m
, callback
);
2399 int varlink_server_bind_method_many_internal(VarlinkServer
*s
, ...) {
2403 assert_return(s
, -EINVAL
);
2407 VarlinkMethod callback
;
2410 method
= va_arg(ap
, const char *);
2414 callback
= va_arg(ap
, VarlinkMethod
);
2416 r
= varlink_server_bind_method(s
, method
, callback
);
2425 int varlink_server_bind_connect(VarlinkServer
*s
, VarlinkConnect callback
) {
2426 assert_return(s
, -EINVAL
);
2428 if (callback
&& s
->connect_callback
&& callback
!= s
->connect_callback
)
2431 s
->connect_callback
= callback
;
2435 int varlink_server_bind_disconnect(VarlinkServer
*s
, VarlinkDisconnect callback
) {
2436 assert_return(s
, -EINVAL
);
2438 if (callback
&& s
->disconnect_callback
&& callback
!= s
->disconnect_callback
)
2441 s
->disconnect_callback
= callback
;
2445 unsigned varlink_server_connections_max(VarlinkServer
*s
) {
2448 /* If a server is specified, return the setting for that server, otherwise the default value */
2450 return s
->connections_max
;
2452 dts
= getdtablesize();
2455 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
2456 if (VARLINK_DEFAULT_CONNECTIONS_MAX
> (unsigned) dts
/ 4 * 3)
2459 return VARLINK_DEFAULT_CONNECTIONS_MAX
;
2462 unsigned varlink_server_connections_per_uid_max(VarlinkServer
*s
) {
2466 return s
->connections_per_uid_max
;
2468 /* Make sure to never use up more than ¾th of available connections for a single user */
2469 m
= varlink_server_connections_max(NULL
);
2470 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
> m
)
2473 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
;
2476 int varlink_server_set_connections_per_uid_max(VarlinkServer
*s
, unsigned m
) {
2477 assert_return(s
, -EINVAL
);
2478 assert_return(m
> 0, -EINVAL
);
2480 s
->connections_per_uid_max
= m
;
2484 int varlink_server_set_connections_max(VarlinkServer
*s
, unsigned m
) {
2485 assert_return(s
, -EINVAL
);
2486 assert_return(m
> 0, -EINVAL
);
2488 s
->connections_max
= m
;
2492 unsigned varlink_server_current_connections(VarlinkServer
*s
) {
2493 assert_return(s
, UINT_MAX
);
2495 return s
->n_connections
;
2498 int varlink_server_set_description(VarlinkServer
*s
, const char *description
) {
2499 assert_return(s
, -EINVAL
);
2501 return free_and_strdup(&s
->description
, description
);