]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/varlink.c
util: define initializer for 'struct ucred' that properly invalidates all fields
[thirdparty/systemd.git] / src / shared / varlink.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
d41bd96f 2
319a4f4b 3#include <malloc.h>
2b6c0bb2 4#include <poll.h>
d41bd96f
LP
5
6#include "alloc-util.h"
7#include "errno-util.h"
8#include "fd-util.h"
9#include "hashmap.h"
0f2d351f 10#include "io-util.h"
d41bd96f
LP
11#include "list.h"
12#include "process-util.h"
63e00ccd 13#include "selinux-util.h"
d41bd96f
LP
14#include "set.h"
15#include "socket-util.h"
16#include "string-table.h"
17#include "string-util.h"
18#include "strv.h"
19#include "time-util.h"
20#include "umask-util.h"
21#include "user-util.h"
22#include "varlink.h"
23
24#define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
25#define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
26
27#define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
28#define VARLINK_BUFFER_MAX (16U*1024U*1024U)
29#define VARLINK_READ_SIZE (64U*1024U)
30
31typedef enum VarlinkState {
32 /* Client side states */
33 VARLINK_IDLE_CLIENT,
34 VARLINK_AWAITING_REPLY,
45a6c965 35 VARLINK_AWAITING_REPLY_MORE,
d41bd96f
LP
36 VARLINK_CALLING,
37 VARLINK_CALLED,
38 VARLINK_PROCESSING_REPLY,
39
40 /* Server side states */
41 VARLINK_IDLE_SERVER,
42 VARLINK_PROCESSING_METHOD,
43 VARLINK_PROCESSING_METHOD_MORE,
44 VARLINK_PROCESSING_METHOD_ONEWAY,
45 VARLINK_PROCESSED_METHOD,
d41bd96f
LP
46 VARLINK_PENDING_METHOD,
47 VARLINK_PENDING_METHOD_MORE,
48
49 /* Common states (only during shutdown) */
50 VARLINK_PENDING_DISCONNECT,
51 VARLINK_PENDING_TIMEOUT,
52 VARLINK_PROCESSING_DISCONNECT,
53 VARLINK_PROCESSING_TIMEOUT,
54 VARLINK_PROCESSING_FAILURE,
55 VARLINK_DISCONNECTED,
56
57 _VARLINK_STATE_MAX,
2d93c20e 58 _VARLINK_STATE_INVALID = -EINVAL,
d41bd96f
LP
59} VarlinkState;
60
61/* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
62 * is still good for something, and false only when it's dead for good. This means: when we are
63 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
64 * the connection is still good, and we are likely to be able to properly operate on it soon. */
65#define VARLINK_STATE_IS_ALIVE(state) \
66 IN_SET(state, \
67 VARLINK_IDLE_CLIENT, \
68 VARLINK_AWAITING_REPLY, \
45a6c965 69 VARLINK_AWAITING_REPLY_MORE, \
d41bd96f
LP
70 VARLINK_CALLING, \
71 VARLINK_CALLED, \
72 VARLINK_PROCESSING_REPLY, \
73 VARLINK_IDLE_SERVER, \
74 VARLINK_PROCESSING_METHOD, \
75 VARLINK_PROCESSING_METHOD_MORE, \
76 VARLINK_PROCESSING_METHOD_ONEWAY, \
77 VARLINK_PROCESSED_METHOD, \
d41bd96f
LP
78 VARLINK_PENDING_METHOD, \
79 VARLINK_PENDING_METHOD_MORE)
80
81struct Varlink {
82 unsigned n_ref;
83
84 VarlinkServer *server;
85
86 VarlinkState state;
87 bool connecting; /* This boolean indicates whether the socket fd we are operating on is currently
88 * processing an asynchronous connect(). In that state we watch the socket for
89 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
90 * will trigger ENOTCONN. Note that this boolean is kept separate from the
91 * VarlinkState above on purpose: while the connect() is still not complete we
92 * already want to allow queuing of messages and similar. Thus it's nice to keep
93 * these two state concepts separate: the VarlinkState encodes what our own view of
94 * the connection is, i.e. whether we think it's a server, a client, and has
95 * something queued already, while 'connecting' tells us a detail about the
96 * transport used below, that should have no effect on how we otherwise accept and
97 * process operations from the user.
98 *
99 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
100 * connection is good to use, even if it might not be fully connected
101 * yet. connecting=true then informs you that actually we are still connecting, and
102 * the connection is actually not established yet and thus any requests you enqueue
103 * now will still work fine but will be queued only, not sent yet, but that
104 * shouldn't stop you from using the connection, since eventually whatever you queue
105 * *will* be sent.
106 *
107 * Or to say this even differently: 'state' is a high-level ("application layer"
108 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
109 * low, if you so will) state, and while they are not entirely unrelated and
110 * sometimes propagate effects to each other they are only asynchronously connected
111 * at most. */
112 unsigned n_pending;
113
114 int fd;
115
116 char *input_buffer; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
d41bd96f
LP
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 */
d41bd96f
LP
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) {
f35e9b10 224 return (v ? v->description : NULL) ?: "varlink";
d41bd96f
LP
225}
226
227static inline const char *varlink_server_description(VarlinkServer *s) {
f35e9b10 228 return (s ? s->description : NULL) ?: "varlink";
d41bd96f
LP
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)
953394e3 236 varlink_log(v, "Setting state %s",
77740b59
ZJS
237 varlink_state_to_string(state));
238 else
953394e3 239 varlink_log(v, "Changing state %s → %s",
77740b59
ZJS
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
a995ce47 261 .ucred = UCRED_INVALID,
d41bd96f
LP
262
263 .timestamp = USEC_INFINITY,
264 .timeout = VARLINK_DEFAULT_TIMEOUT_USEC
265 };
266
267 *ret = v;
268 return 0;
269}
270
271int varlink_connect_address(Varlink **ret, const char *address) {
272 _cleanup_(varlink_unrefp) Varlink *v = NULL;
273 union sockaddr_union sockaddr;
f36a9d59 274 socklen_t sockaddr_len;
d41bd96f
LP
275 int r;
276
277 assert_return(ret, -EINVAL);
278 assert_return(address, -EINVAL);
279
280 r = sockaddr_un_set_path(&sockaddr.un, address);
281 if (r < 0)
db3d4222 282 return log_debug_errno(r, "Failed to set socket address '%s': %m", address);
f36a9d59 283 sockaddr_len = r;
d41bd96f
LP
284
285 r = varlink_new(&v);
286 if (r < 0)
db3d4222 287 return log_debug_errno(r, "Failed to create varlink object: %m");
d41bd96f
LP
288
289 v->fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
290 if (v->fd < 0)
db3d4222 291 return log_debug_errno(errno, "Failed to create AF_UNIX socket: %m");
d41bd96f 292
a0c41de2
LP
293 v->fd = fd_move_above_stdio(v->fd);
294
f36a9d59 295 if (connect(v->fd, &sockaddr.sa, sockaddr_len) < 0) {
d41bd96f 296 if (!IN_SET(errno, EAGAIN, EINPROGRESS))
db3d4222 297 return log_debug_errno(errno, "Failed to connect to %s: %m", address);
d41bd96f
LP
298
299 v->connecting = true; /* We are asynchronously connecting, i.e. the connect() is being
300 * processed in the background. As long as that's the case the socket
301 * is in a special state: it's there, we can poll it for EPOLLOUT, but
302 * if we attempt to write() to it before we see EPOLLOUT we'll get
303 * ENOTCONN (and not EAGAIN, like we would for a normal connected
304 * socket that isn't writable at the moment). Since ENOTCONN on write()
305 * hence can mean two different things (i.e. connection not complete
306 * yet vs. already disconnected again), we store as a boolean whether
307 * we are still in connect(). */
308 }
309
310 varlink_set_state(v, VARLINK_IDLE_CLIENT);
311
312 *ret = TAKE_PTR(v);
db3d4222 313 return 0;
d41bd96f
LP
314}
315
316int varlink_connect_fd(Varlink **ret, int fd) {
317 Varlink *v;
318 int r;
319
320 assert_return(ret, -EINVAL);
321 assert_return(fd >= 0, -EBADF);
322
323 r = fd_nonblock(fd, true);
324 if (r < 0)
db3d4222 325 return log_debug_errno(r, "Failed to make fd %d nonblocking: %m", fd);
d41bd96f
LP
326
327 r = varlink_new(&v);
328 if (r < 0)
db3d4222 329 return log_debug_errno(r, "Failed to create varlink object: %m");
d41bd96f
LP
330
331 v->fd = fd;
332 varlink_set_state(v, VARLINK_IDLE_CLIENT);
333
334 /* Note that if this function is called we assume the passed socket (if it is one) is already
335 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
336 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
337 * until the connection is fully set up. Behaviour here is hence a bit different from
338 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
339 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
340
341 *ret = v;
342 return 0;
343}
344
345static void varlink_detach_event_sources(Varlink *v) {
346 assert(v);
347
1d3fe304 348 v->io_event_source = sd_event_source_disable_unref(v->io_event_source);
1d3fe304 349 v->time_event_source = sd_event_source_disable_unref(v->time_event_source);
1d3fe304 350 v->quit_event_source = sd_event_source_disable_unref(v->quit_event_source);
1d3fe304 351 v->defer_event_source = sd_event_source_disable_unref(v->defer_event_source);
d41bd96f
LP
352}
353
354static void varlink_clear(Varlink *v) {
355 assert(v);
356
357 varlink_detach_event_sources(v);
358
359 v->fd = safe_close(v->fd);
360
361 v->input_buffer = mfree(v->input_buffer);
362 v->output_buffer = mfree(v->output_buffer);
363
364 v->current = json_variant_unref(v->current);
365 v->reply = json_variant_unref(v->reply);
366
367 v->event = sd_event_unref(v->event);
368}
369
370static Varlink* varlink_destroy(Varlink *v) {
371 if (!v)
372 return NULL;
373
374 /* If this is called the server object must already been unreffed here. Why that? because when we
375 * linked up the varlink connection with the server object we took one ref in each direction */
376 assert(!v->server);
377
378 varlink_clear(v);
379
380 free(v->description);
381 return mfree(v);
382}
383
384DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink, varlink, varlink_destroy);
385
386static int varlink_test_disconnect(Varlink *v) {
387 assert(v);
388
37b22b3b 389 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
d41bd96f
LP
390 * prematurely, since we want to handle half-open connections as well as possible and want to flush
391 * out and read data before we close down if we can. */
392
393 /* Already disconnected? */
394 if (!VARLINK_STATE_IS_ALIVE(v->state))
395 return 0;
396
397 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
398 if (v->connecting)
399 return 0;
400
401 /* Still something to write and we can write? Stay around */
402 if (v->output_buffer_size > 0 && !v->write_disconnected)
403 return 0;
404
405 /* Both sides gone already? Then there's no need to stick around */
406 if (v->read_disconnected && v->write_disconnected)
407 goto disconnect;
408
409 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
45a6c965 410 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER) && v->read_disconnected)
d41bd96f
LP
411 goto disconnect;
412
413 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
414 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
415 * being down if we never wrote anything. */
416 if (IN_SET(v->state, VARLINK_IDLE_CLIENT) && (v->write_disconnected || v->got_pollhup))
417 goto disconnect;
418
e8e9227f
AZ
419 /* The server is still expecting to write more, but its write end is disconnected and it got a POLLHUP
420 * (i.e. from a disconnected client), so disconnect. */
421 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE) && v->write_disconnected && v->got_pollhup)
422 goto disconnect;
423
d41bd96f
LP
424 return 0;
425
426disconnect:
427 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
428 return 1;
429}
430
431static int varlink_write(Varlink *v) {
432 ssize_t n;
433
434 assert(v);
435
436 if (!VARLINK_STATE_IS_ALIVE(v->state))
437 return 0;
438 if (v->connecting) /* Writing while we are still wait for a non-blocking connect() to complete will
439 * result in ENOTCONN, hence exit early here */
440 return 0;
441 if (v->output_buffer_size == 0)
442 return 0;
443 if (v->write_disconnected)
444 return 0;
445
446 assert(v->fd >= 0);
447
448 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
4990d4b8
ZJS
449 * with non-socket IO, hence fall back automatically.
450 *
451 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
452 bool prefer_write = v->prefer_read_write;
453 if (!prefer_write) {
d41bd96f
LP
454 n = send(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size, MSG_DONTWAIT|MSG_NOSIGNAL);
455 if (n < 0 && errno == ENOTSOCK)
4990d4b8 456 prefer_write = v->prefer_read_write = true;
d41bd96f 457 }
4990d4b8 458 if (prefer_write)
d41bd96f
LP
459 n = write(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size);
460 if (n < 0) {
461 if (errno == EAGAIN)
462 return 0;
463
464 if (ERRNO_IS_DISCONNECT(errno)) {
465 /* If we get informed about a disconnect on write, then let's remember that, but not
466 * act on it just yet. Let's wait for read() to report the issue first. */
467 v->write_disconnected = true;
468 return 1;
469 }
470
471 return -errno;
472 }
473
474 v->output_buffer_size -= n;
475
476 if (v->output_buffer_size == 0)
477 v->output_buffer_index = 0;
478 else
479 v->output_buffer_index += n;
480
481 v->timestamp = now(CLOCK_MONOTONIC);
482 return 1;
483}
484
485static int varlink_read(Varlink *v) {
486 size_t rs;
487 ssize_t n;
488
489 assert(v);
490
45a6c965 491 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER))
d41bd96f
LP
492 return 0;
493 if (v->connecting) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
494 return 0;
495 if (v->current)
496 return 0;
497 if (v->input_buffer_unscanned > 0)
498 return 0;
499 if (v->read_disconnected)
500 return 0;
501
502 if (v->input_buffer_size >= VARLINK_BUFFER_MAX)
503 return -ENOBUFS;
504
505 assert(v->fd >= 0);
506
319a4f4b 507 if (MALLOC_SIZEOF_SAFE(v->input_buffer) <= v->input_buffer_index + v->input_buffer_size) {
d41bd96f
LP
508 size_t add;
509
510 add = MIN(VARLINK_BUFFER_MAX - v->input_buffer_size, VARLINK_READ_SIZE);
511
512 if (v->input_buffer_index == 0) {
513
319a4f4b 514 if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_size + add))
d41bd96f
LP
515 return -ENOMEM;
516
517 } else {
518 char *b;
519
520 b = new(char, v->input_buffer_size + add);
521 if (!b)
522 return -ENOMEM;
523
524 memcpy(b, v->input_buffer + v->input_buffer_index, v->input_buffer_size);
525
526 free_and_replace(v->input_buffer, b);
d41bd96f
LP
527 v->input_buffer_index = 0;
528 }
529 }
530
319a4f4b 531 rs = MALLOC_SIZEOF_SAFE(v->input_buffer) - (v->input_buffer_index + v->input_buffer_size);
d41bd96f 532
4990d4b8
ZJS
533 bool prefer_read = v->prefer_read_write;
534 if (!prefer_read) {
d41bd96f
LP
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)
4990d4b8 537 prefer_read = v->prefer_read_write = true;
d41bd96f 538 }
4990d4b8 539 if (prefer_read)
d41bd96f
LP
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);
319a4f4b 576 assert(v->input_buffer_index + v->input_buffer_size <= MALLOC_SIZEOF_SAFE(v->input_buffer));
d41bd96f
LP
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:
04499a70 907 assert_not_reached();
d41bd96f
LP
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
cc6b0a18
LP
1209 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1210 * which would destroy us before we can call varlink_clear() */
d41bd96f
LP
1211 varlink_ref(v);
1212 varlink_detach_server(v);
1213 varlink_clear(v);
1214 varlink_unref(v);
1215
1216 return 1;
1217}
1218
9652d740 1219Varlink* varlink_close_unref(Varlink *v) {
9652d740
LP
1220 if (!v)
1221 return NULL;
1222
cc6b0a18 1223 (void) varlink_close(v);
9652d740
LP
1224 return varlink_unref(v);
1225}
1226
d41bd96f 1227Varlink* varlink_flush_close_unref(Varlink *v) {
cc6b0a18
LP
1228 if (!v)
1229 return NULL;
d41bd96f 1230
cc6b0a18 1231 (void) varlink_flush(v);
39ad3f1c 1232 return varlink_close_unref(v);
d41bd96f
LP
1233}
1234
1235static int varlink_enqueue_json(Varlink *v, JsonVariant *m) {
1236 _cleanup_free_ char *text = NULL;
1237 int r;
1238
1239 assert(v);
1240 assert(m);
1241
1242 r = json_variant_format(m, 0, &text);
1243 if (r < 0)
1244 return r;
2a04712c 1245 assert(text[r] == '\0');
d41bd96f
LP
1246
1247 if (v->output_buffer_size + r + 1 > VARLINK_BUFFER_MAX)
1248 return -ENOBUFS;
1249
1250 varlink_log(v, "Sending message: %s", text);
1251
1252 if (v->output_buffer_size == 0) {
1253
1254 free_and_replace(v->output_buffer, text);
1255
319a4f4b 1256 v->output_buffer_size = r + 1;
d41bd96f
LP
1257 v->output_buffer_index = 0;
1258
1259 } else if (v->output_buffer_index == 0) {
1260
319a4f4b 1261 if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_size + r + 1))
d41bd96f
LP
1262 return -ENOMEM;
1263
1264 memcpy(v->output_buffer + v->output_buffer_size, text, r + 1);
1265 v->output_buffer_size += r + 1;
1266
1267 } else {
1268 char *n;
be44e091 1269 const size_t new_size = v->output_buffer_size + r + 1;
d41bd96f 1270
be44e091 1271 n = new(char, new_size);
d41bd96f
LP
1272 if (!n)
1273 return -ENOMEM;
1274
1275 memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, r + 1);
1276
1277 free_and_replace(v->output_buffer, n);
319a4f4b 1278 v->output_buffer_size = new_size;
d41bd96f
LP
1279 v->output_buffer_index = 0;
1280 }
1281
1282 return 0;
1283}
1284
1285int varlink_send(Varlink *v, const char *method, JsonVariant *parameters) {
1286 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1287 int r;
1288
1289 assert_return(v, -EINVAL);
1290 assert_return(method, -EINVAL);
1291
1292 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1293 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965
LP
1294
1295 /* We allow enqueuing multiple method calls at once! */
d41bd96f 1296 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 1297 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1298
1299 r = varlink_sanitize_parameters(&parameters);
1300 if (r < 0)
db3d4222 1301 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1302
1303 r = json_build(&m, JSON_BUILD_OBJECT(
1304 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1305 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1306 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1307 if (r < 0)
db3d4222 1308 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1309
1310 r = varlink_enqueue_json(v, m);
1311 if (r < 0)
db3d4222 1312 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1313
1314 /* No state change here, this is one-way only after all */
1315 v->timestamp = now(CLOCK_MONOTONIC);
1316 return 0;
1317}
1318
1319int varlink_sendb(Varlink *v, const char *method, ...) {
1320 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1321 va_list ap;
1322 int r;
1323
1324 assert_return(v, -EINVAL);
1325
1326 va_start(ap, method);
1327 r = json_buildv(&parameters, ap);
1328 va_end(ap);
1329
1330 if (r < 0)
db3d4222 1331 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1332
1333 return varlink_send(v, method, parameters);
1334}
1335
1336int varlink_invoke(Varlink *v, const char *method, JsonVariant *parameters) {
1337 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1338 int r;
1339
1340 assert_return(v, -EINVAL);
1341 assert_return(method, -EINVAL);
1342
1343 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1344 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965 1345
86b52a39 1346 /* We allow enqueuing multiple method calls at once! */
d41bd96f 1347 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 1348 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1349
1350 r = varlink_sanitize_parameters(&parameters);
1351 if (r < 0)
db3d4222 1352 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1353
1354 r = json_build(&m, JSON_BUILD_OBJECT(
1355 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1356 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1357 if (r < 0)
db3d4222 1358 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1359
1360 r = varlink_enqueue_json(v, m);
1361 if (r < 0)
db3d4222 1362 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1363
1364 varlink_set_state(v, VARLINK_AWAITING_REPLY);
1365 v->n_pending++;
1366 v->timestamp = now(CLOCK_MONOTONIC);
1367
1368 return 0;
1369}
1370
1371int varlink_invokeb(Varlink *v, const char *method, ...) {
1372 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1373 va_list ap;
1374 int r;
1375
1376 assert_return(v, -EINVAL);
1377
1378 va_start(ap, method);
1379 r = json_buildv(&parameters, ap);
1380 va_end(ap);
1381
1382 if (r < 0)
db3d4222 1383 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1384
1385 return varlink_invoke(v, method, parameters);
45a6c965
LP
1386}
1387
1388int varlink_observe(Varlink *v, const char *method, JsonVariant *parameters) {
1389 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1390 int r;
1391
1392 assert_return(v, -EINVAL);
1393 assert_return(method, -EINVAL);
1394
1395 if (v->state == VARLINK_DISCONNECTED)
db3d4222
ZJS
1396 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1397
45a6c965
LP
1398 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1399 * thus insist on an idle client here. */
1400 if (v->state != VARLINK_IDLE_CLIENT)
db3d4222 1401 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
45a6c965
LP
1402
1403 r = varlink_sanitize_parameters(&parameters);
1404 if (r < 0)
db3d4222 1405 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
45a6c965
LP
1406
1407 r = json_build(&m, JSON_BUILD_OBJECT(
1408 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1409 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1410 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1411 if (r < 0)
db3d4222 1412 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
1413
1414 r = varlink_enqueue_json(v, m);
1415 if (r < 0)
db3d4222 1416 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
45a6c965
LP
1417
1418 varlink_set_state(v, VARLINK_AWAITING_REPLY_MORE);
1419 v->n_pending++;
1420 v->timestamp = now(CLOCK_MONOTONIC);
1421
1422 return 0;
1423}
1424
1425int varlink_observeb(Varlink *v, const char *method, ...) {
1426 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1427 va_list ap;
1428 int r;
1429
1430 assert_return(v, -EINVAL);
1431
1432 va_start(ap, method);
1433 r = json_buildv(&parameters, ap);
1434 va_end(ap);
1435
1436 if (r < 0)
db3d4222 1437 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
1438
1439 return varlink_observe(v, method, parameters);
d41bd96f
LP
1440}
1441
1442int varlink_call(
1443 Varlink *v,
1444 const char *method,
1445 JsonVariant *parameters,
1446 JsonVariant **ret_parameters,
1447 const char **ret_error_id,
1448 VarlinkReplyFlags *ret_flags) {
1449
1450 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1451 int r;
1452
1453 assert_return(v, -EINVAL);
1454 assert_return(method, -EINVAL);
1455
1456 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1457 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f 1458 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT))
db3d4222 1459 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1460
1461 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1462
1463 r = varlink_sanitize_parameters(&parameters);
1464 if (r < 0)
db3d4222 1465 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1466
1467 r = json_build(&m, JSON_BUILD_OBJECT(
1468 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1469 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1470 if (r < 0)
db3d4222 1471 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1472
1473 r = varlink_enqueue_json(v, m);
1474 if (r < 0)
db3d4222 1475 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1476
1477 varlink_set_state(v, VARLINK_CALLING);
1478 v->n_pending++;
1479 v->timestamp = now(CLOCK_MONOTONIC);
1480
1481 while (v->state == VARLINK_CALLING) {
1482
1483 r = varlink_process(v);
1484 if (r < 0)
1485 return r;
1486 if (r > 0)
1487 continue;
1488
1489 r = varlink_wait(v, USEC_INFINITY);
1490 if (r < 0)
1491 return r;
1492 }
1493
1494 switch (v->state) {
1495
1496 case VARLINK_CALLED:
1497 assert(v->current);
1498
1499 json_variant_unref(v->reply);
1500 v->reply = TAKE_PTR(v->current);
1501
1502 varlink_set_state(v, VARLINK_IDLE_CLIENT);
1503 assert(v->n_pending == 1);
1504 v->n_pending--;
1505
1506 if (ret_parameters)
1507 *ret_parameters = json_variant_by_key(v->reply, "parameters");
1508 if (ret_error_id)
1509 *ret_error_id = json_variant_string(json_variant_by_key(v->reply, "error"));
1510 if (ret_flags)
1511 *ret_flags = 0;
1512
1513 return 1;
1514
1515 case VARLINK_PENDING_DISCONNECT:
1516 case VARLINK_DISCONNECTED:
db3d4222 1517 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
d41bd96f
LP
1518
1519 case VARLINK_PENDING_TIMEOUT:
db3d4222 1520 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
d41bd96f
LP
1521
1522 default:
04499a70 1523 assert_not_reached();
d41bd96f
LP
1524 }
1525}
1526
1527int varlink_callb(
1528 Varlink *v,
1529 const char *method,
1530 JsonVariant **ret_parameters,
1531 const char **ret_error_id,
1532 VarlinkReplyFlags *ret_flags, ...) {
1533
1534 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1535 va_list ap;
1536 int r;
1537
1538 assert_return(v, -EINVAL);
1539
1540 va_start(ap, ret_flags);
1541 r = json_buildv(&parameters, ap);
1542 va_end(ap);
1543
1544 if (r < 0)
db3d4222 1545 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1546
1547 return varlink_call(v, method, parameters, ret_parameters, ret_error_id, ret_flags);
1548}
1549
1550int varlink_reply(Varlink *v, JsonVariant *parameters) {
1551 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1552 int r;
1553
1554 assert_return(v, -EINVAL);
1555
1556 if (v->state == VARLINK_DISCONNECTED)
1557 return -ENOTCONN;
1558 if (!IN_SET(v->state,
1559 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1560 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1561 return -EBUSY;
1562
1563 r = varlink_sanitize_parameters(&parameters);
1564 if (r < 0)
db3d4222 1565 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1566
1567 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1568 if (r < 0)
db3d4222 1569 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1570
1571 r = varlink_enqueue_json(v, m);
1572 if (r < 0)
db3d4222 1573 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1574
1575 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1576 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1577 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1578 * process further messages. */
1579 v->current = json_variant_unref(v->current);
1580 varlink_set_state(v, VARLINK_IDLE_SERVER);
1581 } else
1582 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1583 * means we should it handle the rest of the state engine. */
1584 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1585
1586 return 1;
1587}
1588
1589int varlink_replyb(Varlink *v, ...) {
1590 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1591 va_list ap;
1592 int r;
1593
1594 assert_return(v, -EINVAL);
1595
1596 va_start(ap, v);
1597 r = json_buildv(&parameters, ap);
1598 va_end(ap);
1599
1600 if (r < 0)
1601 return r;
1602
1603 return varlink_reply(v, parameters);
1604}
1605
1606int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
1607 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1608 int r;
1609
1610 assert_return(v, -EINVAL);
1611 assert_return(error_id, -EINVAL);
1612
1613 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1614 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1615 if (!IN_SET(v->state,
1616 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1617 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
db3d4222 1618 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1619
1620 r = varlink_sanitize_parameters(&parameters);
1621 if (r < 0)
db3d4222 1622 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1623
1624 r = json_build(&m, JSON_BUILD_OBJECT(
1625 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
1626 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1627 if (r < 0)
db3d4222 1628 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1629
1630 r = varlink_enqueue_json(v, m);
1631 if (r < 0)
db3d4222 1632 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1633
1634 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1635 v->current = json_variant_unref(v->current);
1636 varlink_set_state(v, VARLINK_IDLE_SERVER);
1637 } else
1638 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1639
1640 return 1;
1641}
1642
1643int varlink_errorb(Varlink *v, const char *error_id, ...) {
1644 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1645 va_list ap;
1646 int r;
1647
1648 assert_return(v, -EINVAL);
1649 assert_return(error_id, -EINVAL);
1650
1651 va_start(ap, error_id);
1652 r = json_buildv(&parameters, ap);
1653 va_end(ap);
1654
1655 if (r < 0)
db3d4222 1656 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1657
1658 return varlink_error(v, error_id, parameters);
1659}
1660
1661int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
1662
1663 assert_return(v, -EINVAL);
1664 assert_return(parameters, -EINVAL);
1665
1666 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1667 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1668 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1669 * don't expect any arguments. */
1670
1671 if (json_variant_is_string(parameters))
1672 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters);
1673
1674 if (json_variant_is_object(parameters) &&
1675 json_variant_elements(parameters) > 0)
1676 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER,
1677 json_variant_by_index(parameters, 0));
1678
1679 return -EINVAL;
1680}
1681
7466e94f
LP
1682int varlink_error_errno(Varlink *v, int error) {
1683 return varlink_errorb(
1684 v,
1685 VARLINK_ERROR_SYSTEM,
1686 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error)))));
1687}
1688
d41bd96f
LP
1689int varlink_notify(Varlink *v, JsonVariant *parameters) {
1690 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1691 int r;
1692
1693 assert_return(v, -EINVAL);
1694
1695 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1696 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f 1697 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
db3d4222 1698 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1699
1700 r = varlink_sanitize_parameters(&parameters);
1701 if (r < 0)
db3d4222 1702 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1703
1704 r = json_build(&m, JSON_BUILD_OBJECT(
1705 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1706 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
1707 if (r < 0)
db3d4222 1708 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1709
1710 r = varlink_enqueue_json(v, m);
1711 if (r < 0)
db3d4222 1712 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1713
1714 /* No state change, as more is coming */
1715 return 1;
1716}
1717
1718int varlink_notifyb(Varlink *v, ...) {
1719 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1720 va_list ap;
1721 int r;
1722
1723 assert_return(v, -EINVAL);
1724
1725 va_start(ap, v);
1726 r = json_buildv(&parameters, ap);
1727 va_end(ap);
1728
1729 if (r < 0)
db3d4222 1730 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1731
1732 return varlink_notify(v, parameters);
1733}
1734
1735int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
1736 assert_return(v, -EINVAL);
1737
1738 if (callback && v->reply_callback && callback != v->reply_callback)
db3d4222 1739 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
1740
1741 v->reply_callback = callback;
1742
1743 return 0;
1744}
1745
1746void* varlink_set_userdata(Varlink *v, void *userdata) {
1747 void *old;
1748
1749 assert_return(v, NULL);
1750
1751 old = v->userdata;
1752 v->userdata = userdata;
1753
1754 return old;
1755}
1756
1757void* varlink_get_userdata(Varlink *v) {
1758 assert_return(v, NULL);
1759
1760 return v->userdata;
1761}
1762
1763static int varlink_acquire_ucred(Varlink *v) {
1764 int r;
1765
1766 assert(v);
1767
1768 if (v->ucred_acquired)
1769 return 0;
1770
1771 r = getpeercred(v->fd, &v->ucred);
1772 if (r < 0)
1773 return r;
1774
1775 v->ucred_acquired = true;
1776 return 0;
1777}
1778
1779int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
1780 int r;
1781
1782 assert_return(v, -EINVAL);
1783 assert_return(ret, -EINVAL);
1784
1785 r = varlink_acquire_ucred(v);
1786 if (r < 0)
db3d4222 1787 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
1788
1789 if (!uid_is_valid(v->ucred.uid))
db3d4222 1790 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
1791
1792 *ret = v->ucred.uid;
1793 return 0;
1794}
1795
1796int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
1797 int r;
1798
1799 assert_return(v, -EINVAL);
1800 assert_return(ret, -EINVAL);
1801
1802 r = varlink_acquire_ucred(v);
1803 if (r < 0)
db3d4222 1804 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
1805
1806 if (!pid_is_valid(v->ucred.pid))
db3d4222 1807 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
1808
1809 *ret = v->ucred.pid;
1810 return 0;
1811}
1812
1813int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
1814 assert_return(v, -EINVAL);
1815 assert_return(timeout > 0, -EINVAL);
1816
1817 v->timeout = timeout;
1818 return 0;
1819}
1820
1821VarlinkServer *varlink_get_server(Varlink *v) {
1822 assert_return(v, NULL);
1823
1824 return v->server;
1825}
1826
1827int varlink_set_description(Varlink *v, const char *description) {
1828 assert_return(v, -EINVAL);
1829
1830 return free_and_strdup(&v->description, description);
1831}
1832
1833static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1834 Varlink *v = userdata;
1835
1836 assert(s);
1837 assert(v);
1838
1839 handle_revents(v, revents);
1840 (void) varlink_process(v);
1841
1842 return 1;
1843}
1844
1845static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1846 Varlink *v = userdata;
1847
1848 assert(s);
1849 assert(v);
1850
1851 (void) varlink_process(v);
1852 return 1;
1853}
1854
1855static int defer_callback(sd_event_source *s, void *userdata) {
1856 Varlink *v = userdata;
1857
1858 assert(s);
1859 assert(v);
1860
1861 (void) varlink_process(v);
1862 return 1;
1863}
1864
1865static int prepare_callback(sd_event_source *s, void *userdata) {
1866 Varlink *v = userdata;
1867 int r, e;
1868 usec_t until;
f1194f5d 1869 bool have_timeout;
d41bd96f
LP
1870
1871 assert(s);
1872 assert(v);
1873
1874 e = varlink_get_events(v);
1875 if (e < 0)
1876 return e;
1877
1878 r = sd_event_source_set_io_events(v->io_event_source, e);
1879 if (r < 0)
db3d4222 1880 return varlink_log_errno(v, r, "Failed to set source events: %m");
d41bd96f
LP
1881
1882 r = varlink_get_timeout(v, &until);
1883 if (r < 0)
1884 return r;
f1194f5d
LP
1885 have_timeout = r > 0;
1886
1887 if (have_timeout) {
d41bd96f
LP
1888 r = sd_event_source_set_time(v->time_event_source, until);
1889 if (r < 0)
db3d4222 1890 return varlink_log_errno(v, r, "Failed to set source time: %m");
d41bd96f
LP
1891 }
1892
f1194f5d 1893 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
d41bd96f 1894 if (r < 0)
db3d4222 1895 return varlink_log_errno(v, r, "Failed to enable event source: %m");
d41bd96f
LP
1896
1897 return 1;
1898}
1899
1900static int quit_callback(sd_event_source *event, void *userdata) {
1901 Varlink *v = userdata;
1902
1903 assert(event);
1904 assert(v);
1905
1906 varlink_flush(v);
1907 varlink_close(v);
1908
1909 return 1;
1910}
1911
1912int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
1913 int r;
1914
1915 assert_return(v, -EINVAL);
1916 assert_return(!v->event, -EBUSY);
1917
1918 if (e)
1919 v->event = sd_event_ref(e);
1920 else {
1921 r = sd_event_default(&v->event);
1922 if (r < 0)
db3d4222 1923 return varlink_log_errno(v, r, "Failed to create event source: %m");
d41bd96f
LP
1924 }
1925
1926 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
1927 if (r < 0)
1928 goto fail;
1929
1930 r = sd_event_source_set_priority(v->time_event_source, priority);
1931 if (r < 0)
1932 goto fail;
1933
1934 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
1935
1936 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
1937 if (r < 0)
1938 goto fail;
1939
1940 r = sd_event_source_set_priority(v->quit_event_source, priority);
1941 if (r < 0)
1942 goto fail;
1943
1944 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
1945
1946 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
1947 if (r < 0)
1948 goto fail;
1949
1950 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
1951 if (r < 0)
1952 goto fail;
1953
1954 r = sd_event_source_set_priority(v->io_event_source, priority);
1955 if (r < 0)
1956 goto fail;
1957
1958 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
1959
1960 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
1961 if (r < 0)
1962 goto fail;
1963
1964 r = sd_event_source_set_priority(v->defer_event_source, priority);
1965 if (r < 0)
1966 goto fail;
1967
1968 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
1969
1970 return 0;
1971
1972fail:
db3d4222 1973 varlink_log_errno(v, r, "Failed to setup event source: %m");
d41bd96f
LP
1974 varlink_detach_event(v);
1975 return r;
1976}
1977
d41bd96f
LP
1978void varlink_detach_event(Varlink *v) {
1979 if (!v)
1980 return;
1981
1982 varlink_detach_event_sources(v);
1983
1984 v->event = sd_event_unref(v->event);
1985}
1986
1987sd_event *varlink_get_event(Varlink *v) {
1988 assert_return(v, NULL);
1989
1990 return v->event;
1991}
1992
1993int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
1994 VarlinkServer *s;
1995
1996 assert_return(ret, -EINVAL);
1997 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
1998
1999 s = new(VarlinkServer, 1);
2000 if (!s)
db3d4222 2001 return log_oom_debug();
d41bd96f
LP
2002
2003 *s = (VarlinkServer) {
2004 .n_ref = 1,
2005 .flags = flags,
2006 .connections_max = varlink_server_connections_max(NULL),
2007 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
2008 };
2009
2010 *ret = s;
2011 return 0;
2012}
2013
2014static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
2015 char *m;
2016
2017 if (!s)
2018 return NULL;
2019
2020 varlink_server_shutdown(s);
2021
2022 while ((m = hashmap_steal_first_key(s->methods)))
2023 free(m);
2024
2025 hashmap_free(s->methods);
2026 hashmap_free(s->by_uid);
2027
2028 sd_event_unref(s->event);
2029
2030 free(s->description);
2031
2032 return mfree(s);
2033}
2034
2035DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
2036
2037static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
2038 int allowed = -1;
2039
2040 assert(server);
2041 assert(ucred);
2042
2043 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
2044 allowed = ucred->uid == 0;
2045
2046 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
2047 allowed = allowed > 0 || ucred->uid == getuid();
2048
2049 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
2050 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2051 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
2052 return 0;
2053 }
2054
2055 if (server->n_connections >= server->connections_max) {
2056 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
2057 return 0;
2058 }
2059
2060 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2061 unsigned c;
2062
2063 if (!uid_is_valid(ucred->uid)) {
2064 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
2065 return 0;
2066 }
2067
2068 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2069 if (c >= server->connections_per_uid_max) {
2070 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
2071 server->connections_per_uid_max);
2072 return 0;
2073 }
2074 }
2075
2076 return 1;
2077}
2078
2079static int count_connection(VarlinkServer *server, struct ucred *ucred) {
2080 unsigned c;
2081 int r;
2082
2083 assert(server);
2084 assert(ucred);
2085
2086 server->n_connections++;
2087
2088 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2089 r = hashmap_ensure_allocated(&server->by_uid, NULL);
2090 if (r < 0)
2091 return log_debug_errno(r, "Failed to allocate UID hash table: %m");
2092
2093 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2094
2095 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
2096 ucred->uid, c, server->connections_per_uid_max);
2097
2098 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
2099 if (r < 0)
2100 return log_debug_errno(r, "Failed to increment counter in UID hash table: %m");
2101 }
2102
2103 return 0;
2104}
2105
2106int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
2107 _cleanup_(varlink_unrefp) Varlink *v = NULL;
a995ce47 2108 struct ucred ucred = UCRED_INVALID;
d41bd96f 2109 bool ucred_acquired;
d41bd96f
LP
2110 int r;
2111
2112 assert_return(server, -EINVAL);
2113 assert_return(fd >= 0, -EBADF);
2114
2115 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
2116 r = getpeercred(fd, &ucred);
2117 if (r < 0)
2118 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2119
2120 ucred_acquired = true;
2121
2122 r = validate_connection(server, &ucred);
2123 if (r < 0)
2124 return r;
2125 if (r == 0)
2126 return -EPERM;
2127 } else
2128 ucred_acquired = false;
2129
2130 r = varlink_new(&v);
2131 if (r < 0)
2132 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
2133
2134 r = count_connection(server, &ucred);
2135 if (r < 0)
2136 return r;
2137
2138 v->fd = fd;
9807fdc1
LP
2139 if (server->flags & VARLINK_SERVER_INHERIT_USERDATA)
2140 v->userdata = server->userdata;
2141
d41bd96f
LP
2142 if (ucred_acquired) {
2143 v->ucred = ucred;
2144 v->ucred_acquired = true;
2145 }
2146
12619d0a
ZJS
2147 _cleanup_free_ char *desc = NULL;
2148 if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0)
2149 v->description = TAKE_PTR(desc);
d41bd96f
LP
2150
2151 /* Link up the server and the connection, and take reference in both directions. Note that the
2152 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2153 * which happens in varlink_close(), including in the event loop quit callback. */
2154 v->server = varlink_server_ref(server);
2155 varlink_ref(v);
2156
2157 varlink_set_state(v, VARLINK_IDLE_SERVER);
2158
7e69d90c
LP
2159 if (server->event) {
2160 r = varlink_attach_event(v, server->event, server->event_priority);
2161 if (r < 0) {
2162 varlink_log_errno(v, r, "Failed to attach new connection: %m");
2163 v->fd = -1; /* take the fd out of the connection again */
2164 varlink_close(v);
2165 return r;
2166 }
d41bd96f
LP
2167 }
2168
2169 if (ret)
2170 *ret = v;
2171
2172 return 0;
2173}
2174
2175static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2176 VarlinkServerSocket *ss = userdata;
2177 _cleanup_close_ int cfd = -1;
2178 Varlink *v = NULL;
2179 int r;
2180
2181 assert(source);
2182 assert(ss);
2183
2184 varlink_server_log(ss->server, "New incoming connection.");
2185
2186 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2187 if (cfd < 0) {
2188 if (ERRNO_IS_ACCEPT_AGAIN(errno))
2189 return 0;
2190
2191 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
2192 }
2193
2194 r = varlink_server_add_connection(ss->server, cfd, &v);
2195 if (r < 0)
2196 return 0;
2197
2198 TAKE_FD(cfd);
2199
2200 if (ss->server->connect_callback) {
2201 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
2202 if (r < 0) {
2203 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
2204 varlink_close(v);
2205 return 0;
2206 }
2207 }
2208
2209 return 0;
2210}
2211
2212int varlink_server_listen_fd(VarlinkServer *s, int fd) {
2213 _cleanup_free_ VarlinkServerSocket *ss = NULL;
2214 int r;
2215
2216 assert_return(s, -EINVAL);
2217 assert_return(fd >= 0, -EBADF);
2218
2219 r = fd_nonblock(fd, true);
2220 if (r < 0)
2221 return r;
2222
2223 ss = new(VarlinkServerSocket, 1);
2224 if (!ss)
db3d4222 2225 return log_oom_debug();
d41bd96f
LP
2226
2227 *ss = (VarlinkServerSocket) {
2228 .server = s,
2229 .fd = fd,
2230 };
2231
2232 if (s->event) {
8d91b220 2233 r = sd_event_add_io(s->event, &ss->event_source, fd, EPOLLIN, connect_callback, ss);
d41bd96f
LP
2234 if (r < 0)
2235 return r;
2236
2237 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
2238 if (r < 0)
2239 return r;
2240 }
2241
2242 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
2243 return 0;
2244}
2245
2246int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
2247 union sockaddr_union sockaddr;
f36a9d59 2248 socklen_t sockaddr_len;
d41bd96f
LP
2249 _cleanup_close_ int fd = -1;
2250 int r;
2251
2252 assert_return(s, -EINVAL);
2253 assert_return(address, -EINVAL);
2254 assert_return((m & ~0777) == 0, -EINVAL);
2255
2256 r = sockaddr_un_set_path(&sockaddr.un, address);
2257 if (r < 0)
2258 return r;
f36a9d59 2259 sockaddr_len = r;
d41bd96f
LP
2260
2261 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2262 if (fd < 0)
2263 return -errno;
2264
a0c41de2
LP
2265 fd = fd_move_above_stdio(fd);
2266
d41bd96f
LP
2267 (void) sockaddr_un_unlink(&sockaddr.un);
2268
63e00ccd
CG
2269 RUN_WITH_UMASK(~m & 0777) {
2270 r = mac_selinux_bind(fd, &sockaddr.sa, sockaddr_len);
2271 if (r < 0)
2272 return r;
2273 }
d41bd96f
LP
2274
2275 if (listen(fd, SOMAXCONN) < 0)
2276 return -errno;
2277
2278 r = varlink_server_listen_fd(s, fd);
2279 if (r < 0)
2280 return r;
2281
2282 TAKE_FD(fd);
2283 return 0;
2284}
2285
2286void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
2287 void *ret;
2288
2289 assert_return(s, NULL);
2290
2291 ret = s->userdata;
2292 s->userdata = userdata;
2293
2294 return ret;
2295}
2296
2297void* varlink_server_get_userdata(VarlinkServer *s) {
2298 assert_return(s, NULL);
2299
2300 return s->userdata;
2301}
2302
2303static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
2304 if (!ss)
2305 return NULL;
2306
2307 if (ss->server)
2308 LIST_REMOVE(sockets, ss->server->sockets, ss);
2309
1d3fe304 2310 sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
2311
2312 free(ss->address);
2313 safe_close(ss->fd);
2314
2315 return mfree(ss);
2316}
2317
2318int varlink_server_shutdown(VarlinkServer *s) {
2319 assert_return(s, -EINVAL);
2320
2321 while (s->sockets)
2322 varlink_server_socket_destroy(s->sockets);
2323
2324 return 0;
2325}
2326
2327int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
2328 VarlinkServerSocket *ss;
2329 int r;
2330
2331 assert_return(s, -EINVAL);
2332 assert_return(!s->event, -EBUSY);
2333
2334 if (e)
2335 s->event = sd_event_ref(e);
2336 else {
2337 r = sd_event_default(&s->event);
2338 if (r < 0)
2339 return r;
2340 }
2341
2342 LIST_FOREACH(sockets, ss, s->sockets) {
2343 assert(!ss->event_source);
2344
2345 r = sd_event_add_io(s->event, &ss->event_source, ss->fd, EPOLLIN, connect_callback, ss);
2346 if (r < 0)
2347 goto fail;
2348
2349 r = sd_event_source_set_priority(ss->event_source, priority);
2350 if (r < 0)
2351 goto fail;
2352 }
2353
2354 s->event_priority = priority;
2355 return 0;
2356
2357fail:
2358 varlink_server_detach_event(s);
2359 return r;
2360}
2361
2362int varlink_server_detach_event(VarlinkServer *s) {
2363 VarlinkServerSocket *ss;
2364
2365 assert_return(s, -EINVAL);
2366
2367 LIST_FOREACH(sockets, ss, s->sockets) {
2368
2369 if (!ss->event_source)
2370 continue;
2371
2372 (void) sd_event_source_set_enabled(ss->event_source, SD_EVENT_OFF);
2373 ss->event_source = sd_event_source_unref(ss->event_source);
2374 }
2375
2376 sd_event_unref(s->event);
2377 return 0;
2378}
2379
2380sd_event *varlink_server_get_event(VarlinkServer *s) {
2381 assert_return(s, NULL);
2382
2383 return s->event;
2384}
2385
2386int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
db3d4222 2387 _cleanup_free_ char *m = NULL;
d41bd96f
LP
2388 int r;
2389
2390 assert_return(s, -EINVAL);
2391 assert_return(method, -EINVAL);
2392 assert_return(callback, -EINVAL);
2393
2394 if (startswith(method, "org.varlink.service."))
db3d4222 2395 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST), "Cannot bind server to '%s'.", method);
d41bd96f 2396
d41bd96f
LP
2397 m = strdup(method);
2398 if (!m)
db3d4222 2399 return log_oom_debug();
d41bd96f 2400
1d2d1654
SS
2401 r = hashmap_ensure_put(&s->methods, &string_hash_ops, m, callback);
2402 if (r == -ENOMEM)
2403 return log_oom_debug();
db3d4222
ZJS
2404 if (r < 0)
2405 return log_debug_errno(r, "Failed to register callback: %m");
2406 if (r > 0)
2407 TAKE_PTR(m);
d41bd96f
LP
2408
2409 return 0;
2410}
2411
2412int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
2413 va_list ap;
e7b93f97 2414 int r = 0;
d41bd96f
LP
2415
2416 assert_return(s, -EINVAL);
2417
2418 va_start(ap, s);
2419 for (;;) {
2420 VarlinkMethod callback;
2421 const char *method;
2422
2423 method = va_arg(ap, const char *);
2424 if (!method)
2425 break;
2426
2427 callback = va_arg(ap, VarlinkMethod);
2428
2429 r = varlink_server_bind_method(s, method, callback);
2430 if (r < 0)
e7b93f97 2431 break;
d41bd96f 2432 }
e7b93f97 2433 va_end(ap);
d41bd96f 2434
e7b93f97 2435 return r;
d41bd96f
LP
2436}
2437
2438int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
2439 assert_return(s, -EINVAL);
2440
2441 if (callback && s->connect_callback && callback != s->connect_callback)
db3d4222 2442 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
2443
2444 s->connect_callback = callback;
2445 return 0;
2446}
2447
6d4d6002
LP
2448int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
2449 assert_return(s, -EINVAL);
2450
2451 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
db3d4222 2452 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
6d4d6002
LP
2453
2454 s->disconnect_callback = callback;
2455 return 0;
2456}
2457
d41bd96f 2458unsigned varlink_server_connections_max(VarlinkServer *s) {
88a36d36 2459 int dts;
d41bd96f
LP
2460
2461 /* If a server is specified, return the setting for that server, otherwise the default value */
2462 if (s)
2463 return s->connections_max;
2464
88a36d36
LP
2465 dts = getdtablesize();
2466 assert_se(dts > 0);
d41bd96f
LP
2467
2468 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
88a36d36
LP
2469 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
2470 return dts / 4 * 3;
d41bd96f
LP
2471
2472 return VARLINK_DEFAULT_CONNECTIONS_MAX;
2473}
2474
2475unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
2476 unsigned m;
2477
2478 if (s)
2479 return s->connections_per_uid_max;
2480
2481 /* Make sure to never use up more than ¾th of available connections for a single user */
2482 m = varlink_server_connections_max(NULL);
2483 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
2484 return m / 4 * 3;
2485
2486 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
2487}
2488
2489int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
2490 assert_return(s, -EINVAL);
2491 assert_return(m > 0, -EINVAL);
2492
2493 s->connections_per_uid_max = m;
2494 return 0;
2495}
2496
2497int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
2498 assert_return(s, -EINVAL);
2499 assert_return(m > 0, -EINVAL);
2500
2501 s->connections_max = m;
2502 return 0;
2503}
2504
c4f601f2
LP
2505unsigned varlink_server_current_connections(VarlinkServer *s) {
2506 assert_return(s, UINT_MAX);
2507
2508 return s->n_connections;
2509}
2510
d41bd96f
LP
2511int varlink_server_set_description(VarlinkServer *s, const char *description) {
2512 assert_return(s, -EINVAL);
2513
2514 return free_and_strdup(&s->description, description);
2515}