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