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