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