1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "alloc-util.h"
6 #include "errno-util.h"
10 #include "process-util.h"
12 #include "socket-util.h"
13 #include "string-table.h"
14 #include "string-util.h"
16 #include "time-util.h"
17 #include "umask-util.h"
18 #include "user-util.h"
21 #define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
22 #define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
24 #define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
25 #define VARLINK_BUFFER_MAX (16U*1024U*1024U)
26 #define VARLINK_READ_SIZE (64U*1024U)
28 typedef enum VarlinkState
{
29 /* Client side states */
31 VARLINK_AWAITING_REPLY
,
34 VARLINK_PROCESSING_REPLY
,
36 /* Server side states */
38 VARLINK_PROCESSING_METHOD
,
39 VARLINK_PROCESSING_METHOD_MORE
,
40 VARLINK_PROCESSING_METHOD_ONEWAY
,
41 VARLINK_PROCESSED_METHOD
,
42 VARLINK_PROCESSED_METHOD_MORE
,
43 VARLINK_PENDING_METHOD
,
44 VARLINK_PENDING_METHOD_MORE
,
46 /* Common states (only during shutdown) */
47 VARLINK_PENDING_DISCONNECT
,
48 VARLINK_PENDING_TIMEOUT
,
49 VARLINK_PROCESSING_DISCONNECT
,
50 VARLINK_PROCESSING_TIMEOUT
,
51 VARLINK_PROCESSING_FAILURE
,
55 _VARLINK_STATE_INVALID
= -1
58 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
59 * is still good for something, and false only when it's dead for good. This means: when we are
60 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
61 * the connection is still good, and we are likely to be able to properly operate on it soon. */
62 #define VARLINK_STATE_IS_ALIVE(state) \
64 VARLINK_IDLE_CLIENT, \
65 VARLINK_AWAITING_REPLY, \
68 VARLINK_PROCESSING_REPLY, \
69 VARLINK_IDLE_SERVER, \
70 VARLINK_PROCESSING_METHOD, \
71 VARLINK_PROCESSING_METHOD_MORE, \
72 VARLINK_PROCESSING_METHOD_ONEWAY, \
73 VARLINK_PROCESSED_METHOD, \
74 VARLINK_PROCESSED_METHOD_MORE, \
75 VARLINK_PENDING_METHOD, \
76 VARLINK_PENDING_METHOD_MORE)
81 VarlinkServer
*server
;
84 bool connecting
; /* This boolean indicates whether the socket fd we are operating on is currently
85 * processing an asynchronous connect(). In that state we watch the socket for
86 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
87 * will trigger ENOTCONN. Note that this boolean is kept separate from the
88 * VarlinkState above on purpose: while the connect() is still not complete we
89 * already want to allow queuing of messages and similar. Thus it's nice to keep
90 * these two state concepts separate: the VarlinkState encodes what our own view of
91 * the connection is, i.e. whether we think it's a server, a client, and has
92 * something queued already, while 'connecting' tells us a detail about the
93 * transport used below, that should have no effect on how we otherwise accept and
94 * process operations from the user.
96 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
97 * connection is good to use, even if it might not be fully connected
98 * yet. connecting=true then informs you that actually we are still connecting, and
99 * the connection is actually not established yet and thus any requests you enqueue
100 * now will still work fine but will be queued only, not sent yet, but that
101 * shouldn't stop you from using the connection, since eventually whatever you queue
104 * Or to say this even differently: 'state' is a high-level ("application layer"
105 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
106 * low, if you so will) state, and while they are not entirely unrelated and
107 * sometimes propagate effects to each other they are only asynchronously connected
113 char *input_buffer
; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
114 size_t input_buffer_allocated
;
115 size_t input_buffer_index
;
116 size_t input_buffer_size
;
117 size_t input_buffer_unscanned
;
119 char *output_buffer
; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
120 size_t output_buffer_allocated
;
121 size_t output_buffer_index
;
122 size_t output_buffer_size
;
124 VarlinkReply reply_callback
;
126 JsonVariant
*current
;
130 bool ucred_acquired
:1;
132 bool write_disconnected
:1;
133 bool read_disconnected
:1;
134 bool prefer_read_write
:1;
144 sd_event_source
*io_event_source
;
145 sd_event_source
*time_event_source
;
146 sd_event_source
*quit_event_source
;
147 sd_event_source
*defer_event_source
;
150 typedef struct VarlinkServerSocket VarlinkServerSocket
;
152 struct VarlinkServerSocket
{
153 VarlinkServer
*server
;
158 sd_event_source
*event_source
;
160 LIST_FIELDS(VarlinkServerSocket
, sockets
);
163 struct VarlinkServer
{
165 VarlinkServerFlags flags
;
167 LIST_HEAD(VarlinkServerSocket
, sockets
);
170 VarlinkConnect connect_callback
;
173 int64_t event_priority
;
175 unsigned n_connections
;
181 unsigned connections_max
;
182 unsigned connections_per_uid_max
;
185 static const char* const varlink_state_table
[_VARLINK_STATE_MAX
] = {
186 [VARLINK_IDLE_CLIENT
] = "idle-client",
187 [VARLINK_AWAITING_REPLY
] = "awaiting-reply",
188 [VARLINK_CALLING
] = "calling",
189 [VARLINK_CALLED
] = "called",
190 [VARLINK_PROCESSING_REPLY
] = "processing-reply",
191 [VARLINK_IDLE_SERVER
] = "idle-server",
192 [VARLINK_PROCESSING_METHOD
] = "processing-method",
193 [VARLINK_PROCESSING_METHOD_MORE
] = "processing-method-more",
194 [VARLINK_PROCESSING_METHOD_ONEWAY
] = "processing-method-oneway",
195 [VARLINK_PROCESSED_METHOD
] = "processed-method",
196 [VARLINK_PROCESSED_METHOD_MORE
] = "processed-method-more",
197 [VARLINK_PENDING_METHOD
] = "pending-method",
198 [VARLINK_PENDING_METHOD_MORE
] = "pending-method-more",
199 [VARLINK_PENDING_DISCONNECT
] = "pending-disconnect",
200 [VARLINK_PENDING_TIMEOUT
] = "pending-timeout",
201 [VARLINK_PROCESSING_DISCONNECT
] = "processing-disconnect",
202 [VARLINK_PROCESSING_TIMEOUT
] = "processing-timeout",
203 [VARLINK_PROCESSING_FAILURE
] = "processing-failure",
204 [VARLINK_DISCONNECTED
] = "disconnected",
207 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state
, VarlinkState
);
209 #define varlink_log_errno(v, error, fmt, ...) \
210 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
212 #define varlink_log(v, fmt, ...) \
213 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
215 #define varlink_server_log_errno(s, error, fmt, ...) \
216 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
218 #define varlink_server_log(s, fmt, ...) \
219 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
221 static inline const char *varlink_description(Varlink
*v
) {
222 return strna(v
? v
->description
: NULL
);
225 static inline const char *varlink_server_description(VarlinkServer
*s
) {
226 return strna(s
? s
->description
: NULL
);
229 static void varlink_set_state(Varlink
*v
, VarlinkState state
) {
231 assert(state
>= 0 && state
< _VARLINK_STATE_MAX
);
234 varlink_log(v
, "varlink: setting state %s",
235 varlink_state_to_string(state
));
237 varlink_log(v
, "varlink: changing state %s → %s",
238 varlink_state_to_string(v
->state
),
239 varlink_state_to_string(state
));
244 static int varlink_new(Varlink
**ret
) {
257 .state
= _VARLINK_STATE_INVALID
,
259 .ucred
.uid
= UID_INVALID
,
260 .ucred
.gid
= GID_INVALID
,
262 .timestamp
= USEC_INFINITY
,
263 .timeout
= VARLINK_DEFAULT_TIMEOUT_USEC
270 int varlink_connect_address(Varlink
**ret
, const char *address
) {
271 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
272 union sockaddr_union sockaddr
;
275 assert_return(ret
, -EINVAL
);
276 assert_return(address
, -EINVAL
);
278 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
286 v
->fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
290 if (connect(v
->fd
, &sockaddr
.sa
, SOCKADDR_UN_LEN(sockaddr
.un
)) < 0) {
291 if (!IN_SET(errno
, EAGAIN
, EINPROGRESS
))
294 v
->connecting
= true; /* We are asynchronously connecting, i.e. the connect() is being
295 * processed in the background. As long as that's the case the socket
296 * is in a special state: it's there, we can poll it for EPOLLOUT, but
297 * if we attempt to write() to it before we see EPOLLOUT we'll get
298 * ENOTCONN (and not EAGAIN, like we would for a normal connected
299 * socket that isn't writable at the moment). Since ENOTCONN on write()
300 * hence can mean two different things (i.e. connection not complete
301 * yet vs. already disconnected again), we store as a boolean whether
302 * we are still in connect(). */
305 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
311 int varlink_connect_fd(Varlink
**ret
, int fd
) {
315 assert_return(ret
, -EINVAL
);
316 assert_return(fd
>= 0, -EBADF
);
318 r
= fd_nonblock(fd
, true);
327 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
329 /* Note that if this function is called we assume the passed socket (if it is one) is already
330 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
331 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
332 * until the connection is fully set up. Behaviour here is hence a bit different from
333 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
334 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
340 static void varlink_detach_event_sources(Varlink
*v
) {
343 v
->io_event_source
= sd_event_source_disable_unref(v
->io_event_source
);
345 v
->time_event_source
= sd_event_source_disable_unref(v
->time_event_source
);
347 v
->quit_event_source
= sd_event_source_disable_unref(v
->quit_event_source
);
349 v
->defer_event_source
= sd_event_source_disable_unref(v
->defer_event_source
);
352 static void varlink_clear(Varlink
*v
) {
355 varlink_detach_event_sources(v
);
357 v
->fd
= safe_close(v
->fd
);
359 v
->input_buffer
= mfree(v
->input_buffer
);
360 v
->output_buffer
= mfree(v
->output_buffer
);
362 v
->current
= json_variant_unref(v
->current
);
363 v
->reply
= json_variant_unref(v
->reply
);
365 v
->event
= sd_event_unref(v
->event
);
368 static Varlink
* varlink_destroy(Varlink
*v
) {
372 /* If this is called the server object must already been unreffed here. Why that? because when we
373 * linked up the varlink connection with the server object we took one ref in each direction */
378 free(v
->description
);
382 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink
, varlink
, varlink_destroy
);
384 static int varlink_test_disconnect(Varlink
*v
) {
387 /* Tests whether we the the connection has been terminated. We are careful to not stop processing it
388 * prematurely, since we want to handle half-open connections as well as possible and want to flush
389 * out and read data before we close down if we can. */
391 /* Already disconnected? */
392 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
395 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
399 /* Still something to write and we can write? Stay around */
400 if (v
->output_buffer_size
> 0 && !v
->write_disconnected
)
403 /* Both sides gone already? Then there's no need to stick around */
404 if (v
->read_disconnected
&& v
->write_disconnected
)
407 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
408 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) && v
->read_disconnected
)
411 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
412 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
413 * being down if we never wrote anything. */
414 if (IN_SET(v
->state
, VARLINK_IDLE_CLIENT
) && (v
->write_disconnected
|| v
->got_pollhup
))
420 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
424 static int varlink_write(Varlink
*v
) {
429 if (!VARLINK_STATE_IS_ALIVE(v
->state
))
431 if (v
->connecting
) /* Writing while we are still wait for a non-blocking connect() to complete will
432 * result in ENOTCONN, hence exit early here */
434 if (v
->output_buffer_size
== 0)
436 if (v
->write_disconnected
)
441 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
442 * with non-socket IO, hence fall back automatically */
443 if (!v
->prefer_read_write
) {
444 n
= send(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
, MSG_DONTWAIT
|MSG_NOSIGNAL
);
445 if (n
< 0 && errno
== ENOTSOCK
)
446 v
->prefer_read_write
= true;
448 if (v
->prefer_read_write
)
449 n
= write(v
->fd
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
);
454 if (ERRNO_IS_DISCONNECT(errno
)) {
455 /* If we get informed about a disconnect on write, then let's remember that, but not
456 * act on it just yet. Let's wait for read() to report the issue first. */
457 v
->write_disconnected
= true;
464 v
->output_buffer_size
-= n
;
466 if (v
->output_buffer_size
== 0)
467 v
->output_buffer_index
= 0;
469 v
->output_buffer_index
+= n
;
471 v
->timestamp
= now(CLOCK_MONOTONIC
);
475 static int varlink_read(Varlink
*v
) {
481 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
))
483 if (v
->connecting
) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
487 if (v
->input_buffer_unscanned
> 0)
489 if (v
->read_disconnected
)
492 if (v
->input_buffer_size
>= VARLINK_BUFFER_MAX
)
497 if (v
->input_buffer_allocated
<= v
->input_buffer_index
+ v
->input_buffer_size
) {
500 add
= MIN(VARLINK_BUFFER_MAX
- v
->input_buffer_size
, VARLINK_READ_SIZE
);
502 if (v
->input_buffer_index
== 0) {
504 if (!GREEDY_REALLOC(v
->input_buffer
, v
->input_buffer_allocated
, v
->input_buffer_size
+ add
))
510 b
= new(char, v
->input_buffer_size
+ add
);
514 memcpy(b
, v
->input_buffer
+ v
->input_buffer_index
, v
->input_buffer_size
);
516 free_and_replace(v
->input_buffer
, b
);
518 v
->input_buffer_allocated
= v
->input_buffer_size
+ add
;
519 v
->input_buffer_index
= 0;
523 rs
= v
->input_buffer_allocated
- (v
->input_buffer_index
+ v
->input_buffer_size
);
525 if (!v
->prefer_read_write
) {
526 n
= recv(v
->fd
, v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
, rs
, MSG_DONTWAIT
);
527 if (n
< 0 && errno
== ENOTSOCK
)
528 v
->prefer_read_write
= true;
530 if (v
->prefer_read_write
)
531 n
= read(v
->fd
, v
->input_buffer
+ v
->input_buffer_index
+ v
->input_buffer_size
, rs
);
536 if (ERRNO_IS_DISCONNECT(errno
)) {
537 v
->read_disconnected
= true;
543 if (n
== 0) { /* EOF */
544 v
->read_disconnected
= true;
548 v
->input_buffer_size
+= n
;
549 v
->input_buffer_unscanned
+= n
;
554 static int varlink_parse_message(Varlink
*v
) {
555 const char *e
, *begin
;
563 if (v
->input_buffer_unscanned
<= 0)
566 assert(v
->input_buffer_unscanned
<= v
->input_buffer_size
);
567 assert(v
->input_buffer_index
+ v
->input_buffer_size
<= v
->input_buffer_allocated
);
569 begin
= v
->input_buffer
+ v
->input_buffer_index
;
571 e
= memchr(begin
+ v
->input_buffer_size
- v
->input_buffer_unscanned
, 0, v
->input_buffer_unscanned
);
573 v
->input_buffer_unscanned
= 0;
579 varlink_log(v
, "New incoming message: %s", begin
);
581 r
= json_parse(begin
, &v
->current
, NULL
, NULL
);
585 v
->input_buffer_size
-= sz
;
587 if (v
->input_buffer_size
== 0)
588 v
->input_buffer_index
= 0;
590 v
->input_buffer_index
+= sz
;
592 v
->input_buffer_unscanned
= v
->input_buffer_size
;
596 static int varlink_test_timeout(Varlink
*v
) {
599 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
))
601 if (v
->timeout
== USEC_INFINITY
)
604 if (now(CLOCK_MONOTONIC
) < usec_add(v
->timestamp
, v
->timeout
))
607 varlink_set_state(v
, VARLINK_PENDING_TIMEOUT
);
612 static int varlink_dispatch_local_error(Varlink
*v
, const char *error
) {
618 if (!v
->reply_callback
)
621 r
= v
->reply_callback(v
, NULL
, error
, VARLINK_REPLY_ERROR
|VARLINK_REPLY_LOCAL
, v
->userdata
);
623 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
628 static int varlink_dispatch_timeout(Varlink
*v
) {
631 if (v
->state
!= VARLINK_PENDING_TIMEOUT
)
634 varlink_set_state(v
, VARLINK_PROCESSING_TIMEOUT
);
635 varlink_dispatch_local_error(v
, VARLINK_ERROR_TIMEOUT
);
641 static int varlink_dispatch_disconnect(Varlink
*v
) {
644 if (v
->state
!= VARLINK_PENDING_DISCONNECT
)
647 varlink_set_state(v
, VARLINK_PROCESSING_DISCONNECT
);
648 varlink_dispatch_local_error(v
, VARLINK_ERROR_DISCONNECTED
);
654 static int varlink_sanitize_parameters(JsonVariant
**v
) {
657 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
659 return json_variant_new_object(v
, NULL
, 0);
660 else if (!json_variant_is_object(*v
))
666 static int varlink_dispatch_reply(Varlink
*v
) {
667 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
668 VarlinkReplyFlags flags
= 0;
669 const char *error
= NULL
;
676 if (!IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
))
681 assert(v
->n_pending
> 0);
683 if (!json_variant_is_object(v
->current
))
686 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
688 if (streq(k
, "error")) {
691 if (!json_variant_is_string(e
))
694 error
= json_variant_string(e
);
695 flags
|= VARLINK_REPLY_ERROR
;
697 } else if (streq(k
, "parameters")) {
700 if (!json_variant_is_object(e
))
703 parameters
= json_variant_ref(e
);
705 } else if (streq(k
, "continues")) {
706 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
709 if (!json_variant_is_boolean(e
))
712 if (json_variant_boolean(e
))
713 flags
|= VARLINK_REPLY_CONTINUES
;
718 if (error
&& FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
721 r
= varlink_sanitize_parameters(¶meters
);
725 if (v
->state
== VARLINK_AWAITING_REPLY
) {
726 varlink_set_state(v
, VARLINK_PROCESSING_REPLY
);
728 if (v
->reply_callback
) {
729 r
= v
->reply_callback(v
, parameters
, error
, flags
, v
->userdata
);
731 log_debug_errno(r
, "Reply callback returned error, ignoring: %m");
734 v
->current
= json_variant_unref(v
->current
);
736 if (v
->state
== VARLINK_PROCESSING_REPLY
) {
737 assert(v
->n_pending
> 0);
740 varlink_set_state(v
, v
->n_pending
== 0 ? VARLINK_IDLE_CLIENT
: VARLINK_AWAITING_REPLY
);
743 assert(v
->state
== VARLINK_CALLING
);
745 if (FLAGS_SET(flags
, VARLINK_REPLY_CONTINUES
))
748 varlink_set_state(v
, VARLINK_CALLED
);
754 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
755 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
761 static int varlink_dispatch_method(Varlink
*v
) {
762 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
763 VarlinkMethodFlags flags
= 0;
764 const char *method
= NULL
, *error
;
766 VarlinkMethod callback
;
772 if (v
->state
!= VARLINK_IDLE_SERVER
)
777 if (!json_variant_is_object(v
->current
))
780 JSON_VARIANT_OBJECT_FOREACH(k
, e
, v
->current
) {
782 if (streq(k
, "method")) {
785 if (!json_variant_is_string(e
))
788 method
= json_variant_string(e
);
790 } else if (streq(k
, "parameters")) {
793 if (!json_variant_is_object(e
))
796 parameters
= json_variant_ref(e
);
798 } else if (streq(k
, "oneway")) {
800 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
803 if (!json_variant_is_boolean(e
))
806 if (json_variant_boolean(e
))
807 flags
|= VARLINK_METHOD_ONEWAY
;
809 } else if (streq(k
, "more")) {
811 if ((flags
& (VARLINK_METHOD_ONEWAY
|VARLINK_METHOD_MORE
)) != 0)
814 if (!json_variant_is_boolean(e
))
817 if (json_variant_boolean(e
))
818 flags
|= VARLINK_METHOD_MORE
;
827 r
= varlink_sanitize_parameters(¶meters
);
831 varlink_set_state(v
, (flags
& VARLINK_METHOD_MORE
) ? VARLINK_PROCESSING_METHOD_MORE
:
832 (flags
& VARLINK_METHOD_ONEWAY
) ? VARLINK_PROCESSING_METHOD_ONEWAY
:
833 VARLINK_PROCESSING_METHOD
);
837 if (STR_IN_SET(method
, "org.varlink.service.GetInfo", "org.varlink.service.GetInterface")) {
838 /* For now, we don't implement a single of varlink's own methods */
840 error
= VARLINK_ERROR_METHOD_NOT_IMPLEMENTED
;
841 } else if (startswith(method
, "org.varlink.service.")) {
843 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
845 callback
= hashmap_get(v
->server
->methods
, method
);
846 error
= VARLINK_ERROR_METHOD_NOT_FOUND
;
850 r
= callback(v
, parameters
, flags
, v
->userdata
);
852 log_debug_errno(r
, "Callback for %s returned error: %m", method
);
854 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
855 if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
856 r
= varlink_errorb(v
, VARLINK_ERROR_SYSTEM
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(-r
))));
861 } else if (!FLAGS_SET(flags
, VARLINK_METHOD_ONEWAY
)) {
864 r
= varlink_errorb(v
, error
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
))));
871 case VARLINK_PROCESSED_METHOD
: /* Method call is fully processed */
872 case VARLINK_PROCESSING_METHOD_ONEWAY
: /* ditto */
873 v
->current
= json_variant_unref(v
->current
);
874 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
877 case VARLINK_PROCESSING_METHOD
: /* Method call wasn't replied to, will be replied to later */
878 varlink_set_state(v
, VARLINK_PENDING_METHOD
);
881 case VARLINK_PROCESSED_METHOD_MORE
: /* One reply for a "more" message was sent, more to come */
882 case VARLINK_PROCESSING_METHOD_MORE
: /* No reply for a "more" message was sent, more to come */
883 varlink_set_state(v
, VARLINK_PENDING_METHOD_MORE
);
887 assert_not_reached("Unexpected state");
897 varlink_set_state(v
, VARLINK_PROCESSING_FAILURE
);
898 varlink_dispatch_local_error(v
, VARLINK_ERROR_PROTOCOL
);
904 int varlink_process(Varlink
*v
) {
907 assert_return(v
, -EINVAL
);
909 if (v
->state
== VARLINK_DISCONNECTED
)
914 r
= varlink_write(v
);
918 r
= varlink_dispatch_reply(v
);
922 r
= varlink_dispatch_method(v
);
926 r
= varlink_parse_message(v
);
934 r
= varlink_test_disconnect(v
);
938 r
= varlink_dispatch_disconnect(v
);
942 r
= varlink_test_timeout(v
);
946 r
= varlink_dispatch_timeout(v
);
951 if (r
>= 0 && v
->defer_event_source
) {
954 /* If we did some processing, make sure we are called again soon */
955 q
= sd_event_source_set_enabled(v
->defer_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
961 if (VARLINK_STATE_IS_ALIVE(v
->state
))
962 /* Initiate disconnection */
963 varlink_set_state(v
, VARLINK_PENDING_DISCONNECT
);
965 /* We failed while disconnecting, in that case close right away */
973 static void handle_revents(Varlink
*v
, int revents
) {
977 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
978 * to complete on, we know we are ready. We don't read the connection error here though,
979 * we'll get the error on the next read() or write(). */
980 if ((revents
& (POLLOUT
|POLLHUP
)) == 0)
983 varlink_log(v
, "Anynchronous connection completed.");
984 v
->connecting
= false;
986 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
987 * what we can. However, we do care about POLLHUP to detect connection termination even if we
988 * momentarily don't want to read nor write anything. */
990 if (!FLAGS_SET(revents
, POLLHUP
))
993 varlink_log(v
, "Got POLLHUP from socket.");
994 v
->got_pollhup
= true;
998 int varlink_wait(Varlink
*v
, usec_t timeout
) {
1004 assert_return(v
, -EINVAL
);
1005 assert_return(!v
->server
, -ENOTTY
);
1007 if (v
->state
== VARLINK_DISCONNECTED
)
1010 r
= varlink_get_timeout(v
, &t
);
1013 if (t
!= USEC_INFINITY
) {
1016 n
= now(CLOCK_MONOTONIC
);
1020 t
= usec_sub_unsigned(t
, n
);
1023 if (timeout
!= USEC_INFINITY
&&
1024 (t
== USEC_INFINITY
|| timeout
< t
))
1027 fd
= varlink_get_fd(v
);
1031 events
= varlink_get_events(v
);
1035 pfd
= (struct pollfd
) {
1041 t
== USEC_INFINITY
? NULL
: timespec_store(&ts
, t
),
1046 handle_revents(v
, pfd
.revents
);
1048 return r
> 0 ? 1 : 0;
1051 int varlink_get_fd(Varlink
*v
) {
1053 assert_return(v
, -EINVAL
);
1055 if (v
->state
== VARLINK_DISCONNECTED
)
1063 int varlink_get_events(Varlink
*v
) {
1066 assert_return(v
, -EINVAL
);
1068 if (v
->state
== VARLINK_DISCONNECTED
)
1071 if (v
->connecting
) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1072 * tells us that the connection is now complete. Before that we should neither
1073 * write() or read() from the fd. */
1076 if (!v
->read_disconnected
&&
1077 IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
, VARLINK_IDLE_SERVER
) &&
1079 v
->input_buffer_unscanned
<= 0)
1082 if (!v
->write_disconnected
&&
1083 v
->output_buffer_size
> 0)
1089 int varlink_get_timeout(Varlink
*v
, usec_t
*ret
) {
1090 assert_return(v
, -EINVAL
);
1092 if (v
->state
== VARLINK_DISCONNECTED
)
1095 if (IN_SET(v
->state
, VARLINK_AWAITING_REPLY
, VARLINK_CALLING
) &&
1096 v
->timeout
!= USEC_INFINITY
) {
1098 *ret
= usec_add(v
->timestamp
, v
->timeout
);
1102 *ret
= USEC_INFINITY
;
1107 int varlink_flush(Varlink
*v
) {
1110 assert_return(v
, -EINVAL
);
1112 if (v
->state
== VARLINK_DISCONNECTED
)
1118 if (v
->output_buffer_size
== 0)
1120 if (v
->write_disconnected
)
1123 r
= varlink_write(v
);
1131 pfd
= (struct pollfd
) {
1136 if (poll(&pfd
, 1, -1) < 0)
1139 handle_revents(v
, pfd
.revents
);
1145 static void varlink_detach_server(Varlink
*v
) {
1151 if (v
->server
->by_uid
&&
1152 v
->ucred_acquired
&&
1153 uid_is_valid(v
->ucred
.uid
)) {
1156 c
= PTR_TO_UINT(hashmap_get(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
)));
1160 (void) hashmap_remove(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
));
1162 (void) hashmap_replace(v
->server
->by_uid
, UID_TO_PTR(v
->ucred
.uid
), UINT_TO_PTR(c
- 1));
1165 assert(v
->server
->n_connections
> 0);
1166 v
->server
->n_connections
--;
1168 /* If this is a connection associated to a server, then let's disconnect the server and the
1169 * connection from each other. This drops the dangling reference that connect_callback() set up. */
1170 v
->server
= varlink_server_unref(v
->server
);
1174 int varlink_close(Varlink
*v
) {
1176 assert_return(v
, -EINVAL
);
1178 if (v
->state
== VARLINK_DISCONNECTED
)
1181 varlink_set_state(v
, VARLINK_DISCONNECTED
);
1183 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1184 * which would destroy us before we can call varlink_clear() */
1186 varlink_detach_server(v
);
1193 Varlink
* varlink_flush_close_unref(Varlink
*v
) {
1198 (void) varlink_flush(v
);
1199 (void) varlink_close(v
);
1201 return varlink_unref(v
);
1204 static int varlink_enqueue_json(Varlink
*v
, JsonVariant
*m
) {
1205 _cleanup_free_
char *text
= NULL
;
1211 r
= json_variant_format(m
, 0, &text
);
1214 assert(text
[r
] == '\0');
1216 if (v
->output_buffer_size
+ r
+ 1 > VARLINK_BUFFER_MAX
)
1219 varlink_log(v
, "Sending message: %s", text
);
1221 if (v
->output_buffer_size
== 0) {
1223 free_and_replace(v
->output_buffer
, text
);
1225 v
->output_buffer_size
= v
->output_buffer_allocated
= r
+ 1;
1226 v
->output_buffer_index
= 0;
1228 } else if (v
->output_buffer_index
== 0) {
1230 if (!GREEDY_REALLOC(v
->output_buffer
, v
->output_buffer_allocated
, v
->output_buffer_size
+ r
+ 1))
1233 memcpy(v
->output_buffer
+ v
->output_buffer_size
, text
, r
+ 1);
1234 v
->output_buffer_size
+= r
+ 1;
1238 const size_t new_size
= v
->output_buffer_size
+ r
+ 1;
1240 n
= new(char, new_size
);
1244 memcpy(mempcpy(n
, v
->output_buffer
+ v
->output_buffer_index
, v
->output_buffer_size
), text
, r
+ 1);
1246 free_and_replace(v
->output_buffer
, n
);
1247 v
->output_buffer_allocated
= v
->output_buffer_size
= new_size
;
1248 v
->output_buffer_index
= 0;
1254 int varlink_send(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1255 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1258 assert_return(v
, -EINVAL
);
1259 assert_return(method
, -EINVAL
);
1261 if (v
->state
== VARLINK_DISCONNECTED
)
1263 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1266 r
= varlink_sanitize_parameters(¶meters
);
1270 r
= json_build(&m
, JSON_BUILD_OBJECT(
1271 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1272 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1273 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1277 r
= varlink_enqueue_json(v
, m
);
1281 /* No state change here, this is one-way only after all */
1282 v
->timestamp
= now(CLOCK_MONOTONIC
);
1286 int varlink_sendb(Varlink
*v
, const char *method
, ...) {
1287 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1291 assert_return(v
, -EINVAL
);
1293 va_start(ap
, method
);
1294 r
= json_buildv(¶meters
, ap
);
1300 return varlink_send(v
, method
, parameters
);
1303 int varlink_invoke(Varlink
*v
, const char *method
, JsonVariant
*parameters
) {
1304 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1307 assert_return(v
, -EINVAL
);
1308 assert_return(method
, -EINVAL
);
1310 if (v
->state
== VARLINK_DISCONNECTED
)
1312 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
, VARLINK_AWAITING_REPLY
))
1315 r
= varlink_sanitize_parameters(¶meters
);
1319 r
= json_build(&m
, JSON_BUILD_OBJECT(
1320 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1321 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1325 r
= varlink_enqueue_json(v
, m
);
1329 varlink_set_state(v
, VARLINK_AWAITING_REPLY
);
1331 v
->timestamp
= now(CLOCK_MONOTONIC
);
1336 int varlink_invokeb(Varlink
*v
, const char *method
, ...) {
1337 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1341 assert_return(v
, -EINVAL
);
1343 va_start(ap
, method
);
1344 r
= json_buildv(¶meters
, ap
);
1350 return varlink_invoke(v
, method
, parameters
);
1356 JsonVariant
*parameters
,
1357 JsonVariant
**ret_parameters
,
1358 const char **ret_error_id
,
1359 VarlinkReplyFlags
*ret_flags
) {
1361 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1364 assert_return(v
, -EINVAL
);
1365 assert_return(method
, -EINVAL
);
1367 if (v
->state
== VARLINK_DISCONNECTED
)
1369 if (!IN_SET(v
->state
, VARLINK_IDLE_CLIENT
))
1372 assert(v
->n_pending
== 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1374 r
= varlink_sanitize_parameters(¶meters
);
1378 r
= json_build(&m
, JSON_BUILD_OBJECT(
1379 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method
)),
1380 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1384 r
= varlink_enqueue_json(v
, m
);
1388 varlink_set_state(v
, VARLINK_CALLING
);
1390 v
->timestamp
= now(CLOCK_MONOTONIC
);
1392 while (v
->state
== VARLINK_CALLING
) {
1394 r
= varlink_process(v
);
1400 r
= varlink_wait(v
, USEC_INFINITY
);
1407 case VARLINK_CALLED
:
1410 json_variant_unref(v
->reply
);
1411 v
->reply
= TAKE_PTR(v
->current
);
1413 varlink_set_state(v
, VARLINK_IDLE_CLIENT
);
1414 assert(v
->n_pending
== 1);
1418 *ret_parameters
= json_variant_by_key(v
->reply
, "parameters");
1420 *ret_error_id
= json_variant_string(json_variant_by_key(v
->reply
, "error"));
1426 case VARLINK_PENDING_DISCONNECT
:
1427 case VARLINK_DISCONNECTED
:
1430 case VARLINK_PENDING_TIMEOUT
:
1434 assert_not_reached("Unexpected state after method call.");
1441 JsonVariant
**ret_parameters
,
1442 const char **ret_error_id
,
1443 VarlinkReplyFlags
*ret_flags
, ...) {
1445 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1449 assert_return(v
, -EINVAL
);
1451 va_start(ap
, ret_flags
);
1452 r
= json_buildv(¶meters
, ap
);
1458 return varlink_call(v
, method
, parameters
, ret_parameters
, ret_error_id
, ret_flags
);
1461 int varlink_reply(Varlink
*v
, JsonVariant
*parameters
) {
1462 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1465 assert_return(v
, -EINVAL
);
1467 if (v
->state
== VARLINK_DISCONNECTED
)
1469 if (!IN_SET(v
->state
,
1470 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1471 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1474 r
= varlink_sanitize_parameters(¶meters
);
1478 r
= json_build(&m
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1482 r
= varlink_enqueue_json(v
, m
);
1486 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1487 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1488 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1489 * process further messages. */
1490 v
->current
= json_variant_unref(v
->current
);
1491 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1493 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1494 * means we should it handle the rest of the state engine. */
1495 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1500 int varlink_replyb(Varlink
*v
, ...) {
1501 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1505 assert_return(v
, -EINVAL
);
1508 r
= json_buildv(¶meters
, ap
);
1514 return varlink_reply(v
, parameters
);
1517 int varlink_error(Varlink
*v
, const char *error_id
, JsonVariant
*parameters
) {
1518 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1521 assert_return(v
, -EINVAL
);
1522 assert_return(error_id
, -EINVAL
);
1524 if (v
->state
== VARLINK_DISCONNECTED
)
1526 if (!IN_SET(v
->state
,
1527 VARLINK_PROCESSING_METHOD
, VARLINK_PROCESSING_METHOD_MORE
,
1528 VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
))
1531 r
= varlink_sanitize_parameters(¶meters
);
1535 r
= json_build(&m
, JSON_BUILD_OBJECT(
1536 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id
)),
1537 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
))));
1541 r
= varlink_enqueue_json(v
, m
);
1545 if (IN_SET(v
->state
, VARLINK_PENDING_METHOD
, VARLINK_PENDING_METHOD_MORE
)) {
1546 v
->current
= json_variant_unref(v
->current
);
1547 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
1549 varlink_set_state(v
, VARLINK_PROCESSED_METHOD
);
1554 int varlink_errorb(Varlink
*v
, const char *error_id
, ...) {
1555 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1559 assert_return(v
, -EINVAL
);
1560 assert_return(error_id
, -EINVAL
);
1562 va_start(ap
, error_id
);
1563 r
= json_buildv(¶meters
, ap
);
1569 return varlink_error(v
, error_id
, parameters
);
1572 int varlink_error_invalid_parameter(Varlink
*v
, JsonVariant
*parameters
) {
1574 assert_return(v
, -EINVAL
);
1575 assert_return(parameters
, -EINVAL
);
1577 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1578 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1579 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1580 * don't expect any arguments. */
1582 if (json_variant_is_string(parameters
))
1583 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
, parameters
);
1585 if (json_variant_is_object(parameters
) &&
1586 json_variant_elements(parameters
) > 0)
1587 return varlink_error(v
, VARLINK_ERROR_INVALID_PARAMETER
,
1588 json_variant_by_index(parameters
, 0));
1593 int varlink_notify(Varlink
*v
, JsonVariant
*parameters
) {
1594 _cleanup_(json_variant_unrefp
) JsonVariant
*m
= NULL
;
1597 assert_return(v
, -EINVAL
);
1599 if (v
->state
== VARLINK_DISCONNECTED
)
1601 if (!IN_SET(v
->state
, VARLINK_PROCESSING_METHOD_MORE
, VARLINK_PENDING_METHOD_MORE
))
1604 r
= varlink_sanitize_parameters(¶meters
);
1608 r
= json_build(&m
, JSON_BUILD_OBJECT(
1609 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters
)),
1610 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
1614 r
= varlink_enqueue_json(v
, m
);
1618 /* No state change, as more is coming */
1622 int varlink_notifyb(Varlink
*v
, ...) {
1623 _cleanup_(json_variant_unrefp
) JsonVariant
*parameters
= NULL
;
1627 assert_return(v
, -EINVAL
);
1630 r
= json_buildv(¶meters
, ap
);
1636 return varlink_notify(v
, parameters
);
1639 int varlink_bind_reply(Varlink
*v
, VarlinkReply callback
) {
1640 assert_return(v
, -EINVAL
);
1642 if (callback
&& v
->reply_callback
&& callback
!= v
->reply_callback
)
1645 v
->reply_callback
= callback
;
1650 void* varlink_set_userdata(Varlink
*v
, void *userdata
) {
1653 assert_return(v
, NULL
);
1656 v
->userdata
= userdata
;
1661 void* varlink_get_userdata(Varlink
*v
) {
1662 assert_return(v
, NULL
);
1667 static int varlink_acquire_ucred(Varlink
*v
) {
1672 if (v
->ucred_acquired
)
1675 r
= getpeercred(v
->fd
, &v
->ucred
);
1679 v
->ucred_acquired
= true;
1683 int varlink_get_peer_uid(Varlink
*v
, uid_t
*ret
) {
1686 assert_return(v
, -EINVAL
);
1687 assert_return(ret
, -EINVAL
);
1689 r
= varlink_acquire_ucred(v
);
1693 if (!uid_is_valid(v
->ucred
.uid
))
1696 *ret
= v
->ucred
.uid
;
1700 int varlink_get_peer_pid(Varlink
*v
, pid_t
*ret
) {
1703 assert_return(v
, -EINVAL
);
1704 assert_return(ret
, -EINVAL
);
1706 r
= varlink_acquire_ucred(v
);
1710 if (!pid_is_valid(v
->ucred
.pid
))
1713 *ret
= v
->ucred
.pid
;
1717 int varlink_set_relative_timeout(Varlink
*v
, usec_t timeout
) {
1718 assert_return(v
, -EINVAL
);
1719 assert_return(timeout
> 0, -EINVAL
);
1721 v
->timeout
= timeout
;
1725 VarlinkServer
*varlink_get_server(Varlink
*v
) {
1726 assert_return(v
, NULL
);
1731 int varlink_set_description(Varlink
*v
, const char *description
) {
1732 assert_return(v
, -EINVAL
);
1734 return free_and_strdup(&v
->description
, description
);
1737 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1738 Varlink
*v
= userdata
;
1743 handle_revents(v
, revents
);
1744 (void) varlink_process(v
);
1749 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
1750 Varlink
*v
= userdata
;
1755 (void) varlink_process(v
);
1759 static int defer_callback(sd_event_source
*s
, void *userdata
) {
1760 Varlink
*v
= userdata
;
1765 (void) varlink_process(v
);
1769 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
1770 Varlink
*v
= userdata
;
1777 e
= varlink_get_events(v
);
1781 r
= sd_event_source_set_io_events(v
->io_event_source
, e
);
1785 r
= varlink_get_timeout(v
, &until
);
1789 r
= sd_event_source_set_time(v
->time_event_source
, until
);
1794 r
= sd_event_source_set_enabled(v
->time_event_source
, r
> 0 ? SD_EVENT_ON
: SD_EVENT_OFF
);
1801 static int quit_callback(sd_event_source
*event
, void *userdata
) {
1802 Varlink
*v
= userdata
;
1813 int varlink_attach_event(Varlink
*v
, sd_event
*e
, int64_t priority
) {
1816 assert_return(v
, -EINVAL
);
1817 assert_return(!v
->event
, -EBUSY
);
1820 v
->event
= sd_event_ref(e
);
1822 r
= sd_event_default(&v
->event
);
1827 r
= sd_event_add_time(v
->event
, &v
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, v
);
1831 r
= sd_event_source_set_priority(v
->time_event_source
, priority
);
1835 (void) sd_event_source_set_description(v
->time_event_source
, "varlink-time");
1837 r
= sd_event_add_exit(v
->event
, &v
->quit_event_source
, quit_callback
, v
);
1841 r
= sd_event_source_set_priority(v
->quit_event_source
, priority
);
1845 (void) sd_event_source_set_description(v
->quit_event_source
, "varlink-quit");
1847 r
= sd_event_add_io(v
->event
, &v
->io_event_source
, v
->fd
, 0, io_callback
, v
);
1851 r
= sd_event_source_set_prepare(v
->io_event_source
, prepare_callback
);
1855 r
= sd_event_source_set_priority(v
->io_event_source
, priority
);
1859 (void) sd_event_source_set_description(v
->io_event_source
, "varlink-io");
1861 r
= sd_event_add_defer(v
->event
, &v
->defer_event_source
, defer_callback
, v
);
1865 r
= sd_event_source_set_priority(v
->defer_event_source
, priority
);
1869 (void) sd_event_source_set_description(v
->defer_event_source
, "varlink-defer");
1874 varlink_detach_event(v
);
1879 void varlink_detach_event(Varlink
*v
) {
1883 varlink_detach_event_sources(v
);
1885 v
->event
= sd_event_unref(v
->event
);
1888 sd_event
*varlink_get_event(Varlink
*v
) {
1889 assert_return(v
, NULL
);
1894 int varlink_server_new(VarlinkServer
**ret
, VarlinkServerFlags flags
) {
1897 assert_return(ret
, -EINVAL
);
1898 assert_return((flags
& ~_VARLINK_SERVER_FLAGS_ALL
) == 0, -EINVAL
);
1900 s
= new(VarlinkServer
, 1);
1904 *s
= (VarlinkServer
) {
1907 .connections_max
= varlink_server_connections_max(NULL
),
1908 .connections_per_uid_max
= varlink_server_connections_per_uid_max(NULL
),
1915 static VarlinkServer
* varlink_server_destroy(VarlinkServer
*s
) {
1921 varlink_server_shutdown(s
);
1923 while ((m
= hashmap_steal_first_key(s
->methods
)))
1926 hashmap_free(s
->methods
);
1927 hashmap_free(s
->by_uid
);
1929 sd_event_unref(s
->event
);
1931 free(s
->description
);
1936 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer
, varlink_server
, varlink_server_destroy
);
1938 static int validate_connection(VarlinkServer
*server
, const struct ucred
*ucred
) {
1944 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ROOT_ONLY
))
1945 allowed
= ucred
->uid
== 0;
1947 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_MYSELF_ONLY
))
1948 allowed
= allowed
> 0 || ucred
->uid
== getuid();
1950 if (allowed
== 0) { /* Allow access when it is explicitly allowed or when neither
1951 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
1952 varlink_server_log(server
, "Unprivileged client attempted connection, refusing.");
1956 if (server
->n_connections
>= server
->connections_max
) {
1957 varlink_server_log(server
, "Connection limit of %u reached, refusing.", server
->connections_max
);
1961 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
1964 if (!uid_is_valid(ucred
->uid
)) {
1965 varlink_server_log(server
, "Client with invalid UID attempted connection, refusing.");
1969 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
1970 if (c
>= server
->connections_per_uid_max
) {
1971 varlink_server_log(server
, "Per-UID connection limit of %u reached, refusing.",
1972 server
->connections_per_uid_max
);
1980 static int count_connection(VarlinkServer
*server
, struct ucred
*ucred
) {
1987 server
->n_connections
++;
1989 if (FLAGS_SET(server
->flags
, VARLINK_SERVER_ACCOUNT_UID
)) {
1990 r
= hashmap_ensure_allocated(&server
->by_uid
, NULL
);
1992 return log_debug_errno(r
, "Failed to allocate UID hash table: %m");
1994 c
= PTR_TO_UINT(hashmap_get(server
->by_uid
, UID_TO_PTR(ucred
->uid
)));
1996 varlink_server_log(server
, "Connections of user " UID_FMT
": %u (of %u max)",
1997 ucred
->uid
, c
, server
->connections_per_uid_max
);
1999 r
= hashmap_replace(server
->by_uid
, UID_TO_PTR(ucred
->uid
), UINT_TO_PTR(c
+ 1));
2001 return log_debug_errno(r
, "Failed to increment counter in UID hash table: %m");
2007 int varlink_server_add_connection(VarlinkServer
*server
, int fd
, Varlink
**ret
) {
2008 _cleanup_(varlink_unrefp
) Varlink
*v
= NULL
;
2009 bool ucred_acquired
;
2013 assert_return(server
, -EINVAL
);
2014 assert_return(fd
>= 0, -EBADF
);
2016 if ((server
->flags
& (VARLINK_SERVER_ROOT_ONLY
|VARLINK_SERVER_ACCOUNT_UID
)) != 0) {
2017 r
= getpeercred(fd
, &ucred
);
2019 return varlink_server_log_errno(server
, r
, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2021 ucred_acquired
= true;
2023 r
= validate_connection(server
, &ucred
);
2029 ucred_acquired
= false;
2031 r
= varlink_new(&v
);
2033 return varlink_server_log_errno(server
, r
, "Failed to allocate connection object: %m");
2035 r
= count_connection(server
, &ucred
);
2040 v
->userdata
= server
->userdata
;
2041 if (ucred_acquired
) {
2043 v
->ucred_acquired
= true;
2046 (void) asprintf(&v
->description
, "%s-%i", server
->description
?: "varlink", v
->fd
);
2048 /* Link up the server and the connection, and take reference in both directions. Note that the
2049 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2050 * which happens in varlink_close(), including in the event loop quit callback. */
2051 v
->server
= varlink_server_ref(server
);
2054 varlink_set_state(v
, VARLINK_IDLE_SERVER
);
2056 r
= varlink_attach_event(v
, server
->event
, server
->event_priority
);
2058 varlink_log_errno(v
, r
, "Failed to attach new connection: %m");
2059 v
->fd
= -1; /* take the fd out of the connection again */
2070 static int connect_callback(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2071 VarlinkServerSocket
*ss
= userdata
;
2072 _cleanup_close_
int cfd
= -1;
2079 varlink_server_log(ss
->server
, "New incoming connection.");
2081 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2083 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
2086 return varlink_server_log_errno(ss
->server
, errno
, "Failed to accept incoming socket: %m");
2089 r
= varlink_server_add_connection(ss
->server
, cfd
, &v
);
2095 if (ss
->server
->connect_callback
) {
2096 r
= ss
->server
->connect_callback(ss
->server
, v
, ss
->server
->userdata
);
2098 varlink_log_errno(v
, r
, "Connection callback returned error, disconnecting client: %m");
2107 int varlink_server_listen_fd(VarlinkServer
*s
, int fd
) {
2108 _cleanup_free_ VarlinkServerSocket
*ss
= NULL
;
2111 assert_return(s
, -EINVAL
);
2112 assert_return(fd
>= 0, -EBADF
);
2114 r
= fd_nonblock(fd
, true);
2118 ss
= new(VarlinkServerSocket
, 1);
2122 *ss
= (VarlinkServerSocket
) {
2128 _cleanup_(sd_event_source_unrefp
) sd_event_source
*es
= NULL
;
2130 r
= sd_event_add_io(s
->event
, &es
, fd
, EPOLLIN
, connect_callback
, ss
);
2134 r
= sd_event_source_set_priority(ss
->event_source
, s
->event_priority
);
2139 LIST_PREPEND(sockets
, s
->sockets
, TAKE_PTR(ss
));
2143 int varlink_server_listen_address(VarlinkServer
*s
, const char *address
, mode_t m
) {
2144 union sockaddr_union sockaddr
;
2145 _cleanup_close_
int fd
= -1;
2148 assert_return(s
, -EINVAL
);
2149 assert_return(address
, -EINVAL
);
2150 assert_return((m
& ~0777) == 0, -EINVAL
);
2152 r
= sockaddr_un_set_path(&sockaddr
.un
, address
);
2156 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2160 (void) sockaddr_un_unlink(&sockaddr
.un
);
2162 RUN_WITH_UMASK(~m
& 0777)
2163 if (bind(fd
, &sockaddr
.sa
, SOCKADDR_UN_LEN(sockaddr
.un
)) < 0)
2166 if (listen(fd
, SOMAXCONN
) < 0)
2169 r
= varlink_server_listen_fd(s
, fd
);
2177 void* varlink_server_set_userdata(VarlinkServer
*s
, void *userdata
) {
2180 assert_return(s
, NULL
);
2183 s
->userdata
= userdata
;
2188 void* varlink_server_get_userdata(VarlinkServer
*s
) {
2189 assert_return(s
, NULL
);
2194 static VarlinkServerSocket
* varlink_server_socket_destroy(VarlinkServerSocket
*ss
) {
2199 LIST_REMOVE(sockets
, ss
->server
->sockets
, ss
);
2201 sd_event_source_disable_unref(ss
->event_source
);
2209 int varlink_server_shutdown(VarlinkServer
*s
) {
2210 assert_return(s
, -EINVAL
);
2213 varlink_server_socket_destroy(s
->sockets
);
2218 int varlink_server_attach_event(VarlinkServer
*s
, sd_event
*e
, int64_t priority
) {
2219 VarlinkServerSocket
*ss
;
2222 assert_return(s
, -EINVAL
);
2223 assert_return(!s
->event
, -EBUSY
);
2226 s
->event
= sd_event_ref(e
);
2228 r
= sd_event_default(&s
->event
);
2233 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
2234 assert(!ss
->event_source
);
2236 r
= sd_event_add_io(s
->event
, &ss
->event_source
, ss
->fd
, EPOLLIN
, connect_callback
, ss
);
2240 r
= sd_event_source_set_priority(ss
->event_source
, priority
);
2245 s
->event_priority
= priority
;
2249 varlink_server_detach_event(s
);
2253 int varlink_server_detach_event(VarlinkServer
*s
) {
2254 VarlinkServerSocket
*ss
;
2256 assert_return(s
, -EINVAL
);
2258 LIST_FOREACH(sockets
, ss
, s
->sockets
) {
2260 if (!ss
->event_source
)
2263 (void) sd_event_source_set_enabled(ss
->event_source
, SD_EVENT_OFF
);
2264 ss
->event_source
= sd_event_source_unref(ss
->event_source
);
2267 sd_event_unref(s
->event
);
2271 sd_event
*varlink_server_get_event(VarlinkServer
*s
) {
2272 assert_return(s
, NULL
);
2277 int varlink_server_bind_method(VarlinkServer
*s
, const char *method
, VarlinkMethod callback
) {
2281 assert_return(s
, -EINVAL
);
2282 assert_return(method
, -EINVAL
);
2283 assert_return(callback
, -EINVAL
);
2285 if (startswith(method
, "org.varlink.service."))
2288 r
= hashmap_ensure_allocated(&s
->methods
, &string_hash_ops
);
2296 r
= hashmap_put(s
->methods
, m
, callback
);
2305 int varlink_server_bind_method_many_internal(VarlinkServer
*s
, ...) {
2309 assert_return(s
, -EINVAL
);
2313 VarlinkMethod callback
;
2316 method
= va_arg(ap
, const char *);
2320 callback
= va_arg(ap
, VarlinkMethod
);
2322 r
= varlink_server_bind_method(s
, method
, callback
);
2331 int varlink_server_bind_connect(VarlinkServer
*s
, VarlinkConnect callback
) {
2332 assert_return(s
, -EINVAL
);
2334 if (callback
&& s
->connect_callback
&& callback
!= s
->connect_callback
)
2337 s
->connect_callback
= callback
;
2341 unsigned varlink_server_connections_max(VarlinkServer
*s
) {
2344 /* If a server is specified, return the setting for that server, otherwise the default value */
2346 return s
->connections_max
;
2348 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
2350 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
2351 if (VARLINK_DEFAULT_CONNECTIONS_MAX
> rl
.rlim_cur
/ 4 * 3)
2352 return rl
.rlim_cur
/ 4 * 3;
2354 return VARLINK_DEFAULT_CONNECTIONS_MAX
;
2357 unsigned varlink_server_connections_per_uid_max(VarlinkServer
*s
) {
2361 return s
->connections_per_uid_max
;
2363 /* Make sure to never use up more than ¾th of available connections for a single user */
2364 m
= varlink_server_connections_max(NULL
);
2365 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
> m
)
2368 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX
;
2371 int varlink_server_set_connections_per_uid_max(VarlinkServer
*s
, unsigned m
) {
2372 assert_return(s
, -EINVAL
);
2373 assert_return(m
> 0, -EINVAL
);
2375 s
->connections_per_uid_max
= m
;
2379 int varlink_server_set_connections_max(VarlinkServer
*s
, unsigned m
) {
2380 assert_return(s
, -EINVAL
);
2381 assert_return(m
> 0, -EINVAL
);
2383 s
->connections_max
= m
;
2387 int varlink_server_set_description(VarlinkServer
*s
, const char *description
) {
2388 assert_return(s
, -EINVAL
);
2390 return free_and_strdup(&s
->description
, description
);