]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/varlink.c
Merge pull request #32523 from cgzones/inaccessible_label
[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 5
206504a5
LP
6#include <sd-daemon.h>
7
d41bd96f
LP
8#include "alloc-util.h"
9#include "errno-util.h"
10#include "fd-util.h"
e2341b6b 11#include "glyph-util.h"
d41bd96f 12#include "hashmap.h"
0f2d351f 13#include "io-util.h"
bd1ae178 14#include "iovec-util.h"
d41bd96f 15#include "list.h"
0f274a87 16#include "path-util.h"
d41bd96f 17#include "process-util.h"
63e00ccd 18#include "selinux-util.h"
008798e9 19#include "serialize.h"
d41bd96f
LP
20#include "set.h"
21#include "socket-util.h"
22#include "string-table.h"
23#include "string-util.h"
24#include "strv.h"
25#include "time-util.h"
26#include "umask-util.h"
27#include "user-util.h"
28#include "varlink.h"
008798e9 29#include "varlink-internal.h"
7e006b49
LP
30#include "varlink-org.varlink.service.h"
31#include "varlink-io.systemd.h"
32#include "version.h"
d41bd96f
LP
33
34#define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
35#define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
36
37#define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
38#define VARLINK_BUFFER_MAX (16U*1024U*1024U)
39#define VARLINK_READ_SIZE (64U*1024U)
0430a11e 40#define VARLINK_COLLECT_MAX 1024U
d41bd96f
LP
41
42typedef enum VarlinkState {
43 /* Client side states */
44 VARLINK_IDLE_CLIENT,
45 VARLINK_AWAITING_REPLY,
45a6c965 46 VARLINK_AWAITING_REPLY_MORE,
d41bd96f
LP
47 VARLINK_CALLING,
48 VARLINK_CALLED,
9bca9891
LP
49 VARLINK_COLLECTING,
50 VARLINK_COLLECTING_REPLY,
d41bd96f
LP
51 VARLINK_PROCESSING_REPLY,
52
53 /* Server side states */
54 VARLINK_IDLE_SERVER,
55 VARLINK_PROCESSING_METHOD,
56 VARLINK_PROCESSING_METHOD_MORE,
57 VARLINK_PROCESSING_METHOD_ONEWAY,
58 VARLINK_PROCESSED_METHOD,
d41bd96f
LP
59 VARLINK_PENDING_METHOD,
60 VARLINK_PENDING_METHOD_MORE,
61
62 /* Common states (only during shutdown) */
63 VARLINK_PENDING_DISCONNECT,
64 VARLINK_PENDING_TIMEOUT,
65 VARLINK_PROCESSING_DISCONNECT,
66 VARLINK_PROCESSING_TIMEOUT,
67 VARLINK_PROCESSING_FAILURE,
68 VARLINK_DISCONNECTED,
69
70 _VARLINK_STATE_MAX,
2d93c20e 71 _VARLINK_STATE_INVALID = -EINVAL,
d41bd96f
LP
72} VarlinkState;
73
74/* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
75 * is still good for something, and false only when it's dead for good. This means: when we are
76 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
77 * the connection is still good, and we are likely to be able to properly operate on it soon. */
78#define VARLINK_STATE_IS_ALIVE(state) \
79 IN_SET(state, \
80 VARLINK_IDLE_CLIENT, \
81 VARLINK_AWAITING_REPLY, \
45a6c965 82 VARLINK_AWAITING_REPLY_MORE, \
d41bd96f
LP
83 VARLINK_CALLING, \
84 VARLINK_CALLED, \
9bca9891
LP
85 VARLINK_COLLECTING, \
86 VARLINK_COLLECTING_REPLY, \
d41bd96f
LP
87 VARLINK_PROCESSING_REPLY, \
88 VARLINK_IDLE_SERVER, \
89 VARLINK_PROCESSING_METHOD, \
90 VARLINK_PROCESSING_METHOD_MORE, \
91 VARLINK_PROCESSING_METHOD_ONEWAY, \
92 VARLINK_PROCESSED_METHOD, \
d41bd96f
LP
93 VARLINK_PENDING_METHOD, \
94 VARLINK_PENDING_METHOD_MORE)
95
d37cdac6
LP
96typedef struct VarlinkJsonQueueItem VarlinkJsonQueueItem;
97
98/* A queued message we shall write into the socket, along with the file descriptors to send at the same
99 * time. This queue item binds them together so that message/fd boundaries are maintained throughout the
100 * whole pipeline. */
101struct VarlinkJsonQueueItem {
102 LIST_FIELDS(VarlinkJsonQueueItem, queue);
103 JsonVariant *data;
104 size_t n_fds;
105 int fds[];
106};
107
d41bd96f
LP
108struct Varlink {
109 unsigned n_ref;
110
111 VarlinkServer *server;
112
113 VarlinkState state;
114 bool connecting; /* This boolean indicates whether the socket fd we are operating on is currently
115 * processing an asynchronous connect(). In that state we watch the socket for
116 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
117 * will trigger ENOTCONN. Note that this boolean is kept separate from the
118 * VarlinkState above on purpose: while the connect() is still not complete we
119 * already want to allow queuing of messages and similar. Thus it's nice to keep
120 * these two state concepts separate: the VarlinkState encodes what our own view of
121 * the connection is, i.e. whether we think it's a server, a client, and has
122 * something queued already, while 'connecting' tells us a detail about the
123 * transport used below, that should have no effect on how we otherwise accept and
124 * process operations from the user.
125 *
126 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
127 * connection is good to use, even if it might not be fully connected
128 * yet. connecting=true then informs you that actually we are still connecting, and
129 * the connection is actually not established yet and thus any requests you enqueue
130 * now will still work fine but will be queued only, not sent yet, but that
131 * shouldn't stop you from using the connection, since eventually whatever you queue
132 * *will* be sent.
133 *
134 * Or to say this even differently: 'state' is a high-level ("application layer"
135 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
136 * low, if you so will) state, and while they are not entirely unrelated and
137 * sometimes propagate effects to each other they are only asynchronously connected
138 * at most. */
139 unsigned n_pending;
140
141 int fd;
142
143 char *input_buffer; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
d41bd96f
LP
144 size_t input_buffer_index;
145 size_t input_buffer_size;
146 size_t input_buffer_unscanned;
147
3c868058
LP
148 void *input_control_buffer;
149 size_t input_control_buffer_size;
150
d41bd96f 151 char *output_buffer; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
d41bd96f
LP
152 size_t output_buffer_index;
153 size_t output_buffer_size;
154
d37cdac6
LP
155 int *input_fds; /* file descriptors associated with the data in input_buffer (for fd passing) */
156 size_t n_input_fds;
157
158 int *output_fds; /* file descriptors associated with the data in output_buffer (for fd passing) */
159 size_t n_output_fds;
160
161 /* Further messages to output not yet formatted into text, and thus not included in output_buffer
162 * yet. We keep them separate from output_buffer, to not violate fd message boundaries: we want that
163 * each fd that is sent is associated with its fds, and that fds cannot be accidentally associated
94d82b59 164 * with preceding or following messages. */
d37cdac6
LP
165 LIST_HEAD(VarlinkJsonQueueItem, output_queue);
166 VarlinkJsonQueueItem *output_queue_tail;
167
168 /* The fds to associate with the next message that is about to be enqueued. The user first pushes the
169 * fds it intends to send via varlink_push_fd() into this queue, and then once the message data is
170 * submitted we'll combine the fds and the message data into one. */
171 int *pushed_fds;
172 size_t n_pushed_fds;
173
d41bd96f
LP
174 VarlinkReply reply_callback;
175
176 JsonVariant *current;
9bca9891 177 JsonVariant *current_collected;
72226a2f 178 VarlinkReplyFlags current_reply_flags;
7e006b49 179 VarlinkSymbol *current_method;
d41bd96f 180
0eccf725 181 int peer_pidfd;
d41bd96f
LP
182 struct ucred ucred;
183 bool ucred_acquired:1;
184
185 bool write_disconnected:1;
186 bool read_disconnected:1;
187 bool prefer_read_write:1;
188 bool got_pollhup:1;
189
d37cdac6
LP
190 bool allow_fd_passing_input:1;
191 bool allow_fd_passing_output:1;
192
db1f7c84 193 bool output_buffer_sensitive:1; /* whether to erase the output buffer after writing it to the socket */
a570877c 194 bool input_sensitive:1; /* Whether incoming messages might be sensitive */
db1f7c84 195
d37cdac6
LP
196 int af; /* address family if socket; AF_UNSPEC if not socket; negative if not known */
197
d41bd96f
LP
198 usec_t timestamp;
199 usec_t timeout;
200
201 void *userdata;
202 char *description;
203
204 sd_event *event;
205 sd_event_source *io_event_source;
206 sd_event_source *time_event_source;
207 sd_event_source *quit_event_source;
208 sd_event_source *defer_event_source;
0f274a87
LP
209
210 pid_t exec_pid;
d41bd96f
LP
211};
212
213typedef struct VarlinkServerSocket VarlinkServerSocket;
214
215struct VarlinkServerSocket {
216 VarlinkServer *server;
217
218 int fd;
219 char *address;
220
221 sd_event_source *event_source;
222
223 LIST_FIELDS(VarlinkServerSocket, sockets);
224};
225
226struct VarlinkServer {
227 unsigned n_ref;
228 VarlinkServerFlags flags;
229
230 LIST_HEAD(VarlinkServerSocket, sockets);
231
7e006b49
LP
232 Hashmap *methods; /* Fully qualified symbol name of a method → VarlinkMethod */
233 Hashmap *interfaces; /* Fully qualified interface name → VarlinkInterface* */
939630ae 234 Hashmap *symbols; /* Fully qualified symbol name of method/error → VarlinkSymbol* */
d41bd96f 235 VarlinkConnect connect_callback;
6d4d6002 236 VarlinkDisconnect disconnect_callback;
d41bd96f
LP
237
238 sd_event *event;
239 int64_t event_priority;
240
241 unsigned n_connections;
7e006b49 242 Hashmap *by_uid; /* UID_TO_PTR(uid) → UINT_TO_PTR(n_connections) */
d41bd96f
LP
243
244 void *userdata;
245 char *description;
246
247 unsigned connections_max;
248 unsigned connections_per_uid_max;
47723340
LP
249
250 bool exit_on_idle;
d41bd96f
LP
251};
252
253static const char* const varlink_state_table[_VARLINK_STATE_MAX] = {
254 [VARLINK_IDLE_CLIENT] = "idle-client",
255 [VARLINK_AWAITING_REPLY] = "awaiting-reply",
45a6c965 256 [VARLINK_AWAITING_REPLY_MORE] = "awaiting-reply-more",
d41bd96f
LP
257 [VARLINK_CALLING] = "calling",
258 [VARLINK_CALLED] = "called",
9bca9891
LP
259 [VARLINK_COLLECTING] = "collecting",
260 [VARLINK_COLLECTING_REPLY] = "collecting-reply",
d41bd96f
LP
261 [VARLINK_PROCESSING_REPLY] = "processing-reply",
262 [VARLINK_IDLE_SERVER] = "idle-server",
263 [VARLINK_PROCESSING_METHOD] = "processing-method",
264 [VARLINK_PROCESSING_METHOD_MORE] = "processing-method-more",
265 [VARLINK_PROCESSING_METHOD_ONEWAY] = "processing-method-oneway",
266 [VARLINK_PROCESSED_METHOD] = "processed-method",
d41bd96f
LP
267 [VARLINK_PENDING_METHOD] = "pending-method",
268 [VARLINK_PENDING_METHOD_MORE] = "pending-method-more",
269 [VARLINK_PENDING_DISCONNECT] = "pending-disconnect",
270 [VARLINK_PENDING_TIMEOUT] = "pending-timeout",
271 [VARLINK_PROCESSING_DISCONNECT] = "processing-disconnect",
272 [VARLINK_PROCESSING_TIMEOUT] = "processing-timeout",
273 [VARLINK_PROCESSING_FAILURE] = "processing-failure",
274 [VARLINK_DISCONNECTED] = "disconnected",
275};
276
277DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state, VarlinkState);
278
279#define varlink_log_errno(v, error, fmt, ...) \
280 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
281
282#define varlink_log(v, fmt, ...) \
283 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
284
285#define varlink_server_log_errno(s, error, fmt, ...) \
286 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
287
288#define varlink_server_log(s, fmt, ...) \
289 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
290
d37cdac6 291static int varlink_format_queue(Varlink *v);
47723340 292static void varlink_server_test_exit_on_idle(VarlinkServer *s);
d37cdac6 293
cf1ab844 294static const char *varlink_description(Varlink *v) {
f35e9b10 295 return (v ? v->description : NULL) ?: "varlink";
d41bd96f
LP
296}
297
cf1ab844 298static const char *varlink_server_description(VarlinkServer *s) {
f35e9b10 299 return (s ? s->description : NULL) ?: "varlink";
d41bd96f
LP
300}
301
d37cdac6
LP
302static VarlinkJsonQueueItem *varlink_json_queue_item_free(VarlinkJsonQueueItem *q) {
303 if (!q)
304 return NULL;
305
306 json_variant_unref(q->data);
307 close_many(q->fds, q->n_fds);
308
309 return mfree(q);
310}
311
312static VarlinkJsonQueueItem *varlink_json_queue_item_new(JsonVariant *m, const int fds[], size_t n_fds) {
313 VarlinkJsonQueueItem *q;
314
315 assert(m);
316 assert(fds || n_fds == 0);
317
318 q = malloc(offsetof(VarlinkJsonQueueItem, fds) + sizeof(int) * n_fds);
319 if (!q)
320 return NULL;
321
322 *q = (VarlinkJsonQueueItem) {
323 .data = json_variant_ref(m),
324 .n_fds = n_fds,
325 };
326
327 memcpy_safe(q->fds, fds, n_fds * sizeof(int));
328
329 return TAKE_PTR(q);
330}
331
d41bd96f
LP
332static void varlink_set_state(Varlink *v, VarlinkState state) {
333 assert(v);
77740b59
ZJS
334 assert(state >= 0 && state < _VARLINK_STATE_MAX);
335
336 if (v->state < 0)
953394e3 337 varlink_log(v, "Setting state %s",
77740b59
ZJS
338 varlink_state_to_string(state));
339 else
e2341b6b 340 varlink_log(v, "Changing state %s %s %s",
77740b59 341 varlink_state_to_string(v->state),
e2341b6b 342 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
77740b59 343 varlink_state_to_string(state));
d41bd96f
LP
344
345 v->state = state;
346}
347
348static int varlink_new(Varlink **ret) {
349 Varlink *v;
350
351 assert(ret);
352
a48481dc 353 v = new(Varlink, 1);
d41bd96f
LP
354 if (!v)
355 return -ENOMEM;
356
357 *v = (Varlink) {
358 .n_ref = 1,
254d1313 359 .fd = -EBADF,
d41bd96f
LP
360
361 .state = _VARLINK_STATE_INVALID,
362
a995ce47 363 .ucred = UCRED_INVALID,
d41bd96f
LP
364
365 .timestamp = USEC_INFINITY,
d37cdac6
LP
366 .timeout = VARLINK_DEFAULT_TIMEOUT_USEC,
367
368 .af = -1,
0eccf725
LP
369
370 .peer_pidfd = -EBADF,
d41bd96f
LP
371 };
372
373 *ret = v;
374 return 0;
375}
376
377int varlink_connect_address(Varlink **ret, const char *address) {
378 _cleanup_(varlink_unrefp) Varlink *v = NULL;
379 union sockaddr_union sockaddr;
380 int r;
381
382 assert_return(ret, -EINVAL);
383 assert_return(address, -EINVAL);
384
d41bd96f
LP
385 r = varlink_new(&v);
386 if (r < 0)
db3d4222 387 return log_debug_errno(r, "Failed to create varlink object: %m");
d41bd96f
LP
388
389 v->fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
390 if (v->fd < 0)
db3d4222 391 return log_debug_errno(errno, "Failed to create AF_UNIX socket: %m");
d41bd96f 392
a0c41de2 393 v->fd = fd_move_above_stdio(v->fd);
d37cdac6 394 v->af = AF_UNIX;
a0c41de2 395
1861986a
LP
396 r = sockaddr_un_set_path(&sockaddr.un, address);
397 if (r < 0) {
398 if (r != -ENAMETOOLONG)
399 return log_debug_errno(r, "Failed to set socket address '%s': %m", address);
400
401 /* This is a file system path, and too long to fit into sockaddr_un. Let's connect via O_PATH
402 * to this socket. */
403
404 r = connect_unix_path(v->fd, AT_FDCWD, address);
405 } else
406 r = RET_NERRNO(connect(v->fd, &sockaddr.sa, r));
407
408 if (r < 0) {
409 if (!IN_SET(r, -EAGAIN, -EINPROGRESS))
410 return log_debug_errno(r, "Failed to connect to %s: %m", address);
d41bd96f
LP
411
412 v->connecting = true; /* We are asynchronously connecting, i.e. the connect() is being
413 * processed in the background. As long as that's the case the socket
414 * is in a special state: it's there, we can poll it for EPOLLOUT, but
415 * if we attempt to write() to it before we see EPOLLOUT we'll get
416 * ENOTCONN (and not EAGAIN, like we would for a normal connected
417 * socket that isn't writable at the moment). Since ENOTCONN on write()
418 * hence can mean two different things (i.e. connection not complete
419 * yet vs. already disconnected again), we store as a boolean whether
420 * we are still in connect(). */
421 }
422
423 varlink_set_state(v, VARLINK_IDLE_CLIENT);
424
425 *ret = TAKE_PTR(v);
db3d4222 426 return 0;
d41bd96f
LP
427}
428
0f274a87 429int varlink_connect_exec(Varlink **ret, const char *_command, char **_argv) {
71136404 430 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
0f274a87
LP
431 _cleanup_(sigkill_waitp) pid_t pid = 0;
432 _cleanup_free_ char *command = NULL;
433 _cleanup_strv_free_ char **argv = NULL;
434 int r;
435
436 assert_return(ret, -EINVAL);
437 assert_return(_command, -EINVAL);
438
439 /* Copy the strings, in case they point into our own argv[], which we'll invalidate shortly because
440 * we rename the child process */
441 command = strdup(_command);
442 if (!command)
443 return -ENOMEM;
444
445 if (strv_isempty(_argv))
446 argv = strv_new(command);
447 else
448 argv = strv_copy(_argv);
449 if (!argv)
450 return -ENOMEM;
451
452 log_debug("Forking off Varlink child process '%s'.", command);
453
454 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0, pair) < 0)
455 return log_debug_errno(errno, "Failed to allocate AF_UNIX socket pair: %m");
456
07dca3c4
LP
457 r = fd_nonblock(pair[1], false);
458 if (r < 0)
459 return log_debug_errno(r, "Failed to disable O_NONBLOCK for varlink socket: %m");
460
0f274a87
LP
461 r = safe_fork_full(
462 "(sd-vlexec)",
463 /* stdio_fds= */ NULL,
464 /* except_fds= */ (int[]) { pair[1] },
465 /* n_except_fds= */ 1,
e9ccae31 466 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REOPEN_LOG|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE,
0f274a87
LP
467 &pid);
468 if (r < 0)
469 return log_debug_errno(r, "Failed to spawn process: %m");
470 if (r == 0) {
471 char spid[DECIMAL_STR_MAX(pid_t)+1];
472 const char *setenv_list[] = {
473 "LISTEN_FDS", "1",
474 "LISTEN_PID", spid,
475 "LISTEN_FDNAMES", "varlink",
476 NULL, NULL,
477 };
478 /* Child */
479
480 pair[0] = -EBADF;
481
482 r = move_fd(pair[1], 3, /* cloexec= */ false);
483 if (r < 0) {
484 log_debug_errno(r, "Failed to move file descriptor to 3: %m");
485 _exit(EXIT_FAILURE);
486 }
487
488 xsprintf(spid, PID_FMT, pid);
489
490 STRV_FOREACH_PAIR(a, b, setenv_list) {
491 if (setenv(*a, *b, /* override= */ true) < 0) {
492 log_debug_errno(errno, "Failed to set environment variable '%s': %m", *a);
493 _exit(EXIT_FAILURE);
494 }
495 }
496
497 execvp(command, argv);
498 log_debug_errno(r, "Failed to invoke process '%s': %m", command);
499 _exit(EXIT_FAILURE);
500 }
501
502 pair[1] = safe_close(pair[1]);
503
504 Varlink *v;
505 r = varlink_new(&v);
506 if (r < 0)
507 return log_debug_errno(r, "Failed to create varlink object: %m");
508
509 v->fd = TAKE_FD(pair[0]);
510 v->af = AF_UNIX;
511 v->exec_pid = TAKE_PID(pid);
512 varlink_set_state(v, VARLINK_IDLE_CLIENT);
513
514 *ret = v;
515 return 0;
516}
517
a1bb30de
LP
518static int varlink_connect_ssh(Varlink **ret, const char *where) {
519 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
520 _cleanup_(sigkill_waitp) pid_t pid = 0;
521 int r;
522
523 assert_return(ret, -EINVAL);
524 assert_return(where, -EINVAL);
525
526 /* Connects to an SSH server via OpenSSH 9.4's -W switch to connect to a remote AF_UNIX socket. For
527 * now we do not expose this function directly, but only via varlink_connect_url(). */
528
529 const char *ssh = secure_getenv("SYSTEMD_SSH") ?: "ssh";
530 if (!path_is_valid(ssh))
531 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "SSH path is not valid, refusing: %s", ssh);
532
533 const char *e = strchr(where, ':');
534 if (!e)
535 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "SSH specification lacks a : separator between host and path, refusing: %s", where);
536
537 _cleanup_free_ char *h = strndup(where, e - where);
538 if (!h)
539 return log_oom_debug();
540
541 _cleanup_free_ char *c = strdup(e + 1);
542 if (!c)
543 return log_oom_debug();
544
545 if (!path_is_absolute(c))
546 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Remote AF_UNIX socket path is not absolute, refusing: %s", c);
547
548 _cleanup_free_ char *p = NULL;
549 r = path_simplify_alloc(c, &p);
550 if (r < 0)
551 return r;
552
553 if (!path_is_normalized(p))
554 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path is not normalized, refusing: %s", p);
555
556 log_debug("Forking off SSH child process '%s -W %s %s'.", ssh, p, h);
557
558 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0, pair) < 0)
559 return log_debug_errno(errno, "Failed to allocate AF_UNIX socket pair: %m");
560
561 r = safe_fork_full(
562 "(sd-vlssh)",
563 /* stdio_fds= */ (int[]) { pair[1], pair[1], STDERR_FILENO },
564 /* except_fds= */ NULL,
565 /* n_except_fds= */ 0,
566 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_REOPEN_LOG|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE|FORK_REARRANGE_STDIO,
567 &pid);
568 if (r < 0)
569 return log_debug_errno(r, "Failed to spawn process: %m");
570 if (r == 0) {
571 /* Child */
572
573 execlp(ssh, "ssh", "-W", p, h, NULL);
574 log_debug_errno(errno, "Failed to invoke %s: %m", ssh);
575 _exit(EXIT_FAILURE);
576 }
577
578 pair[1] = safe_close(pair[1]);
579
580 Varlink *v;
581 r = varlink_new(&v);
582 if (r < 0)
583 return log_debug_errno(r, "Failed to create varlink object: %m");
584
585 v->fd = TAKE_FD(pair[0]);
586 v->af = AF_UNIX;
587 v->exec_pid = TAKE_PID(pid);
588 varlink_set_state(v, VARLINK_IDLE_CLIENT);
589
590 *ret = v;
591 return 0;
592}
593
0f274a87
LP
594int varlink_connect_url(Varlink **ret, const char *url) {
595 _cleanup_free_ char *c = NULL;
596 const char *p;
a1bb30de
LP
597 enum {
598 SCHEME_UNIX,
599 SCHEME_EXEC,
600 SCHEME_SSH,
601 } scheme;
cf3d95b2 602 int r;
0f274a87
LP
603
604 assert_return(ret, -EINVAL);
605 assert_return(url, -EINVAL);
606
a1bb30de 607 // FIXME: Maybe add support for vsock: and ssh-exec: URL schemes here.
0f274a87 608
a1bb30de
LP
609 /* The Varlink URL scheme is a bit underdefined. We support only the spec-defined unix: transport for
610 * now, plus exec:, ssh: transports we made up ourselves. Strictly speaking this shouldn't even be
611 * called "URL", since it has nothing to do with Internet URLs by RFC. */
0f274a87
LP
612
613 p = startswith(url, "unix:");
614 if (p)
a1bb30de
LP
615 scheme = SCHEME_UNIX;
616 else if ((p = startswith(url, "exec:")))
617 scheme = SCHEME_EXEC;
618 else if ((p = startswith(url, "ssh:")))
619 scheme = SCHEME_SSH;
620 else
621 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "URL scheme not supported.");
0f274a87
LP
622
623 /* The varlink.org reference C library supports more than just file system paths. We might want to
624 * support that one day too. For now simply refuse that. */
625 if (p[strcspn(p, ";?#")] != '\0')
626 return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "URL parameterization with ';', '?', '#' not supported.");
627
a1bb30de
LP
628 if (scheme == SCHEME_SSH)
629 return varlink_connect_ssh(ret, p);
630
631 if (scheme == SCHEME_EXEC || p[0] != '@') { /* no path validity checks for abstract namespace sockets */
0f274a87
LP
632
633 if (!path_is_absolute(p))
634 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path not absolute, refusing.");
635
cf3d95b2
YW
636 r = path_simplify_alloc(p, &c);
637 if (r < 0)
638 return r;
0f274a87
LP
639
640 if (!path_is_normalized(c))
641 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path is not normalized, refusing.");
642 }
643
a1bb30de 644 if (scheme == SCHEME_EXEC)
86f6d32e 645 return varlink_connect_exec(ret, c, NULL);
0f274a87
LP
646
647 return varlink_connect_address(ret, c ?: p);
648}
649
d41bd96f
LP
650int varlink_connect_fd(Varlink **ret, int fd) {
651 Varlink *v;
652 int r;
653
654 assert_return(ret, -EINVAL);
655 assert_return(fd >= 0, -EBADF);
656
657 r = fd_nonblock(fd, true);
658 if (r < 0)
db3d4222 659 return log_debug_errno(r, "Failed to make fd %d nonblocking: %m", fd);
d41bd96f
LP
660
661 r = varlink_new(&v);
662 if (r < 0)
db3d4222 663 return log_debug_errno(r, "Failed to create varlink object: %m");
d41bd96f
LP
664
665 v->fd = fd;
d37cdac6 666 v->af = -1,
d41bd96f
LP
667 varlink_set_state(v, VARLINK_IDLE_CLIENT);
668
669 /* Note that if this function is called we assume the passed socket (if it is one) is already
670 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
671 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
672 * until the connection is fully set up. Behaviour here is hence a bit different from
673 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
674 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
675
676 *ret = v;
677 return 0;
678}
679
680static void varlink_detach_event_sources(Varlink *v) {
681 assert(v);
682
1d3fe304 683 v->io_event_source = sd_event_source_disable_unref(v->io_event_source);
1d3fe304 684 v->time_event_source = sd_event_source_disable_unref(v->time_event_source);
1d3fe304 685 v->quit_event_source = sd_event_source_disable_unref(v->quit_event_source);
1d3fe304 686 v->defer_event_source = sd_event_source_disable_unref(v->defer_event_source);
d41bd96f
LP
687}
688
790446bd
LP
689static void varlink_clear_current(Varlink *v) {
690 assert(v);
691
692 /* Clears the currently processed incoming message */
693 v->current = json_variant_unref(v->current);
9bca9891 694 v->current_collected = json_variant_unref(v->current_collected);
7e006b49 695 v->current_method = NULL;
72226a2f 696 v->current_reply_flags = 0;
d37cdac6
LP
697
698 close_many(v->input_fds, v->n_input_fds);
699 v->input_fds = mfree(v->input_fds);
700 v->n_input_fds = 0;
790446bd
LP
701}
702
d41bd96f
LP
703static void varlink_clear(Varlink *v) {
704 assert(v);
705
706 varlink_detach_event_sources(v);
707
708 v->fd = safe_close(v->fd);
709
d37cdac6
LP
710 varlink_clear_current(v);
711
a570877c 712 v->input_buffer = v->input_sensitive ? erase_and_free(v->input_buffer) : mfree(v->input_buffer);
db1f7c84 713 v->output_buffer = v->output_buffer_sensitive ? erase_and_free(v->output_buffer) : mfree(v->output_buffer);
d41bd96f 714
3c868058
LP
715 v->input_control_buffer = mfree(v->input_control_buffer);
716 v->input_control_buffer_size = 0;
717
d37cdac6
LP
718 close_many(v->output_fds, v->n_output_fds);
719 v->output_fds = mfree(v->output_fds);
720 v->n_output_fds = 0;
721
722 close_many(v->pushed_fds, v->n_pushed_fds);
723 v->pushed_fds = mfree(v->pushed_fds);
724 v->n_pushed_fds = 0;
725
9aad490e 726 LIST_CLEAR(queue, v->output_queue, varlink_json_queue_item_free);
d37cdac6
LP
727 v->output_queue_tail = NULL;
728
d41bd96f 729 v->event = sd_event_unref(v->event);
0f274a87
LP
730
731 if (v->exec_pid > 0) {
732 sigterm_wait(v->exec_pid);
733 v->exec_pid = 0;
734 }
0eccf725
LP
735
736 v->peer_pidfd = safe_close(v->peer_pidfd);
d41bd96f
LP
737}
738
739static Varlink* varlink_destroy(Varlink *v) {
740 if (!v)
741 return NULL;
742
743 /* If this is called the server object must already been unreffed here. Why that? because when we
744 * linked up the varlink connection with the server object we took one ref in each direction */
745 assert(!v->server);
746
747 varlink_clear(v);
748
749 free(v->description);
750 return mfree(v);
751}
752
753DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink, varlink, varlink_destroy);
754
755static int varlink_test_disconnect(Varlink *v) {
756 assert(v);
757
37b22b3b 758 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
d41bd96f
LP
759 * prematurely, since we want to handle half-open connections as well as possible and want to flush
760 * out and read data before we close down if we can. */
761
762 /* Already disconnected? */
763 if (!VARLINK_STATE_IS_ALIVE(v->state))
764 return 0;
765
766 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
767 if (v->connecting)
768 return 0;
769
770 /* Still something to write and we can write? Stay around */
771 if (v->output_buffer_size > 0 && !v->write_disconnected)
772 return 0;
773
774 /* Both sides gone already? Then there's no need to stick around */
775 if (v->read_disconnected && v->write_disconnected)
776 goto disconnect;
777
778 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
9bca9891 779 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING, VARLINK_IDLE_SERVER) && v->read_disconnected)
d41bd96f
LP
780 goto disconnect;
781
782 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
783 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
784 * being down if we never wrote anything. */
4f06325c 785 if (v->state == VARLINK_IDLE_CLIENT && (v->write_disconnected || v->got_pollhup))
d41bd96f
LP
786 goto disconnect;
787
7c26a631
LP
788 /* We are on the server side and still want to send out more replies, but we saw POLLHUP already, and
789 * either got no buffered bytes to write anymore or already saw a write error. In that case we should
790 * shut down the varlink link. */
791 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE) && (v->write_disconnected || v->output_buffer_size == 0) && v->got_pollhup)
e8e9227f
AZ
792 goto disconnect;
793
d41bd96f
LP
794 return 0;
795
796disconnect:
797 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
798 return 1;
799}
800
801static int varlink_write(Varlink *v) {
802 ssize_t n;
d37cdac6 803 int r;
d41bd96f
LP
804
805 assert(v);
806
807 if (!VARLINK_STATE_IS_ALIVE(v->state))
808 return 0;
809 if (v->connecting) /* Writing while we are still wait for a non-blocking connect() to complete will
810 * result in ENOTCONN, hence exit early here */
811 return 0;
d41bd96f
LP
812 if (v->write_disconnected)
813 return 0;
814
d37cdac6
LP
815 /* If needed let's convert some output queue json variants into text form */
816 r = varlink_format_queue(v);
817 if (r < 0)
818 return r;
819
820 if (v->output_buffer_size == 0)
821 return 0;
822
d41bd96f
LP
823 assert(v->fd >= 0);
824
d37cdac6
LP
825 if (v->n_output_fds > 0) { /* If we shall send fds along, we must use sendmsg() */
826 struct iovec iov = {
827 .iov_base = v->output_buffer + v->output_buffer_index,
828 .iov_len = v->output_buffer_size,
829 };
830 struct msghdr mh = {
831 .msg_iov = &iov,
832 .msg_iovlen = 1,
833 .msg_controllen = CMSG_SPACE(sizeof(int) * v->n_output_fds),
834 };
835
836 mh.msg_control = alloca0(mh.msg_controllen);
837
838 struct cmsghdr *control = CMSG_FIRSTHDR(&mh);
839 control->cmsg_len = CMSG_LEN(sizeof(int) * v->n_output_fds);
840 control->cmsg_level = SOL_SOCKET;
841 control->cmsg_type = SCM_RIGHTS;
842 memcpy(CMSG_DATA(control), v->output_fds, sizeof(int) * v->n_output_fds);
843
844 n = sendmsg(v->fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
845 } else {
846 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
847 * with non-socket IO, hence fall back automatically.
848 *
849 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
850 bool prefer_write = v->prefer_read_write;
851 if (!prefer_write) {
852 n = send(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size, MSG_DONTWAIT|MSG_NOSIGNAL);
853 if (n < 0 && errno == ENOTSOCK)
854 prefer_write = v->prefer_read_write = true;
855 }
856 if (prefer_write)
857 n = write(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size);
d41bd96f 858 }
d41bd96f
LP
859 if (n < 0) {
860 if (errno == EAGAIN)
861 return 0;
862
863 if (ERRNO_IS_DISCONNECT(errno)) {
864 /* If we get informed about a disconnect on write, then let's remember that, but not
865 * act on it just yet. Let's wait for read() to report the issue first. */
866 v->write_disconnected = true;
867 return 1;
868 }
869
870 return -errno;
871 }
872
db1f7c84
LP
873 if (v->output_buffer_sensitive)
874 explicit_bzero_safe(v->output_buffer + v->output_buffer_index, n);
875
d41bd96f
LP
876 v->output_buffer_size -= n;
877
db1f7c84 878 if (v->output_buffer_size == 0) {
d41bd96f 879 v->output_buffer_index = 0;
db1f7c84
LP
880 v->output_buffer_sensitive = false; /* We can reset the sensitive flag once the buffer is empty */
881 } else
d41bd96f
LP
882 v->output_buffer_index += n;
883
d37cdac6
LP
884 close_many(v->output_fds, v->n_output_fds);
885 v->n_output_fds = 0;
886
d41bd96f
LP
887 v->timestamp = now(CLOCK_MONOTONIC);
888 return 1;
889}
890
d37cdac6
LP
891#define VARLINK_FDS_MAX (16U*1024U)
892
d41bd96f 893static int varlink_read(Varlink *v) {
d37cdac6
LP
894 struct iovec iov;
895 struct msghdr mh;
d41bd96f
LP
896 size_t rs;
897 ssize_t n;
d37cdac6 898 void *p;
d41bd96f
LP
899
900 assert(v);
901
9bca9891 902 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING, VARLINK_IDLE_SERVER))
d41bd96f
LP
903 return 0;
904 if (v->connecting) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
905 return 0;
906 if (v->current)
907 return 0;
908 if (v->input_buffer_unscanned > 0)
909 return 0;
910 if (v->read_disconnected)
911 return 0;
912
913 if (v->input_buffer_size >= VARLINK_BUFFER_MAX)
914 return -ENOBUFS;
915
916 assert(v->fd >= 0);
917
319a4f4b 918 if (MALLOC_SIZEOF_SAFE(v->input_buffer) <= v->input_buffer_index + v->input_buffer_size) {
d41bd96f
LP
919 size_t add;
920
921 add = MIN(VARLINK_BUFFER_MAX - v->input_buffer_size, VARLINK_READ_SIZE);
922
923 if (v->input_buffer_index == 0) {
924
319a4f4b 925 if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_size + add))
d41bd96f
LP
926 return -ENOMEM;
927
928 } else {
929 char *b;
930
931 b = new(char, v->input_buffer_size + add);
932 if (!b)
933 return -ENOMEM;
934
935 memcpy(b, v->input_buffer + v->input_buffer_index, v->input_buffer_size);
936
937 free_and_replace(v->input_buffer, b);
d41bd96f
LP
938 v->input_buffer_index = 0;
939 }
940 }
941
d37cdac6 942 p = v->input_buffer + v->input_buffer_index + v->input_buffer_size;
319a4f4b 943 rs = MALLOC_SIZEOF_SAFE(v->input_buffer) - (v->input_buffer_index + v->input_buffer_size);
d41bd96f 944
d37cdac6 945 if (v->allow_fd_passing_input) {
0347b9fd 946 iov = IOVEC_MAKE(p, rs);
3c868058
LP
947
948 /* Allocate the fd buffer on the heap, since we need a lot of space potentially */
949 if (!v->input_control_buffer) {
950 v->input_control_buffer_size = CMSG_SPACE(sizeof(int) * VARLINK_FDS_MAX);
951 v->input_control_buffer = malloc(v->input_control_buffer_size);
952 if (!v->input_control_buffer)
953 return -ENOMEM;
954 }
955
d37cdac6
LP
956 mh = (struct msghdr) {
957 .msg_iov = &iov,
958 .msg_iovlen = 1,
3c868058
LP
959 .msg_control = v->input_control_buffer,
960 .msg_controllen = v->input_control_buffer_size,
d37cdac6 961 };
b456f226 962
d37cdac6
LP
963 n = recvmsg_safe(v->fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
964 } else {
965 bool prefer_read = v->prefer_read_write;
966 if (!prefer_read) {
967 n = recv(v->fd, p, rs, MSG_DONTWAIT);
968 if (n < 0 && errno == ENOTSOCK)
969 prefer_read = v->prefer_read_write = true;
970 }
971 if (prefer_read)
972 n = read(v->fd, p, rs);
d41bd96f 973 }
d41bd96f
LP
974 if (n < 0) {
975 if (errno == EAGAIN)
976 return 0;
977
978 if (ERRNO_IS_DISCONNECT(errno)) {
979 v->read_disconnected = true;
980 return 1;
981 }
982
983 return -errno;
984 }
985 if (n == 0) { /* EOF */
d37cdac6
LP
986
987 if (v->allow_fd_passing_input)
988 cmsg_close_all(&mh);
989
d41bd96f
LP
990 v->read_disconnected = true;
991 return 1;
992 }
993
d37cdac6
LP
994 if (v->allow_fd_passing_input) {
995 struct cmsghdr* cmsg;
996
997 cmsg = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, (socklen_t) -1);
998 if (cmsg) {
999 size_t add;
1000
1001 /* We only allow file descriptors to be passed along with the first byte of a
1002 * message. If they are passed with any other byte this is a protocol violation. */
1003 if (v->input_buffer_size != 0) {
1004 cmsg_close_all(&mh);
1005 return -EPROTO;
1006 }
1007
1008 add = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1009 if (add > INT_MAX - v->n_input_fds) {
1010 cmsg_close_all(&mh);
1011 return -EBADF;
1012 }
1013
1014 if (!GREEDY_REALLOC(v->input_fds, v->n_input_fds + add)) {
1015 cmsg_close_all(&mh);
1016 return -ENOMEM;
1017 }
1018
1019 memcpy_safe(v->input_fds + v->n_input_fds, CMSG_TYPED_DATA(cmsg, int), add * sizeof(int));
1020 v->n_input_fds += add;
1021 }
1022 }
1023
d41bd96f
LP
1024 v->input_buffer_size += n;
1025 v->input_buffer_unscanned += n;
1026
1027 return 1;
1028}
1029
1030static int varlink_parse_message(Varlink *v) {
a570877c
LP
1031 const char *e;
1032 char *begin;
d41bd96f
LP
1033 size_t sz;
1034 int r;
1035
1036 assert(v);
1037
1038 if (v->current)
1039 return 0;
1040 if (v->input_buffer_unscanned <= 0)
1041 return 0;
1042
1043 assert(v->input_buffer_unscanned <= v->input_buffer_size);
319a4f4b 1044 assert(v->input_buffer_index + v->input_buffer_size <= MALLOC_SIZEOF_SAFE(v->input_buffer));
d41bd96f
LP
1045
1046 begin = v->input_buffer + v->input_buffer_index;
1047
1048 e = memchr(begin + v->input_buffer_size - v->input_buffer_unscanned, 0, v->input_buffer_unscanned);
1049 if (!e) {
1050 v->input_buffer_unscanned = 0;
1051 return 0;
1052 }
1053
1054 sz = e - begin + 1;
1055
d642f640 1056 r = json_parse(begin, 0, &v->current, NULL, NULL);
a570877c
LP
1057 if (v->input_sensitive)
1058 explicit_bzero_safe(begin, sz);
77472d06
ZJS
1059 if (r < 0) {
1060 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
1061 * hence drop all buffered data now. */
1062 v->input_buffer_index = v->input_buffer_size = v->input_buffer_unscanned = 0;
1063 return varlink_log_errno(v, r, "Failed to parse JSON: %m");
1064 }
d41bd96f 1065
a570877c
LP
1066 if (v->input_sensitive) {
1067 /* Mark the parameters subfield as sensitive right-away, if that's requested */
1068 JsonVariant *parameters = json_variant_by_key(v->current, "parameters");
1069 if (parameters)
1070 json_variant_sensitive(parameters);
1071 }
1072
85978d29
LP
1073 if (DEBUG_LOGGING) {
1074 _cleanup_(erase_and_freep) char *censored_text = NULL;
1075
1076 /* Suppress sensitive fields in the debug output */
1077 r = json_variant_format(v->current, /* flags= */ JSON_FORMAT_CENSOR_SENSITIVE, &censored_text);
1078 if (r < 0)
1079 return r;
1080
1081 varlink_log(v, "Received message: %s", censored_text);
1082 }
1083
d41bd96f
LP
1084 v->input_buffer_size -= sz;
1085
1086 if (v->input_buffer_size == 0)
1087 v->input_buffer_index = 0;
1088 else
1089 v->input_buffer_index += sz;
1090
1091 v->input_buffer_unscanned = v->input_buffer_size;
1092 return 1;
1093}
1094
1095static int varlink_test_timeout(Varlink *v) {
1096 assert(v);
1097
9bca9891 1098 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING))
d41bd96f
LP
1099 return 0;
1100 if (v->timeout == USEC_INFINITY)
1101 return 0;
1102
1103 if (now(CLOCK_MONOTONIC) < usec_add(v->timestamp, v->timeout))
1104 return 0;
1105
1106 varlink_set_state(v, VARLINK_PENDING_TIMEOUT);
1107
1108 return 1;
1109}
1110
1111static int varlink_dispatch_local_error(Varlink *v, const char *error) {
1112 int r;
1113
1114 assert(v);
1115 assert(error);
1116
1117 if (!v->reply_callback)
1118 return 0;
1119
1120 r = v->reply_callback(v, NULL, error, VARLINK_REPLY_ERROR|VARLINK_REPLY_LOCAL, v->userdata);
1121 if (r < 0)
6bcc1232 1122 varlink_log_errno(v, r, "Reply callback returned error, ignoring: %m");
d41bd96f
LP
1123
1124 return 1;
1125}
1126
1127static int varlink_dispatch_timeout(Varlink *v) {
1128 assert(v);
1129
1130 if (v->state != VARLINK_PENDING_TIMEOUT)
1131 return 0;
1132
1133 varlink_set_state(v, VARLINK_PROCESSING_TIMEOUT);
1134 varlink_dispatch_local_error(v, VARLINK_ERROR_TIMEOUT);
1135 varlink_close(v);
1136
1137 return 1;
1138}
1139
1140static int varlink_dispatch_disconnect(Varlink *v) {
1141 assert(v);
1142
1143 if (v->state != VARLINK_PENDING_DISCONNECT)
1144 return 0;
1145
1146 varlink_set_state(v, VARLINK_PROCESSING_DISCONNECT);
1147 varlink_dispatch_local_error(v, VARLINK_ERROR_DISCONNECTED);
1148 varlink_close(v);
1149
1150 return 1;
1151}
1152
1153static int varlink_sanitize_parameters(JsonVariant **v) {
f2ad8924
LP
1154 int r;
1155
d41bd96f
LP
1156 assert(v);
1157
1158 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
1159 if (!*v)
1160 return json_variant_new_object(v, NULL, 0);
f2ad8924
LP
1161 if (json_variant_is_null(*v)) {
1162 JsonVariant *empty;
1163
1164 r = json_variant_new_object(&empty, NULL, 0);
1165 if (r < 0)
1166 return r;
1167
1168 json_variant_unref(*v);
1169 *v = empty;
1170 return 0;
1171 }
1172 if (!json_variant_is_object(*v))
d41bd96f
LP
1173 return -EINVAL;
1174
1175 return 0;
1176}
1177
1178static int varlink_dispatch_reply(Varlink *v) {
1179 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1180 VarlinkReplyFlags flags = 0;
1181 const char *error = NULL;
1182 JsonVariant *e;
1183 const char *k;
1184 int r;
1185
1186 assert(v);
1187
9bca9891 1188 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING))
d41bd96f
LP
1189 return 0;
1190 if (!v->current)
1191 return 0;
1192
1193 assert(v->n_pending > 0);
1194
1195 if (!json_variant_is_object(v->current))
1196 goto invalid;
1197
1198 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
1199
1200 if (streq(k, "error")) {
1201 if (error)
1202 goto invalid;
1203 if (!json_variant_is_string(e))
1204 goto invalid;
1205
1206 error = json_variant_string(e);
1207 flags |= VARLINK_REPLY_ERROR;
1208
1209 } else if (streq(k, "parameters")) {
1210 if (parameters)
1211 goto invalid;
f2ad8924 1212 if (!json_variant_is_object(e) && !json_variant_is_null(e))
d41bd96f
LP
1213 goto invalid;
1214
1215 parameters = json_variant_ref(e);
1216
1217 } else if (streq(k, "continues")) {
1218 if (FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
1219 goto invalid;
1220
1221 if (!json_variant_is_boolean(e))
1222 goto invalid;
1223
1224 if (json_variant_boolean(e))
1225 flags |= VARLINK_REPLY_CONTINUES;
1226 } else
1227 goto invalid;
1228 }
1229
45a6c965 1230 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
9bca9891 1231 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY_MORE, VARLINK_COLLECTING) && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
45a6c965
LP
1232 goto invalid;
1233
1234 /* An error is final */
d41bd96f
LP
1235 if (error && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
1236 goto invalid;
1237
1238 r = varlink_sanitize_parameters(&parameters);
1239 if (r < 0)
1240 goto invalid;
1241
72226a2f
LP
1242 v->current_reply_flags = flags;
1243
45a6c965 1244 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE)) {
d41bd96f
LP
1245 varlink_set_state(v, VARLINK_PROCESSING_REPLY);
1246
1247 if (v->reply_callback) {
1248 r = v->reply_callback(v, parameters, error, flags, v->userdata);
1249 if (r < 0)
6bcc1232 1250 varlink_log_errno(v, r, "Reply callback returned error, ignoring: %m");
d41bd96f
LP
1251 }
1252
790446bd 1253 varlink_clear_current(v);
d41bd96f
LP
1254
1255 if (v->state == VARLINK_PROCESSING_REPLY) {
1256 assert(v->n_pending > 0);
d41bd96f 1257
45a6c965
LP
1258 if (!FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
1259 v->n_pending--;
1260
1261 varlink_set_state(v,
1262 FLAGS_SET(flags, VARLINK_REPLY_CONTINUES) ? VARLINK_AWAITING_REPLY_MORE :
1263 v->n_pending == 0 ? VARLINK_IDLE_CLIENT : VARLINK_AWAITING_REPLY);
d41bd96f 1264 }
9bca9891
LP
1265 } else if (v->state == VARLINK_COLLECTING)
1266 varlink_set_state(v, VARLINK_COLLECTING_REPLY);
1267 else {
d41bd96f 1268 assert(v->state == VARLINK_CALLING);
d41bd96f
LP
1269 varlink_set_state(v, VARLINK_CALLED);
1270 }
1271
1272 return 1;
1273
1274invalid:
1275 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
1276 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
1277 varlink_close(v);
1278
1279 return 1;
1280}
1281
7e006b49
LP
1282static int generic_method_get_info(
1283 Varlink *link,
1284 JsonVariant *parameters,
1285 VarlinkMethodFlags flags,
1286 void *userdata) {
1287
1288 _cleanup_strv_free_ char **interfaces = NULL;
1289 _cleanup_free_ char *product = NULL;
1290 int r;
1291
1292 assert(link);
1293
1294 if (json_variant_elements(parameters) != 0)
c2fb27ca 1295 return varlink_error_invalid_parameter(link, parameters);
7e006b49
LP
1296
1297 product = strjoin("systemd (", program_invocation_short_name, ")");
1298 if (!product)
1299 return -ENOMEM;
1300
1301 VarlinkInterface *interface;
1302 HASHMAP_FOREACH(interface, ASSERT_PTR(link->server)->interfaces) {
1303 r = strv_extend(&interfaces, interface->name);
1304 if (r < 0)
1305 return r;
1306 }
1307
1308 strv_sort(interfaces);
1309
1310 return varlink_replyb(link, JSON_BUILD_OBJECT(
1311 JSON_BUILD_PAIR_STRING("vendor", "The systemd Project"),
1312 JSON_BUILD_PAIR_STRING("product", product),
ea2a57be 1313 JSON_BUILD_PAIR_STRING("version", PROJECT_VERSION_FULL " (" GIT_VERSION ")"),
7e006b49
LP
1314 JSON_BUILD_PAIR_STRING("url", "https://systemd.io/"),
1315 JSON_BUILD_PAIR_STRV("interfaces", interfaces)));
1316}
1317
1318static int generic_method_get_interface_description(
1319 Varlink *link,
1320 JsonVariant *parameters,
1321 VarlinkMethodFlags flags,
1322 void *userdata) {
1323
1324 static const struct JsonDispatch dispatch_table[] = {
1325 { "interface", JSON_VARIANT_STRING, json_dispatch_const_string, 0, JSON_MANDATORY },
1326 {}
1327 };
1328 _cleanup_free_ char *text = NULL;
1329 const VarlinkInterface *interface;
1330 const char *name = NULL;
1331 int r;
1332
1333 assert(link);
1334
f1b622a0 1335 r = json_dispatch(parameters, dispatch_table, 0, &name);
7e006b49
LP
1336 if (r < 0)
1337 return r;
1338
1339 interface = hashmap_get(ASSERT_PTR(link->server)->interfaces, name);
1340 if (!interface)
1341 return varlink_errorb(link, VARLINK_ERROR_INTERFACE_NOT_FOUND,
1342 JSON_BUILD_OBJECT(
1343 JSON_BUILD_PAIR_STRING("interface", name)));
1344
1345 r = varlink_idl_format(interface, &text);
1346 if (r < 0)
1347 return r;
1348
1349 return varlink_replyb(link,
1350 JSON_BUILD_OBJECT(
1351 JSON_BUILD_PAIR_STRING("description", text)));
1352}
1353
d41bd96f
LP
1354static int varlink_dispatch_method(Varlink *v) {
1355 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1356 VarlinkMethodFlags flags = 0;
7e006b49 1357 const char *method = NULL;
d41bd96f
LP
1358 JsonVariant *e;
1359 VarlinkMethod callback;
1360 const char *k;
1361 int r;
1362
1363 assert(v);
1364
1365 if (v->state != VARLINK_IDLE_SERVER)
1366 return 0;
1367 if (!v->current)
1368 return 0;
1369
1370 if (!json_variant_is_object(v->current))
1371 goto invalid;
1372
1373 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
1374
1375 if (streq(k, "method")) {
1376 if (method)
1377 goto invalid;
1378 if (!json_variant_is_string(e))
1379 goto invalid;
1380
1381 method = json_variant_string(e);
1382
1383 } else if (streq(k, "parameters")) {
1384 if (parameters)
1385 goto invalid;
f2ad8924 1386 if (!json_variant_is_object(e) && !json_variant_is_null(e))
d41bd96f
LP
1387 goto invalid;
1388
1389 parameters = json_variant_ref(e);
1390
1391 } else if (streq(k, "oneway")) {
1392
1393 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
1394 goto invalid;
1395
1396 if (!json_variant_is_boolean(e))
1397 goto invalid;
1398
1399 if (json_variant_boolean(e))
1400 flags |= VARLINK_METHOD_ONEWAY;
1401
1402 } else if (streq(k, "more")) {
1403
1404 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
1405 goto invalid;
1406
1407 if (!json_variant_is_boolean(e))
1408 goto invalid;
1409
1410 if (json_variant_boolean(e))
1411 flags |= VARLINK_METHOD_MORE;
1412
1413 } else
1414 goto invalid;
1415 }
1416
1417 if (!method)
1418 goto invalid;
1419
1420 r = varlink_sanitize_parameters(&parameters);
1421 if (r < 0)
1422 goto fail;
1423
1424 varlink_set_state(v, (flags & VARLINK_METHOD_MORE) ? VARLINK_PROCESSING_METHOD_MORE :
1425 (flags & VARLINK_METHOD_ONEWAY) ? VARLINK_PROCESSING_METHOD_ONEWAY :
1426 VARLINK_PROCESSING_METHOD);
1427
1428 assert(v->server);
1429
7e006b49
LP
1430 /* First consult user supplied method implementations */
1431 callback = hashmap_get(v->server->methods, method);
1432 if (!callback) {
1433 if (streq(method, "org.varlink.service.GetInfo"))
1434 callback = generic_method_get_info;
1435 else if (streq(method, "org.varlink.service.GetInterfaceDescription"))
1436 callback = generic_method_get_interface_description;
d41bd96f
LP
1437 }
1438
1439 if (callback) {
7e006b49
LP
1440 bool invalid = false;
1441
1442 v->current_method = hashmap_get(v->server->symbols, method);
1443 if (!v->current_method)
6bcc1232 1444 varlink_log(v, "No interface description defined for method '%s', not validating.", method);
7e006b49
LP
1445 else {
1446 const char *bad_field;
1447
1448 r = varlink_idl_validate_method_call(v->current_method, parameters, &bad_field);
1449 if (r < 0) {
613d9539
YW
1450 /* Please adjust test/units/end.sh when updating the log message. */
1451 varlink_log_errno(v, r, "Parameters for method %s() didn't pass validation on field '%s': %m",
1452 method, strna(bad_field));
c270fc44 1453
7ff96ce3 1454 if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE)) {
afc50293 1455 r = varlink_error_invalid_parameter_name(v, bad_field);
c270fc44
LP
1456 if (r < 0)
1457 return r;
1458 }
7e006b49
LP
1459 invalid = true;
1460 }
1461 }
d41bd96f 1462
7e006b49
LP
1463 if (!invalid) {
1464 r = callback(v, parameters, flags, v->userdata);
1465 if (r < 0) {
6bcc1232 1466 varlink_log_errno(v, r, "Callback for %s returned error: %m", method);
7e006b49
LP
1467
1468 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
7ff96ce3 1469 if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE)) {
7e006b49
LP
1470 r = varlink_error_errno(v, r);
1471 if (r < 0)
1472 return r;
1473 }
d41bd96f
LP
1474 }
1475 }
7ff96ce3 1476 } else if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE)) {
7e006b49 1477 r = varlink_errorb(v, VARLINK_ERROR_METHOD_NOT_FOUND, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method))));
d41bd96f
LP
1478 if (r < 0)
1479 return r;
c931c871 1480 }
d41bd96f
LP
1481
1482 switch (v->state) {
1483
1484 case VARLINK_PROCESSED_METHOD: /* Method call is fully processed */
1485 case VARLINK_PROCESSING_METHOD_ONEWAY: /* ditto */
790446bd 1486 varlink_clear_current(v);
d41bd96f
LP
1487 varlink_set_state(v, VARLINK_IDLE_SERVER);
1488 break;
1489
1490 case VARLINK_PROCESSING_METHOD: /* Method call wasn't replied to, will be replied to later */
1491 varlink_set_state(v, VARLINK_PENDING_METHOD);
1492 break;
1493
d41bd96f
LP
1494 case VARLINK_PROCESSING_METHOD_MORE: /* No reply for a "more" message was sent, more to come */
1495 varlink_set_state(v, VARLINK_PENDING_METHOD_MORE);
1496 break;
1497
1498 default:
04499a70 1499 assert_not_reached();
d41bd96f
LP
1500 }
1501
c931c871 1502 return 1;
d41bd96f
LP
1503
1504invalid:
1505 r = -EINVAL;
1506
1507fail:
1508 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
1509 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
1510 varlink_close(v);
1511
1512 return r;
1513}
1514
1515int varlink_process(Varlink *v) {
1516 int r;
1517
1518 assert_return(v, -EINVAL);
1519
1520 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1521 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1522
1523 varlink_ref(v);
1524
1525 r = varlink_write(v);
db3d4222
ZJS
1526 if (r < 0)
1527 varlink_log_errno(v, r, "Write failed: %m");
d41bd96f
LP
1528 if (r != 0)
1529 goto finish;
1530
1531 r = varlink_dispatch_reply(v);
db3d4222
ZJS
1532 if (r < 0)
1533 varlink_log_errno(v, r, "Reply dispatch failed: %m");
d41bd96f
LP
1534 if (r != 0)
1535 goto finish;
1536
1537 r = varlink_dispatch_method(v);
db3d4222
ZJS
1538 if (r < 0)
1539 varlink_log_errno(v, r, "Method dispatch failed: %m");
d41bd96f
LP
1540 if (r != 0)
1541 goto finish;
1542
1543 r = varlink_parse_message(v);
db3d4222
ZJS
1544 if (r < 0)
1545 varlink_log_errno(v, r, "Message parsing failed: %m");
d41bd96f
LP
1546 if (r != 0)
1547 goto finish;
1548
1549 r = varlink_read(v);
db3d4222
ZJS
1550 if (r < 0)
1551 varlink_log_errno(v, r, "Read failed: %m");
d41bd96f
LP
1552 if (r != 0)
1553 goto finish;
1554
1555 r = varlink_test_disconnect(v);
db3d4222 1556 assert(r >= 0);
d41bd96f
LP
1557 if (r != 0)
1558 goto finish;
1559
1560 r = varlink_dispatch_disconnect(v);
db3d4222 1561 assert(r >= 0);
d41bd96f
LP
1562 if (r != 0)
1563 goto finish;
1564
1565 r = varlink_test_timeout(v);
db3d4222 1566 assert(r >= 0);
d41bd96f
LP
1567 if (r != 0)
1568 goto finish;
1569
1570 r = varlink_dispatch_timeout(v);
db3d4222 1571 assert(r >= 0);
d41bd96f
LP
1572 if (r != 0)
1573 goto finish;
1574
1575finish:
1576 if (r >= 0 && v->defer_event_source) {
1577 int q;
1578
1579 /* If we did some processing, make sure we are called again soon */
1580 q = sd_event_source_set_enabled(v->defer_event_source, r > 0 ? SD_EVENT_ON : SD_EVENT_OFF);
1581 if (q < 0)
db3d4222 1582 r = varlink_log_errno(v, q, "Failed to enable deferred event source: %m");
d41bd96f
LP
1583 }
1584
1585 if (r < 0) {
1586 if (VARLINK_STATE_IS_ALIVE(v->state))
1587 /* Initiate disconnection */
1588 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
1589 else
1590 /* We failed while disconnecting, in that case close right away */
1591 varlink_close(v);
1592 }
1593
1594 varlink_unref(v);
1595 return r;
1596}
1597
35793c71
LP
1598int varlink_dispatch_again(Varlink *v) {
1599 int r;
1600
1601 assert_return(v, -EINVAL);
1602
1603 /* If a method call handler could not process the method call just yet (for example because it needed
1604 * some Polkit authentication first), then it can leave the call unanswered, do its thing, and then
1605 * ask to be dispatched a second time, via this call. It will then be called again, for the same
1606 * message */
1607
1608 if (v->state == VARLINK_DISCONNECTED)
1609 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1610 if (v->state != VARLINK_PENDING_METHOD)
1611 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection has no pending method.");
1612
1613 varlink_set_state(v, VARLINK_IDLE_SERVER);
1614
1615 r = sd_event_source_set_enabled(v->defer_event_source, SD_EVENT_ON);
1616 if (r < 0)
1617 return varlink_log_errno(v, r, "Failed to enable deferred event source: %m");
1618
1619 return 0;
1620}
1621
1622int varlink_get_current_parameters(Varlink *v, JsonVariant **ret) {
1623 JsonVariant *p;
1624
1625 assert_return(v, -EINVAL);
1626
1627 if (!v->current)
1628 return -ENODATA;
1629
1630 p = json_variant_by_key(v->current, "parameters");
1631 if (!p)
1632 return -ENODATA;
1633
1634 if (ret)
1635 *ret = json_variant_ref(p);
1636
1637 return 0;
1638}
1639
d41bd96f
LP
1640static void handle_revents(Varlink *v, int revents) {
1641 assert(v);
1642
1643 if (v->connecting) {
1644 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
1645 * to complete on, we know we are ready. We don't read the connection error here though,
1646 * we'll get the error on the next read() or write(). */
1647 if ((revents & (POLLOUT|POLLHUP)) == 0)
1648 return;
1649
6976bf5c 1650 varlink_log(v, "Asynchronous connection completed.");
d41bd96f
LP
1651 v->connecting = false;
1652 } else {
1653 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1654 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1655 * momentarily don't want to read nor write anything. */
1656
1657 if (!FLAGS_SET(revents, POLLHUP))
1658 return;
1659
1660 varlink_log(v, "Got POLLHUP from socket.");
1661 v->got_pollhup = true;
1662 }
1663}
1664
1665int varlink_wait(Varlink *v, usec_t timeout) {
d41bd96f
LP
1666 int r, fd, events;
1667 usec_t t;
1668
1669 assert_return(v, -EINVAL);
d41bd96f
LP
1670
1671 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1672 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1673
1674 r = varlink_get_timeout(v, &t);
1675 if (r < 0)
1676 return r;
1677 if (t != USEC_INFINITY) {
1678 usec_t n;
1679
1680 n = now(CLOCK_MONOTONIC);
1681 if (t < n)
1682 t = 0;
1683 else
1684 t = usec_sub_unsigned(t, n);
1685 }
1686
1687 if (timeout != USEC_INFINITY &&
1688 (t == USEC_INFINITY || timeout < t))
1689 t = timeout;
1690
1691 fd = varlink_get_fd(v);
1692 if (fd < 0)
1693 return fd;
1694
1695 events = varlink_get_events(v);
1696 if (events < 0)
1697 return events;
1698
0f2d351f 1699 r = fd_wait_for_event(fd, events, t);
13d84288
ZJS
1700 if (ERRNO_IS_NEG_TRANSIENT(r)) /* Treat EINTR as not a timeout, but also nothing happened, and
1701 * the caller gets a chance to call back into us */
6976bf5c 1702 return 1;
05827831 1703 if (r <= 0)
0f2d351f 1704 return r;
d41bd96f 1705
0f2d351f 1706 handle_revents(v, r);
dad28bff 1707 return 1;
d41bd96f
LP
1708}
1709
8240fa92
LP
1710int varlink_is_idle(Varlink *v) {
1711 assert_return(v, -EINVAL);
1712
1713 /* Returns true if there's nothing pending on the connection anymore, i.e. we processed all incoming
1714 * or outgoing messages fully, or finished disconnection */
1715
1716 return IN_SET(v->state, VARLINK_DISCONNECTED, VARLINK_IDLE_CLIENT, VARLINK_IDLE_SERVER);
1717}
1718
d41bd96f
LP
1719int varlink_get_fd(Varlink *v) {
1720
1721 assert_return(v, -EINVAL);
1722
1723 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1724 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f 1725 if (v->fd < 0)
db3d4222 1726 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBADF), "No valid fd.");
d41bd96f
LP
1727
1728 return v->fd;
1729}
1730
1731int varlink_get_events(Varlink *v) {
1732 int ret = 0;
1733
1734 assert_return(v, -EINVAL);
1735
1736 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1737 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1738
1739 if (v->connecting) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1740 * tells us that the connection is now complete. Before that we should neither
1741 * write() or read() from the fd. */
1742 return EPOLLOUT;
1743
1744 if (!v->read_disconnected &&
9bca9891 1745 IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING, VARLINK_IDLE_SERVER) &&
d41bd96f
LP
1746 !v->current &&
1747 v->input_buffer_unscanned <= 0)
1748 ret |= EPOLLIN;
1749
1750 if (!v->write_disconnected &&
1751 v->output_buffer_size > 0)
1752 ret |= EPOLLOUT;
1753
1754 return ret;
1755}
1756
1757int varlink_get_timeout(Varlink *v, usec_t *ret) {
1758 assert_return(v, -EINVAL);
1759
1760 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1761 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f 1762
9bca9891 1763 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_COLLECTING) &&
d41bd96f
LP
1764 v->timeout != USEC_INFINITY) {
1765 if (ret)
1766 *ret = usec_add(v->timestamp, v->timeout);
1767 return 1;
1768 } else {
1769 if (ret)
1770 *ret = USEC_INFINITY;
1771 return 0;
1772 }
1773}
1774
1775int varlink_flush(Varlink *v) {
1776 int ret = 0, r;
1777
1778 assert_return(v, -EINVAL);
1779
1780 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1781 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1782
1783 for (;;) {
d41bd96f
LP
1784 if (v->output_buffer_size == 0)
1785 break;
1786 if (v->write_disconnected)
1787 return -ECONNRESET;
1788
1789 r = varlink_write(v);
1790 if (r < 0)
1791 return r;
1792 if (r > 0) {
1793 ret = 1;
1794 continue;
1795 }
1796
0f2d351f 1797 r = fd_wait_for_event(v->fd, POLLOUT, USEC_INFINITY);
bb44fd07
ZJS
1798 if (ERRNO_IS_NEG_TRANSIENT(r))
1799 continue;
1800 if (r < 0)
db3d4222 1801 return varlink_log_errno(v, r, "Poll failed on fd: %m");
bb44fd07 1802 assert(r > 0);
dad28bff 1803
0f2d351f 1804 handle_revents(v, r);
d41bd96f
LP
1805 }
1806
1807 return ret;
1808}
1809
1810static void varlink_detach_server(Varlink *v) {
6d4d6002 1811 VarlinkServer *saved_server;
d41bd96f
LP
1812 assert(v);
1813
1814 if (!v->server)
1815 return;
1816
1817 if (v->server->by_uid &&
1818 v->ucred_acquired &&
1819 uid_is_valid(v->ucred.uid)) {
1820 unsigned c;
1821
1822 c = PTR_TO_UINT(hashmap_get(v->server->by_uid, UID_TO_PTR(v->ucred.uid)));
1823 assert(c > 0);
1824
1825 if (c == 1)
1826 (void) hashmap_remove(v->server->by_uid, UID_TO_PTR(v->ucred.uid));
1827 else
1828 (void) hashmap_replace(v->server->by_uid, UID_TO_PTR(v->ucred.uid), UINT_TO_PTR(c - 1));
1829 }
1830
1831 assert(v->server->n_connections > 0);
1832 v->server->n_connections--;
1833
1834 /* If this is a connection associated to a server, then let's disconnect the server and the
6d4d6002
LP
1835 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1836 * before we release the references, let's call the disconnection callback if it is defined. */
1837
1838 saved_server = TAKE_PTR(v->server);
1839
1840 if (saved_server->disconnect_callback)
1841 saved_server->disconnect_callback(saved_server, v, saved_server->userdata);
1842
47723340 1843 varlink_server_test_exit_on_idle(saved_server);
6d4d6002 1844 varlink_server_unref(saved_server);
d41bd96f
LP
1845 varlink_unref(v);
1846}
1847
1848int varlink_close(Varlink *v) {
d41bd96f
LP
1849 assert_return(v, -EINVAL);
1850
1851 if (v->state == VARLINK_DISCONNECTED)
1852 return 0;
1853
1854 varlink_set_state(v, VARLINK_DISCONNECTED);
1855
cc6b0a18
LP
1856 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1857 * which would destroy us before we can call varlink_clear() */
d41bd96f
LP
1858 varlink_ref(v);
1859 varlink_detach_server(v);
1860 varlink_clear(v);
1861 varlink_unref(v);
1862
1863 return 1;
1864}
1865
9652d740 1866Varlink* varlink_close_unref(Varlink *v) {
9652d740
LP
1867 if (!v)
1868 return NULL;
1869
cc6b0a18 1870 (void) varlink_close(v);
9652d740
LP
1871 return varlink_unref(v);
1872}
1873
d41bd96f 1874Varlink* varlink_flush_close_unref(Varlink *v) {
cc6b0a18
LP
1875 if (!v)
1876 return NULL;
d41bd96f 1877
cc6b0a18 1878 (void) varlink_flush(v);
39ad3f1c 1879 return varlink_close_unref(v);
d41bd96f
LP
1880}
1881
d37cdac6 1882static int varlink_format_json(Varlink *v, JsonVariant *m) {
db1f7c84 1883 _cleanup_(erase_and_freep) char *text = NULL;
99128971 1884 int sz, r;
d41bd96f
LP
1885
1886 assert(v);
1887 assert(m);
1888
99128971
LP
1889 sz = json_variant_format(m, /* flags= */ 0, &text);
1890 if (sz < 0)
1891 return sz;
1892 assert(text[sz] == '\0');
d41bd96f 1893
99128971 1894 if (v->output_buffer_size + sz + 1 > VARLINK_BUFFER_MAX)
d41bd96f
LP
1895 return -ENOBUFS;
1896
99128971
LP
1897 if (DEBUG_LOGGING) {
1898 _cleanup_(erase_and_freep) char *censored_text = NULL;
1899
1900 /* Suppress sensitive fields in the debug output */
1901 r = json_variant_format(m, /* flags= */ JSON_FORMAT_CENSOR_SENSITIVE, &censored_text);
1902 if (r < 0)
1903 return r;
1904
1905 varlink_log(v, "Sending message: %s", censored_text);
1906 }
d41bd96f
LP
1907
1908 if (v->output_buffer_size == 0) {
1909
1910 free_and_replace(v->output_buffer, text);
1911
99128971 1912 v->output_buffer_size = sz + 1;
d41bd96f
LP
1913 v->output_buffer_index = 0;
1914
1915 } else if (v->output_buffer_index == 0) {
1916
99128971 1917 if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_size + sz + 1))
d41bd96f
LP
1918 return -ENOMEM;
1919
99128971
LP
1920 memcpy(v->output_buffer + v->output_buffer_size, text, sz + 1);
1921 v->output_buffer_size += sz + 1;
d41bd96f
LP
1922 } else {
1923 char *n;
99128971 1924 const size_t new_size = v->output_buffer_size + sz + 1;
d41bd96f 1925
be44e091 1926 n = new(char, new_size);
d41bd96f
LP
1927 if (!n)
1928 return -ENOMEM;
1929
99128971 1930 memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, sz + 1);
d41bd96f
LP
1931
1932 free_and_replace(v->output_buffer, n);
319a4f4b 1933 v->output_buffer_size = new_size;
d41bd96f
LP
1934 v->output_buffer_index = 0;
1935 }
1936
99128971 1937 if (json_variant_is_sensitive_recursive(m))
db1f7c84
LP
1938 v->output_buffer_sensitive = true; /* Propagate sensitive flag */
1939 else
1940 text = mfree(text); /* No point in the erase_and_free() destructor declared above */
1941
d41bd96f
LP
1942 return 0;
1943}
1944
d37cdac6
LP
1945static int varlink_enqueue_json(Varlink *v, JsonVariant *m) {
1946 VarlinkJsonQueueItem *q;
1947
1948 assert(v);
1949 assert(m);
1950
94d82b59 1951 /* If there are no file descriptors to be queued and no queue entries yet we can shortcut things and
d37cdac6
LP
1952 * append this entry directly to the output buffer */
1953 if (v->n_pushed_fds == 0 && !v->output_queue)
1954 return varlink_format_json(v, m);
1955
1956 /* Otherwise add a queue entry for this */
1957 q = varlink_json_queue_item_new(m, v->pushed_fds, v->n_pushed_fds);
1958 if (!q)
1959 return -ENOMEM;
1960
1961 v->n_pushed_fds = 0; /* fds now belong to the queue entry */
1962
1963 LIST_INSERT_AFTER(queue, v->output_queue, v->output_queue_tail, q);
1964 v->output_queue_tail = q;
1965 return 0;
1966}
1967
1968static int varlink_format_queue(Varlink *v) {
1969 int r;
1970
1971 assert(v);
1972
1973 /* Takes entries out of the output queue and formats them into the output buffer. But only if this
1974 * would not corrupt our fd message boundaries */
1975
1976 while (v->output_queue) {
1977 _cleanup_free_ int *array = NULL;
1978 VarlinkJsonQueueItem *q = v->output_queue;
1979
1980 if (v->n_output_fds > 0) /* unwritten fds? if we'd add more we'd corrupt the fd message boundaries, hence wait */
1981 return 0;
1982
1983 if (q->n_fds > 0) {
1984 array = newdup(int, q->fds, q->n_fds);
1985 if (!array)
1986 return -ENOMEM;
1987 }
1988
1989 r = varlink_format_json(v, q->data);
1990 if (r < 0)
1991 return r;
1992
1993 /* Take possession of the queue element's fds */
1994 free(v->output_fds);
1995 v->output_fds = TAKE_PTR(array);
1996 v->n_output_fds = q->n_fds;
1997 q->n_fds = 0;
1998
1999 LIST_REMOVE(queue, v->output_queue, q);
2000 if (!v->output_queue)
2001 v->output_queue_tail = NULL;
2002
2003 varlink_json_queue_item_free(q);
2004 }
2005
2006 return 0;
2007}
2008
d41bd96f
LP
2009int varlink_send(Varlink *v, const char *method, JsonVariant *parameters) {
2010 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2011 int r;
2012
2013 assert_return(v, -EINVAL);
2014 assert_return(method, -EINVAL);
2015
2016 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2017 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965
LP
2018
2019 /* We allow enqueuing multiple method calls at once! */
d41bd96f 2020 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 2021 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2022
2023 r = varlink_sanitize_parameters(&parameters);
2024 if (r < 0)
db3d4222 2025 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2026
2027 r = json_build(&m, JSON_BUILD_OBJECT(
2028 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
2029 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2030 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
2031 if (r < 0)
db3d4222 2032 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2033
2034 r = varlink_enqueue_json(v, m);
2035 if (r < 0)
db3d4222 2036 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2037
2038 /* No state change here, this is one-way only after all */
2039 v->timestamp = now(CLOCK_MONOTONIC);
2040 return 0;
2041}
2042
2043int varlink_sendb(Varlink *v, const char *method, ...) {
2044 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2045 va_list ap;
2046 int r;
2047
2048 assert_return(v, -EINVAL);
2049
2050 va_start(ap, method);
2051 r = json_buildv(&parameters, ap);
2052 va_end(ap);
2053
2054 if (r < 0)
db3d4222 2055 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2056
2057 return varlink_send(v, method, parameters);
2058}
2059
2060int varlink_invoke(Varlink *v, const char *method, JsonVariant *parameters) {
2061 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2062 int r;
2063
2064 assert_return(v, -EINVAL);
2065 assert_return(method, -EINVAL);
2066
2067 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2068 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965 2069
86b52a39 2070 /* We allow enqueuing multiple method calls at once! */
d41bd96f 2071 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 2072 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2073
2074 r = varlink_sanitize_parameters(&parameters);
2075 if (r < 0)
db3d4222 2076 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2077
2078 r = json_build(&m, JSON_BUILD_OBJECT(
2079 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
2080 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2081 if (r < 0)
db3d4222 2082 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2083
2084 r = varlink_enqueue_json(v, m);
2085 if (r < 0)
db3d4222 2086 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2087
2088 varlink_set_state(v, VARLINK_AWAITING_REPLY);
2089 v->n_pending++;
2090 v->timestamp = now(CLOCK_MONOTONIC);
2091
2092 return 0;
2093}
2094
2095int varlink_invokeb(Varlink *v, const char *method, ...) {
2096 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2097 va_list ap;
2098 int r;
2099
2100 assert_return(v, -EINVAL);
2101
2102 va_start(ap, method);
2103 r = json_buildv(&parameters, ap);
2104 va_end(ap);
2105
2106 if (r < 0)
db3d4222 2107 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2108
2109 return varlink_invoke(v, method, parameters);
45a6c965
LP
2110}
2111
2112int varlink_observe(Varlink *v, const char *method, JsonVariant *parameters) {
2113 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2114 int r;
2115
2116 assert_return(v, -EINVAL);
2117 assert_return(method, -EINVAL);
2118
2119 if (v->state == VARLINK_DISCONNECTED)
db3d4222
ZJS
2120 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
2121
45a6c965
LP
2122 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
2123 * thus insist on an idle client here. */
2124 if (v->state != VARLINK_IDLE_CLIENT)
db3d4222 2125 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
45a6c965
LP
2126
2127 r = varlink_sanitize_parameters(&parameters);
2128 if (r < 0)
db3d4222 2129 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
45a6c965
LP
2130
2131 r = json_build(&m, JSON_BUILD_OBJECT(
2132 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
2133 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2134 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
2135 if (r < 0)
db3d4222 2136 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
2137
2138 r = varlink_enqueue_json(v, m);
2139 if (r < 0)
db3d4222 2140 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
45a6c965
LP
2141
2142 varlink_set_state(v, VARLINK_AWAITING_REPLY_MORE);
2143 v->n_pending++;
2144 v->timestamp = now(CLOCK_MONOTONIC);
2145
2146 return 0;
2147}
2148
2149int varlink_observeb(Varlink *v, const char *method, ...) {
2150 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2151 va_list ap;
2152 int r;
2153
2154 assert_return(v, -EINVAL);
2155
2156 va_start(ap, method);
2157 r = json_buildv(&parameters, ap);
2158 va_end(ap);
2159
2160 if (r < 0)
db3d4222 2161 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
2162
2163 return varlink_observe(v, method, parameters);
d41bd96f
LP
2164}
2165
0444391d 2166int varlink_call_full(
d41bd96f
LP
2167 Varlink *v,
2168 const char *method,
2169 JsonVariant *parameters,
2170 JsonVariant **ret_parameters,
2171 const char **ret_error_id,
2172 VarlinkReplyFlags *ret_flags) {
2173
2174 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2175 int r;
2176
2177 assert_return(v, -EINVAL);
2178 assert_return(method, -EINVAL);
2179
2180 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2181 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
4f06325c 2182 if (v->state != VARLINK_IDLE_CLIENT)
db3d4222 2183 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2184
2185 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2186
d37cdac6
LP
2187 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2188 * that we can assign a new reply shortly. */
790446bd 2189 varlink_clear_current(v);
85316317 2190
d41bd96f
LP
2191 r = varlink_sanitize_parameters(&parameters);
2192 if (r < 0)
db3d4222 2193 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2194
2195 r = json_build(&m, JSON_BUILD_OBJECT(
2196 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
2197 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2198 if (r < 0)
db3d4222 2199 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2200
2201 r = varlink_enqueue_json(v, m);
2202 if (r < 0)
db3d4222 2203 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2204
2205 varlink_set_state(v, VARLINK_CALLING);
2206 v->n_pending++;
2207 v->timestamp = now(CLOCK_MONOTONIC);
2208
2209 while (v->state == VARLINK_CALLING) {
d41bd96f
LP
2210 r = varlink_process(v);
2211 if (r < 0)
2212 return r;
2213 if (r > 0)
2214 continue;
2215
2216 r = varlink_wait(v, USEC_INFINITY);
2217 if (r < 0)
2218 return r;
2219 }
2220
2221 switch (v->state) {
2222
19ea126e 2223 case VARLINK_CALLED: {
d41bd96f
LP
2224 assert(v->current);
2225
d41bd96f
LP
2226 varlink_set_state(v, VARLINK_IDLE_CLIENT);
2227 assert(v->n_pending == 1);
2228 v->n_pending--;
2229
19ea126e
LP
2230 JsonVariant *e = json_variant_by_key(v->current, "error"),
2231 *p = json_variant_by_key(v->current, "parameters");
2232
2233 /* If caller doesn't ask for the error string, then let's return an error code in case of failure */
2234 if (!ret_error_id && e)
2235 return varlink_error_to_errno(json_variant_string(e), p);
2236
d41bd96f 2237 if (ret_parameters)
19ea126e 2238 *ret_parameters = p;
d41bd96f 2239 if (ret_error_id)
19ea126e 2240 *ret_error_id = e ? json_variant_string(e) : NULL;
d41bd96f 2241 if (ret_flags)
72226a2f 2242 *ret_flags = v->current_reply_flags;
d41bd96f
LP
2243
2244 return 1;
19ea126e 2245 }
d41bd96f
LP
2246
2247 case VARLINK_PENDING_DISCONNECT:
2248 case VARLINK_DISCONNECTED:
db3d4222 2249 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
d41bd96f
LP
2250
2251 case VARLINK_PENDING_TIMEOUT:
db3d4222 2252 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
d41bd96f
LP
2253
2254 default:
04499a70 2255 assert_not_reached();
d41bd96f
LP
2256 }
2257}
2258
0444391d 2259int varlink_callb_ap(
d41bd96f
LP
2260 Varlink *v,
2261 const char *method,
2262 JsonVariant **ret_parameters,
2263 const char **ret_error_id,
0444391d
LP
2264 VarlinkReplyFlags *ret_flags,
2265 va_list ap) {
d41bd96f
LP
2266
2267 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
d41bd96f
LP
2268 int r;
2269
2270 assert_return(v, -EINVAL);
71d0ecc5 2271 assert_return(method, -EINVAL);
d41bd96f 2272
d41bd96f 2273 r = json_buildv(&parameters, ap);
d41bd96f 2274 if (r < 0)
db3d4222 2275 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2276
0444391d 2277 return varlink_call_full(v, method, parameters, ret_parameters, ret_error_id, ret_flags);
d41bd96f
LP
2278}
2279
71d0ecc5
LP
2280int varlink_call_and_log(
2281 Varlink *v,
2282 const char *method,
2283 JsonVariant *parameters,
2284 JsonVariant **ret_parameters) {
2285
2286 JsonVariant *reply = NULL;
2287 const char *error_id = NULL;
2288 int r;
2289
2290 assert_return(v, -EINVAL);
2291 assert_return(method, -EINVAL);
2292
2293 r = varlink_call(v, method, parameters, &reply, &error_id);
2294 if (r < 0)
2295 return log_error_errno(r, "Failed to issue %s() varlink call: %m", method);
2296 if (error_id)
2297 return log_error_errno(varlink_error_to_errno(error_id, reply),
2298 "Failed to issue %s() varlink call: %s", method, error_id);
2299
2300 if (ret_parameters)
2301 *ret_parameters = TAKE_PTR(reply);
2302
2303 return 0;
2304}
2305
2306int varlink_callb_and_log(
2307 Varlink *v,
2308 const char *method,
2309 JsonVariant **ret_parameters,
2310 ...) {
2311
2312 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2313 va_list ap;
2314 int r;
2315
2316 assert_return(v, -EINVAL);
2317 assert_return(method, -EINVAL);
2318
2319 va_start(ap, ret_parameters);
2320 r = json_buildv(&parameters, ap);
2321 va_end(ap);
2322 if (r < 0)
2323 return log_error_errno(r, "Failed to build JSON message: %m");
2324
2325 return varlink_call_and_log(v, method, parameters, ret_parameters);
2326}
2327
9bca9891 2328int varlink_collect_full(
1bd0b9c0
AS
2329 Varlink *v,
2330 const char *method,
2331 JsonVariant *parameters,
2332 JsonVariant **ret_parameters,
2333 const char **ret_error_id,
2334 VarlinkReplyFlags *ret_flags) {
2335
9bca9891 2336 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL, *collected = NULL;
1bd0b9c0
AS
2337 int r;
2338
2339 assert_return(v, -EINVAL);
2340 assert_return(method, -EINVAL);
2341
2342 if (v->state == VARLINK_DISCONNECTED)
2343 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
2344 if (v->state != VARLINK_IDLE_CLIENT)
2345 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
2346
2347 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
2348
2349 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
2350 * that we can assign a new reply shortly. */
2351 varlink_clear_current(v);
2352
9bca9891 2353 r = varlink_sanitize_parameters(&parameters);
1bd0b9c0 2354 if (r < 0)
9bca9891 2355 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1bd0b9c0 2356
9bca9891
LP
2357 r = json_build(&m, JSON_BUILD_OBJECT(
2358 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
2359 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2360 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1bd0b9c0 2361 if (r < 0)
9bca9891 2362 return varlink_log_errno(v, r, "Failed to build json message: %m");
1bd0b9c0 2363
9bca9891
LP
2364 r = varlink_enqueue_json(v, m);
2365 if (r < 0)
2366 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1bd0b9c0 2367
9bca9891
LP
2368 varlink_set_state(v, VARLINK_COLLECTING);
2369 v->n_pending++;
2370 v->timestamp = now(CLOCK_MONOTONIC);
19ea126e 2371
9bca9891
LP
2372 for (;;) {
2373 while (v->state == VARLINK_COLLECTING) {
2374 r = varlink_process(v);
2375 if (r < 0)
2376 return r;
2377 if (r > 0)
2378 continue;
19ea126e 2379
9bca9891
LP
2380 r = varlink_wait(v, USEC_INFINITY);
2381 if (r < 0)
2382 return r;
1bd0b9c0
AS
2383 }
2384
9bca9891 2385 switch (v->state) {
1bd0b9c0 2386
9bca9891
LP
2387 case VARLINK_COLLECTING_REPLY: {
2388 assert(v->current);
1bd0b9c0 2389
9bca9891
LP
2390 JsonVariant *e = json_variant_by_key(v->current, "error"),
2391 *p = json_variant_by_key(v->current, "parameters");
1bd0b9c0 2392
9f78da68
TP
2393 /* Unless there is more to collect we reset state to idle */
2394 if (!FLAGS_SET(v->current_reply_flags, VARLINK_REPLY_CONTINUES)) {
2395 varlink_set_state(v, VARLINK_IDLE_CLIENT);
2396 assert(v->n_pending == 1);
2397 v->n_pending--;
2398 }
2399
9bca9891
LP
2400 if (e) {
2401 if (!ret_error_id)
2402 return varlink_error_to_errno(json_variant_string(e), p);
1bd0b9c0 2403
9bca9891
LP
2404 if (ret_parameters)
2405 *ret_parameters = p;
2406 if (ret_error_id)
e1390da0 2407 *ret_error_id = json_variant_string(e);
9bca9891
LP
2408 if (ret_flags)
2409 *ret_flags = v->current_reply_flags;
1bd0b9c0 2410
9bca9891
LP
2411 return 1;
2412 }
1bd0b9c0 2413
9bca9891
LP
2414 if (json_variant_elements(collected) >= VARLINK_COLLECT_MAX)
2415 return varlink_log_errno(v, SYNTHETIC_ERRNO(E2BIG), "Number of reply messages grew too large (%zu) while collecting.", json_variant_elements(collected));
1bd0b9c0 2416
9bca9891
LP
2417 r = json_variant_append_array(&collected, p);
2418 if (r < 0)
2419 return varlink_log_errno(v, r, "Failed to append JSON object to array: %m");
19ea126e 2420
9bca9891
LP
2421 if (FLAGS_SET(v->current_reply_flags, VARLINK_REPLY_CONTINUES)) {
2422 /* There's more to collect, continue */
2423 varlink_clear_current(v);
2424 varlink_set_state(v, VARLINK_COLLECTING);
2425 continue;
2426 }
2427
9bca9891
LP
2428 if (ret_parameters)
2429 /* Install the collection array in the connection object, so that we can hand
2430 * out a pointer to it without passing over ownership, to make it work more
2431 * alike regular method call replies */
2432 *ret_parameters = v->current_collected = TAKE_PTR(collected);
2433 if (ret_error_id)
2434 *ret_error_id = NULL;
2435 if (ret_flags)
2436 *ret_flags = v->current_reply_flags;
2437
2438 return 1;
2439 }
2440
2441 case VARLINK_PENDING_DISCONNECT:
2442 case VARLINK_DISCONNECTED:
2443 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
2444
2445 case VARLINK_PENDING_TIMEOUT:
2446 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
2447
2448 default:
2449 assert_not_reached();
2450 }
2451 }
1bd0b9c0
AS
2452}
2453
2454int varlink_collectb(
2455 Varlink *v,
2456 const char *method,
2457 JsonVariant **ret_parameters,
2458 const char **ret_error_id,
9bca9891 2459 ...) {
1bd0b9c0
AS
2460
2461 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2462 va_list ap;
2463 int r;
2464
2465 assert_return(v, -EINVAL);
2466
9bca9891 2467 va_start(ap, ret_error_id);
1bd0b9c0
AS
2468 r = json_buildv(&parameters, ap);
2469 va_end(ap);
2470
2471 if (r < 0)
2472 return varlink_log_errno(v, r, "Failed to build json message: %m");
2473
9bca9891 2474 return varlink_collect_full(v, method, parameters, ret_parameters, ret_error_id, NULL);
1bd0b9c0
AS
2475}
2476
d41bd96f
LP
2477int varlink_reply(Varlink *v, JsonVariant *parameters) {
2478 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2479 int r;
2480
2481 assert_return(v, -EINVAL);
2482
2483 if (v->state == VARLINK_DISCONNECTED)
2484 return -ENOTCONN;
2485 if (!IN_SET(v->state,
2486 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
2487 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
2488 return -EBUSY;
2489
2490 r = varlink_sanitize_parameters(&parameters);
2491 if (r < 0)
db3d4222 2492 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2493
2494 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2495 if (r < 0)
db3d4222 2496 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2497
7e006b49
LP
2498 if (v->current_method) {
2499 const char *bad_field = NULL;
2500
2501 r = varlink_idl_validate_method_reply(v->current_method, parameters, &bad_field);
2502 if (r < 0)
613d9539
YW
2503 /* Please adjust test/units/end.sh when updating the log message. */
2504 varlink_log_errno(v, r, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2505 v->current_method->name, strna(bad_field));
7e006b49
LP
2506 }
2507
d41bd96f
LP
2508 r = varlink_enqueue_json(v, m);
2509 if (r < 0)
db3d4222 2510 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2511
2512 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
2513 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
2514 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
2515 * process further messages. */
790446bd 2516 varlink_clear_current(v);
d41bd96f
LP
2517 varlink_set_state(v, VARLINK_IDLE_SERVER);
2518 } else
2519 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
2520 * means we should it handle the rest of the state engine. */
2521 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
2522
2523 return 1;
2524}
2525
2526int varlink_replyb(Varlink *v, ...) {
2527 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2528 va_list ap;
2529 int r;
2530
2531 assert_return(v, -EINVAL);
2532
2533 va_start(ap, v);
2534 r = json_buildv(&parameters, ap);
2535 va_end(ap);
2536
2537 if (r < 0)
2538 return r;
2539
2540 return varlink_reply(v, parameters);
2541}
2542
2543int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
2544 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2545 int r;
2546
2547 assert_return(v, -EINVAL);
2548 assert_return(error_id, -EINVAL);
2549
2550 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2551 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
2552 if (!IN_SET(v->state,
2553 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
2554 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
db3d4222 2555 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f 2556
d37cdac6
LP
2557 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
2558 * simplify code that puts together a complex reply message with fds, and half-way something
2559 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
2560 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
2561 * the callers don't need to do this explicitly. */
2562 varlink_reset_fds(v);
2563
d41bd96f
LP
2564 r = varlink_sanitize_parameters(&parameters);
2565 if (r < 0)
db3d4222 2566 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2567
2568 r = json_build(&m, JSON_BUILD_OBJECT(
2569 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
2570 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2571 if (r < 0)
db3d4222 2572 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2573
7e006b49
LP
2574 VarlinkSymbol *symbol = hashmap_get(v->server->symbols, error_id);
2575 if (!symbol)
6bcc1232 2576 varlink_log(v, "No interface description defined for error '%s', not validating.", error_id);
7e006b49
LP
2577 else {
2578 const char *bad_field = NULL;
2579
80f6507c 2580 r = varlink_idl_validate_error(symbol, parameters, &bad_field);
7e006b49 2581 if (r < 0)
613d9539
YW
2582 /* Please adjust test/units/end.sh when updating the log message. */
2583 varlink_log_errno(v, r, "Parameters for error %s didn't pass validation on field '%s', ignoring: %m",
2584 error_id, strna(bad_field));
7e006b49
LP
2585 }
2586
d41bd96f
LP
2587 r = varlink_enqueue_json(v, m);
2588 if (r < 0)
db3d4222 2589 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2590
2591 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
790446bd 2592 varlink_clear_current(v);
d41bd96f
LP
2593 varlink_set_state(v, VARLINK_IDLE_SERVER);
2594 } else
2595 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
2596
2597 return 1;
2598}
2599
2600int varlink_errorb(Varlink *v, const char *error_id, ...) {
2601 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2602 va_list ap;
2603 int r;
2604
2605 assert_return(v, -EINVAL);
2606 assert_return(error_id, -EINVAL);
2607
2608 va_start(ap, error_id);
2609 r = json_buildv(&parameters, ap);
2610 va_end(ap);
2611
2612 if (r < 0)
db3d4222 2613 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2614
2615 return varlink_error(v, error_id, parameters);
2616}
2617
2618int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
e8aba093 2619 int r;
d41bd96f
LP
2620
2621 assert_return(v, -EINVAL);
2622 assert_return(parameters, -EINVAL);
2623
2624 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
2625 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
2626 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
2627 * don't expect any arguments. */
2628
e8aba093
VCS
2629 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
2630 * parameter sanitization to fail, and it returns -EINVAL. */
2631
2632 if (json_variant_is_string(parameters)) {
2633 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
2634
2635 r = json_build(&parameters_obj,
2636 JSON_BUILD_OBJECT(
2637 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters))));
2638 if (r < 0)
2639 return r;
2640
2641 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
2642 }
d41bd96f
LP
2643
2644 if (json_variant_is_object(parameters) &&
e8aba093
VCS
2645 json_variant_elements(parameters) > 0) {
2646 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
2647
2648 r = json_build(&parameters_obj,
2649 JSON_BUILD_OBJECT(
2650 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters, 0)))));
2651 if (r < 0)
2652 return r;
2653
2654 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
2655 }
d41bd96f
LP
2656
2657 return -EINVAL;
2658}
2659
afc50293
LP
2660int varlink_error_invalid_parameter_name(Varlink *v, const char *name) {
2661 return varlink_errorb(
2662 v,
2663 VARLINK_ERROR_INVALID_PARAMETER,
2664 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameter", JSON_BUILD_STRING(name))));
2665}
2666
7466e94f
LP
2667int varlink_error_errno(Varlink *v, int error) {
2668 return varlink_errorb(
2669 v,
2670 VARLINK_ERROR_SYSTEM,
2671 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error)))));
2672}
2673
d41bd96f
LP
2674int varlink_notify(Varlink *v, JsonVariant *parameters) {
2675 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2676 int r;
2677
2678 assert_return(v, -EINVAL);
2679
2680 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2681 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
47c9bbb1
LP
2682
2683 /* If we want to reply with a notify connection but the caller didn't set "more", then return an
2684 * error indicating that we expected to be called with "more" set */
2685 if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PENDING_METHOD))
2686 return varlink_error(v, VARLINK_ERROR_EXPECTED_MORE, NULL);
2687
d41bd96f 2688 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
db3d4222 2689 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2690
2691 r = varlink_sanitize_parameters(&parameters);
2692 if (r < 0)
db3d4222 2693 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2694
2695 r = json_build(&m, JSON_BUILD_OBJECT(
2696 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2697 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2698 if (r < 0)
db3d4222 2699 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2700
7e006b49
LP
2701 if (v->current_method) {
2702 const char *bad_field = NULL;
2703
2704 r = varlink_idl_validate_method_reply(v->current_method, parameters, &bad_field);
2705 if (r < 0)
613d9539
YW
2706 /* Please adjust test/units/end.sh when updating the log message. */
2707 varlink_log_errno(v, r, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2708 v->current_method->name, strna(bad_field));
7e006b49
LP
2709 }
2710
d41bd96f
LP
2711 r = varlink_enqueue_json(v, m);
2712 if (r < 0)
db3d4222 2713 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2714
2715 /* No state change, as more is coming */
2716 return 1;
2717}
2718
2719int varlink_notifyb(Varlink *v, ...) {
2720 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2721 va_list ap;
2722 int r;
2723
2724 assert_return(v, -EINVAL);
2725
2726 va_start(ap, v);
2727 r = json_buildv(&parameters, ap);
2728 va_end(ap);
2729
2730 if (r < 0)
db3d4222 2731 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2732
2733 return varlink_notify(v, parameters);
2734}
2735
f1b622a0
LP
2736int varlink_dispatch(Varlink *v, JsonVariant *parameters, const JsonDispatch table[], void *userdata) {
2737 const char *bad_field = NULL;
2738 int r;
2739
2740 assert_return(v, -EINVAL);
2741 assert_return(table, -EINVAL);
2742
2743 /* A wrapper around json_dispatch_full() that returns a nice InvalidParameter error if we hit a problem with some field. */
2744
2745 r = json_dispatch_full(parameters, table, /* bad= */ NULL, /* flags= */ 0, userdata, &bad_field);
2746 if (r < 0) {
2747 if (bad_field)
afc50293 2748 return varlink_error_invalid_parameter_name(v, bad_field);
f1b622a0
LP
2749 return r;
2750 }
2751
2752 return 0;
2753}
2754
d41bd96f
LP
2755int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
2756 assert_return(v, -EINVAL);
2757
2758 if (callback && v->reply_callback && callback != v->reply_callback)
db3d4222 2759 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
2760
2761 v->reply_callback = callback;
2762
2763 return 0;
2764}
2765
2766void* varlink_set_userdata(Varlink *v, void *userdata) {
2767 void *old;
2768
2769 assert_return(v, NULL);
2770
2771 old = v->userdata;
2772 v->userdata = userdata;
2773
2774 return old;
2775}
2776
2777void* varlink_get_userdata(Varlink *v) {
2778 assert_return(v, NULL);
2779
2780 return v->userdata;
2781}
2782
2783static int varlink_acquire_ucred(Varlink *v) {
2784 int r;
2785
2786 assert(v);
2787
2788 if (v->ucred_acquired)
2789 return 0;
2790
2791 r = getpeercred(v->fd, &v->ucred);
2792 if (r < 0)
2793 return r;
2794
2795 v->ucred_acquired = true;
2796 return 0;
2797}
2798
2799int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
2800 int r;
2801
2802 assert_return(v, -EINVAL);
2803 assert_return(ret, -EINVAL);
2804
2805 r = varlink_acquire_ucred(v);
2806 if (r < 0)
db3d4222 2807 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2808
2809 if (!uid_is_valid(v->ucred.uid))
52bd6137 2810 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer UID is invalid.");
d41bd96f
LP
2811
2812 *ret = v->ucred.uid;
2813 return 0;
2814}
2815
52bd6137
LP
2816int varlink_get_peer_gid(Varlink *v, gid_t *ret) {
2817 int r;
2818
2819 assert_return(v, -EINVAL);
2820 assert_return(ret, -EINVAL);
2821
2822 r = varlink_acquire_ucred(v);
2823 if (r < 0)
2824 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
2825
2826 if (!gid_is_valid(v->ucred.gid))
2827 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer GID is invalid.");
2828
2829 *ret = v->ucred.gid;
2830 return 0;
2831}
2832
d41bd96f
LP
2833int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
2834 int r;
2835
2836 assert_return(v, -EINVAL);
2837 assert_return(ret, -EINVAL);
2838
2839 r = varlink_acquire_ucred(v);
2840 if (r < 0)
db3d4222 2841 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2842
2843 if (!pid_is_valid(v->ucred.pid))
db3d4222 2844 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
2845
2846 *ret = v->ucred.pid;
2847 return 0;
2848}
2849
0eccf725
LP
2850static int varlink_acquire_pidfd(Varlink *v) {
2851 assert(v);
2852
2853 if (v->peer_pidfd >= 0)
2854 return 0;
2855
2856 v->peer_pidfd = getpeerpidfd(v->fd);
2857 if (v->peer_pidfd < 0)
2858 return v->peer_pidfd;
2859
2860 return 0;
2861}
2862
2863int varlink_get_peer_pidref(Varlink *v, PidRef *ret) {
2864 int r;
2865
2866 assert_return(v, -EINVAL);
2867 assert_return(ret, -EINVAL);
2868
2869 /* Returns r > 0 if we acquired the pidref via SO_PEERPIDFD (i.e. if we can use it for
2870 * authentication). Returns == 0 if we didn't, and the pidref should not be used for
2871 * authentication. */
2872
2873 r = varlink_acquire_pidfd(v);
78ef6635 2874 if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
0eccf725
LP
2875 return r;
2876
2877 if (v->peer_pidfd < 0) {
2878 pid_t pid;
2879
2880 r = varlink_get_peer_pid(v, &pid);
2881 if (r < 0)
2882 return r;
2883
2884 r = pidref_set_pid(ret, pid);
2885 if (r < 0)
2886 return r;
2887
2888 return 0; /* didn't get pidfd securely */
2889 }
2890
2891 r = pidref_set_pidfd(ret, v->peer_pidfd);
2892 if (r < 0)
2893 return r;
2894
2895 return 1; /* got pidfd securely */
2896}
2897
d41bd96f
LP
2898int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
2899 assert_return(v, -EINVAL);
2900 assert_return(timeout > 0, -EINVAL);
2901
2902 v->timeout = timeout;
2903 return 0;
2904}
2905
2906VarlinkServer *varlink_get_server(Varlink *v) {
2907 assert_return(v, NULL);
2908
2909 return v->server;
2910}
2911
2912int varlink_set_description(Varlink *v, const char *description) {
2913 assert_return(v, -EINVAL);
2914
2915 return free_and_strdup(&v->description, description);
2916}
2917
2918static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
99534007 2919 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2920
2921 assert(s);
d41bd96f
LP
2922
2923 handle_revents(v, revents);
2924 (void) varlink_process(v);
2925
2926 return 1;
2927}
2928
2929static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
99534007 2930 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2931
2932 assert(s);
d41bd96f
LP
2933
2934 (void) varlink_process(v);
2935 return 1;
2936}
2937
2938static int defer_callback(sd_event_source *s, void *userdata) {
99534007 2939 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2940
2941 assert(s);
d41bd96f
LP
2942
2943 (void) varlink_process(v);
2944 return 1;
2945}
2946
2947static int prepare_callback(sd_event_source *s, void *userdata) {
99534007 2948 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2949 int r, e;
2950 usec_t until;
f1194f5d 2951 bool have_timeout;
d41bd96f
LP
2952
2953 assert(s);
d41bd96f
LP
2954
2955 e = varlink_get_events(v);
2956 if (e < 0)
2957 return e;
2958
2959 r = sd_event_source_set_io_events(v->io_event_source, e);
2960 if (r < 0)
db3d4222 2961 return varlink_log_errno(v, r, "Failed to set source events: %m");
d41bd96f
LP
2962
2963 r = varlink_get_timeout(v, &until);
2964 if (r < 0)
2965 return r;
f1194f5d
LP
2966 have_timeout = r > 0;
2967
2968 if (have_timeout) {
d41bd96f
LP
2969 r = sd_event_source_set_time(v->time_event_source, until);
2970 if (r < 0)
db3d4222 2971 return varlink_log_errno(v, r, "Failed to set source time: %m");
d41bd96f
LP
2972 }
2973
f1194f5d 2974 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
d41bd96f 2975 if (r < 0)
db3d4222 2976 return varlink_log_errno(v, r, "Failed to enable event source: %m");
d41bd96f
LP
2977
2978 return 1;
2979}
2980
2981static int quit_callback(sd_event_source *event, void *userdata) {
99534007 2982 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2983
2984 assert(event);
d41bd96f
LP
2985
2986 varlink_flush(v);
2987 varlink_close(v);
2988
2989 return 1;
2990}
2991
2992int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
2993 int r;
2994
2995 assert_return(v, -EINVAL);
2996 assert_return(!v->event, -EBUSY);
2997
2998 if (e)
2999 v->event = sd_event_ref(e);
3000 else {
3001 r = sd_event_default(&v->event);
3002 if (r < 0)
db3d4222 3003 return varlink_log_errno(v, r, "Failed to create event source: %m");
d41bd96f
LP
3004 }
3005
3006 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
3007 if (r < 0)
3008 goto fail;
3009
3010 r = sd_event_source_set_priority(v->time_event_source, priority);
3011 if (r < 0)
3012 goto fail;
3013
3014 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
3015
3016 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
3017 if (r < 0)
3018 goto fail;
3019
3020 r = sd_event_source_set_priority(v->quit_event_source, priority);
3021 if (r < 0)
3022 goto fail;
3023
3024 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
3025
3026 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
3027 if (r < 0)
3028 goto fail;
3029
3030 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
3031 if (r < 0)
3032 goto fail;
3033
3034 r = sd_event_source_set_priority(v->io_event_source, priority);
3035 if (r < 0)
3036 goto fail;
3037
3038 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
3039
3040 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
3041 if (r < 0)
3042 goto fail;
3043
3044 r = sd_event_source_set_priority(v->defer_event_source, priority);
3045 if (r < 0)
3046 goto fail;
3047
3048 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
3049
3050 return 0;
3051
3052fail:
db3d4222 3053 varlink_log_errno(v, r, "Failed to setup event source: %m");
d41bd96f
LP
3054 varlink_detach_event(v);
3055 return r;
3056}
3057
d41bd96f
LP
3058void varlink_detach_event(Varlink *v) {
3059 if (!v)
3060 return;
3061
3062 varlink_detach_event_sources(v);
3063
3064 v->event = sd_event_unref(v->event);
3065}
3066
3067sd_event *varlink_get_event(Varlink *v) {
3068 assert_return(v, NULL);
3069
3070 return v->event;
3071}
3072
d37cdac6
LP
3073int varlink_push_fd(Varlink *v, int fd) {
3074 int i;
3075
3076 assert_return(v, -EINVAL);
3077 assert_return(fd >= 0, -EBADF);
3078
3079 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
3080 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
3081
3082 if (!v->allow_fd_passing_output)
3083 return -EPERM;
3084
3085 if (v->n_pushed_fds >= INT_MAX)
3086 return -ENOMEM;
3087
3088 if (!GREEDY_REALLOC(v->pushed_fds, v->n_pushed_fds + 1))
3089 return -ENOMEM;
3090
3091 i = (int) v->n_pushed_fds;
3092 v->pushed_fds[v->n_pushed_fds++] = fd;
3093 return i;
3094}
3095
b219dcd4 3096int varlink_push_dup_fd(Varlink *v, int fd) {
d37cdac6
LP
3097 _cleanup_close_ int dp = -1;
3098 int r;
3099
3100 assert_return(v, -EINVAL);
3101 assert_return(fd >= 0, -EBADF);
3102
3103 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
3104
3105 dp = fcntl(fd, F_DUPFD_CLOEXEC, 3);
3106 if (dp < 0)
3107 return -errno;
3108
3109 r = varlink_push_fd(v, dp);
3110 if (r < 0)
3111 return r;
3112
3113 TAKE_FD(dp);
3114 return r;
3115}
3116
3117int varlink_reset_fds(Varlink *v) {
3118 assert_return(v, -EINVAL);
3119
3120 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
3121 * of putting together a message with fds, and then eventually something fails and they need to
3122 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
3123
3124 close_many(v->output_fds, v->n_output_fds);
3125 v->n_output_fds = 0;
3126 return 0;
3127}
3128
3129int varlink_peek_fd(Varlink *v, size_t i) {
3130 assert_return(v, -EINVAL);
3131
94d82b59 3132 /* Returns one of the file descriptors that were received along with the current message. This does
d37cdac6
LP
3133 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
3134
3135 if (!v->allow_fd_passing_input)
3136 return -EPERM;
3137
3138 if (i >= v->n_input_fds)
3139 return -ENXIO;
3140
3141 return v->input_fds[i];
3142}
3143
b219dcd4
LP
3144int varlink_peek_dup_fd(Varlink *v, size_t i) {
3145 int fd;
3146
3147 fd = varlink_peek_fd(v, i);
3148 if (fd < 0)
3149 return fd;
3150
3151 return RET_NERRNO(fcntl(fd, F_DUPFD_CLOEXEC, 3));
3152}
3153
d37cdac6
LP
3154int varlink_take_fd(Varlink *v, size_t i) {
3155 assert_return(v, -EINVAL);
3156
3157 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
3158 * we'll invalidate the reference to it under our possession. If called twice in a row will return
3159 * -EBADF */
3160
3161 if (!v->allow_fd_passing_input)
3162 return -EPERM;
3163
3164 if (i >= v->n_input_fds)
3165 return -ENXIO;
3166
3167 return TAKE_FD(v->input_fds[i]);
3168}
3169
3170static int verify_unix_socket(Varlink *v) {
3171 assert(v);
3172
b24c384b
LP
3173 /* Returns:
3174 * • 0 if this is an AF_UNIX socket
3175 * • -ENOTSOCK if this is not a socket at all
3176 * • -ENOMEDIUM if this is a socket, but not an AF_UNIX socket
3177 *
3178 * Reminder:
3179 * • v->af is < 0 if we haven't checked what kind of address family the thing is yet.
3180 * • v->af == AF_UNSPEC if we checked but it's not a socket
3181 * • otherwise: v->af contains the address family we determined */
3182
d37cdac6
LP
3183 if (v->af < 0) {
3184 struct stat st;
3185
3186 if (fstat(v->fd, &st) < 0)
3187 return -errno;
3188 if (!S_ISSOCK(st.st_mode)) {
3189 v->af = AF_UNSPEC;
3190 return -ENOTSOCK;
3191 }
3192
3193 v->af = socket_get_family(v->fd);
3194 if (v->af < 0)
3195 return v->af;
3196 }
3197
b24c384b
LP
3198 return v->af == AF_UNIX ? 0 :
3199 v->af == AF_UNSPEC ? -ENOTSOCK : -ENOMEDIUM;
d37cdac6
LP
3200}
3201
3202int varlink_set_allow_fd_passing_input(Varlink *v, bool b) {
3203 int r;
3204
3205 assert_return(v, -EINVAL);
3206
3207 if (v->allow_fd_passing_input == b)
3208 return 0;
3209
3210 if (!b) {
3211 v->allow_fd_passing_input = false;
3212 return 1;
3213 }
3214
3215 r = verify_unix_socket(v);
3216 if (r < 0)
3217 return r;
3218
3219 v->allow_fd_passing_input = true;
3220 return 0;
3221}
3222
3223int varlink_set_allow_fd_passing_output(Varlink *v, bool b) {
3224 int r;
3225
3226 assert_return(v, -EINVAL);
3227
3228 if (v->allow_fd_passing_output == b)
3229 return 0;
3230
3231 if (!b) {
3232 v->allow_fd_passing_output = false;
3233 return 1;
3234 }
3235
3236 r = verify_unix_socket(v);
3237 if (r < 0)
3238 return r;
3239
3240 v->allow_fd_passing_output = true;
3241 return 0;
3242}
3243
a570877c
LP
3244int varlink_set_input_sensitive(Varlink *v) {
3245 assert_return(v, -EINVAL);
3246
3247 v->input_sensitive = true;
3248 return 0;
3249}
3250
d41bd96f 3251int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
7e006b49
LP
3252 _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL;
3253 int r;
d41bd96f
LP
3254
3255 assert_return(ret, -EINVAL);
3256 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
3257
3258 s = new(VarlinkServer, 1);
3259 if (!s)
db3d4222 3260 return log_oom_debug();
d41bd96f
LP
3261
3262 *s = (VarlinkServer) {
3263 .n_ref = 1,
3264 .flags = flags,
3265 .connections_max = varlink_server_connections_max(NULL),
3266 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
3267 };
3268
7e006b49
LP
3269 r = varlink_server_add_interface_many(
3270 s,
3271 &vl_interface_io_systemd,
3272 &vl_interface_org_varlink_service);
3273 if (r < 0)
3274 return r;
3275
3276 *ret = TAKE_PTR(s);
d41bd96f
LP
3277 return 0;
3278}
3279
3280static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
3281 char *m;
3282
3283 if (!s)
3284 return NULL;
3285
3286 varlink_server_shutdown(s);
3287
3288 while ((m = hashmap_steal_first_key(s->methods)))
3289 free(m);
3290
3291 hashmap_free(s->methods);
9fc843ed 3292 hashmap_free(s->interfaces);
7e006b49 3293 hashmap_free(s->symbols);
d41bd96f
LP
3294 hashmap_free(s->by_uid);
3295
3296 sd_event_unref(s->event);
3297
3298 free(s->description);
3299
3300 return mfree(s);
3301}
3302
3303DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
3304
3305static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
3306 int allowed = -1;
3307
3308 assert(server);
3309 assert(ucred);
3310
3311 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
3312 allowed = ucred->uid == 0;
3313
3314 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
3315 allowed = allowed > 0 || ucred->uid == getuid();
3316
3317 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
3318 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
3319 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
3320 return 0;
3321 }
3322
3323 if (server->n_connections >= server->connections_max) {
3324 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
3325 return 0;
3326 }
3327
3328 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
3329 unsigned c;
3330
3331 if (!uid_is_valid(ucred->uid)) {
3332 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
3333 return 0;
3334 }
3335
3336 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
3337 if (c >= server->connections_per_uid_max) {
3338 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
3339 server->connections_per_uid_max);
3340 return 0;
3341 }
3342 }
3343
3344 return 1;
3345}
3346
678ca213 3347static int count_connection(VarlinkServer *server, const struct ucred *ucred) {
d41bd96f
LP
3348 unsigned c;
3349 int r;
3350
3351 assert(server);
3352 assert(ucred);
3353
3354 server->n_connections++;
3355
3356 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
a1351823
LP
3357 assert(uid_is_valid(ucred->uid));
3358
d41bd96f
LP
3359 r = hashmap_ensure_allocated(&server->by_uid, NULL);
3360 if (r < 0)
6bcc1232 3361 return varlink_server_log_errno(server, r, "Failed to allocate UID hash table: %m");
d41bd96f
LP
3362
3363 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
3364
3365 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
3366 ucred->uid, c, server->connections_per_uid_max);
3367
3368 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
3369 if (r < 0)
6bcc1232 3370 return varlink_server_log_errno(server, r, "Failed to increment counter in UID hash table: %m");
d41bd96f
LP
3371 }
3372
3373 return 0;
3374}
3375
3376int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
3377 _cleanup_(varlink_unrefp) Varlink *v = NULL;
a995ce47 3378 struct ucred ucred = UCRED_INVALID;
d41bd96f 3379 bool ucred_acquired;
d41bd96f
LP
3380 int r;
3381
3382 assert_return(server, -EINVAL);
3383 assert_return(fd >= 0, -EBADF);
3384
3385 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
3386 r = getpeercred(fd, &ucred);
3387 if (r < 0)
3388 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
3389
3390 ucred_acquired = true;
3391
3392 r = validate_connection(server, &ucred);
3393 if (r < 0)
3394 return r;
3395 if (r == 0)
3396 return -EPERM;
3397 } else
3398 ucred_acquired = false;
3399
3400 r = varlink_new(&v);
3401 if (r < 0)
3402 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
3403
3404 r = count_connection(server, &ucred);
3405 if (r < 0)
3406 return r;
3407
3408 v->fd = fd;
9807fdc1
LP
3409 if (server->flags & VARLINK_SERVER_INHERIT_USERDATA)
3410 v->userdata = server->userdata;
3411
d41bd96f
LP
3412 if (ucred_acquired) {
3413 v->ucred = ucred;
3414 v->ucred_acquired = true;
3415 }
3416
12619d0a 3417 _cleanup_free_ char *desc = NULL;
10157428 3418 if (asprintf(&desc, "%s-%i", varlink_server_description(server), v->fd) >= 0)
12619d0a 3419 v->description = TAKE_PTR(desc);
d41bd96f
LP
3420
3421 /* Link up the server and the connection, and take reference in both directions. Note that the
3422 * reference on the connection is left dangling. It will be dropped when the connection is closed,
3423 * which happens in varlink_close(), including in the event loop quit callback. */
3424 v->server = varlink_server_ref(server);
3425 varlink_ref(v);
3426
3427 varlink_set_state(v, VARLINK_IDLE_SERVER);
3428
7e69d90c
LP
3429 if (server->event) {
3430 r = varlink_attach_event(v, server->event, server->event_priority);
3431 if (r < 0) {
3432 varlink_log_errno(v, r, "Failed to attach new connection: %m");
254d1313 3433 v->fd = -EBADF; /* take the fd out of the connection again */
7e69d90c
LP
3434 varlink_close(v);
3435 return r;
3436 }
d41bd96f
LP
3437 }
3438
3439 if (ret)
3440 *ret = v;
3441
3442 return 0;
3443}
3444
c14e841f
AZ
3445static VarlinkServerSocket *varlink_server_socket_free(VarlinkServerSocket *ss) {
3446 if (!ss)
3447 return NULL;
3448
3449 free(ss->address);
3450 return mfree(ss);
3451}
3452
3453DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket *, varlink_server_socket_free);
3454
d41bd96f 3455static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
99534007 3456 VarlinkServerSocket *ss = ASSERT_PTR(userdata);
254d1313 3457 _cleanup_close_ int cfd = -EBADF;
d41bd96f
LP
3458 Varlink *v = NULL;
3459 int r;
3460
3461 assert(source);
d41bd96f
LP
3462
3463 varlink_server_log(ss->server, "New incoming connection.");
3464
3465 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
3466 if (cfd < 0) {
3467 if (ERRNO_IS_ACCEPT_AGAIN(errno))
3468 return 0;
3469
3470 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
3471 }
3472
3473 r = varlink_server_add_connection(ss->server, cfd, &v);
3474 if (r < 0)
3475 return 0;
3476
3477 TAKE_FD(cfd);
3478
a570877c
LP
3479 if (FLAGS_SET(ss->server->flags, VARLINK_SERVER_INPUT_SENSITIVE))
3480 varlink_set_input_sensitive(v);
3481
d41bd96f
LP
3482 if (ss->server->connect_callback) {
3483 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
3484 if (r < 0) {
3485 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
3486 varlink_close(v);
3487 return 0;
3488 }
3489 }
3490
3491 return 0;
3492}
3493
c14e841f
AZ
3494static int varlink_server_create_listen_fd_socket(VarlinkServer *s, int fd, VarlinkServerSocket **ret_ss) {
3495 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f
LP
3496 int r;
3497
c14e841f
AZ
3498 assert(s);
3499 assert(fd >= 0);
3500 assert(ret_ss);
d41bd96f 3501
d41bd96f
LP
3502 ss = new(VarlinkServerSocket, 1);
3503 if (!ss)
db3d4222 3504 return log_oom_debug();
d41bd96f
LP
3505
3506 *ss = (VarlinkServerSocket) {
3507 .server = s,
3508 .fd = fd,
3509 };
3510
3511 if (s->event) {
8d91b220 3512 r = sd_event_add_io(s->event, &ss->event_source, fd, EPOLLIN, connect_callback, ss);
d41bd96f
LP
3513 if (r < 0)
3514 return r;
3515
3516 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
3517 if (r < 0)
3518 return r;
3519 }
3520
c14e841f
AZ
3521 *ret_ss = TAKE_PTR(ss);
3522 return 0;
3523}
3524
3525int varlink_server_listen_fd(VarlinkServer *s, int fd) {
3526 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
3527 int r;
3528
3529 assert_return(s, -EINVAL);
3530 assert_return(fd >= 0, -EBADF);
3531
a4edf033
LP
3532 r = fd_nonblock(fd, true);
3533 if (r < 0)
3534 return r;
3535
3536 r = fd_cloexec(fd, true);
3537 if (r < 0)
3538 return r;
3539
c14e841f
AZ
3540 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
3541 if (r < 0)
3542 return r;
3543
d41bd96f
LP
3544 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
3545 return 0;
3546}
3547
3548int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
c14e841f 3549 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f 3550 union sockaddr_union sockaddr;
f36a9d59 3551 socklen_t sockaddr_len;
254d1313 3552 _cleanup_close_ int fd = -EBADF;
d41bd96f
LP
3553 int r;
3554
3555 assert_return(s, -EINVAL);
3556 assert_return(address, -EINVAL);
3557 assert_return((m & ~0777) == 0, -EINVAL);
3558
3559 r = sockaddr_un_set_path(&sockaddr.un, address);
3560 if (r < 0)
3561 return r;
f36a9d59 3562 sockaddr_len = r;
d41bd96f
LP
3563
3564 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
3565 if (fd < 0)
3566 return -errno;
3567
a0c41de2
LP
3568 fd = fd_move_above_stdio(fd);
3569
d41bd96f
LP
3570 (void) sockaddr_un_unlink(&sockaddr.un);
3571
2053593f 3572 WITH_UMASK(~m & 0777) {
63e00ccd
CG
3573 r = mac_selinux_bind(fd, &sockaddr.sa, sockaddr_len);
3574 if (r < 0)
3575 return r;
3576 }
d41bd96f 3577
768fcd77 3578 if (listen(fd, SOMAXCONN_DELUXE) < 0)
d41bd96f
LP
3579 return -errno;
3580
c14e841f 3581 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
d41bd96f
LP
3582 if (r < 0)
3583 return r;
3584
c14e841f
AZ
3585 r = free_and_strdup(&ss->address, address);
3586 if (r < 0)
3587 return r;
3588
3589 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
d41bd96f
LP
3590 TAKE_FD(fd);
3591 return 0;
3592}
3593
206504a5
LP
3594int varlink_server_listen_auto(VarlinkServer *s) {
3595 _cleanup_strv_free_ char **names = NULL;
3596 int r, n = 0;
3597
3598 assert_return(s, -EINVAL);
3599
3600 /* Adds all passed fds marked as "varlink" to our varlink server. These fds can either refer to a
3601 * listening socket or to a connection socket.
3602 *
3603 * See https://varlink.org/#activation for the environment variables this is backed by and the
3604 * recommended "varlink" identifier in $LISTEN_FDNAMES. */
3605
3606 r = sd_listen_fds_with_names(/* unset_environment= */ false, &names);
3607 if (r < 0)
3608 return r;
3609
3610 for (int i = 0; i < r; i++) {
3611 int b, fd;
3612 socklen_t l = sizeof(b);
3613
3614 if (!streq(names[i], "varlink"))
3615 continue;
3616
3617 fd = SD_LISTEN_FDS_START + i;
3618
3619 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
3620 return -errno;
3621
3622 assert(l == sizeof(b));
3623
3624 if (b) /* Listening socket? */
3625 r = varlink_server_listen_fd(s, fd);
3626 else /* Otherwise assume connection socket */
3627 r = varlink_server_add_connection(s, fd, NULL);
3628 if (r < 0)
3629 return r;
3630
3631 n++;
3632 }
3633
4a6fe5f0
LP
3634 /* For debug purposes let's listen on an explicitly specified address */
3635 const char *e = secure_getenv("SYSTEMD_VARLINK_LISTEN");
3636 if (e) {
3637 r = varlink_server_listen_address(s, e, FLAGS_SET(s->flags, VARLINK_SERVER_ROOT_ONLY) ? 0600 : 0666);
3638 if (r < 0)
3639 return r;
3640 }
3641
206504a5
LP
3642 return n;
3643}
3644
d41bd96f
LP
3645void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
3646 void *ret;
3647
3648 assert_return(s, NULL);
3649
3650 ret = s->userdata;
3651 s->userdata = userdata;
3652
3653 return ret;
3654}
3655
3656void* varlink_server_get_userdata(VarlinkServer *s) {
3657 assert_return(s, NULL);
3658
3659 return s->userdata;
3660}
3661
2e5edb93
LP
3662int varlink_server_loop_auto(VarlinkServer *server) {
3663 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
3664 int r;
3665
3666 assert_return(server, -EINVAL);
3667 assert_return(!server->event, -EBUSY);
3668
3669 /* Runs a Varlink service event loop populated with a passed fd. Exits on the last connection. */
3670
3671 r = sd_event_new(&event);
3672 if (r < 0)
3673 return r;
3674
3675 r = varlink_server_set_exit_on_idle(server, true);
3676 if (r < 0)
3677 return r;
3678
3679 r = varlink_server_attach_event(server, event, 0);
3680 if (r < 0)
3681 return r;
3682
3683 r = varlink_server_listen_auto(server);
3684 if (r < 0)
3685 return r;
3686
3687 return sd_event_loop(event);
3688}
3689
d41bd96f
LP
3690static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
3691 if (!ss)
3692 return NULL;
3693
3694 if (ss->server)
3695 LIST_REMOVE(sockets, ss->server->sockets, ss);
3696
1d3fe304 3697 sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
3698
3699 free(ss->address);
3700 safe_close(ss->fd);
3701
3702 return mfree(ss);
3703}
3704
3705int varlink_server_shutdown(VarlinkServer *s) {
3706 assert_return(s, -EINVAL);
3707
3708 while (s->sockets)
3709 varlink_server_socket_destroy(s->sockets);
3710
3711 return 0;
3712}
3713
47723340
LP
3714static void varlink_server_test_exit_on_idle(VarlinkServer *s) {
3715 assert(s);
3716
3717 if (s->exit_on_idle && s->event && s->n_connections == 0)
3718 (void) sd_event_exit(s->event, 0);
3719}
3720
3721int varlink_server_set_exit_on_idle(VarlinkServer *s, bool b) {
3722 assert_return(s, -EINVAL);
3723
3724 s->exit_on_idle = b;
3725 varlink_server_test_exit_on_idle(s);
3726 return 0;
3727}
3728
536827e0
AZ
3729static int varlink_server_add_socket_event_source(VarlinkServer *s, VarlinkServerSocket *ss, int64_t priority) {
3730 _cleanup_(sd_event_source_unrefp) sd_event_source *es = NULL;
536827e0
AZ
3731 int r;
3732
3733 assert(s);
3734 assert(s->event);
3735 assert(ss);
3736 assert(ss->fd >= 0);
3737 assert(!ss->event_source);
3738
3739 r = sd_event_add_io(s->event, &es, ss->fd, EPOLLIN, connect_callback, ss);
3740 if (r < 0)
3741 return r;
3742
3743 r = sd_event_source_set_priority(es, priority);
3744 if (r < 0)
3745 return r;
3746
3747 ss->event_source = TAKE_PTR(es);
3748 return 0;
3749}
3750
d41bd96f 3751int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
d41bd96f
LP
3752 int r;
3753
3754 assert_return(s, -EINVAL);
3755 assert_return(!s->event, -EBUSY);
3756
3757 if (e)
3758 s->event = sd_event_ref(e);
3759 else {
3760 r = sd_event_default(&s->event);
3761 if (r < 0)
3762 return r;
3763 }
3764
3765 LIST_FOREACH(sockets, ss, s->sockets) {
536827e0 3766 r = varlink_server_add_socket_event_source(s, ss, priority);
d41bd96f
LP
3767 if (r < 0)
3768 goto fail;
3769 }
3770
3771 s->event_priority = priority;
3772 return 0;
3773
3774fail:
3775 varlink_server_detach_event(s);
3776 return r;
3777}
3778
3779int varlink_server_detach_event(VarlinkServer *s) {
d41bd96f
LP
3780 assert_return(s, -EINVAL);
3781
4f538d7b
LP
3782 LIST_FOREACH(sockets, ss, s->sockets)
3783 ss->event_source = sd_event_source_disable_unref(ss->event_source);
d41bd96f 3784
03a83186 3785 s->event = sd_event_unref(s->event);
d41bd96f
LP
3786 return 0;
3787}
3788
3789sd_event *varlink_server_get_event(VarlinkServer *s) {
3790 assert_return(s, NULL);
3791
3792 return s->event;
3793}
3794
7e006b49
LP
3795static bool varlink_symbol_in_interface(const char *method, const char *interface) {
3796 const char *p;
3797
3798 assert(method);
3799 assert(interface);
3800
3801 p = startswith(method, interface);
3802 if (!p)
3803 return false;
3804
3805 if (*p != '.')
3806 return false;
3807
3808 return !strchr(p+1, '.');
3809}
3810
d41bd96f 3811int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
db3d4222 3812 _cleanup_free_ char *m = NULL;
d41bd96f
LP
3813 int r;
3814
3815 assert_return(s, -EINVAL);
3816 assert_return(method, -EINVAL);
3817 assert_return(callback, -EINVAL);
3818
7e006b49
LP
3819 if (varlink_symbol_in_interface(method, "org.varlink.service") ||
3820 varlink_symbol_in_interface(method, "io.systemd"))
6bcc1232 3821 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EEXIST), "Cannot bind server to '%s'.", method);
d41bd96f 3822
d41bd96f
LP
3823 m = strdup(method);
3824 if (!m)
db3d4222 3825 return log_oom_debug();
d41bd96f 3826
1d2d1654
SS
3827 r = hashmap_ensure_put(&s->methods, &string_hash_ops, m, callback);
3828 if (r == -ENOMEM)
3829 return log_oom_debug();
db3d4222 3830 if (r < 0)
6bcc1232 3831 return varlink_server_log_errno(s, r, "Failed to register callback: %m");
db3d4222
ZJS
3832 if (r > 0)
3833 TAKE_PTR(m);
d41bd96f
LP
3834
3835 return 0;
3836}
3837
3838int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
3839 va_list ap;
e7b93f97 3840 int r = 0;
d41bd96f
LP
3841
3842 assert_return(s, -EINVAL);
3843
3844 va_start(ap, s);
3845 for (;;) {
3846 VarlinkMethod callback;
3847 const char *method;
3848
3849 method = va_arg(ap, const char *);
3850 if (!method)
3851 break;
3852
3853 callback = va_arg(ap, VarlinkMethod);
3854
3855 r = varlink_server_bind_method(s, method, callback);
3856 if (r < 0)
e7b93f97 3857 break;
d41bd96f 3858 }
e7b93f97 3859 va_end(ap);
d41bd96f 3860
e7b93f97 3861 return r;
d41bd96f
LP
3862}
3863
3864int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
3865 assert_return(s, -EINVAL);
3866
3867 if (callback && s->connect_callback && callback != s->connect_callback)
6bcc1232 3868 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
3869
3870 s->connect_callback = callback;
3871 return 0;
3872}
3873
6d4d6002
LP
3874int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
3875 assert_return(s, -EINVAL);
3876
3877 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
6bcc1232 3878 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
6d4d6002
LP
3879
3880 s->disconnect_callback = callback;
3881 return 0;
3882}
3883
9fc843ed 3884int varlink_server_add_interface(VarlinkServer *s, const VarlinkInterface *interface) {
7e006b49
LP
3885 int r;
3886
9fc843ed
LP
3887 assert_return(s, -EINVAL);
3888 assert_return(interface, -EINVAL);
3889 assert_return(interface->name, -EINVAL);
3890
3891 if (hashmap_contains(s->interfaces, interface->name))
6bcc1232 3892 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EEXIST), "Duplicate registration of interface '%s'.", interface->name);
9fc843ed 3893
7e006b49
LP
3894 r = hashmap_ensure_put(&s->interfaces, &string_hash_ops, interface->name, (void*) interface);
3895 if (r < 0)
3896 return r;
3897
3898 for (const VarlinkSymbol *const*symbol = interface->symbols; *symbol; symbol++) {
3899 _cleanup_free_ char *j = NULL;
3900
3901 /* We only ever want to validate method calls/replies and errors against the interface
3902 * definitions, hence don't bother with the type symbols */
3903 if (!IN_SET((*symbol)->symbol_type, VARLINK_METHOD, VARLINK_ERROR))
3904 continue;
3905
3906 j = strjoin(interface->name, ".", (*symbol)->name);
3907 if (!j)
3908 return -ENOMEM;
3909
3910 r = hashmap_ensure_put(&s->symbols, &string_hash_ops_free, j, (void*) *symbol);
3911 if (r < 0)
3912 return r;
3913
3914 TAKE_PTR(j);
3915 }
3916
3917 return 0;
9fc843ed
LP
3918}
3919
3920int varlink_server_add_interface_many_internal(VarlinkServer *s, ...) {
3921 va_list ap;
3922 int r = 0;
3923
3924 assert_return(s, -EINVAL);
3925
3926 va_start(ap, s);
3927 for (;;) {
3928 const VarlinkInterface *interface = va_arg(ap, const VarlinkInterface*);
3929 if (!interface)
3930 break;
3931
3932 r = varlink_server_add_interface(s, interface);
3933 if (r < 0)
3934 break;
3935 }
3936 va_end(ap);
3937
3938 return r;
3939}
3940
d41bd96f 3941unsigned varlink_server_connections_max(VarlinkServer *s) {
88a36d36 3942 int dts;
d41bd96f
LP
3943
3944 /* If a server is specified, return the setting for that server, otherwise the default value */
3945 if (s)
3946 return s->connections_max;
3947
88a36d36
LP
3948 dts = getdtablesize();
3949 assert_se(dts > 0);
d41bd96f
LP
3950
3951 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
88a36d36
LP
3952 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
3953 return dts / 4 * 3;
d41bd96f
LP
3954
3955 return VARLINK_DEFAULT_CONNECTIONS_MAX;
3956}
3957
3958unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
3959 unsigned m;
3960
3961 if (s)
3962 return s->connections_per_uid_max;
3963
3964 /* Make sure to never use up more than ¾th of available connections for a single user */
3965 m = varlink_server_connections_max(NULL);
3966 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
3967 return m / 4 * 3;
3968
3969 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
3970}
3971
3972int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
3973 assert_return(s, -EINVAL);
3974 assert_return(m > 0, -EINVAL);
3975
3976 s->connections_per_uid_max = m;
3977 return 0;
3978}
3979
3980int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
3981 assert_return(s, -EINVAL);
3982 assert_return(m > 0, -EINVAL);
3983
3984 s->connections_max = m;
3985 return 0;
3986}
3987
c4f601f2
LP
3988unsigned varlink_server_current_connections(VarlinkServer *s) {
3989 assert_return(s, UINT_MAX);
3990
3991 return s->n_connections;
3992}
3993
d41bd96f
LP
3994int varlink_server_set_description(VarlinkServer *s, const char *description) {
3995 assert_return(s, -EINVAL);
3996
3997 return free_and_strdup(&s->description, description);
3998}
008798e9
AZ
3999
4000int varlink_server_serialize(VarlinkServer *s, FILE *f, FDSet *fds) {
4001 assert(f);
4002 assert(fds);
4003
4004 if (!s)
4005 return 0;
4006
4007 LIST_FOREACH(sockets, ss, s->sockets) {
4008 int copy;
4009
4010 assert(ss->address);
4011 assert(ss->fd >= 0);
4012
4013 fprintf(f, "varlink-server-socket-address=%s", ss->address);
4014
4015 /* If we fail to serialize the fd, it will be considered an error during deserialization */
4016 copy = fdset_put_dup(fds, ss->fd);
4017 if (copy < 0)
4018 return copy;
4019
4020 fprintf(f, " varlink-server-socket-fd=%i", copy);
4021
4022 fputc('\n', f);
4023 }
4024
4025 return 0;
4026}
4027
4028int varlink_server_deserialize_one(VarlinkServer *s, const char *value, FDSet *fds) {
4029 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
4030 _cleanup_free_ char *address = NULL;
4031 const char *v = ASSERT_PTR(value);
254d1313 4032 int r, fd = -EBADF;
008798e9
AZ
4033 char *buf;
4034 size_t n;
4035
4036 assert(s);
4037 assert(fds);
4038
4039 n = strcspn(v, " ");
4040 address = strndup(v, n);
4041 if (!address)
4042 return log_oom_debug();
4043
4044 if (v[n] != ' ')
6bcc1232 4045 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EINVAL),
008798e9
AZ
4046 "Failed to deserialize VarlinkServerSocket: %s: %m", value);
4047 v = startswith(v + n + 1, "varlink-server-socket-fd=");
4048 if (!v)
6bcc1232 4049 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EINVAL),
008798e9
AZ
4050 "Failed to deserialize VarlinkServerSocket fd %s: %m", value);
4051
4052 n = strcspn(v, " ");
4053 buf = strndupa_safe(v, n);
4054
e652663a 4055 fd = parse_fd(buf);
e652663a 4056 if (fd < 0)
6bcc1232 4057 return varlink_server_log_errno(s, fd, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf);
008798e9 4058 if (!fdset_contains(fds, fd))
6bcc1232 4059 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBADF),
008798e9
AZ
4060 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd);
4061
4062 ss = new(VarlinkServerSocket, 1);
4063 if (!ss)
4064 return log_oom_debug();
4065
4066 *ss = (VarlinkServerSocket) {
4067 .server = s,
4068 .address = TAKE_PTR(address),
4069 .fd = fdset_remove(fds, fd),
4070 };
4071
4072 r = varlink_server_add_socket_event_source(s, ss, SD_EVENT_PRIORITY_NORMAL);
4073 if (r < 0)
6bcc1232 4074 return varlink_server_log_errno(s, r, "Failed to add VarlinkServerSocket event source to the event loop: %m");
008798e9
AZ
4075
4076 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
4077 return 0;
4078}
02b0d24d
LP
4079
4080int varlink_invocation(VarlinkInvocationFlags flags) {
4081 _cleanup_strv_free_ char **names = NULL;
4082 int r, b;
4083 socklen_t l = sizeof(b);
4084
4085 /* Returns true if this is a "pure" varlink server invocation, i.e. with one fd passed. */
4086
4a6fe5f0
LP
4087 const char *e = secure_getenv("SYSTEMD_VARLINK_LISTEN"); /* Permit a manual override for testing purposes */
4088 if (e)
4089 return true;
4090
02b0d24d
LP
4091 r = sd_listen_fds_with_names(/* unset_environment= */ false, &names);
4092 if (r < 0)
4093 return r;
4094 if (r == 0)
4095 return false;
4096 if (r > 1)
4097 return -ETOOMANYREFS;
4098
4099 if (!strv_equal(names, STRV_MAKE("varlink")))
4100 return false;
4101
4102 if (FLAGS_SET(flags, VARLINK_ALLOW_LISTEN|VARLINK_ALLOW_ACCEPT)) /* Both flags set? Then allow everything */
4103 return true;
4104
4105 if ((flags & (VARLINK_ALLOW_LISTEN|VARLINK_ALLOW_ACCEPT)) == 0) /* Neither is set, then fail */
4106 return -EISCONN;
4107
4108 if (getsockopt(SD_LISTEN_FDS_START, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
4109 return -errno;
4110
4111 assert(l == sizeof(b));
4112
4113 if (!FLAGS_SET(flags, b ? VARLINK_ALLOW_LISTEN : VARLINK_ALLOW_ACCEPT))
4114 return -EISCONN;
4115
4116 return true;
4117}
a4562f94
LP
4118
4119int varlink_error_to_errno(const char *error, JsonVariant *parameters) {
4120 static const struct {
4121 const char *error;
4122 int value;
4123 } table[] = {
4124 { VARLINK_ERROR_DISCONNECTED, -ECONNRESET },
4125 { VARLINK_ERROR_TIMEOUT, -ETIMEDOUT },
4126 { VARLINK_ERROR_PROTOCOL, -EPROTO },
4127 { VARLINK_ERROR_INTERFACE_NOT_FOUND, -EADDRNOTAVAIL },
4128 { VARLINK_ERROR_METHOD_NOT_FOUND, -ENXIO },
4129 { VARLINK_ERROR_METHOD_NOT_IMPLEMENTED, -ENOTTY },
4130 { VARLINK_ERROR_INVALID_PARAMETER, -EINVAL },
4131 { VARLINK_ERROR_PERMISSION_DENIED, -EACCES },
4132 { VARLINK_ERROR_EXPECTED_MORE, -EBADE },
4133 };
4134
4135 if (!error)
4136 return 0;
4137
85471164 4138 FOREACH_ELEMENT(t, table)
a4562f94
LP
4139 if (streq(error, t->error))
4140 return t->value;
4141
4142 if (streq(error, VARLINK_ERROR_SYSTEM) && parameters) {
4143 JsonVariant *e;
4144
4145 e = json_variant_by_key(parameters, "errno");
4146 if (json_variant_is_integer(e)) {
4147 int64_t i;
4148
4149 i = json_variant_integer(e);
4150 if (i > 0 && i < ERRNO_MAX)
4151 return -i;
4152 }
4153 }
4154
4155 return -EBADR; /* Catch-all */
4156}