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