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