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