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