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