]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/varlink.c
varlink: rework varlink_collect()
[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),
1313 JSON_BUILD_PAIR_STRING("version", STRINGIFY(PROJECT_VERSION) " (" GIT_VERSION ")"),
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
9bca9891
LP
2393 if (e) {
2394 if (!ret_error_id)
2395 return varlink_error_to_errno(json_variant_string(e), p);
1bd0b9c0 2396
9bca9891
LP
2397 if (ret_parameters)
2398 *ret_parameters = p;
2399 if (ret_error_id)
2400 *ret_error_id = e ? json_variant_string(e) : NULL;
2401 if (ret_flags)
2402 *ret_flags = v->current_reply_flags;
1bd0b9c0 2403
9bca9891
LP
2404 return 1;
2405 }
1bd0b9c0 2406
9bca9891
LP
2407 if (json_variant_elements(collected) >= VARLINK_COLLECT_MAX)
2408 return varlink_log_errno(v, SYNTHETIC_ERRNO(E2BIG), "Number of reply messages grew too large (%zu) while collecting.", json_variant_elements(collected));
1bd0b9c0 2409
9bca9891
LP
2410 r = json_variant_append_array(&collected, p);
2411 if (r < 0)
2412 return varlink_log_errno(v, r, "Failed to append JSON object to array: %m");
19ea126e 2413
9bca9891
LP
2414 if (FLAGS_SET(v->current_reply_flags, VARLINK_REPLY_CONTINUES)) {
2415 /* There's more to collect, continue */
2416 varlink_clear_current(v);
2417 varlink_set_state(v, VARLINK_COLLECTING);
2418 continue;
2419 }
2420
2421 varlink_set_state(v, VARLINK_IDLE_CLIENT);
2422 assert(v->n_pending == 1);
2423 v->n_pending--;
2424
2425 if (ret_parameters)
2426 /* Install the collection array in the connection object, so that we can hand
2427 * out a pointer to it without passing over ownership, to make it work more
2428 * alike regular method call replies */
2429 *ret_parameters = v->current_collected = TAKE_PTR(collected);
2430 if (ret_error_id)
2431 *ret_error_id = NULL;
2432 if (ret_flags)
2433 *ret_flags = v->current_reply_flags;
2434
2435 return 1;
2436 }
2437
2438 case VARLINK_PENDING_DISCONNECT:
2439 case VARLINK_DISCONNECTED:
2440 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
2441
2442 case VARLINK_PENDING_TIMEOUT:
2443 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
2444
2445 default:
2446 assert_not_reached();
2447 }
2448 }
1bd0b9c0
AS
2449}
2450
2451int varlink_collectb(
2452 Varlink *v,
2453 const char *method,
2454 JsonVariant **ret_parameters,
2455 const char **ret_error_id,
9bca9891 2456 ...) {
1bd0b9c0
AS
2457
2458 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2459 va_list ap;
2460 int r;
2461
2462 assert_return(v, -EINVAL);
2463
9bca9891 2464 va_start(ap, ret_error_id);
1bd0b9c0
AS
2465 r = json_buildv(&parameters, ap);
2466 va_end(ap);
2467
2468 if (r < 0)
2469 return varlink_log_errno(v, r, "Failed to build json message: %m");
2470
9bca9891 2471 return varlink_collect_full(v, method, parameters, ret_parameters, ret_error_id, NULL);
1bd0b9c0
AS
2472}
2473
d41bd96f
LP
2474int varlink_reply(Varlink *v, JsonVariant *parameters) {
2475 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2476 int r;
2477
2478 assert_return(v, -EINVAL);
2479
2480 if (v->state == VARLINK_DISCONNECTED)
2481 return -ENOTCONN;
2482 if (!IN_SET(v->state,
2483 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
2484 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
2485 return -EBUSY;
2486
2487 r = varlink_sanitize_parameters(&parameters);
2488 if (r < 0)
db3d4222 2489 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2490
2491 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2492 if (r < 0)
db3d4222 2493 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2494
7e006b49
LP
2495 if (v->current_method) {
2496 const char *bad_field = NULL;
2497
2498 r = varlink_idl_validate_method_reply(v->current_method, parameters, &bad_field);
2499 if (r < 0)
613d9539
YW
2500 /* Please adjust test/units/end.sh when updating the log message. */
2501 varlink_log_errno(v, r, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2502 v->current_method->name, strna(bad_field));
7e006b49
LP
2503 }
2504
d41bd96f
LP
2505 r = varlink_enqueue_json(v, m);
2506 if (r < 0)
db3d4222 2507 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2508
2509 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
2510 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
2511 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
2512 * process further messages. */
790446bd 2513 varlink_clear_current(v);
d41bd96f
LP
2514 varlink_set_state(v, VARLINK_IDLE_SERVER);
2515 } else
2516 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
2517 * means we should it handle the rest of the state engine. */
2518 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
2519
2520 return 1;
2521}
2522
2523int varlink_replyb(Varlink *v, ...) {
2524 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2525 va_list ap;
2526 int r;
2527
2528 assert_return(v, -EINVAL);
2529
2530 va_start(ap, v);
2531 r = json_buildv(&parameters, ap);
2532 va_end(ap);
2533
2534 if (r < 0)
2535 return r;
2536
2537 return varlink_reply(v, parameters);
2538}
2539
2540int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
2541 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2542 int r;
2543
2544 assert_return(v, -EINVAL);
2545 assert_return(error_id, -EINVAL);
2546
2547 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2548 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
2549 if (!IN_SET(v->state,
2550 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
2551 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
db3d4222 2552 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f 2553
d37cdac6
LP
2554 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
2555 * simplify code that puts together a complex reply message with fds, and half-way something
2556 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
2557 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
2558 * the callers don't need to do this explicitly. */
2559 varlink_reset_fds(v);
2560
d41bd96f
LP
2561 r = varlink_sanitize_parameters(&parameters);
2562 if (r < 0)
db3d4222 2563 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2564
2565 r = json_build(&m, JSON_BUILD_OBJECT(
2566 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
2567 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
2568 if (r < 0)
db3d4222 2569 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2570
7e006b49
LP
2571 VarlinkSymbol *symbol = hashmap_get(v->server->symbols, error_id);
2572 if (!symbol)
6bcc1232 2573 varlink_log(v, "No interface description defined for error '%s', not validating.", error_id);
7e006b49
LP
2574 else {
2575 const char *bad_field = NULL;
2576
80f6507c 2577 r = varlink_idl_validate_error(symbol, parameters, &bad_field);
7e006b49 2578 if (r < 0)
613d9539
YW
2579 /* Please adjust test/units/end.sh when updating the log message. */
2580 varlink_log_errno(v, r, "Parameters for error %s didn't pass validation on field '%s', ignoring: %m",
2581 error_id, strna(bad_field));
7e006b49
LP
2582 }
2583
d41bd96f
LP
2584 r = varlink_enqueue_json(v, m);
2585 if (r < 0)
db3d4222 2586 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2587
2588 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
790446bd 2589 varlink_clear_current(v);
d41bd96f
LP
2590 varlink_set_state(v, VARLINK_IDLE_SERVER);
2591 } else
2592 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
2593
2594 return 1;
2595}
2596
2597int varlink_errorb(Varlink *v, const char *error_id, ...) {
2598 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2599 va_list ap;
2600 int r;
2601
2602 assert_return(v, -EINVAL);
2603 assert_return(error_id, -EINVAL);
2604
2605 va_start(ap, error_id);
2606 r = json_buildv(&parameters, ap);
2607 va_end(ap);
2608
2609 if (r < 0)
db3d4222 2610 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2611
2612 return varlink_error(v, error_id, parameters);
2613}
2614
2615int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
e8aba093 2616 int r;
d41bd96f
LP
2617
2618 assert_return(v, -EINVAL);
2619 assert_return(parameters, -EINVAL);
2620
2621 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
2622 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
2623 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
2624 * don't expect any arguments. */
2625
e8aba093
VCS
2626 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
2627 * parameter sanitization to fail, and it returns -EINVAL. */
2628
2629 if (json_variant_is_string(parameters)) {
2630 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
2631
2632 r = json_build(&parameters_obj,
2633 JSON_BUILD_OBJECT(
2634 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters))));
2635 if (r < 0)
2636 return r;
2637
2638 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
2639 }
d41bd96f
LP
2640
2641 if (json_variant_is_object(parameters) &&
e8aba093
VCS
2642 json_variant_elements(parameters) > 0) {
2643 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
2644
2645 r = json_build(&parameters_obj,
2646 JSON_BUILD_OBJECT(
2647 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters, 0)))));
2648 if (r < 0)
2649 return r;
2650
2651 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
2652 }
d41bd96f
LP
2653
2654 return -EINVAL;
2655}
2656
afc50293
LP
2657int varlink_error_invalid_parameter_name(Varlink *v, const char *name) {
2658 return varlink_errorb(
2659 v,
2660 VARLINK_ERROR_INVALID_PARAMETER,
2661 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameter", JSON_BUILD_STRING(name))));
2662}
2663
7466e94f
LP
2664int varlink_error_errno(Varlink *v, int error) {
2665 return varlink_errorb(
2666 v,
2667 VARLINK_ERROR_SYSTEM,
2668 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error)))));
2669}
2670
d41bd96f
LP
2671int varlink_notify(Varlink *v, JsonVariant *parameters) {
2672 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2673 int r;
2674
2675 assert_return(v, -EINVAL);
2676
2677 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2678 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
47c9bbb1
LP
2679
2680 /* If we want to reply with a notify connection but the caller didn't set "more", then return an
2681 * error indicating that we expected to be called with "more" set */
2682 if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PENDING_METHOD))
2683 return varlink_error(v, VARLINK_ERROR_EXPECTED_MORE, NULL);
2684
d41bd96f 2685 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
db3d4222 2686 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2687
2688 r = varlink_sanitize_parameters(&parameters);
2689 if (r < 0)
db3d4222 2690 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2691
2692 r = json_build(&m, JSON_BUILD_OBJECT(
2693 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2694 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2695 if (r < 0)
db3d4222 2696 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f 2697
7e006b49
LP
2698 if (v->current_method) {
2699 const char *bad_field = NULL;
2700
2701 r = varlink_idl_validate_method_reply(v->current_method, parameters, &bad_field);
2702 if (r < 0)
613d9539
YW
2703 /* Please adjust test/units/end.sh when updating the log message. */
2704 varlink_log_errno(v, r, "Return parameters for method reply %s() didn't pass validation on field '%s', ignoring: %m",
2705 v->current_method->name, strna(bad_field));
7e006b49
LP
2706 }
2707
d41bd96f
LP
2708 r = varlink_enqueue_json(v, m);
2709 if (r < 0)
db3d4222 2710 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2711
2712 /* No state change, as more is coming */
2713 return 1;
2714}
2715
2716int varlink_notifyb(Varlink *v, ...) {
2717 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2718 va_list ap;
2719 int r;
2720
2721 assert_return(v, -EINVAL);
2722
2723 va_start(ap, v);
2724 r = json_buildv(&parameters, ap);
2725 va_end(ap);
2726
2727 if (r < 0)
db3d4222 2728 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2729
2730 return varlink_notify(v, parameters);
2731}
2732
f1b622a0
LP
2733int varlink_dispatch(Varlink *v, JsonVariant *parameters, const JsonDispatch table[], void *userdata) {
2734 const char *bad_field = NULL;
2735 int r;
2736
2737 assert_return(v, -EINVAL);
2738 assert_return(table, -EINVAL);
2739
2740 /* A wrapper around json_dispatch_full() that returns a nice InvalidParameter error if we hit a problem with some field. */
2741
2742 r = json_dispatch_full(parameters, table, /* bad= */ NULL, /* flags= */ 0, userdata, &bad_field);
2743 if (r < 0) {
2744 if (bad_field)
afc50293 2745 return varlink_error_invalid_parameter_name(v, bad_field);
f1b622a0
LP
2746 return r;
2747 }
2748
2749 return 0;
2750}
2751
d41bd96f
LP
2752int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
2753 assert_return(v, -EINVAL);
2754
2755 if (callback && v->reply_callback && callback != v->reply_callback)
db3d4222 2756 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
2757
2758 v->reply_callback = callback;
2759
2760 return 0;
2761}
2762
2763void* varlink_set_userdata(Varlink *v, void *userdata) {
2764 void *old;
2765
2766 assert_return(v, NULL);
2767
2768 old = v->userdata;
2769 v->userdata = userdata;
2770
2771 return old;
2772}
2773
2774void* varlink_get_userdata(Varlink *v) {
2775 assert_return(v, NULL);
2776
2777 return v->userdata;
2778}
2779
2780static int varlink_acquire_ucred(Varlink *v) {
2781 int r;
2782
2783 assert(v);
2784
2785 if (v->ucred_acquired)
2786 return 0;
2787
2788 r = getpeercred(v->fd, &v->ucred);
2789 if (r < 0)
2790 return r;
2791
2792 v->ucred_acquired = true;
2793 return 0;
2794}
2795
2796int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
2797 int r;
2798
2799 assert_return(v, -EINVAL);
2800 assert_return(ret, -EINVAL);
2801
2802 r = varlink_acquire_ucred(v);
2803 if (r < 0)
db3d4222 2804 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2805
2806 if (!uid_is_valid(v->ucred.uid))
db3d4222 2807 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
2808
2809 *ret = v->ucred.uid;
2810 return 0;
2811}
2812
2813int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
2814 int r;
2815
2816 assert_return(v, -EINVAL);
2817 assert_return(ret, -EINVAL);
2818
2819 r = varlink_acquire_ucred(v);
2820 if (r < 0)
db3d4222 2821 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2822
2823 if (!pid_is_valid(v->ucred.pid))
db3d4222 2824 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
2825
2826 *ret = v->ucred.pid;
2827 return 0;
2828}
2829
0eccf725
LP
2830static int varlink_acquire_pidfd(Varlink *v) {
2831 assert(v);
2832
2833 if (v->peer_pidfd >= 0)
2834 return 0;
2835
2836 v->peer_pidfd = getpeerpidfd(v->fd);
2837 if (v->peer_pidfd < 0)
2838 return v->peer_pidfd;
2839
2840 return 0;
2841}
2842
2843int varlink_get_peer_pidref(Varlink *v, PidRef *ret) {
2844 int r;
2845
2846 assert_return(v, -EINVAL);
2847 assert_return(ret, -EINVAL);
2848
2849 /* Returns r > 0 if we acquired the pidref via SO_PEERPIDFD (i.e. if we can use it for
2850 * authentication). Returns == 0 if we didn't, and the pidref should not be used for
2851 * authentication. */
2852
2853 r = varlink_acquire_pidfd(v);
2854 if (r < 0)
2855 return r;
2856
2857 if (v->peer_pidfd < 0) {
2858 pid_t pid;
2859
2860 r = varlink_get_peer_pid(v, &pid);
2861 if (r < 0)
2862 return r;
2863
2864 r = pidref_set_pid(ret, pid);
2865 if (r < 0)
2866 return r;
2867
2868 return 0; /* didn't get pidfd securely */
2869 }
2870
2871 r = pidref_set_pidfd(ret, v->peer_pidfd);
2872 if (r < 0)
2873 return r;
2874
2875 return 1; /* got pidfd securely */
2876}
2877
d41bd96f
LP
2878int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
2879 assert_return(v, -EINVAL);
2880 assert_return(timeout > 0, -EINVAL);
2881
2882 v->timeout = timeout;
2883 return 0;
2884}
2885
2886VarlinkServer *varlink_get_server(Varlink *v) {
2887 assert_return(v, NULL);
2888
2889 return v->server;
2890}
2891
2892int varlink_set_description(Varlink *v, const char *description) {
2893 assert_return(v, -EINVAL);
2894
2895 return free_and_strdup(&v->description, description);
2896}
2897
2898static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
99534007 2899 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2900
2901 assert(s);
d41bd96f
LP
2902
2903 handle_revents(v, revents);
2904 (void) varlink_process(v);
2905
2906 return 1;
2907}
2908
2909static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
99534007 2910 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2911
2912 assert(s);
d41bd96f
LP
2913
2914 (void) varlink_process(v);
2915 return 1;
2916}
2917
2918static int defer_callback(sd_event_source *s, void *userdata) {
99534007 2919 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2920
2921 assert(s);
d41bd96f
LP
2922
2923 (void) varlink_process(v);
2924 return 1;
2925}
2926
2927static int prepare_callback(sd_event_source *s, void *userdata) {
99534007 2928 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2929 int r, e;
2930 usec_t until;
f1194f5d 2931 bool have_timeout;
d41bd96f
LP
2932
2933 assert(s);
d41bd96f
LP
2934
2935 e = varlink_get_events(v);
2936 if (e < 0)
2937 return e;
2938
2939 r = sd_event_source_set_io_events(v->io_event_source, e);
2940 if (r < 0)
db3d4222 2941 return varlink_log_errno(v, r, "Failed to set source events: %m");
d41bd96f
LP
2942
2943 r = varlink_get_timeout(v, &until);
2944 if (r < 0)
2945 return r;
f1194f5d
LP
2946 have_timeout = r > 0;
2947
2948 if (have_timeout) {
d41bd96f
LP
2949 r = sd_event_source_set_time(v->time_event_source, until);
2950 if (r < 0)
db3d4222 2951 return varlink_log_errno(v, r, "Failed to set source time: %m");
d41bd96f
LP
2952 }
2953
f1194f5d 2954 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
d41bd96f 2955 if (r < 0)
db3d4222 2956 return varlink_log_errno(v, r, "Failed to enable event source: %m");
d41bd96f
LP
2957
2958 return 1;
2959}
2960
2961static int quit_callback(sd_event_source *event, void *userdata) {
99534007 2962 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2963
2964 assert(event);
d41bd96f
LP
2965
2966 varlink_flush(v);
2967 varlink_close(v);
2968
2969 return 1;
2970}
2971
2972int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
2973 int r;
2974
2975 assert_return(v, -EINVAL);
2976 assert_return(!v->event, -EBUSY);
2977
2978 if (e)
2979 v->event = sd_event_ref(e);
2980 else {
2981 r = sd_event_default(&v->event);
2982 if (r < 0)
db3d4222 2983 return varlink_log_errno(v, r, "Failed to create event source: %m");
d41bd96f
LP
2984 }
2985
2986 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
2987 if (r < 0)
2988 goto fail;
2989
2990 r = sd_event_source_set_priority(v->time_event_source, priority);
2991 if (r < 0)
2992 goto fail;
2993
2994 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
2995
2996 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
2997 if (r < 0)
2998 goto fail;
2999
3000 r = sd_event_source_set_priority(v->quit_event_source, priority);
3001 if (r < 0)
3002 goto fail;
3003
3004 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
3005
3006 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
3007 if (r < 0)
3008 goto fail;
3009
3010 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
3011 if (r < 0)
3012 goto fail;
3013
3014 r = sd_event_source_set_priority(v->io_event_source, priority);
3015 if (r < 0)
3016 goto fail;
3017
3018 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
3019
3020 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
3021 if (r < 0)
3022 goto fail;
3023
3024 r = sd_event_source_set_priority(v->defer_event_source, priority);
3025 if (r < 0)
3026 goto fail;
3027
3028 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
3029
3030 return 0;
3031
3032fail:
db3d4222 3033 varlink_log_errno(v, r, "Failed to setup event source: %m");
d41bd96f
LP
3034 varlink_detach_event(v);
3035 return r;
3036}
3037
d41bd96f
LP
3038void varlink_detach_event(Varlink *v) {
3039 if (!v)
3040 return;
3041
3042 varlink_detach_event_sources(v);
3043
3044 v->event = sd_event_unref(v->event);
3045}
3046
3047sd_event *varlink_get_event(Varlink *v) {
3048 assert_return(v, NULL);
3049
3050 return v->event;
3051}
3052
d37cdac6
LP
3053int varlink_push_fd(Varlink *v, int fd) {
3054 int i;
3055
3056 assert_return(v, -EINVAL);
3057 assert_return(fd >= 0, -EBADF);
3058
3059 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
3060 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
3061
3062 if (!v->allow_fd_passing_output)
3063 return -EPERM;
3064
3065 if (v->n_pushed_fds >= INT_MAX)
3066 return -ENOMEM;
3067
3068 if (!GREEDY_REALLOC(v->pushed_fds, v->n_pushed_fds + 1))
3069 return -ENOMEM;
3070
3071 i = (int) v->n_pushed_fds;
3072 v->pushed_fds[v->n_pushed_fds++] = fd;
3073 return i;
3074}
3075
3076int varlink_dup_fd(Varlink *v, int fd) {
3077 _cleanup_close_ int dp = -1;
3078 int r;
3079
3080 assert_return(v, -EINVAL);
3081 assert_return(fd >= 0, -EBADF);
3082
3083 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
3084
3085 dp = fcntl(fd, F_DUPFD_CLOEXEC, 3);
3086 if (dp < 0)
3087 return -errno;
3088
3089 r = varlink_push_fd(v, dp);
3090 if (r < 0)
3091 return r;
3092
3093 TAKE_FD(dp);
3094 return r;
3095}
3096
3097int varlink_reset_fds(Varlink *v) {
3098 assert_return(v, -EINVAL);
3099
3100 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
3101 * of putting together a message with fds, and then eventually something fails and they need to
3102 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
3103
3104 close_many(v->output_fds, v->n_output_fds);
3105 v->n_output_fds = 0;
3106 return 0;
3107}
3108
3109int varlink_peek_fd(Varlink *v, size_t i) {
3110 assert_return(v, -EINVAL);
3111
94d82b59 3112 /* Returns one of the file descriptors that were received along with the current message. This does
d37cdac6
LP
3113 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
3114
3115 if (!v->allow_fd_passing_input)
3116 return -EPERM;
3117
3118 if (i >= v->n_input_fds)
3119 return -ENXIO;
3120
3121 return v->input_fds[i];
3122}
3123
3124int varlink_take_fd(Varlink *v, size_t i) {
3125 assert_return(v, -EINVAL);
3126
3127 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
3128 * we'll invalidate the reference to it under our possession. If called twice in a row will return
3129 * -EBADF */
3130
3131 if (!v->allow_fd_passing_input)
3132 return -EPERM;
3133
3134 if (i >= v->n_input_fds)
3135 return -ENXIO;
3136
3137 return TAKE_FD(v->input_fds[i]);
3138}
3139
3140static int verify_unix_socket(Varlink *v) {
3141 assert(v);
3142
3143 if (v->af < 0) {
3144 struct stat st;
3145
3146 if (fstat(v->fd, &st) < 0)
3147 return -errno;
3148 if (!S_ISSOCK(st.st_mode)) {
3149 v->af = AF_UNSPEC;
3150 return -ENOTSOCK;
3151 }
3152
3153 v->af = socket_get_family(v->fd);
3154 if (v->af < 0)
3155 return v->af;
3156 }
3157
3158 return v->af == AF_UNIX ? 0 : -ENOMEDIUM;
3159}
3160
3161int varlink_set_allow_fd_passing_input(Varlink *v, bool b) {
3162 int r;
3163
3164 assert_return(v, -EINVAL);
3165
3166 if (v->allow_fd_passing_input == b)
3167 return 0;
3168
3169 if (!b) {
3170 v->allow_fd_passing_input = false;
3171 return 1;
3172 }
3173
3174 r = verify_unix_socket(v);
3175 if (r < 0)
3176 return r;
3177
3178 v->allow_fd_passing_input = true;
3179 return 0;
3180}
3181
3182int varlink_set_allow_fd_passing_output(Varlink *v, bool b) {
3183 int r;
3184
3185 assert_return(v, -EINVAL);
3186
3187 if (v->allow_fd_passing_output == b)
3188 return 0;
3189
3190 if (!b) {
3191 v->allow_fd_passing_output = false;
3192 return 1;
3193 }
3194
3195 r = verify_unix_socket(v);
3196 if (r < 0)
3197 return r;
3198
3199 v->allow_fd_passing_output = true;
3200 return 0;
3201}
3202
a570877c
LP
3203int varlink_set_input_sensitive(Varlink *v) {
3204 assert_return(v, -EINVAL);
3205
3206 v->input_sensitive = true;
3207 return 0;
3208}
3209
d41bd96f 3210int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
7e006b49
LP
3211 _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL;
3212 int r;
d41bd96f
LP
3213
3214 assert_return(ret, -EINVAL);
3215 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
3216
3217 s = new(VarlinkServer, 1);
3218 if (!s)
db3d4222 3219 return log_oom_debug();
d41bd96f
LP
3220
3221 *s = (VarlinkServer) {
3222 .n_ref = 1,
3223 .flags = flags,
3224 .connections_max = varlink_server_connections_max(NULL),
3225 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
3226 };
3227
7e006b49
LP
3228 r = varlink_server_add_interface_many(
3229 s,
3230 &vl_interface_io_systemd,
3231 &vl_interface_org_varlink_service);
3232 if (r < 0)
3233 return r;
3234
3235 *ret = TAKE_PTR(s);
d41bd96f
LP
3236 return 0;
3237}
3238
3239static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
3240 char *m;
3241
3242 if (!s)
3243 return NULL;
3244
3245 varlink_server_shutdown(s);
3246
3247 while ((m = hashmap_steal_first_key(s->methods)))
3248 free(m);
3249
3250 hashmap_free(s->methods);
9fc843ed 3251 hashmap_free(s->interfaces);
7e006b49 3252 hashmap_free(s->symbols);
d41bd96f
LP
3253 hashmap_free(s->by_uid);
3254
3255 sd_event_unref(s->event);
3256
3257 free(s->description);
3258
3259 return mfree(s);
3260}
3261
3262DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
3263
3264static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
3265 int allowed = -1;
3266
3267 assert(server);
3268 assert(ucred);
3269
3270 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
3271 allowed = ucred->uid == 0;
3272
3273 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
3274 allowed = allowed > 0 || ucred->uid == getuid();
3275
3276 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
3277 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
3278 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
3279 return 0;
3280 }
3281
3282 if (server->n_connections >= server->connections_max) {
3283 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
3284 return 0;
3285 }
3286
3287 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
3288 unsigned c;
3289
3290 if (!uid_is_valid(ucred->uid)) {
3291 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
3292 return 0;
3293 }
3294
3295 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
3296 if (c >= server->connections_per_uid_max) {
3297 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
3298 server->connections_per_uid_max);
3299 return 0;
3300 }
3301 }
3302
3303 return 1;
3304}
3305
678ca213 3306static int count_connection(VarlinkServer *server, const struct ucred *ucred) {
d41bd96f
LP
3307 unsigned c;
3308 int r;
3309
3310 assert(server);
3311 assert(ucred);
3312
3313 server->n_connections++;
3314
3315 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
a1351823
LP
3316 assert(uid_is_valid(ucred->uid));
3317
d41bd96f
LP
3318 r = hashmap_ensure_allocated(&server->by_uid, NULL);
3319 if (r < 0)
6bcc1232 3320 return varlink_server_log_errno(server, r, "Failed to allocate UID hash table: %m");
d41bd96f
LP
3321
3322 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
3323
3324 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
3325 ucred->uid, c, server->connections_per_uid_max);
3326
3327 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
3328 if (r < 0)
6bcc1232 3329 return varlink_server_log_errno(server, r, "Failed to increment counter in UID hash table: %m");
d41bd96f
LP
3330 }
3331
3332 return 0;
3333}
3334
3335int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
3336 _cleanup_(varlink_unrefp) Varlink *v = NULL;
a995ce47 3337 struct ucred ucred = UCRED_INVALID;
d41bd96f 3338 bool ucred_acquired;
d41bd96f
LP
3339 int r;
3340
3341 assert_return(server, -EINVAL);
3342 assert_return(fd >= 0, -EBADF);
3343
3344 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
3345 r = getpeercred(fd, &ucred);
3346 if (r < 0)
3347 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
3348
3349 ucred_acquired = true;
3350
3351 r = validate_connection(server, &ucred);
3352 if (r < 0)
3353 return r;
3354 if (r == 0)
3355 return -EPERM;
3356 } else
3357 ucred_acquired = false;
3358
3359 r = varlink_new(&v);
3360 if (r < 0)
3361 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
3362
3363 r = count_connection(server, &ucred);
3364 if (r < 0)
3365 return r;
3366
3367 v->fd = fd;
9807fdc1
LP
3368 if (server->flags & VARLINK_SERVER_INHERIT_USERDATA)
3369 v->userdata = server->userdata;
3370
d41bd96f
LP
3371 if (ucred_acquired) {
3372 v->ucred = ucred;
3373 v->ucred_acquired = true;
3374 }
3375
12619d0a
ZJS
3376 _cleanup_free_ char *desc = NULL;
3377 if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0)
3378 v->description = TAKE_PTR(desc);
d41bd96f
LP
3379
3380 /* Link up the server and the connection, and take reference in both directions. Note that the
3381 * reference on the connection is left dangling. It will be dropped when the connection is closed,
3382 * which happens in varlink_close(), including in the event loop quit callback. */
3383 v->server = varlink_server_ref(server);
3384 varlink_ref(v);
3385
3386 varlink_set_state(v, VARLINK_IDLE_SERVER);
3387
7e69d90c
LP
3388 if (server->event) {
3389 r = varlink_attach_event(v, server->event, server->event_priority);
3390 if (r < 0) {
3391 varlink_log_errno(v, r, "Failed to attach new connection: %m");
254d1313 3392 v->fd = -EBADF; /* take the fd out of the connection again */
7e69d90c
LP
3393 varlink_close(v);
3394 return r;
3395 }
d41bd96f
LP
3396 }
3397
3398 if (ret)
3399 *ret = v;
3400
3401 return 0;
3402}
3403
c14e841f
AZ
3404static VarlinkServerSocket *varlink_server_socket_free(VarlinkServerSocket *ss) {
3405 if (!ss)
3406 return NULL;
3407
3408 free(ss->address);
3409 return mfree(ss);
3410}
3411
3412DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket *, varlink_server_socket_free);
3413
d41bd96f 3414static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
99534007 3415 VarlinkServerSocket *ss = ASSERT_PTR(userdata);
254d1313 3416 _cleanup_close_ int cfd = -EBADF;
d41bd96f
LP
3417 Varlink *v = NULL;
3418 int r;
3419
3420 assert(source);
d41bd96f
LP
3421
3422 varlink_server_log(ss->server, "New incoming connection.");
3423
3424 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
3425 if (cfd < 0) {
3426 if (ERRNO_IS_ACCEPT_AGAIN(errno))
3427 return 0;
3428
3429 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
3430 }
3431
3432 r = varlink_server_add_connection(ss->server, cfd, &v);
3433 if (r < 0)
3434 return 0;
3435
3436 TAKE_FD(cfd);
3437
a570877c
LP
3438 if (FLAGS_SET(ss->server->flags, VARLINK_SERVER_INPUT_SENSITIVE))
3439 varlink_set_input_sensitive(v);
3440
d41bd96f
LP
3441 if (ss->server->connect_callback) {
3442 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
3443 if (r < 0) {
3444 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
3445 varlink_close(v);
3446 return 0;
3447 }
3448 }
3449
3450 return 0;
3451}
3452
c14e841f
AZ
3453static int varlink_server_create_listen_fd_socket(VarlinkServer *s, int fd, VarlinkServerSocket **ret_ss) {
3454 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f
LP
3455 int r;
3456
c14e841f
AZ
3457 assert(s);
3458 assert(fd >= 0);
3459 assert(ret_ss);
d41bd96f 3460
d41bd96f
LP
3461 ss = new(VarlinkServerSocket, 1);
3462 if (!ss)
db3d4222 3463 return log_oom_debug();
d41bd96f
LP
3464
3465 *ss = (VarlinkServerSocket) {
3466 .server = s,
3467 .fd = fd,
3468 };
3469
3470 if (s->event) {
8d91b220 3471 r = sd_event_add_io(s->event, &ss->event_source, fd, EPOLLIN, connect_callback, ss);
d41bd96f
LP
3472 if (r < 0)
3473 return r;
3474
3475 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
3476 if (r < 0)
3477 return r;
3478 }
3479
c14e841f
AZ
3480 *ret_ss = TAKE_PTR(ss);
3481 return 0;
3482}
3483
3484int varlink_server_listen_fd(VarlinkServer *s, int fd) {
3485 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
3486 int r;
3487
3488 assert_return(s, -EINVAL);
3489 assert_return(fd >= 0, -EBADF);
3490
a4edf033
LP
3491 r = fd_nonblock(fd, true);
3492 if (r < 0)
3493 return r;
3494
3495 r = fd_cloexec(fd, true);
3496 if (r < 0)
3497 return r;
3498
c14e841f
AZ
3499 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
3500 if (r < 0)
3501 return r;
3502
d41bd96f
LP
3503 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
3504 return 0;
3505}
3506
3507int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
c14e841f 3508 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f 3509 union sockaddr_union sockaddr;
f36a9d59 3510 socklen_t sockaddr_len;
254d1313 3511 _cleanup_close_ int fd = -EBADF;
d41bd96f
LP
3512 int r;
3513
3514 assert_return(s, -EINVAL);
3515 assert_return(address, -EINVAL);
3516 assert_return((m & ~0777) == 0, -EINVAL);
3517
3518 r = sockaddr_un_set_path(&sockaddr.un, address);
3519 if (r < 0)
3520 return r;
f36a9d59 3521 sockaddr_len = r;
d41bd96f
LP
3522
3523 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
3524 if (fd < 0)
3525 return -errno;
3526
a0c41de2
LP
3527 fd = fd_move_above_stdio(fd);
3528
d41bd96f
LP
3529 (void) sockaddr_un_unlink(&sockaddr.un);
3530
2053593f 3531 WITH_UMASK(~m & 0777) {
63e00ccd
CG
3532 r = mac_selinux_bind(fd, &sockaddr.sa, sockaddr_len);
3533 if (r < 0)
3534 return r;
3535 }
d41bd96f 3536
768fcd77 3537 if (listen(fd, SOMAXCONN_DELUXE) < 0)
d41bd96f
LP
3538 return -errno;
3539
c14e841f 3540 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
d41bd96f
LP
3541 if (r < 0)
3542 return r;
3543
c14e841f
AZ
3544 r = free_and_strdup(&ss->address, address);
3545 if (r < 0)
3546 return r;
3547
3548 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
d41bd96f
LP
3549 TAKE_FD(fd);
3550 return 0;
3551}
3552
206504a5
LP
3553int varlink_server_listen_auto(VarlinkServer *s) {
3554 _cleanup_strv_free_ char **names = NULL;
3555 int r, n = 0;
3556
3557 assert_return(s, -EINVAL);
3558
3559 /* Adds all passed fds marked as "varlink" to our varlink server. These fds can either refer to a
3560 * listening socket or to a connection socket.
3561 *
3562 * See https://varlink.org/#activation for the environment variables this is backed by and the
3563 * recommended "varlink" identifier in $LISTEN_FDNAMES. */
3564
3565 r = sd_listen_fds_with_names(/* unset_environment= */ false, &names);
3566 if (r < 0)
3567 return r;
3568
3569 for (int i = 0; i < r; i++) {
3570 int b, fd;
3571 socklen_t l = sizeof(b);
3572
3573 if (!streq(names[i], "varlink"))
3574 continue;
3575
3576 fd = SD_LISTEN_FDS_START + i;
3577
3578 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
3579 return -errno;
3580
3581 assert(l == sizeof(b));
3582
3583 if (b) /* Listening socket? */
3584 r = varlink_server_listen_fd(s, fd);
3585 else /* Otherwise assume connection socket */
3586 r = varlink_server_add_connection(s, fd, NULL);
3587 if (r < 0)
3588 return r;
3589
3590 n++;
3591 }
3592
4a6fe5f0
LP
3593 /* For debug purposes let's listen on an explicitly specified address */
3594 const char *e = secure_getenv("SYSTEMD_VARLINK_LISTEN");
3595 if (e) {
3596 r = varlink_server_listen_address(s, e, FLAGS_SET(s->flags, VARLINK_SERVER_ROOT_ONLY) ? 0600 : 0666);
3597 if (r < 0)
3598 return r;
3599 }
3600
206504a5
LP
3601 return n;
3602}
3603
d41bd96f
LP
3604void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
3605 void *ret;
3606
3607 assert_return(s, NULL);
3608
3609 ret = s->userdata;
3610 s->userdata = userdata;
3611
3612 return ret;
3613}
3614
3615void* varlink_server_get_userdata(VarlinkServer *s) {
3616 assert_return(s, NULL);
3617
3618 return s->userdata;
3619}
3620
2e5edb93
LP
3621int varlink_server_loop_auto(VarlinkServer *server) {
3622 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
3623 int r;
3624
3625 assert_return(server, -EINVAL);
3626 assert_return(!server->event, -EBUSY);
3627
3628 /* Runs a Varlink service event loop populated with a passed fd. Exits on the last connection. */
3629
3630 r = sd_event_new(&event);
3631 if (r < 0)
3632 return r;
3633
3634 r = varlink_server_set_exit_on_idle(server, true);
3635 if (r < 0)
3636 return r;
3637
3638 r = varlink_server_attach_event(server, event, 0);
3639 if (r < 0)
3640 return r;
3641
3642 r = varlink_server_listen_auto(server);
3643 if (r < 0)
3644 return r;
3645
3646 return sd_event_loop(event);
3647}
3648
d41bd96f
LP
3649static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
3650 if (!ss)
3651 return NULL;
3652
3653 if (ss->server)
3654 LIST_REMOVE(sockets, ss->server->sockets, ss);
3655
1d3fe304 3656 sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
3657
3658 free(ss->address);
3659 safe_close(ss->fd);
3660
3661 return mfree(ss);
3662}
3663
3664int varlink_server_shutdown(VarlinkServer *s) {
3665 assert_return(s, -EINVAL);
3666
3667 while (s->sockets)
3668 varlink_server_socket_destroy(s->sockets);
3669
3670 return 0;
3671}
3672
47723340
LP
3673static void varlink_server_test_exit_on_idle(VarlinkServer *s) {
3674 assert(s);
3675
3676 if (s->exit_on_idle && s->event && s->n_connections == 0)
3677 (void) sd_event_exit(s->event, 0);
3678}
3679
3680int varlink_server_set_exit_on_idle(VarlinkServer *s, bool b) {
3681 assert_return(s, -EINVAL);
3682
3683 s->exit_on_idle = b;
3684 varlink_server_test_exit_on_idle(s);
3685 return 0;
3686}
3687
536827e0
AZ
3688static int varlink_server_add_socket_event_source(VarlinkServer *s, VarlinkServerSocket *ss, int64_t priority) {
3689 _cleanup_(sd_event_source_unrefp) sd_event_source *es = NULL;
536827e0
AZ
3690 int r;
3691
3692 assert(s);
3693 assert(s->event);
3694 assert(ss);
3695 assert(ss->fd >= 0);
3696 assert(!ss->event_source);
3697
3698 r = sd_event_add_io(s->event, &es, ss->fd, EPOLLIN, connect_callback, ss);
3699 if (r < 0)
3700 return r;
3701
3702 r = sd_event_source_set_priority(es, priority);
3703 if (r < 0)
3704 return r;
3705
3706 ss->event_source = TAKE_PTR(es);
3707 return 0;
3708}
3709
d41bd96f 3710int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
d41bd96f
LP
3711 int r;
3712
3713 assert_return(s, -EINVAL);
3714 assert_return(!s->event, -EBUSY);
3715
3716 if (e)
3717 s->event = sd_event_ref(e);
3718 else {
3719 r = sd_event_default(&s->event);
3720 if (r < 0)
3721 return r;
3722 }
3723
3724 LIST_FOREACH(sockets, ss, s->sockets) {
536827e0 3725 r = varlink_server_add_socket_event_source(s, ss, priority);
d41bd96f
LP
3726 if (r < 0)
3727 goto fail;
3728 }
3729
3730 s->event_priority = priority;
3731 return 0;
3732
3733fail:
3734 varlink_server_detach_event(s);
3735 return r;
3736}
3737
3738int varlink_server_detach_event(VarlinkServer *s) {
d41bd96f
LP
3739 assert_return(s, -EINVAL);
3740
4f538d7b
LP
3741 LIST_FOREACH(sockets, ss, s->sockets)
3742 ss->event_source = sd_event_source_disable_unref(ss->event_source);
d41bd96f 3743
03a83186 3744 s->event = sd_event_unref(s->event);
d41bd96f
LP
3745 return 0;
3746}
3747
3748sd_event *varlink_server_get_event(VarlinkServer *s) {
3749 assert_return(s, NULL);
3750
3751 return s->event;
3752}
3753
7e006b49
LP
3754static bool varlink_symbol_in_interface(const char *method, const char *interface) {
3755 const char *p;
3756
3757 assert(method);
3758 assert(interface);
3759
3760 p = startswith(method, interface);
3761 if (!p)
3762 return false;
3763
3764 if (*p != '.')
3765 return false;
3766
3767 return !strchr(p+1, '.');
3768}
3769
d41bd96f 3770int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
db3d4222 3771 _cleanup_free_ char *m = NULL;
d41bd96f
LP
3772 int r;
3773
3774 assert_return(s, -EINVAL);
3775 assert_return(method, -EINVAL);
3776 assert_return(callback, -EINVAL);
3777
7e006b49
LP
3778 if (varlink_symbol_in_interface(method, "org.varlink.service") ||
3779 varlink_symbol_in_interface(method, "io.systemd"))
6bcc1232 3780 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EEXIST), "Cannot bind server to '%s'.", method);
d41bd96f 3781
d41bd96f
LP
3782 m = strdup(method);
3783 if (!m)
db3d4222 3784 return log_oom_debug();
d41bd96f 3785
1d2d1654
SS
3786 r = hashmap_ensure_put(&s->methods, &string_hash_ops, m, callback);
3787 if (r == -ENOMEM)
3788 return log_oom_debug();
db3d4222 3789 if (r < 0)
6bcc1232 3790 return varlink_server_log_errno(s, r, "Failed to register callback: %m");
db3d4222
ZJS
3791 if (r > 0)
3792 TAKE_PTR(m);
d41bd96f
LP
3793
3794 return 0;
3795}
3796
3797int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
3798 va_list ap;
e7b93f97 3799 int r = 0;
d41bd96f
LP
3800
3801 assert_return(s, -EINVAL);
3802
3803 va_start(ap, s);
3804 for (;;) {
3805 VarlinkMethod callback;
3806 const char *method;
3807
3808 method = va_arg(ap, const char *);
3809 if (!method)
3810 break;
3811
3812 callback = va_arg(ap, VarlinkMethod);
3813
3814 r = varlink_server_bind_method(s, method, callback);
3815 if (r < 0)
e7b93f97 3816 break;
d41bd96f 3817 }
e7b93f97 3818 va_end(ap);
d41bd96f 3819
e7b93f97 3820 return r;
d41bd96f
LP
3821}
3822
3823int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
3824 assert_return(s, -EINVAL);
3825
3826 if (callback && s->connect_callback && callback != s->connect_callback)
6bcc1232 3827 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
3828
3829 s->connect_callback = callback;
3830 return 0;
3831}
3832
6d4d6002
LP
3833int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
3834 assert_return(s, -EINVAL);
3835
3836 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
6bcc1232 3837 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
6d4d6002
LP
3838
3839 s->disconnect_callback = callback;
3840 return 0;
3841}
3842
9fc843ed 3843int varlink_server_add_interface(VarlinkServer *s, const VarlinkInterface *interface) {
7e006b49
LP
3844 int r;
3845
9fc843ed
LP
3846 assert_return(s, -EINVAL);
3847 assert_return(interface, -EINVAL);
3848 assert_return(interface->name, -EINVAL);
3849
3850 if (hashmap_contains(s->interfaces, interface->name))
6bcc1232 3851 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EEXIST), "Duplicate registration of interface '%s'.", interface->name);
9fc843ed 3852
7e006b49
LP
3853 r = hashmap_ensure_put(&s->interfaces, &string_hash_ops, interface->name, (void*) interface);
3854 if (r < 0)
3855 return r;
3856
3857 for (const VarlinkSymbol *const*symbol = interface->symbols; *symbol; symbol++) {
3858 _cleanup_free_ char *j = NULL;
3859
3860 /* We only ever want to validate method calls/replies and errors against the interface
3861 * definitions, hence don't bother with the type symbols */
3862 if (!IN_SET((*symbol)->symbol_type, VARLINK_METHOD, VARLINK_ERROR))
3863 continue;
3864
3865 j = strjoin(interface->name, ".", (*symbol)->name);
3866 if (!j)
3867 return -ENOMEM;
3868
3869 r = hashmap_ensure_put(&s->symbols, &string_hash_ops_free, j, (void*) *symbol);
3870 if (r < 0)
3871 return r;
3872
3873 TAKE_PTR(j);
3874 }
3875
3876 return 0;
9fc843ed
LP
3877}
3878
3879int varlink_server_add_interface_many_internal(VarlinkServer *s, ...) {
3880 va_list ap;
3881 int r = 0;
3882
3883 assert_return(s, -EINVAL);
3884
3885 va_start(ap, s);
3886 for (;;) {
3887 const VarlinkInterface *interface = va_arg(ap, const VarlinkInterface*);
3888 if (!interface)
3889 break;
3890
3891 r = varlink_server_add_interface(s, interface);
3892 if (r < 0)
3893 break;
3894 }
3895 va_end(ap);
3896
3897 return r;
3898}
3899
d41bd96f 3900unsigned varlink_server_connections_max(VarlinkServer *s) {
88a36d36 3901 int dts;
d41bd96f
LP
3902
3903 /* If a server is specified, return the setting for that server, otherwise the default value */
3904 if (s)
3905 return s->connections_max;
3906
88a36d36
LP
3907 dts = getdtablesize();
3908 assert_se(dts > 0);
d41bd96f
LP
3909
3910 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
88a36d36
LP
3911 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
3912 return dts / 4 * 3;
d41bd96f
LP
3913
3914 return VARLINK_DEFAULT_CONNECTIONS_MAX;
3915}
3916
3917unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
3918 unsigned m;
3919
3920 if (s)
3921 return s->connections_per_uid_max;
3922
3923 /* Make sure to never use up more than ¾th of available connections for a single user */
3924 m = varlink_server_connections_max(NULL);
3925 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
3926 return m / 4 * 3;
3927
3928 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
3929}
3930
3931int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
3932 assert_return(s, -EINVAL);
3933 assert_return(m > 0, -EINVAL);
3934
3935 s->connections_per_uid_max = m;
3936 return 0;
3937}
3938
3939int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
3940 assert_return(s, -EINVAL);
3941 assert_return(m > 0, -EINVAL);
3942
3943 s->connections_max = m;
3944 return 0;
3945}
3946
c4f601f2
LP
3947unsigned varlink_server_current_connections(VarlinkServer *s) {
3948 assert_return(s, UINT_MAX);
3949
3950 return s->n_connections;
3951}
3952
d41bd96f
LP
3953int varlink_server_set_description(VarlinkServer *s, const char *description) {
3954 assert_return(s, -EINVAL);
3955
3956 return free_and_strdup(&s->description, description);
3957}
008798e9
AZ
3958
3959int varlink_server_serialize(VarlinkServer *s, FILE *f, FDSet *fds) {
3960 assert(f);
3961 assert(fds);
3962
3963 if (!s)
3964 return 0;
3965
3966 LIST_FOREACH(sockets, ss, s->sockets) {
3967 int copy;
3968
3969 assert(ss->address);
3970 assert(ss->fd >= 0);
3971
3972 fprintf(f, "varlink-server-socket-address=%s", ss->address);
3973
3974 /* If we fail to serialize the fd, it will be considered an error during deserialization */
3975 copy = fdset_put_dup(fds, ss->fd);
3976 if (copy < 0)
3977 return copy;
3978
3979 fprintf(f, " varlink-server-socket-fd=%i", copy);
3980
3981 fputc('\n', f);
3982 }
3983
3984 return 0;
3985}
3986
3987int varlink_server_deserialize_one(VarlinkServer *s, const char *value, FDSet *fds) {
3988 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
3989 _cleanup_free_ char *address = NULL;
3990 const char *v = ASSERT_PTR(value);
254d1313 3991 int r, fd = -EBADF;
008798e9
AZ
3992 char *buf;
3993 size_t n;
3994
3995 assert(s);
3996 assert(fds);
3997
3998 n = strcspn(v, " ");
3999 address = strndup(v, n);
4000 if (!address)
4001 return log_oom_debug();
4002
4003 if (v[n] != ' ')
6bcc1232 4004 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EINVAL),
008798e9
AZ
4005 "Failed to deserialize VarlinkServerSocket: %s: %m", value);
4006 v = startswith(v + n + 1, "varlink-server-socket-fd=");
4007 if (!v)
6bcc1232 4008 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EINVAL),
008798e9
AZ
4009 "Failed to deserialize VarlinkServerSocket fd %s: %m", value);
4010
4011 n = strcspn(v, " ");
4012 buf = strndupa_safe(v, n);
4013
e652663a 4014 fd = parse_fd(buf);
e652663a 4015 if (fd < 0)
6bcc1232 4016 return varlink_server_log_errno(s, fd, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf);
008798e9 4017 if (!fdset_contains(fds, fd))
6bcc1232 4018 return varlink_server_log_errno(s, SYNTHETIC_ERRNO(EBADF),
008798e9
AZ
4019 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd);
4020
4021 ss = new(VarlinkServerSocket, 1);
4022 if (!ss)
4023 return log_oom_debug();
4024
4025 *ss = (VarlinkServerSocket) {
4026 .server = s,
4027 .address = TAKE_PTR(address),
4028 .fd = fdset_remove(fds, fd),
4029 };
4030
4031 r = varlink_server_add_socket_event_source(s, ss, SD_EVENT_PRIORITY_NORMAL);
4032 if (r < 0)
6bcc1232 4033 return varlink_server_log_errno(s, r, "Failed to add VarlinkServerSocket event source to the event loop: %m");
008798e9
AZ
4034
4035 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
4036 return 0;
4037}
02b0d24d
LP
4038
4039int varlink_invocation(VarlinkInvocationFlags flags) {
4040 _cleanup_strv_free_ char **names = NULL;
4041 int r, b;
4042 socklen_t l = sizeof(b);
4043
4044 /* Returns true if this is a "pure" varlink server invocation, i.e. with one fd passed. */
4045
4a6fe5f0
LP
4046 const char *e = secure_getenv("SYSTEMD_VARLINK_LISTEN"); /* Permit a manual override for testing purposes */
4047 if (e)
4048 return true;
4049
02b0d24d
LP
4050 r = sd_listen_fds_with_names(/* unset_environment= */ false, &names);
4051 if (r < 0)
4052 return r;
4053 if (r == 0)
4054 return false;
4055 if (r > 1)
4056 return -ETOOMANYREFS;
4057
4058 if (!strv_equal(names, STRV_MAKE("varlink")))
4059 return false;
4060
4061 if (FLAGS_SET(flags, VARLINK_ALLOW_LISTEN|VARLINK_ALLOW_ACCEPT)) /* Both flags set? Then allow everything */
4062 return true;
4063
4064 if ((flags & (VARLINK_ALLOW_LISTEN|VARLINK_ALLOW_ACCEPT)) == 0) /* Neither is set, then fail */
4065 return -EISCONN;
4066
4067 if (getsockopt(SD_LISTEN_FDS_START, SOL_SOCKET, SO_ACCEPTCONN, &b, &l) < 0)
4068 return -errno;
4069
4070 assert(l == sizeof(b));
4071
4072 if (!FLAGS_SET(flags, b ? VARLINK_ALLOW_LISTEN : VARLINK_ALLOW_ACCEPT))
4073 return -EISCONN;
4074
4075 return true;
4076}
a4562f94
LP
4077
4078int varlink_error_to_errno(const char *error, JsonVariant *parameters) {
4079 static const struct {
4080 const char *error;
4081 int value;
4082 } table[] = {
4083 { VARLINK_ERROR_DISCONNECTED, -ECONNRESET },
4084 { VARLINK_ERROR_TIMEOUT, -ETIMEDOUT },
4085 { VARLINK_ERROR_PROTOCOL, -EPROTO },
4086 { VARLINK_ERROR_INTERFACE_NOT_FOUND, -EADDRNOTAVAIL },
4087 { VARLINK_ERROR_METHOD_NOT_FOUND, -ENXIO },
4088 { VARLINK_ERROR_METHOD_NOT_IMPLEMENTED, -ENOTTY },
4089 { VARLINK_ERROR_INVALID_PARAMETER, -EINVAL },
4090 { VARLINK_ERROR_PERMISSION_DENIED, -EACCES },
4091 { VARLINK_ERROR_EXPECTED_MORE, -EBADE },
4092 };
4093
4094 if (!error)
4095 return 0;
4096
4097 FOREACH_ARRAY(t, table, ELEMENTSOF(table))
4098 if (streq(error, t->error))
4099 return t->value;
4100
4101 if (streq(error, VARLINK_ERROR_SYSTEM) && parameters) {
4102 JsonVariant *e;
4103
4104 e = json_variant_by_key(parameters, "errno");
4105 if (json_variant_is_integer(e)) {
4106 int64_t i;
4107
4108 i = json_variant_integer(e);
4109 if (i > 0 && i < ERRNO_MAX)
4110 return -i;
4111 }
4112 }
4113
4114 return -EBADR; /* Catch-all */
4115}