]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/varlink.c
Merge pull request #16338 from keszybz/spelling2
[thirdparty/systemd.git] / src / shared / varlink.c
CommitLineData
d41bd96f
LP
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#include <sys/poll.h>
4
5#include "alloc-util.h"
6#include "errno-util.h"
7#include "fd-util.h"
8#include "hashmap.h"
0f2d351f 9#include "io-util.h"
d41bd96f
LP
10#include "list.h"
11#include "process-util.h"
12#include "set.h"
13#include "socket-util.h"
14#include "string-table.h"
15#include "string-util.h"
16#include "strv.h"
17#include "time-util.h"
18#include "umask-util.h"
19#include "user-util.h"
20#include "varlink.h"
21
22#define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
23#define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
24
25#define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
26#define VARLINK_BUFFER_MAX (16U*1024U*1024U)
27#define VARLINK_READ_SIZE (64U*1024U)
28
29typedef enum VarlinkState {
30 /* Client side states */
31 VARLINK_IDLE_CLIENT,
32 VARLINK_AWAITING_REPLY,
45a6c965 33 VARLINK_AWAITING_REPLY_MORE,
d41bd96f
LP
34 VARLINK_CALLING,
35 VARLINK_CALLED,
36 VARLINK_PROCESSING_REPLY,
37
38 /* Server side states */
39 VARLINK_IDLE_SERVER,
40 VARLINK_PROCESSING_METHOD,
41 VARLINK_PROCESSING_METHOD_MORE,
42 VARLINK_PROCESSING_METHOD_ONEWAY,
43 VARLINK_PROCESSED_METHOD,
d41bd96f
LP
44 VARLINK_PENDING_METHOD,
45 VARLINK_PENDING_METHOD_MORE,
46
47 /* Common states (only during shutdown) */
48 VARLINK_PENDING_DISCONNECT,
49 VARLINK_PENDING_TIMEOUT,
50 VARLINK_PROCESSING_DISCONNECT,
51 VARLINK_PROCESSING_TIMEOUT,
52 VARLINK_PROCESSING_FAILURE,
53 VARLINK_DISCONNECTED,
54
55 _VARLINK_STATE_MAX,
56 _VARLINK_STATE_INVALID = -1
57} VarlinkState;
58
59/* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
60 * is still good for something, and false only when it's dead for good. This means: when we are
61 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
62 * the connection is still good, and we are likely to be able to properly operate on it soon. */
63#define VARLINK_STATE_IS_ALIVE(state) \
64 IN_SET(state, \
65 VARLINK_IDLE_CLIENT, \
66 VARLINK_AWAITING_REPLY, \
45a6c965 67 VARLINK_AWAITING_REPLY_MORE, \
d41bd96f
LP
68 VARLINK_CALLING, \
69 VARLINK_CALLED, \
70 VARLINK_PROCESSING_REPLY, \
71 VARLINK_IDLE_SERVER, \
72 VARLINK_PROCESSING_METHOD, \
73 VARLINK_PROCESSING_METHOD_MORE, \
74 VARLINK_PROCESSING_METHOD_ONEWAY, \
75 VARLINK_PROCESSED_METHOD, \
d41bd96f
LP
76 VARLINK_PENDING_METHOD, \
77 VARLINK_PENDING_METHOD_MORE)
78
79struct Varlink {
80 unsigned n_ref;
81
82 VarlinkServer *server;
83
84 VarlinkState state;
85 bool connecting; /* This boolean indicates whether the socket fd we are operating on is currently
86 * processing an asynchronous connect(). In that state we watch the socket for
87 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
88 * will trigger ENOTCONN. Note that this boolean is kept separate from the
89 * VarlinkState above on purpose: while the connect() is still not complete we
90 * already want to allow queuing of messages and similar. Thus it's nice to keep
91 * these two state concepts separate: the VarlinkState encodes what our own view of
92 * the connection is, i.e. whether we think it's a server, a client, and has
93 * something queued already, while 'connecting' tells us a detail about the
94 * transport used below, that should have no effect on how we otherwise accept and
95 * process operations from the user.
96 *
97 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
98 * connection is good to use, even if it might not be fully connected
99 * yet. connecting=true then informs you that actually we are still connecting, and
100 * the connection is actually not established yet and thus any requests you enqueue
101 * now will still work fine but will be queued only, not sent yet, but that
102 * shouldn't stop you from using the connection, since eventually whatever you queue
103 * *will* be sent.
104 *
105 * Or to say this even differently: 'state' is a high-level ("application layer"
106 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
107 * low, if you so will) state, and while they are not entirely unrelated and
108 * sometimes propagate effects to each other they are only asynchronously connected
109 * at most. */
110 unsigned n_pending;
111
112 int fd;
113
114 char *input_buffer; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
115 size_t input_buffer_allocated;
116 size_t input_buffer_index;
117 size_t input_buffer_size;
118 size_t input_buffer_unscanned;
119
120 char *output_buffer; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
121 size_t output_buffer_allocated;
122 size_t output_buffer_index;
123 size_t output_buffer_size;
124
125 VarlinkReply reply_callback;
126
127 JsonVariant *current;
128 JsonVariant *reply;
129
130 struct ucred ucred;
131 bool ucred_acquired:1;
132
133 bool write_disconnected:1;
134 bool read_disconnected:1;
135 bool prefer_read_write:1;
136 bool got_pollhup:1;
137
138 usec_t timestamp;
139 usec_t timeout;
140
141 void *userdata;
142 char *description;
143
144 sd_event *event;
145 sd_event_source *io_event_source;
146 sd_event_source *time_event_source;
147 sd_event_source *quit_event_source;
148 sd_event_source *defer_event_source;
149};
150
151typedef struct VarlinkServerSocket VarlinkServerSocket;
152
153struct VarlinkServerSocket {
154 VarlinkServer *server;
155
156 int fd;
157 char *address;
158
159 sd_event_source *event_source;
160
161 LIST_FIELDS(VarlinkServerSocket, sockets);
162};
163
164struct VarlinkServer {
165 unsigned n_ref;
166 VarlinkServerFlags flags;
167
168 LIST_HEAD(VarlinkServerSocket, sockets);
169
170 Hashmap *methods;
171 VarlinkConnect connect_callback;
6d4d6002 172 VarlinkDisconnect disconnect_callback;
d41bd96f
LP
173
174 sd_event *event;
175 int64_t event_priority;
176
177 unsigned n_connections;
178 Hashmap *by_uid;
179
180 void *userdata;
181 char *description;
182
183 unsigned connections_max;
184 unsigned connections_per_uid_max;
185};
186
187static const char* const varlink_state_table[_VARLINK_STATE_MAX] = {
188 [VARLINK_IDLE_CLIENT] = "idle-client",
189 [VARLINK_AWAITING_REPLY] = "awaiting-reply",
45a6c965 190 [VARLINK_AWAITING_REPLY_MORE] = "awaiting-reply-more",
d41bd96f
LP
191 [VARLINK_CALLING] = "calling",
192 [VARLINK_CALLED] = "called",
193 [VARLINK_PROCESSING_REPLY] = "processing-reply",
194 [VARLINK_IDLE_SERVER] = "idle-server",
195 [VARLINK_PROCESSING_METHOD] = "processing-method",
196 [VARLINK_PROCESSING_METHOD_MORE] = "processing-method-more",
197 [VARLINK_PROCESSING_METHOD_ONEWAY] = "processing-method-oneway",
198 [VARLINK_PROCESSED_METHOD] = "processed-method",
d41bd96f
LP
199 [VARLINK_PENDING_METHOD] = "pending-method",
200 [VARLINK_PENDING_METHOD_MORE] = "pending-method-more",
201 [VARLINK_PENDING_DISCONNECT] = "pending-disconnect",
202 [VARLINK_PENDING_TIMEOUT] = "pending-timeout",
203 [VARLINK_PROCESSING_DISCONNECT] = "processing-disconnect",
204 [VARLINK_PROCESSING_TIMEOUT] = "processing-timeout",
205 [VARLINK_PROCESSING_FAILURE] = "processing-failure",
206 [VARLINK_DISCONNECTED] = "disconnected",
207};
208
209DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state, VarlinkState);
210
211#define varlink_log_errno(v, error, fmt, ...) \
212 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
213
214#define varlink_log(v, fmt, ...) \
215 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
216
217#define varlink_server_log_errno(s, error, fmt, ...) \
218 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
219
220#define varlink_server_log(s, fmt, ...) \
221 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
222
223static inline const char *varlink_description(Varlink *v) {
224 return strna(v ? v->description : NULL);
225}
226
227static inline const char *varlink_server_description(VarlinkServer *s) {
228 return strna(s ? s->description : NULL);
229}
230
231static void varlink_set_state(Varlink *v, VarlinkState state) {
232 assert(v);
77740b59
ZJS
233 assert(state >= 0 && state < _VARLINK_STATE_MAX);
234
235 if (v->state < 0)
236 varlink_log(v, "varlink: setting state %s",
237 varlink_state_to_string(state));
238 else
239 varlink_log(v, "varlink: changing state %s → %s",
240 varlink_state_to_string(v->state),
241 varlink_state_to_string(state));
d41bd96f
LP
242
243 v->state = state;
244}
245
246static int varlink_new(Varlink **ret) {
247 Varlink *v;
248
249 assert(ret);
250
a48481dc 251 v = new(Varlink, 1);
d41bd96f
LP
252 if (!v)
253 return -ENOMEM;
254
255 *v = (Varlink) {
256 .n_ref = 1,
257 .fd = -1,
258
259 .state = _VARLINK_STATE_INVALID,
260
261 .ucred.uid = UID_INVALID,
262 .ucred.gid = GID_INVALID,
263
264 .timestamp = USEC_INFINITY,
265 .timeout = VARLINK_DEFAULT_TIMEOUT_USEC
266 };
267
268 *ret = v;
269 return 0;
270}
271
272int varlink_connect_address(Varlink **ret, const char *address) {
273 _cleanup_(varlink_unrefp) Varlink *v = NULL;
274 union sockaddr_union sockaddr;
f36a9d59 275 socklen_t sockaddr_len;
d41bd96f
LP
276 int r;
277
278 assert_return(ret, -EINVAL);
279 assert_return(address, -EINVAL);
280
281 r = sockaddr_un_set_path(&sockaddr.un, address);
282 if (r < 0)
283 return r;
f36a9d59 284 sockaddr_len = r;
d41bd96f
LP
285
286 r = varlink_new(&v);
287 if (r < 0)
288 return r;
289
290 v->fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
291 if (v->fd < 0)
292 return -errno;
293
a0c41de2
LP
294 v->fd = fd_move_above_stdio(v->fd);
295
f36a9d59 296 if (connect(v->fd, &sockaddr.sa, sockaddr_len) < 0) {
d41bd96f
LP
297 if (!IN_SET(errno, EAGAIN, EINPROGRESS))
298 return -errno;
299
300 v->connecting = true; /* We are asynchronously connecting, i.e. the connect() is being
301 * processed in the background. As long as that's the case the socket
302 * is in a special state: it's there, we can poll it for EPOLLOUT, but
303 * if we attempt to write() to it before we see EPOLLOUT we'll get
304 * ENOTCONN (and not EAGAIN, like we would for a normal connected
305 * socket that isn't writable at the moment). Since ENOTCONN on write()
306 * hence can mean two different things (i.e. connection not complete
307 * yet vs. already disconnected again), we store as a boolean whether
308 * we are still in connect(). */
309 }
310
311 varlink_set_state(v, VARLINK_IDLE_CLIENT);
312
313 *ret = TAKE_PTR(v);
314 return r;
315}
316
317int varlink_connect_fd(Varlink **ret, int fd) {
318 Varlink *v;
319 int r;
320
321 assert_return(ret, -EINVAL);
322 assert_return(fd >= 0, -EBADF);
323
324 r = fd_nonblock(fd, true);
325 if (r < 0)
326 return r;
327
328 r = varlink_new(&v);
329 if (r < 0)
330 return r;
331
332 v->fd = fd;
333 varlink_set_state(v, VARLINK_IDLE_CLIENT);
334
335 /* Note that if this function is called we assume the passed socket (if it is one) is already
336 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
337 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
338 * until the connection is fully set up. Behaviour here is hence a bit different from
339 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
340 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
341
342 *ret = v;
343 return 0;
344}
345
346static void varlink_detach_event_sources(Varlink *v) {
347 assert(v);
348
1d3fe304 349 v->io_event_source = sd_event_source_disable_unref(v->io_event_source);
1d3fe304 350 v->time_event_source = sd_event_source_disable_unref(v->time_event_source);
1d3fe304 351 v->quit_event_source = sd_event_source_disable_unref(v->quit_event_source);
1d3fe304 352 v->defer_event_source = sd_event_source_disable_unref(v->defer_event_source);
d41bd96f
LP
353}
354
355static void varlink_clear(Varlink *v) {
356 assert(v);
357
358 varlink_detach_event_sources(v);
359
360 v->fd = safe_close(v->fd);
361
362 v->input_buffer = mfree(v->input_buffer);
363 v->output_buffer = mfree(v->output_buffer);
364
365 v->current = json_variant_unref(v->current);
366 v->reply = json_variant_unref(v->reply);
367
368 v->event = sd_event_unref(v->event);
369}
370
371static Varlink* varlink_destroy(Varlink *v) {
372 if (!v)
373 return NULL;
374
375 /* If this is called the server object must already been unreffed here. Why that? because when we
376 * linked up the varlink connection with the server object we took one ref in each direction */
377 assert(!v->server);
378
379 varlink_clear(v);
380
381 free(v->description);
382 return mfree(v);
383}
384
385DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink, varlink, varlink_destroy);
386
387static int varlink_test_disconnect(Varlink *v) {
388 assert(v);
389
37b22b3b 390 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
d41bd96f
LP
391 * prematurely, since we want to handle half-open connections as well as possible and want to flush
392 * out and read data before we close down if we can. */
393
394 /* Already disconnected? */
395 if (!VARLINK_STATE_IS_ALIVE(v->state))
396 return 0;
397
398 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
399 if (v->connecting)
400 return 0;
401
402 /* Still something to write and we can write? Stay around */
403 if (v->output_buffer_size > 0 && !v->write_disconnected)
404 return 0;
405
406 /* Both sides gone already? Then there's no need to stick around */
407 if (v->read_disconnected && v->write_disconnected)
408 goto disconnect;
409
410 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
45a6c965 411 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER) && v->read_disconnected)
d41bd96f
LP
412 goto disconnect;
413
414 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
415 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
416 * being down if we never wrote anything. */
417 if (IN_SET(v->state, VARLINK_IDLE_CLIENT) && (v->write_disconnected || v->got_pollhup))
418 goto disconnect;
419
420 return 0;
421
422disconnect:
423 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
424 return 1;
425}
426
427static int varlink_write(Varlink *v) {
428 ssize_t n;
429
430 assert(v);
431
432 if (!VARLINK_STATE_IS_ALIVE(v->state))
433 return 0;
434 if (v->connecting) /* Writing while we are still wait for a non-blocking connect() to complete will
435 * result in ENOTCONN, hence exit early here */
436 return 0;
437 if (v->output_buffer_size == 0)
438 return 0;
439 if (v->write_disconnected)
440 return 0;
441
442 assert(v->fd >= 0);
443
444 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
445 * with non-socket IO, hence fall back automatically */
446 if (!v->prefer_read_write) {
447 n = send(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size, MSG_DONTWAIT|MSG_NOSIGNAL);
448 if (n < 0 && errno == ENOTSOCK)
449 v->prefer_read_write = true;
450 }
451 if (v->prefer_read_write)
452 n = write(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size);
453 if (n < 0) {
454 if (errno == EAGAIN)
455 return 0;
456
457 if (ERRNO_IS_DISCONNECT(errno)) {
458 /* If we get informed about a disconnect on write, then let's remember that, but not
459 * act on it just yet. Let's wait for read() to report the issue first. */
460 v->write_disconnected = true;
461 return 1;
462 }
463
464 return -errno;
465 }
466
467 v->output_buffer_size -= n;
468
469 if (v->output_buffer_size == 0)
470 v->output_buffer_index = 0;
471 else
472 v->output_buffer_index += n;
473
474 v->timestamp = now(CLOCK_MONOTONIC);
475 return 1;
476}
477
478static int varlink_read(Varlink *v) {
479 size_t rs;
480 ssize_t n;
481
482 assert(v);
483
45a6c965 484 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER))
d41bd96f
LP
485 return 0;
486 if (v->connecting) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
487 return 0;
488 if (v->current)
489 return 0;
490 if (v->input_buffer_unscanned > 0)
491 return 0;
492 if (v->read_disconnected)
493 return 0;
494
495 if (v->input_buffer_size >= VARLINK_BUFFER_MAX)
496 return -ENOBUFS;
497
498 assert(v->fd >= 0);
499
500 if (v->input_buffer_allocated <= v->input_buffer_index + v->input_buffer_size) {
501 size_t add;
502
503 add = MIN(VARLINK_BUFFER_MAX - v->input_buffer_size, VARLINK_READ_SIZE);
504
505 if (v->input_buffer_index == 0) {
506
507 if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_allocated, v->input_buffer_size + add))
508 return -ENOMEM;
509
510 } else {
511 char *b;
512
513 b = new(char, v->input_buffer_size + add);
514 if (!b)
515 return -ENOMEM;
516
517 memcpy(b, v->input_buffer + v->input_buffer_index, v->input_buffer_size);
518
519 free_and_replace(v->input_buffer, b);
520
521 v->input_buffer_allocated = v->input_buffer_size + add;
522 v->input_buffer_index = 0;
523 }
524 }
525
526 rs = v->input_buffer_allocated - (v->input_buffer_index + v->input_buffer_size);
527
528 if (!v->prefer_read_write) {
529 n = recv(v->fd, v->input_buffer + v->input_buffer_index + v->input_buffer_size, rs, MSG_DONTWAIT);
530 if (n < 0 && errno == ENOTSOCK)
531 v->prefer_read_write = true;
532 }
533 if (v->prefer_read_write)
534 n = read(v->fd, v->input_buffer + v->input_buffer_index + v->input_buffer_size, rs);
535 if (n < 0) {
536 if (errno == EAGAIN)
537 return 0;
538
539 if (ERRNO_IS_DISCONNECT(errno)) {
540 v->read_disconnected = true;
541 return 1;
542 }
543
544 return -errno;
545 }
546 if (n == 0) { /* EOF */
547 v->read_disconnected = true;
548 return 1;
549 }
550
551 v->input_buffer_size += n;
552 v->input_buffer_unscanned += n;
553
554 return 1;
555}
556
557static int varlink_parse_message(Varlink *v) {
558 const char *e, *begin;
559 size_t sz;
560 int r;
561
562 assert(v);
563
564 if (v->current)
565 return 0;
566 if (v->input_buffer_unscanned <= 0)
567 return 0;
568
569 assert(v->input_buffer_unscanned <= v->input_buffer_size);
570 assert(v->input_buffer_index + v->input_buffer_size <= v->input_buffer_allocated);
571
572 begin = v->input_buffer + v->input_buffer_index;
573
574 e = memchr(begin + v->input_buffer_size - v->input_buffer_unscanned, 0, v->input_buffer_unscanned);
575 if (!e) {
576 v->input_buffer_unscanned = 0;
577 return 0;
578 }
579
580 sz = e - begin + 1;
581
582 varlink_log(v, "New incoming message: %s", begin);
583
d642f640 584 r = json_parse(begin, 0, &v->current, NULL, NULL);
d41bd96f
LP
585 if (r < 0)
586 return r;
587
588 v->input_buffer_size -= sz;
589
590 if (v->input_buffer_size == 0)
591 v->input_buffer_index = 0;
592 else
593 v->input_buffer_index += sz;
594
595 v->input_buffer_unscanned = v->input_buffer_size;
596 return 1;
597}
598
599static int varlink_test_timeout(Varlink *v) {
600 assert(v);
601
45a6c965 602 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING))
d41bd96f
LP
603 return 0;
604 if (v->timeout == USEC_INFINITY)
605 return 0;
606
607 if (now(CLOCK_MONOTONIC) < usec_add(v->timestamp, v->timeout))
608 return 0;
609
610 varlink_set_state(v, VARLINK_PENDING_TIMEOUT);
611
612 return 1;
613}
614
615static int varlink_dispatch_local_error(Varlink *v, const char *error) {
616 int r;
617
618 assert(v);
619 assert(error);
620
621 if (!v->reply_callback)
622 return 0;
623
624 r = v->reply_callback(v, NULL, error, VARLINK_REPLY_ERROR|VARLINK_REPLY_LOCAL, v->userdata);
625 if (r < 0)
626 log_debug_errno(r, "Reply callback returned error, ignoring: %m");
627
628 return 1;
629}
630
631static int varlink_dispatch_timeout(Varlink *v) {
632 assert(v);
633
634 if (v->state != VARLINK_PENDING_TIMEOUT)
635 return 0;
636
637 varlink_set_state(v, VARLINK_PROCESSING_TIMEOUT);
638 varlink_dispatch_local_error(v, VARLINK_ERROR_TIMEOUT);
639 varlink_close(v);
640
641 return 1;
642}
643
644static int varlink_dispatch_disconnect(Varlink *v) {
645 assert(v);
646
647 if (v->state != VARLINK_PENDING_DISCONNECT)
648 return 0;
649
650 varlink_set_state(v, VARLINK_PROCESSING_DISCONNECT);
651 varlink_dispatch_local_error(v, VARLINK_ERROR_DISCONNECTED);
652 varlink_close(v);
653
654 return 1;
655}
656
657static int varlink_sanitize_parameters(JsonVariant **v) {
658 assert(v);
659
660 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
661 if (!*v)
662 return json_variant_new_object(v, NULL, 0);
663 else if (!json_variant_is_object(*v))
664 return -EINVAL;
665
666 return 0;
667}
668
669static int varlink_dispatch_reply(Varlink *v) {
670 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
671 VarlinkReplyFlags flags = 0;
672 const char *error = NULL;
673 JsonVariant *e;
674 const char *k;
675 int r;
676
677 assert(v);
678
45a6c965 679 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING))
d41bd96f
LP
680 return 0;
681 if (!v->current)
682 return 0;
683
684 assert(v->n_pending > 0);
685
686 if (!json_variant_is_object(v->current))
687 goto invalid;
688
689 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
690
691 if (streq(k, "error")) {
692 if (error)
693 goto invalid;
694 if (!json_variant_is_string(e))
695 goto invalid;
696
697 error = json_variant_string(e);
698 flags |= VARLINK_REPLY_ERROR;
699
700 } else if (streq(k, "parameters")) {
701 if (parameters)
702 goto invalid;
703 if (!json_variant_is_object(e))
704 goto invalid;
705
706 parameters = json_variant_ref(e);
707
708 } else if (streq(k, "continues")) {
709 if (FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
710 goto invalid;
711
712 if (!json_variant_is_boolean(e))
713 goto invalid;
714
715 if (json_variant_boolean(e))
716 flags |= VARLINK_REPLY_CONTINUES;
717 } else
718 goto invalid;
719 }
720
45a6c965
LP
721 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
722 if (v->state != VARLINK_AWAITING_REPLY_MORE && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
723 goto invalid;
724
725 /* An error is final */
d41bd96f
LP
726 if (error && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
727 goto invalid;
728
729 r = varlink_sanitize_parameters(&parameters);
730 if (r < 0)
731 goto invalid;
732
45a6c965 733 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE)) {
d41bd96f
LP
734 varlink_set_state(v, VARLINK_PROCESSING_REPLY);
735
736 if (v->reply_callback) {
737 r = v->reply_callback(v, parameters, error, flags, v->userdata);
738 if (r < 0)
739 log_debug_errno(r, "Reply callback returned error, ignoring: %m");
740 }
741
742 v->current = json_variant_unref(v->current);
743
744 if (v->state == VARLINK_PROCESSING_REPLY) {
45a6c965 745
d41bd96f 746 assert(v->n_pending > 0);
d41bd96f 747
45a6c965
LP
748 if (!FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
749 v->n_pending--;
750
751 varlink_set_state(v,
752 FLAGS_SET(flags, VARLINK_REPLY_CONTINUES) ? VARLINK_AWAITING_REPLY_MORE :
753 v->n_pending == 0 ? VARLINK_IDLE_CLIENT : VARLINK_AWAITING_REPLY);
d41bd96f
LP
754 }
755 } else {
756 assert(v->state == VARLINK_CALLING);
d41bd96f
LP
757 varlink_set_state(v, VARLINK_CALLED);
758 }
759
760 return 1;
761
762invalid:
763 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
764 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
765 varlink_close(v);
766
767 return 1;
768}
769
770static int varlink_dispatch_method(Varlink *v) {
771 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
772 VarlinkMethodFlags flags = 0;
773 const char *method = NULL, *error;
774 JsonVariant *e;
775 VarlinkMethod callback;
776 const char *k;
777 int r;
778
779 assert(v);
780
781 if (v->state != VARLINK_IDLE_SERVER)
782 return 0;
783 if (!v->current)
784 return 0;
785
786 if (!json_variant_is_object(v->current))
787 goto invalid;
788
789 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
790
791 if (streq(k, "method")) {
792 if (method)
793 goto invalid;
794 if (!json_variant_is_string(e))
795 goto invalid;
796
797 method = json_variant_string(e);
798
799 } else if (streq(k, "parameters")) {
800 if (parameters)
801 goto invalid;
802 if (!json_variant_is_object(e))
803 goto invalid;
804
805 parameters = json_variant_ref(e);
806
807 } else if (streq(k, "oneway")) {
808
809 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
810 goto invalid;
811
812 if (!json_variant_is_boolean(e))
813 goto invalid;
814
815 if (json_variant_boolean(e))
816 flags |= VARLINK_METHOD_ONEWAY;
817
818 } else if (streq(k, "more")) {
819
820 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
821 goto invalid;
822
823 if (!json_variant_is_boolean(e))
824 goto invalid;
825
826 if (json_variant_boolean(e))
827 flags |= VARLINK_METHOD_MORE;
828
829 } else
830 goto invalid;
831 }
832
833 if (!method)
834 goto invalid;
835
836 r = varlink_sanitize_parameters(&parameters);
837 if (r < 0)
838 goto fail;
839
840 varlink_set_state(v, (flags & VARLINK_METHOD_MORE) ? VARLINK_PROCESSING_METHOD_MORE :
841 (flags & VARLINK_METHOD_ONEWAY) ? VARLINK_PROCESSING_METHOD_ONEWAY :
842 VARLINK_PROCESSING_METHOD);
843
844 assert(v->server);
845
846 if (STR_IN_SET(method, "org.varlink.service.GetInfo", "org.varlink.service.GetInterface")) {
847 /* For now, we don't implement a single of varlink's own methods */
848 callback = NULL;
849 error = VARLINK_ERROR_METHOD_NOT_IMPLEMENTED;
850 } else if (startswith(method, "org.varlink.service.")) {
851 callback = NULL;
852 error = VARLINK_ERROR_METHOD_NOT_FOUND;
853 } else {
854 callback = hashmap_get(v->server->methods, method);
855 error = VARLINK_ERROR_METHOD_NOT_FOUND;
856 }
857
858 if (callback) {
859 r = callback(v, parameters, flags, v->userdata);
860 if (r < 0) {
861 log_debug_errno(r, "Callback for %s returned error: %m", method);
862
863 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
864 if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
865 r = varlink_errorb(v, VARLINK_ERROR_SYSTEM, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(-r))));
866 if (r < 0)
867 return r;
868 }
869 }
870 } else if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
871 assert(error);
872
873 r = varlink_errorb(v, error, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method))));
874 if (r < 0)
875 return r;
876 }
877
878 switch (v->state) {
879
880 case VARLINK_PROCESSED_METHOD: /* Method call is fully processed */
881 case VARLINK_PROCESSING_METHOD_ONEWAY: /* ditto */
882 v->current = json_variant_unref(v->current);
883 varlink_set_state(v, VARLINK_IDLE_SERVER);
884 break;
885
886 case VARLINK_PROCESSING_METHOD: /* Method call wasn't replied to, will be replied to later */
887 varlink_set_state(v, VARLINK_PENDING_METHOD);
888 break;
889
d41bd96f
LP
890 case VARLINK_PROCESSING_METHOD_MORE: /* No reply for a "more" message was sent, more to come */
891 varlink_set_state(v, VARLINK_PENDING_METHOD_MORE);
892 break;
893
894 default:
895 assert_not_reached("Unexpected state");
896
897 }
898
899 return r;
900
901invalid:
902 r = -EINVAL;
903
904fail:
905 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
906 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
907 varlink_close(v);
908
909 return r;
910}
911
912int varlink_process(Varlink *v) {
913 int r;
914
915 assert_return(v, -EINVAL);
916
917 if (v->state == VARLINK_DISCONNECTED)
918 return -ENOTCONN;
919
920 varlink_ref(v);
921
922 r = varlink_write(v);
923 if (r != 0)
924 goto finish;
925
926 r = varlink_dispatch_reply(v);
927 if (r != 0)
928 goto finish;
929
930 r = varlink_dispatch_method(v);
931 if (r != 0)
932 goto finish;
933
934 r = varlink_parse_message(v);
935 if (r != 0)
936 goto finish;
937
938 r = varlink_read(v);
939 if (r != 0)
940 goto finish;
941
942 r = varlink_test_disconnect(v);
943 if (r != 0)
944 goto finish;
945
946 r = varlink_dispatch_disconnect(v);
947 if (r != 0)
948 goto finish;
949
950 r = varlink_test_timeout(v);
951 if (r != 0)
952 goto finish;
953
954 r = varlink_dispatch_timeout(v);
955 if (r != 0)
956 goto finish;
957
958finish:
959 if (r >= 0 && v->defer_event_source) {
960 int q;
961
962 /* If we did some processing, make sure we are called again soon */
963 q = sd_event_source_set_enabled(v->defer_event_source, r > 0 ? SD_EVENT_ON : SD_EVENT_OFF);
964 if (q < 0)
965 r = q;
966 }
967
968 if (r < 0) {
969 if (VARLINK_STATE_IS_ALIVE(v->state))
970 /* Initiate disconnection */
971 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
972 else
973 /* We failed while disconnecting, in that case close right away */
974 varlink_close(v);
975 }
976
977 varlink_unref(v);
978 return r;
979}
980
981static void handle_revents(Varlink *v, int revents) {
982 assert(v);
983
984 if (v->connecting) {
985 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
986 * to complete on, we know we are ready. We don't read the connection error here though,
987 * we'll get the error on the next read() or write(). */
988 if ((revents & (POLLOUT|POLLHUP)) == 0)
989 return;
990
991 varlink_log(v, "Anynchronous connection completed.");
992 v->connecting = false;
993 } else {
994 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
995 * what we can. However, we do care about POLLHUP to detect connection termination even if we
996 * momentarily don't want to read nor write anything. */
997
998 if (!FLAGS_SET(revents, POLLHUP))
999 return;
1000
1001 varlink_log(v, "Got POLLHUP from socket.");
1002 v->got_pollhup = true;
1003 }
1004}
1005
1006int varlink_wait(Varlink *v, usec_t timeout) {
d41bd96f
LP
1007 int r, fd, events;
1008 usec_t t;
1009
1010 assert_return(v, -EINVAL);
d41bd96f
LP
1011
1012 if (v->state == VARLINK_DISCONNECTED)
1013 return -ENOTCONN;
1014
1015 r = varlink_get_timeout(v, &t);
1016 if (r < 0)
1017 return r;
1018 if (t != USEC_INFINITY) {
1019 usec_t n;
1020
1021 n = now(CLOCK_MONOTONIC);
1022 if (t < n)
1023 t = 0;
1024 else
1025 t = usec_sub_unsigned(t, n);
1026 }
1027
1028 if (timeout != USEC_INFINITY &&
1029 (t == USEC_INFINITY || timeout < t))
1030 t = timeout;
1031
1032 fd = varlink_get_fd(v);
1033 if (fd < 0)
1034 return fd;
1035
1036 events = varlink_get_events(v);
1037 if (events < 0)
1038 return events;
1039
0f2d351f 1040 r = fd_wait_for_event(fd, events, t);
d41bd96f 1041 if (r < 0)
0f2d351f 1042 return r;
dad28bff
LP
1043 if (r == 0)
1044 return 0;
d41bd96f 1045
0f2d351f 1046 handle_revents(v, r);
dad28bff 1047 return 1;
d41bd96f
LP
1048}
1049
1050int varlink_get_fd(Varlink *v) {
1051
1052 assert_return(v, -EINVAL);
1053
1054 if (v->state == VARLINK_DISCONNECTED)
1055 return -ENOTCONN;
1056 if (v->fd < 0)
1057 return -EBADF;
1058
1059 return v->fd;
1060}
1061
1062int varlink_get_events(Varlink *v) {
1063 int ret = 0;
1064
1065 assert_return(v, -EINVAL);
1066
1067 if (v->state == VARLINK_DISCONNECTED)
1068 return -ENOTCONN;
1069
1070 if (v->connecting) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1071 * tells us that the connection is now complete. Before that we should neither
1072 * write() or read() from the fd. */
1073 return EPOLLOUT;
1074
1075 if (!v->read_disconnected &&
45a6c965 1076 IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER) &&
d41bd96f
LP
1077 !v->current &&
1078 v->input_buffer_unscanned <= 0)
1079 ret |= EPOLLIN;
1080
1081 if (!v->write_disconnected &&
1082 v->output_buffer_size > 0)
1083 ret |= EPOLLOUT;
1084
1085 return ret;
1086}
1087
1088int varlink_get_timeout(Varlink *v, usec_t *ret) {
1089 assert_return(v, -EINVAL);
1090
1091 if (v->state == VARLINK_DISCONNECTED)
1092 return -ENOTCONN;
1093
45a6c965 1094 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING) &&
d41bd96f
LP
1095 v->timeout != USEC_INFINITY) {
1096 if (ret)
1097 *ret = usec_add(v->timestamp, v->timeout);
1098 return 1;
1099 } else {
1100 if (ret)
1101 *ret = USEC_INFINITY;
1102 return 0;
1103 }
1104}
1105
1106int varlink_flush(Varlink *v) {
1107 int ret = 0, r;
1108
1109 assert_return(v, -EINVAL);
1110
1111 if (v->state == VARLINK_DISCONNECTED)
1112 return -ENOTCONN;
1113
1114 for (;;) {
d41bd96f
LP
1115 if (v->output_buffer_size == 0)
1116 break;
1117 if (v->write_disconnected)
1118 return -ECONNRESET;
1119
1120 r = varlink_write(v);
1121 if (r < 0)
1122 return r;
1123 if (r > 0) {
1124 ret = 1;
1125 continue;
1126 }
1127
0f2d351f 1128 r = fd_wait_for_event(v->fd, POLLOUT, USEC_INFINITY);
dad28bff 1129 if (r < 0)
0f2d351f 1130 return r;
d41bd96f 1131
0f2d351f 1132 assert(r != 0);
dad28bff 1133
0f2d351f 1134 handle_revents(v, r);
d41bd96f
LP
1135 }
1136
1137 return ret;
1138}
1139
1140static void varlink_detach_server(Varlink *v) {
6d4d6002 1141 VarlinkServer *saved_server;
d41bd96f
LP
1142 assert(v);
1143
1144 if (!v->server)
1145 return;
1146
1147 if (v->server->by_uid &&
1148 v->ucred_acquired &&
1149 uid_is_valid(v->ucred.uid)) {
1150 unsigned c;
1151
1152 c = PTR_TO_UINT(hashmap_get(v->server->by_uid, UID_TO_PTR(v->ucred.uid)));
1153 assert(c > 0);
1154
1155 if (c == 1)
1156 (void) hashmap_remove(v->server->by_uid, UID_TO_PTR(v->ucred.uid));
1157 else
1158 (void) hashmap_replace(v->server->by_uid, UID_TO_PTR(v->ucred.uid), UINT_TO_PTR(c - 1));
1159 }
1160
1161 assert(v->server->n_connections > 0);
1162 v->server->n_connections--;
1163
1164 /* If this is a connection associated to a server, then let's disconnect the server and the
6d4d6002
LP
1165 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1166 * before we release the references, let's call the disconnection callback if it is defined. */
1167
1168 saved_server = TAKE_PTR(v->server);
1169
1170 if (saved_server->disconnect_callback)
1171 saved_server->disconnect_callback(saved_server, v, saved_server->userdata);
1172
1173 varlink_server_unref(saved_server);
d41bd96f
LP
1174 varlink_unref(v);
1175}
1176
1177int varlink_close(Varlink *v) {
1178
1179 assert_return(v, -EINVAL);
1180
1181 if (v->state == VARLINK_DISCONNECTED)
1182 return 0;
1183
1184 varlink_set_state(v, VARLINK_DISCONNECTED);
1185
1186 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1187 * which would destroy us before we can call varlink_clear() */
1188 varlink_ref(v);
1189 varlink_detach_server(v);
1190 varlink_clear(v);
1191 varlink_unref(v);
1192
1193 return 1;
1194}
1195
9652d740
LP
1196Varlink* varlink_close_unref(Varlink *v) {
1197
1198 if (!v)
1199 return NULL;
1200
1201 (void) varlink_close(v);
1202 return varlink_unref(v);
1203}
1204
d41bd96f
LP
1205Varlink* varlink_flush_close_unref(Varlink *v) {
1206
1207 if (!v)
1208 return NULL;
1209
1210 (void) varlink_flush(v);
1211 (void) varlink_close(v);
d41bd96f
LP
1212 return varlink_unref(v);
1213}
1214
1215static int varlink_enqueue_json(Varlink *v, JsonVariant *m) {
1216 _cleanup_free_ char *text = NULL;
1217 int r;
1218
1219 assert(v);
1220 assert(m);
1221
1222 r = json_variant_format(m, 0, &text);
1223 if (r < 0)
1224 return r;
2a04712c 1225 assert(text[r] == '\0');
d41bd96f
LP
1226
1227 if (v->output_buffer_size + r + 1 > VARLINK_BUFFER_MAX)
1228 return -ENOBUFS;
1229
1230 varlink_log(v, "Sending message: %s", text);
1231
1232 if (v->output_buffer_size == 0) {
1233
1234 free_and_replace(v->output_buffer, text);
1235
1236 v->output_buffer_size = v->output_buffer_allocated = r + 1;
1237 v->output_buffer_index = 0;
1238
1239 } else if (v->output_buffer_index == 0) {
1240
1241 if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_allocated, v->output_buffer_size + r + 1))
1242 return -ENOMEM;
1243
1244 memcpy(v->output_buffer + v->output_buffer_size, text, r + 1);
1245 v->output_buffer_size += r + 1;
1246
1247 } else {
1248 char *n;
be44e091 1249 const size_t new_size = v->output_buffer_size + r + 1;
d41bd96f 1250
be44e091 1251 n = new(char, new_size);
d41bd96f
LP
1252 if (!n)
1253 return -ENOMEM;
1254
1255 memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, r + 1);
1256
1257 free_and_replace(v->output_buffer, n);
be44e091 1258 v->output_buffer_allocated = v->output_buffer_size = new_size;
d41bd96f
LP
1259 v->output_buffer_index = 0;
1260 }
1261
1262 return 0;
1263}
1264
1265int varlink_send(Varlink *v, const char *method, JsonVariant *parameters) {
1266 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1267 int r;
1268
1269 assert_return(v, -EINVAL);
1270 assert_return(method, -EINVAL);
1271
1272 if (v->state == VARLINK_DISCONNECTED)
1273 return -ENOTCONN;
45a6c965
LP
1274
1275 /* We allow enqueuing multiple method calls at once! */
d41bd96f
LP
1276 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
1277 return -EBUSY;
1278
1279 r = varlink_sanitize_parameters(&parameters);
1280 if (r < 0)
1281 return r;
1282
1283 r = json_build(&m, JSON_BUILD_OBJECT(
1284 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1285 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1286 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1287 if (r < 0)
1288 return r;
1289
1290 r = varlink_enqueue_json(v, m);
1291 if (r < 0)
1292 return r;
1293
1294 /* No state change here, this is one-way only after all */
1295 v->timestamp = now(CLOCK_MONOTONIC);
1296 return 0;
1297}
1298
1299int varlink_sendb(Varlink *v, const char *method, ...) {
1300 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1301 va_list ap;
1302 int r;
1303
1304 assert_return(v, -EINVAL);
1305
1306 va_start(ap, method);
1307 r = json_buildv(&parameters, ap);
1308 va_end(ap);
1309
1310 if (r < 0)
1311 return r;
1312
1313 return varlink_send(v, method, parameters);
1314}
1315
1316int varlink_invoke(Varlink *v, const char *method, JsonVariant *parameters) {
1317 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1318 int r;
1319
1320 assert_return(v, -EINVAL);
1321 assert_return(method, -EINVAL);
1322
1323 if (v->state == VARLINK_DISCONNECTED)
1324 return -ENOTCONN;
45a6c965 1325
86b52a39 1326 /* We allow enqueuing multiple method calls at once! */
d41bd96f
LP
1327 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
1328 return -EBUSY;
1329
1330 r = varlink_sanitize_parameters(&parameters);
1331 if (r < 0)
1332 return r;
1333
1334 r = json_build(&m, JSON_BUILD_OBJECT(
1335 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1336 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1337 if (r < 0)
1338 return r;
1339
1340 r = varlink_enqueue_json(v, m);
1341 if (r < 0)
1342 return r;
1343
1344 varlink_set_state(v, VARLINK_AWAITING_REPLY);
1345 v->n_pending++;
1346 v->timestamp = now(CLOCK_MONOTONIC);
1347
1348 return 0;
1349}
1350
1351int varlink_invokeb(Varlink *v, const char *method, ...) {
1352 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1353 va_list ap;
1354 int r;
1355
1356 assert_return(v, -EINVAL);
1357
1358 va_start(ap, method);
1359 r = json_buildv(&parameters, ap);
1360 va_end(ap);
1361
1362 if (r < 0)
1363 return r;
1364
1365 return varlink_invoke(v, method, parameters);
45a6c965
LP
1366}
1367
1368int varlink_observe(Varlink *v, const char *method, JsonVariant *parameters) {
1369 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1370 int r;
1371
1372 assert_return(v, -EINVAL);
1373 assert_return(method, -EINVAL);
1374
1375 if (v->state == VARLINK_DISCONNECTED)
1376 return -ENOTCONN;
1377 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1378 * thus insist on an idle client here. */
1379 if (v->state != VARLINK_IDLE_CLIENT)
1380 return -EBUSY;
1381
1382 r = varlink_sanitize_parameters(&parameters);
1383 if (r < 0)
1384 return r;
1385
1386 r = json_build(&m, JSON_BUILD_OBJECT(
1387 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1388 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1389 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1390 if (r < 0)
1391 return r;
1392
1393 r = varlink_enqueue_json(v, m);
1394 if (r < 0)
1395 return r;
1396
1397
1398 varlink_set_state(v, VARLINK_AWAITING_REPLY_MORE);
1399 v->n_pending++;
1400 v->timestamp = now(CLOCK_MONOTONIC);
1401
1402 return 0;
1403}
1404
1405int varlink_observeb(Varlink *v, const char *method, ...) {
1406 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1407 va_list ap;
1408 int r;
1409
1410 assert_return(v, -EINVAL);
1411
1412 va_start(ap, method);
1413 r = json_buildv(&parameters, ap);
1414 va_end(ap);
1415
1416 if (r < 0)
1417 return r;
1418
1419 return varlink_observe(v, method, parameters);
d41bd96f
LP
1420}
1421
1422int varlink_call(
1423 Varlink *v,
1424 const char *method,
1425 JsonVariant *parameters,
1426 JsonVariant **ret_parameters,
1427 const char **ret_error_id,
1428 VarlinkReplyFlags *ret_flags) {
1429
1430 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1431 int r;
1432
1433 assert_return(v, -EINVAL);
1434 assert_return(method, -EINVAL);
1435
1436 if (v->state == VARLINK_DISCONNECTED)
1437 return -ENOTCONN;
1438 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT))
1439 return -EBUSY;
1440
1441 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1442
1443 r = varlink_sanitize_parameters(&parameters);
1444 if (r < 0)
1445 return r;
1446
1447 r = json_build(&m, JSON_BUILD_OBJECT(
1448 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1449 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1450 if (r < 0)
1451 return r;
1452
1453 r = varlink_enqueue_json(v, m);
1454 if (r < 0)
1455 return r;
1456
1457 varlink_set_state(v, VARLINK_CALLING);
1458 v->n_pending++;
1459 v->timestamp = now(CLOCK_MONOTONIC);
1460
1461 while (v->state == VARLINK_CALLING) {
1462
1463 r = varlink_process(v);
1464 if (r < 0)
1465 return r;
1466 if (r > 0)
1467 continue;
1468
1469 r = varlink_wait(v, USEC_INFINITY);
1470 if (r < 0)
1471 return r;
1472 }
1473
1474 switch (v->state) {
1475
1476 case VARLINK_CALLED:
1477 assert(v->current);
1478
1479 json_variant_unref(v->reply);
1480 v->reply = TAKE_PTR(v->current);
1481
1482 varlink_set_state(v, VARLINK_IDLE_CLIENT);
1483 assert(v->n_pending == 1);
1484 v->n_pending--;
1485
1486 if (ret_parameters)
1487 *ret_parameters = json_variant_by_key(v->reply, "parameters");
1488 if (ret_error_id)
1489 *ret_error_id = json_variant_string(json_variant_by_key(v->reply, "error"));
1490 if (ret_flags)
1491 *ret_flags = 0;
1492
1493 return 1;
1494
1495 case VARLINK_PENDING_DISCONNECT:
1496 case VARLINK_DISCONNECTED:
1497 return -ECONNRESET;
1498
1499 case VARLINK_PENDING_TIMEOUT:
1500 return -ETIME;
1501
1502 default:
1503 assert_not_reached("Unexpected state after method call.");
1504 }
1505}
1506
1507int varlink_callb(
1508 Varlink *v,
1509 const char *method,
1510 JsonVariant **ret_parameters,
1511 const char **ret_error_id,
1512 VarlinkReplyFlags *ret_flags, ...) {
1513
1514 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1515 va_list ap;
1516 int r;
1517
1518 assert_return(v, -EINVAL);
1519
1520 va_start(ap, ret_flags);
1521 r = json_buildv(&parameters, ap);
1522 va_end(ap);
1523
1524 if (r < 0)
1525 return r;
1526
1527 return varlink_call(v, method, parameters, ret_parameters, ret_error_id, ret_flags);
1528}
1529
1530int varlink_reply(Varlink *v, JsonVariant *parameters) {
1531 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1532 int r;
1533
1534 assert_return(v, -EINVAL);
1535
1536 if (v->state == VARLINK_DISCONNECTED)
1537 return -ENOTCONN;
1538 if (!IN_SET(v->state,
1539 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1540 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1541 return -EBUSY;
1542
1543 r = varlink_sanitize_parameters(&parameters);
1544 if (r < 0)
1545 return r;
1546
1547 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1548 if (r < 0)
1549 return r;
1550
1551 r = varlink_enqueue_json(v, m);
1552 if (r < 0)
1553 return r;
1554
1555 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1556 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1557 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1558 * process further messages. */
1559 v->current = json_variant_unref(v->current);
1560 varlink_set_state(v, VARLINK_IDLE_SERVER);
1561 } else
1562 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1563 * means we should it handle the rest of the state engine. */
1564 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1565
1566 return 1;
1567}
1568
1569int varlink_replyb(Varlink *v, ...) {
1570 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1571 va_list ap;
1572 int r;
1573
1574 assert_return(v, -EINVAL);
1575
1576 va_start(ap, v);
1577 r = json_buildv(&parameters, ap);
1578 va_end(ap);
1579
1580 if (r < 0)
1581 return r;
1582
1583 return varlink_reply(v, parameters);
1584}
1585
1586int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
1587 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1588 int r;
1589
1590 assert_return(v, -EINVAL);
1591 assert_return(error_id, -EINVAL);
1592
1593 if (v->state == VARLINK_DISCONNECTED)
1594 return -ENOTCONN;
1595 if (!IN_SET(v->state,
1596 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1597 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1598 return -EBUSY;
1599
1600 r = varlink_sanitize_parameters(&parameters);
1601 if (r < 0)
1602 return r;
1603
1604 r = json_build(&m, JSON_BUILD_OBJECT(
1605 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
1606 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1607 if (r < 0)
1608 return r;
1609
1610 r = varlink_enqueue_json(v, m);
1611 if (r < 0)
1612 return r;
1613
1614 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1615 v->current = json_variant_unref(v->current);
1616 varlink_set_state(v, VARLINK_IDLE_SERVER);
1617 } else
1618 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1619
1620 return 1;
1621}
1622
1623int varlink_errorb(Varlink *v, const char *error_id, ...) {
1624 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1625 va_list ap;
1626 int r;
1627
1628 assert_return(v, -EINVAL);
1629 assert_return(error_id, -EINVAL);
1630
1631 va_start(ap, error_id);
1632 r = json_buildv(&parameters, ap);
1633 va_end(ap);
1634
1635 if (r < 0)
1636 return r;
1637
1638 return varlink_error(v, error_id, parameters);
1639}
1640
1641int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
1642
1643 assert_return(v, -EINVAL);
1644 assert_return(parameters, -EINVAL);
1645
1646 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1647 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1648 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1649 * don't expect any arguments. */
1650
1651 if (json_variant_is_string(parameters))
1652 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters);
1653
1654 if (json_variant_is_object(parameters) &&
1655 json_variant_elements(parameters) > 0)
1656 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER,
1657 json_variant_by_index(parameters, 0));
1658
1659 return -EINVAL;
1660}
1661
1662int varlink_notify(Varlink *v, JsonVariant *parameters) {
1663 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1664 int r;
1665
1666 assert_return(v, -EINVAL);
1667
1668 if (v->state == VARLINK_DISCONNECTED)
1669 return -ENOTCONN;
1670 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
1671 return -EBUSY;
1672
1673 r = varlink_sanitize_parameters(&parameters);
1674 if (r < 0)
1675 return r;
1676
1677 r = json_build(&m, JSON_BUILD_OBJECT(
1678 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1679 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
1680 if (r < 0)
1681 return r;
1682
1683 r = varlink_enqueue_json(v, m);
1684 if (r < 0)
1685 return r;
1686
1687 /* No state change, as more is coming */
1688 return 1;
1689}
1690
1691int varlink_notifyb(Varlink *v, ...) {
1692 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1693 va_list ap;
1694 int r;
1695
1696 assert_return(v, -EINVAL);
1697
1698 va_start(ap, v);
1699 r = json_buildv(&parameters, ap);
1700 va_end(ap);
1701
1702 if (r < 0)
1703 return r;
1704
1705 return varlink_notify(v, parameters);
1706}
1707
1708int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
1709 assert_return(v, -EINVAL);
1710
1711 if (callback && v->reply_callback && callback != v->reply_callback)
1712 return -EBUSY;
1713
1714 v->reply_callback = callback;
1715
1716 return 0;
1717}
1718
1719void* varlink_set_userdata(Varlink *v, void *userdata) {
1720 void *old;
1721
1722 assert_return(v, NULL);
1723
1724 old = v->userdata;
1725 v->userdata = userdata;
1726
1727 return old;
1728}
1729
1730void* varlink_get_userdata(Varlink *v) {
1731 assert_return(v, NULL);
1732
1733 return v->userdata;
1734}
1735
1736static int varlink_acquire_ucred(Varlink *v) {
1737 int r;
1738
1739 assert(v);
1740
1741 if (v->ucred_acquired)
1742 return 0;
1743
1744 r = getpeercred(v->fd, &v->ucred);
1745 if (r < 0)
1746 return r;
1747
1748 v->ucred_acquired = true;
1749 return 0;
1750}
1751
1752int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
1753 int r;
1754
1755 assert_return(v, -EINVAL);
1756 assert_return(ret, -EINVAL);
1757
1758 r = varlink_acquire_ucred(v);
1759 if (r < 0)
1760 return r;
1761
1762 if (!uid_is_valid(v->ucred.uid))
1763 return -ENODATA;
1764
1765 *ret = v->ucred.uid;
1766 return 0;
1767}
1768
1769int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
1770 int r;
1771
1772 assert_return(v, -EINVAL);
1773 assert_return(ret, -EINVAL);
1774
1775 r = varlink_acquire_ucred(v);
1776 if (r < 0)
1777 return r;
1778
1779 if (!pid_is_valid(v->ucred.pid))
1780 return -ENODATA;
1781
1782 *ret = v->ucred.pid;
1783 return 0;
1784}
1785
1786int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
1787 assert_return(v, -EINVAL);
1788 assert_return(timeout > 0, -EINVAL);
1789
1790 v->timeout = timeout;
1791 return 0;
1792}
1793
1794VarlinkServer *varlink_get_server(Varlink *v) {
1795 assert_return(v, NULL);
1796
1797 return v->server;
1798}
1799
1800int varlink_set_description(Varlink *v, const char *description) {
1801 assert_return(v, -EINVAL);
1802
1803 return free_and_strdup(&v->description, description);
1804}
1805
1806static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1807 Varlink *v = userdata;
1808
1809 assert(s);
1810 assert(v);
1811
1812 handle_revents(v, revents);
1813 (void) varlink_process(v);
1814
1815 return 1;
1816}
1817
1818static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1819 Varlink *v = userdata;
1820
1821 assert(s);
1822 assert(v);
1823
1824 (void) varlink_process(v);
1825 return 1;
1826}
1827
1828static int defer_callback(sd_event_source *s, void *userdata) {
1829 Varlink *v = userdata;
1830
1831 assert(s);
1832 assert(v);
1833
1834 (void) varlink_process(v);
1835 return 1;
1836}
1837
1838static int prepare_callback(sd_event_source *s, void *userdata) {
1839 Varlink *v = userdata;
1840 int r, e;
1841 usec_t until;
f1194f5d 1842 bool have_timeout;
d41bd96f
LP
1843
1844 assert(s);
1845 assert(v);
1846
1847 e = varlink_get_events(v);
1848 if (e < 0)
1849 return e;
1850
1851 r = sd_event_source_set_io_events(v->io_event_source, e);
1852 if (r < 0)
1853 return r;
1854
1855 r = varlink_get_timeout(v, &until);
1856 if (r < 0)
1857 return r;
f1194f5d
LP
1858 have_timeout = r > 0;
1859
1860 if (have_timeout) {
d41bd96f
LP
1861 r = sd_event_source_set_time(v->time_event_source, until);
1862 if (r < 0)
1863 return r;
1864 }
1865
f1194f5d 1866 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
d41bd96f
LP
1867 if (r < 0)
1868 return r;
1869
1870 return 1;
1871}
1872
1873static int quit_callback(sd_event_source *event, void *userdata) {
1874 Varlink *v = userdata;
1875
1876 assert(event);
1877 assert(v);
1878
1879 varlink_flush(v);
1880 varlink_close(v);
1881
1882 return 1;
1883}
1884
1885int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
1886 int r;
1887
1888 assert_return(v, -EINVAL);
1889 assert_return(!v->event, -EBUSY);
1890
1891 if (e)
1892 v->event = sd_event_ref(e);
1893 else {
1894 r = sd_event_default(&v->event);
1895 if (r < 0)
1896 return r;
1897 }
1898
1899 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
1900 if (r < 0)
1901 goto fail;
1902
1903 r = sd_event_source_set_priority(v->time_event_source, priority);
1904 if (r < 0)
1905 goto fail;
1906
1907 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
1908
1909 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
1910 if (r < 0)
1911 goto fail;
1912
1913 r = sd_event_source_set_priority(v->quit_event_source, priority);
1914 if (r < 0)
1915 goto fail;
1916
1917 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
1918
1919 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
1920 if (r < 0)
1921 goto fail;
1922
1923 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
1924 if (r < 0)
1925 goto fail;
1926
1927 r = sd_event_source_set_priority(v->io_event_source, priority);
1928 if (r < 0)
1929 goto fail;
1930
1931 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
1932
1933 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
1934 if (r < 0)
1935 goto fail;
1936
1937 r = sd_event_source_set_priority(v->defer_event_source, priority);
1938 if (r < 0)
1939 goto fail;
1940
1941 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
1942
1943 return 0;
1944
1945fail:
1946 varlink_detach_event(v);
1947 return r;
1948}
1949
d41bd96f
LP
1950void varlink_detach_event(Varlink *v) {
1951 if (!v)
1952 return;
1953
1954 varlink_detach_event_sources(v);
1955
1956 v->event = sd_event_unref(v->event);
1957}
1958
1959sd_event *varlink_get_event(Varlink *v) {
1960 assert_return(v, NULL);
1961
1962 return v->event;
1963}
1964
1965int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
1966 VarlinkServer *s;
1967
1968 assert_return(ret, -EINVAL);
1969 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
1970
1971 s = new(VarlinkServer, 1);
1972 if (!s)
1973 return -ENOMEM;
1974
1975 *s = (VarlinkServer) {
1976 .n_ref = 1,
1977 .flags = flags,
1978 .connections_max = varlink_server_connections_max(NULL),
1979 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
1980 };
1981
1982 *ret = s;
1983 return 0;
1984}
1985
1986static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
1987 char *m;
1988
1989 if (!s)
1990 return NULL;
1991
1992 varlink_server_shutdown(s);
1993
1994 while ((m = hashmap_steal_first_key(s->methods)))
1995 free(m);
1996
1997 hashmap_free(s->methods);
1998 hashmap_free(s->by_uid);
1999
2000 sd_event_unref(s->event);
2001
2002 free(s->description);
2003
2004 return mfree(s);
2005}
2006
2007DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
2008
2009static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
2010 int allowed = -1;
2011
2012 assert(server);
2013 assert(ucred);
2014
2015 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
2016 allowed = ucred->uid == 0;
2017
2018 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
2019 allowed = allowed > 0 || ucred->uid == getuid();
2020
2021 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
2022 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2023 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
2024 return 0;
2025 }
2026
2027 if (server->n_connections >= server->connections_max) {
2028 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
2029 return 0;
2030 }
2031
2032 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2033 unsigned c;
2034
2035 if (!uid_is_valid(ucred->uid)) {
2036 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
2037 return 0;
2038 }
2039
2040 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2041 if (c >= server->connections_per_uid_max) {
2042 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
2043 server->connections_per_uid_max);
2044 return 0;
2045 }
2046 }
2047
2048 return 1;
2049}
2050
2051static int count_connection(VarlinkServer *server, struct ucred *ucred) {
2052 unsigned c;
2053 int r;
2054
2055 assert(server);
2056 assert(ucred);
2057
2058 server->n_connections++;
2059
2060 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2061 r = hashmap_ensure_allocated(&server->by_uid, NULL);
2062 if (r < 0)
2063 return log_debug_errno(r, "Failed to allocate UID hash table: %m");
2064
2065 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2066
2067 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
2068 ucred->uid, c, server->connections_per_uid_max);
2069
2070 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
2071 if (r < 0)
2072 return log_debug_errno(r, "Failed to increment counter in UID hash table: %m");
2073 }
2074
2075 return 0;
2076}
2077
2078int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
2079 _cleanup_(varlink_unrefp) Varlink *v = NULL;
2080 bool ucred_acquired;
2081 struct ucred ucred;
2082 int r;
2083
2084 assert_return(server, -EINVAL);
2085 assert_return(fd >= 0, -EBADF);
2086
2087 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
2088 r = getpeercred(fd, &ucred);
2089 if (r < 0)
2090 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2091
2092 ucred_acquired = true;
2093
2094 r = validate_connection(server, &ucred);
2095 if (r < 0)
2096 return r;
2097 if (r == 0)
2098 return -EPERM;
2099 } else
2100 ucred_acquired = false;
2101
2102 r = varlink_new(&v);
2103 if (r < 0)
2104 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
2105
2106 r = count_connection(server, &ucred);
2107 if (r < 0)
2108 return r;
2109
2110 v->fd = fd;
2111 v->userdata = server->userdata;
2112 if (ucred_acquired) {
2113 v->ucred = ucred;
2114 v->ucred_acquired = true;
2115 }
2116
2117 (void) asprintf(&v->description, "%s-%i", server->description ?: "varlink", v->fd);
2118
2119 /* Link up the server and the connection, and take reference in both directions. Note that the
2120 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2121 * which happens in varlink_close(), including in the event loop quit callback. */
2122 v->server = varlink_server_ref(server);
2123 varlink_ref(v);
2124
2125 varlink_set_state(v, VARLINK_IDLE_SERVER);
2126
7e69d90c
LP
2127 if (server->event) {
2128 r = varlink_attach_event(v, server->event, server->event_priority);
2129 if (r < 0) {
2130 varlink_log_errno(v, r, "Failed to attach new connection: %m");
2131 v->fd = -1; /* take the fd out of the connection again */
2132 varlink_close(v);
2133 return r;
2134 }
d41bd96f
LP
2135 }
2136
2137 if (ret)
2138 *ret = v;
2139
2140 return 0;
2141}
2142
2143static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2144 VarlinkServerSocket *ss = userdata;
2145 _cleanup_close_ int cfd = -1;
2146 Varlink *v = NULL;
2147 int r;
2148
2149 assert(source);
2150 assert(ss);
2151
2152 varlink_server_log(ss->server, "New incoming connection.");
2153
2154 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2155 if (cfd < 0) {
2156 if (ERRNO_IS_ACCEPT_AGAIN(errno))
2157 return 0;
2158
2159 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
2160 }
2161
2162 r = varlink_server_add_connection(ss->server, cfd, &v);
2163 if (r < 0)
2164 return 0;
2165
2166 TAKE_FD(cfd);
2167
2168 if (ss->server->connect_callback) {
2169 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
2170 if (r < 0) {
2171 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
2172 varlink_close(v);
2173 return 0;
2174 }
2175 }
2176
2177 return 0;
2178}
2179
2180int varlink_server_listen_fd(VarlinkServer *s, int fd) {
2181 _cleanup_free_ VarlinkServerSocket *ss = NULL;
2182 int r;
2183
2184 assert_return(s, -EINVAL);
2185 assert_return(fd >= 0, -EBADF);
2186
2187 r = fd_nonblock(fd, true);
2188 if (r < 0)
2189 return r;
2190
2191 ss = new(VarlinkServerSocket, 1);
2192 if (!ss)
2193 return -ENOMEM;
2194
2195 *ss = (VarlinkServerSocket) {
2196 .server = s,
2197 .fd = fd,
2198 };
2199
2200 if (s->event) {
2201 _cleanup_(sd_event_source_unrefp) sd_event_source *es = NULL;
2202
2203 r = sd_event_add_io(s->event, &es, fd, EPOLLIN, connect_callback, ss);
2204 if (r < 0)
2205 return r;
2206
2207 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
2208 if (r < 0)
2209 return r;
2210 }
2211
2212 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
2213 return 0;
2214}
2215
2216int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
2217 union sockaddr_union sockaddr;
f36a9d59 2218 socklen_t sockaddr_len;
d41bd96f
LP
2219 _cleanup_close_ int fd = -1;
2220 int r;
2221
2222 assert_return(s, -EINVAL);
2223 assert_return(address, -EINVAL);
2224 assert_return((m & ~0777) == 0, -EINVAL);
2225
2226 r = sockaddr_un_set_path(&sockaddr.un, address);
2227 if (r < 0)
2228 return r;
f36a9d59 2229 sockaddr_len = r;
d41bd96f
LP
2230
2231 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2232 if (fd < 0)
2233 return -errno;
2234
a0c41de2
LP
2235 fd = fd_move_above_stdio(fd);
2236
d41bd96f
LP
2237 (void) sockaddr_un_unlink(&sockaddr.un);
2238
2239 RUN_WITH_UMASK(~m & 0777)
f36a9d59 2240 if (bind(fd, &sockaddr.sa, sockaddr_len) < 0)
d41bd96f
LP
2241 return -errno;
2242
2243 if (listen(fd, SOMAXCONN) < 0)
2244 return -errno;
2245
2246 r = varlink_server_listen_fd(s, fd);
2247 if (r < 0)
2248 return r;
2249
2250 TAKE_FD(fd);
2251 return 0;
2252}
2253
2254void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
2255 void *ret;
2256
2257 assert_return(s, NULL);
2258
2259 ret = s->userdata;
2260 s->userdata = userdata;
2261
2262 return ret;
2263}
2264
2265void* varlink_server_get_userdata(VarlinkServer *s) {
2266 assert_return(s, NULL);
2267
2268 return s->userdata;
2269}
2270
2271static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
2272 if (!ss)
2273 return NULL;
2274
2275 if (ss->server)
2276 LIST_REMOVE(sockets, ss->server->sockets, ss);
2277
1d3fe304 2278 sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
2279
2280 free(ss->address);
2281 safe_close(ss->fd);
2282
2283 return mfree(ss);
2284}
2285
2286int varlink_server_shutdown(VarlinkServer *s) {
2287 assert_return(s, -EINVAL);
2288
2289 while (s->sockets)
2290 varlink_server_socket_destroy(s->sockets);
2291
2292 return 0;
2293}
2294
2295int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
2296 VarlinkServerSocket *ss;
2297 int r;
2298
2299 assert_return(s, -EINVAL);
2300 assert_return(!s->event, -EBUSY);
2301
2302 if (e)
2303 s->event = sd_event_ref(e);
2304 else {
2305 r = sd_event_default(&s->event);
2306 if (r < 0)
2307 return r;
2308 }
2309
2310 LIST_FOREACH(sockets, ss, s->sockets) {
2311 assert(!ss->event_source);
2312
2313 r = sd_event_add_io(s->event, &ss->event_source, ss->fd, EPOLLIN, connect_callback, ss);
2314 if (r < 0)
2315 goto fail;
2316
2317 r = sd_event_source_set_priority(ss->event_source, priority);
2318 if (r < 0)
2319 goto fail;
2320 }
2321
2322 s->event_priority = priority;
2323 return 0;
2324
2325fail:
2326 varlink_server_detach_event(s);
2327 return r;
2328}
2329
2330int varlink_server_detach_event(VarlinkServer *s) {
2331 VarlinkServerSocket *ss;
2332
2333 assert_return(s, -EINVAL);
2334
2335 LIST_FOREACH(sockets, ss, s->sockets) {
2336
2337 if (!ss->event_source)
2338 continue;
2339
2340 (void) sd_event_source_set_enabled(ss->event_source, SD_EVENT_OFF);
2341 ss->event_source = sd_event_source_unref(ss->event_source);
2342 }
2343
2344 sd_event_unref(s->event);
2345 return 0;
2346}
2347
2348sd_event *varlink_server_get_event(VarlinkServer *s) {
2349 assert_return(s, NULL);
2350
2351 return s->event;
2352}
2353
2354int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
2355 char *m;
2356 int r;
2357
2358 assert_return(s, -EINVAL);
2359 assert_return(method, -EINVAL);
2360 assert_return(callback, -EINVAL);
2361
2362 if (startswith(method, "org.varlink.service."))
2363 return -EEXIST;
2364
2365 r = hashmap_ensure_allocated(&s->methods, &string_hash_ops);
2366 if (r < 0)
2367 return r;
2368
2369 m = strdup(method);
2370 if (!m)
2371 return -ENOMEM;
2372
2373 r = hashmap_put(s->methods, m, callback);
2374 if (r < 0) {
2375 free(m);
2376 return r;
2377 }
2378
2379 return 0;
2380}
2381
2382int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
2383 va_list ap;
e7b93f97 2384 int r = 0;
d41bd96f
LP
2385
2386 assert_return(s, -EINVAL);
2387
2388 va_start(ap, s);
2389 for (;;) {
2390 VarlinkMethod callback;
2391 const char *method;
2392
2393 method = va_arg(ap, const char *);
2394 if (!method)
2395 break;
2396
2397 callback = va_arg(ap, VarlinkMethod);
2398
2399 r = varlink_server_bind_method(s, method, callback);
2400 if (r < 0)
e7b93f97 2401 break;
d41bd96f 2402 }
e7b93f97 2403 va_end(ap);
d41bd96f 2404
e7b93f97 2405 return r;
d41bd96f
LP
2406}
2407
2408int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
2409 assert_return(s, -EINVAL);
2410
2411 if (callback && s->connect_callback && callback != s->connect_callback)
2412 return -EBUSY;
2413
2414 s->connect_callback = callback;
2415 return 0;
2416}
2417
6d4d6002
LP
2418int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
2419 assert_return(s, -EINVAL);
2420
2421 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
2422 return -EBUSY;
2423
2424 s->disconnect_callback = callback;
2425 return 0;
2426}
2427
d41bd96f 2428unsigned varlink_server_connections_max(VarlinkServer *s) {
88a36d36 2429 int dts;
d41bd96f
LP
2430
2431 /* If a server is specified, return the setting for that server, otherwise the default value */
2432 if (s)
2433 return s->connections_max;
2434
88a36d36
LP
2435 dts = getdtablesize();
2436 assert_se(dts > 0);
d41bd96f
LP
2437
2438 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
88a36d36
LP
2439 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
2440 return dts / 4 * 3;
d41bd96f
LP
2441
2442 return VARLINK_DEFAULT_CONNECTIONS_MAX;
2443}
2444
2445unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
2446 unsigned m;
2447
2448 if (s)
2449 return s->connections_per_uid_max;
2450
2451 /* Make sure to never use up more than ¾th of available connections for a single user */
2452 m = varlink_server_connections_max(NULL);
2453 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
2454 return m / 4 * 3;
2455
2456 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
2457}
2458
2459int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
2460 assert_return(s, -EINVAL);
2461 assert_return(m > 0, -EINVAL);
2462
2463 s->connections_per_uid_max = m;
2464 return 0;
2465}
2466
2467int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
2468 assert_return(s, -EINVAL);
2469 assert_return(m > 0, -EINVAL);
2470
2471 s->connections_max = m;
2472 return 0;
2473}
2474
c4f601f2
LP
2475unsigned varlink_server_current_connections(VarlinkServer *s) {
2476 assert_return(s, UINT_MAX);
2477
2478 return s->n_connections;
2479}
2480
d41bd96f
LP
2481int varlink_server_set_description(VarlinkServer *s, const char *description) {
2482 assert_return(s, -EINVAL);
2483
2484 return free_and_strdup(&s->description, description);
2485}