]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/varlink.c
various: 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);
bb44fd07
ZJS
1371 if (ERRNO_IS_NEG_TRANSIENT(r))
1372 continue;
1373 if (r < 0)
db3d4222 1374 return varlink_log_errno(v, r, "Poll failed on fd: %m");
bb44fd07 1375 assert(r > 0);
dad28bff 1376
0f2d351f 1377 handle_revents(v, r);
d41bd96f
LP
1378 }
1379
1380 return ret;
1381}
1382
1383static void varlink_detach_server(Varlink *v) {
6d4d6002 1384 VarlinkServer *saved_server;
d41bd96f
LP
1385 assert(v);
1386
1387 if (!v->server)
1388 return;
1389
1390 if (v->server->by_uid &&
1391 v->ucred_acquired &&
1392 uid_is_valid(v->ucred.uid)) {
1393 unsigned c;
1394
1395 c = PTR_TO_UINT(hashmap_get(v->server->by_uid, UID_TO_PTR(v->ucred.uid)));
1396 assert(c > 0);
1397
1398 if (c == 1)
1399 (void) hashmap_remove(v->server->by_uid, UID_TO_PTR(v->ucred.uid));
1400 else
1401 (void) hashmap_replace(v->server->by_uid, UID_TO_PTR(v->ucred.uid), UINT_TO_PTR(c - 1));
1402 }
1403
1404 assert(v->server->n_connections > 0);
1405 v->server->n_connections--;
1406
1407 /* If this is a connection associated to a server, then let's disconnect the server and the
6d4d6002
LP
1408 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1409 * before we release the references, let's call the disconnection callback if it is defined. */
1410
1411 saved_server = TAKE_PTR(v->server);
1412
1413 if (saved_server->disconnect_callback)
1414 saved_server->disconnect_callback(saved_server, v, saved_server->userdata);
1415
1416 varlink_server_unref(saved_server);
d41bd96f
LP
1417 varlink_unref(v);
1418}
1419
1420int varlink_close(Varlink *v) {
d41bd96f
LP
1421 assert_return(v, -EINVAL);
1422
1423 if (v->state == VARLINK_DISCONNECTED)
1424 return 0;
1425
1426 varlink_set_state(v, VARLINK_DISCONNECTED);
1427
cc6b0a18
LP
1428 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1429 * which would destroy us before we can call varlink_clear() */
d41bd96f
LP
1430 varlink_ref(v);
1431 varlink_detach_server(v);
1432 varlink_clear(v);
1433 varlink_unref(v);
1434
1435 return 1;
1436}
1437
9652d740 1438Varlink* varlink_close_unref(Varlink *v) {
9652d740
LP
1439 if (!v)
1440 return NULL;
1441
cc6b0a18 1442 (void) varlink_close(v);
9652d740
LP
1443 return varlink_unref(v);
1444}
1445
d41bd96f 1446Varlink* varlink_flush_close_unref(Varlink *v) {
cc6b0a18
LP
1447 if (!v)
1448 return NULL;
d41bd96f 1449
cc6b0a18 1450 (void) varlink_flush(v);
39ad3f1c 1451 return varlink_close_unref(v);
d41bd96f
LP
1452}
1453
d37cdac6 1454static int varlink_format_json(Varlink *v, JsonVariant *m) {
db1f7c84 1455 _cleanup_(erase_and_freep) char *text = NULL;
d41bd96f
LP
1456 int r;
1457
1458 assert(v);
1459 assert(m);
1460
1461 r = json_variant_format(m, 0, &text);
1462 if (r < 0)
1463 return r;
2a04712c 1464 assert(text[r] == '\0');
d41bd96f
LP
1465
1466 if (v->output_buffer_size + r + 1 > VARLINK_BUFFER_MAX)
1467 return -ENOBUFS;
1468
1469 varlink_log(v, "Sending message: %s", text);
1470
1471 if (v->output_buffer_size == 0) {
1472
1473 free_and_replace(v->output_buffer, text);
1474
319a4f4b 1475 v->output_buffer_size = r + 1;
d41bd96f
LP
1476 v->output_buffer_index = 0;
1477
1478 } else if (v->output_buffer_index == 0) {
1479
319a4f4b 1480 if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_size + r + 1))
d41bd96f
LP
1481 return -ENOMEM;
1482
1483 memcpy(v->output_buffer + v->output_buffer_size, text, r + 1);
1484 v->output_buffer_size += r + 1;
d41bd96f
LP
1485 } else {
1486 char *n;
be44e091 1487 const size_t new_size = v->output_buffer_size + r + 1;
d41bd96f 1488
be44e091 1489 n = new(char, new_size);
d41bd96f
LP
1490 if (!n)
1491 return -ENOMEM;
1492
1493 memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, r + 1);
1494
1495 free_and_replace(v->output_buffer, n);
319a4f4b 1496 v->output_buffer_size = new_size;
d41bd96f
LP
1497 v->output_buffer_index = 0;
1498 }
1499
db1f7c84
LP
1500 if (json_variant_is_sensitive(m))
1501 v->output_buffer_sensitive = true; /* Propagate sensitive flag */
1502 else
1503 text = mfree(text); /* No point in the erase_and_free() destructor declared above */
1504
d41bd96f
LP
1505 return 0;
1506}
1507
d37cdac6
LP
1508static int varlink_enqueue_json(Varlink *v, JsonVariant *m) {
1509 VarlinkJsonQueueItem *q;
1510
1511 assert(v);
1512 assert(m);
1513
94d82b59 1514 /* If there are no file descriptors to be queued and no queue entries yet we can shortcut things and
d37cdac6
LP
1515 * append this entry directly to the output buffer */
1516 if (v->n_pushed_fds == 0 && !v->output_queue)
1517 return varlink_format_json(v, m);
1518
1519 /* Otherwise add a queue entry for this */
1520 q = varlink_json_queue_item_new(m, v->pushed_fds, v->n_pushed_fds);
1521 if (!q)
1522 return -ENOMEM;
1523
1524 v->n_pushed_fds = 0; /* fds now belong to the queue entry */
1525
1526 LIST_INSERT_AFTER(queue, v->output_queue, v->output_queue_tail, q);
1527 v->output_queue_tail = q;
1528 return 0;
1529}
1530
1531static int varlink_format_queue(Varlink *v) {
1532 int r;
1533
1534 assert(v);
1535
1536 /* Takes entries out of the output queue and formats them into the output buffer. But only if this
1537 * would not corrupt our fd message boundaries */
1538
1539 while (v->output_queue) {
1540 _cleanup_free_ int *array = NULL;
1541 VarlinkJsonQueueItem *q = v->output_queue;
1542
1543 if (v->n_output_fds > 0) /* unwritten fds? if we'd add more we'd corrupt the fd message boundaries, hence wait */
1544 return 0;
1545
1546 if (q->n_fds > 0) {
1547 array = newdup(int, q->fds, q->n_fds);
1548 if (!array)
1549 return -ENOMEM;
1550 }
1551
1552 r = varlink_format_json(v, q->data);
1553 if (r < 0)
1554 return r;
1555
1556 /* Take possession of the queue element's fds */
1557 free(v->output_fds);
1558 v->output_fds = TAKE_PTR(array);
1559 v->n_output_fds = q->n_fds;
1560 q->n_fds = 0;
1561
1562 LIST_REMOVE(queue, v->output_queue, q);
1563 if (!v->output_queue)
1564 v->output_queue_tail = NULL;
1565
1566 varlink_json_queue_item_free(q);
1567 }
1568
1569 return 0;
1570}
1571
d41bd96f
LP
1572int varlink_send(Varlink *v, const char *method, JsonVariant *parameters) {
1573 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1574 int r;
1575
1576 assert_return(v, -EINVAL);
1577 assert_return(method, -EINVAL);
1578
1579 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1580 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965
LP
1581
1582 /* We allow enqueuing multiple method calls at once! */
d41bd96f 1583 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 1584 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1585
1586 r = varlink_sanitize_parameters(&parameters);
1587 if (r < 0)
db3d4222 1588 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1589
1590 r = json_build(&m, JSON_BUILD_OBJECT(
1591 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1592 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1593 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1594 if (r < 0)
db3d4222 1595 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1596
1597 r = varlink_enqueue_json(v, m);
1598 if (r < 0)
db3d4222 1599 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1600
1601 /* No state change here, this is one-way only after all */
1602 v->timestamp = now(CLOCK_MONOTONIC);
1603 return 0;
1604}
1605
1606int varlink_sendb(Varlink *v, const char *method, ...) {
1607 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1608 va_list ap;
1609 int r;
1610
1611 assert_return(v, -EINVAL);
1612
1613 va_start(ap, method);
1614 r = json_buildv(&parameters, ap);
1615 va_end(ap);
1616
1617 if (r < 0)
db3d4222 1618 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1619
1620 return varlink_send(v, method, parameters);
1621}
1622
1623int varlink_invoke(Varlink *v, const char *method, JsonVariant *parameters) {
1624 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1625 int r;
1626
1627 assert_return(v, -EINVAL);
1628 assert_return(method, -EINVAL);
1629
1630 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1631 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
45a6c965 1632
86b52a39 1633 /* We allow enqueuing multiple method calls at once! */
d41bd96f 1634 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
db3d4222 1635 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1636
1637 r = varlink_sanitize_parameters(&parameters);
1638 if (r < 0)
db3d4222 1639 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1640
1641 r = json_build(&m, JSON_BUILD_OBJECT(
1642 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1643 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1644 if (r < 0)
db3d4222 1645 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1646
1647 r = varlink_enqueue_json(v, m);
1648 if (r < 0)
db3d4222 1649 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1650
1651 varlink_set_state(v, VARLINK_AWAITING_REPLY);
1652 v->n_pending++;
1653 v->timestamp = now(CLOCK_MONOTONIC);
1654
1655 return 0;
1656}
1657
1658int varlink_invokeb(Varlink *v, const char *method, ...) {
1659 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1660 va_list ap;
1661 int r;
1662
1663 assert_return(v, -EINVAL);
1664
1665 va_start(ap, method);
1666 r = json_buildv(&parameters, ap);
1667 va_end(ap);
1668
1669 if (r < 0)
db3d4222 1670 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1671
1672 return varlink_invoke(v, method, parameters);
45a6c965
LP
1673}
1674
1675int varlink_observe(Varlink *v, const char *method, JsonVariant *parameters) {
1676 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1677 int r;
1678
1679 assert_return(v, -EINVAL);
1680 assert_return(method, -EINVAL);
1681
1682 if (v->state == VARLINK_DISCONNECTED)
db3d4222
ZJS
1683 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1684
45a6c965
LP
1685 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1686 * thus insist on an idle client here. */
1687 if (v->state != VARLINK_IDLE_CLIENT)
db3d4222 1688 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
45a6c965
LP
1689
1690 r = varlink_sanitize_parameters(&parameters);
1691 if (r < 0)
db3d4222 1692 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
45a6c965
LP
1693
1694 r = json_build(&m, JSON_BUILD_OBJECT(
1695 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1696 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1697 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1698 if (r < 0)
db3d4222 1699 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
1700
1701 r = varlink_enqueue_json(v, m);
1702 if (r < 0)
db3d4222 1703 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
45a6c965
LP
1704
1705 varlink_set_state(v, VARLINK_AWAITING_REPLY_MORE);
1706 v->n_pending++;
1707 v->timestamp = now(CLOCK_MONOTONIC);
1708
1709 return 0;
1710}
1711
1712int varlink_observeb(Varlink *v, const char *method, ...) {
1713 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1714 va_list ap;
1715 int r;
1716
1717 assert_return(v, -EINVAL);
1718
1719 va_start(ap, method);
1720 r = json_buildv(&parameters, ap);
1721 va_end(ap);
1722
1723 if (r < 0)
db3d4222 1724 return varlink_log_errno(v, r, "Failed to build json message: %m");
45a6c965
LP
1725
1726 return varlink_observe(v, method, parameters);
d41bd96f
LP
1727}
1728
1729int varlink_call(
1730 Varlink *v,
1731 const char *method,
1732 JsonVariant *parameters,
1733 JsonVariant **ret_parameters,
1734 const char **ret_error_id,
1735 VarlinkReplyFlags *ret_flags) {
1736
1737 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1738 int r;
1739
1740 assert_return(v, -EINVAL);
1741 assert_return(method, -EINVAL);
1742
1743 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1744 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
4f06325c 1745 if (v->state != VARLINK_IDLE_CLIENT)
db3d4222 1746 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
1747
1748 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1749
d37cdac6
LP
1750 /* If there was still a reply pinned from a previous call, now it's the time to get rid of it, so
1751 * that we can assign a new reply shortly. */
790446bd 1752 varlink_clear_current(v);
85316317 1753
d41bd96f
LP
1754 r = varlink_sanitize_parameters(&parameters);
1755 if (r < 0)
db3d4222 1756 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1757
1758 r = json_build(&m, JSON_BUILD_OBJECT(
1759 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1760 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1761 if (r < 0)
db3d4222 1762 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1763
1764 r = varlink_enqueue_json(v, m);
1765 if (r < 0)
db3d4222 1766 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1767
1768 varlink_set_state(v, VARLINK_CALLING);
1769 v->n_pending++;
1770 v->timestamp = now(CLOCK_MONOTONIC);
1771
1772 while (v->state == VARLINK_CALLING) {
1773
1774 r = varlink_process(v);
1775 if (r < 0)
1776 return r;
1777 if (r > 0)
1778 continue;
1779
1780 r = varlink_wait(v, USEC_INFINITY);
1781 if (r < 0)
1782 return r;
1783 }
1784
1785 switch (v->state) {
1786
1787 case VARLINK_CALLED:
1788 assert(v->current);
1789
d41bd96f
LP
1790 varlink_set_state(v, VARLINK_IDLE_CLIENT);
1791 assert(v->n_pending == 1);
1792 v->n_pending--;
1793
1794 if (ret_parameters)
85316317 1795 *ret_parameters = json_variant_by_key(v->current, "parameters");
d41bd96f 1796 if (ret_error_id)
85316317 1797 *ret_error_id = json_variant_string(json_variant_by_key(v->current, "error"));
d41bd96f
LP
1798 if (ret_flags)
1799 *ret_flags = 0;
1800
1801 return 1;
1802
1803 case VARLINK_PENDING_DISCONNECT:
1804 case VARLINK_DISCONNECTED:
db3d4222 1805 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
d41bd96f
LP
1806
1807 case VARLINK_PENDING_TIMEOUT:
db3d4222 1808 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
d41bd96f
LP
1809
1810 default:
04499a70 1811 assert_not_reached();
d41bd96f
LP
1812 }
1813}
1814
1815int varlink_callb(
1816 Varlink *v,
1817 const char *method,
1818 JsonVariant **ret_parameters,
1819 const char **ret_error_id,
1820 VarlinkReplyFlags *ret_flags, ...) {
1821
1822 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1823 va_list ap;
1824 int r;
1825
1826 assert_return(v, -EINVAL);
1827
1828 va_start(ap, ret_flags);
1829 r = json_buildv(&parameters, ap);
1830 va_end(ap);
1831
1832 if (r < 0)
db3d4222 1833 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1834
1835 return varlink_call(v, method, parameters, ret_parameters, ret_error_id, ret_flags);
1836}
1837
1838int varlink_reply(Varlink *v, JsonVariant *parameters) {
1839 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1840 int r;
1841
1842 assert_return(v, -EINVAL);
1843
1844 if (v->state == VARLINK_DISCONNECTED)
1845 return -ENOTCONN;
1846 if (!IN_SET(v->state,
1847 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1848 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1849 return -EBUSY;
1850
1851 r = varlink_sanitize_parameters(&parameters);
1852 if (r < 0)
db3d4222 1853 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1854
1855 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1856 if (r < 0)
db3d4222 1857 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1858
1859 r = varlink_enqueue_json(v, m);
1860 if (r < 0)
db3d4222 1861 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1862
1863 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1864 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1865 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1866 * process further messages. */
790446bd 1867 varlink_clear_current(v);
d41bd96f
LP
1868 varlink_set_state(v, VARLINK_IDLE_SERVER);
1869 } else
1870 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1871 * means we should it handle the rest of the state engine. */
1872 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1873
1874 return 1;
1875}
1876
1877int varlink_replyb(Varlink *v, ...) {
1878 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1879 va_list ap;
1880 int r;
1881
1882 assert_return(v, -EINVAL);
1883
1884 va_start(ap, v);
1885 r = json_buildv(&parameters, ap);
1886 va_end(ap);
1887
1888 if (r < 0)
1889 return r;
1890
1891 return varlink_reply(v, parameters);
1892}
1893
1894int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
1895 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1896 int r;
1897
1898 assert_return(v, -EINVAL);
1899 assert_return(error_id, -EINVAL);
1900
1901 if (v->state == VARLINK_DISCONNECTED)
db3d4222 1902 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f
LP
1903 if (!IN_SET(v->state,
1904 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1905 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
db3d4222 1906 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f 1907
d37cdac6
LP
1908 /* Reset the list of pushed file descriptors before sending an error reply. We do this here to
1909 * simplify code that puts together a complex reply message with fds, and half-way something
1910 * fails. In that case the pushed fds need to be flushed out again. Under the assumption that it
1911 * never makes sense to send fds along with errors we simply flush them out here beforehand, so that
1912 * the callers don't need to do this explicitly. */
1913 varlink_reset_fds(v);
1914
d41bd96f
LP
1915 r = varlink_sanitize_parameters(&parameters);
1916 if (r < 0)
db3d4222 1917 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
1918
1919 r = json_build(&m, JSON_BUILD_OBJECT(
1920 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
1921 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1922 if (r < 0)
db3d4222 1923 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1924
1925 r = varlink_enqueue_json(v, m);
1926 if (r < 0)
db3d4222 1927 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
1928
1929 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
790446bd 1930 varlink_clear_current(v);
d41bd96f
LP
1931 varlink_set_state(v, VARLINK_IDLE_SERVER);
1932 } else
1933 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1934
1935 return 1;
1936}
1937
1938int varlink_errorb(Varlink *v, const char *error_id, ...) {
1939 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1940 va_list ap;
1941 int r;
1942
1943 assert_return(v, -EINVAL);
1944 assert_return(error_id, -EINVAL);
1945
1946 va_start(ap, error_id);
1947 r = json_buildv(&parameters, ap);
1948 va_end(ap);
1949
1950 if (r < 0)
db3d4222 1951 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
1952
1953 return varlink_error(v, error_id, parameters);
1954}
1955
1956int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
e8aba093 1957 int r;
d41bd96f
LP
1958
1959 assert_return(v, -EINVAL);
1960 assert_return(parameters, -EINVAL);
1961
1962 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1963 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1964 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1965 * don't expect any arguments. */
1966
e8aba093
VCS
1967 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
1968 * parameter sanitization to fail, and it returns -EINVAL. */
1969
1970 if (json_variant_is_string(parameters)) {
1971 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
1972
1973 r = json_build(&parameters_obj,
1974 JSON_BUILD_OBJECT(
1975 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters))));
1976 if (r < 0)
1977 return r;
1978
1979 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
1980 }
d41bd96f
LP
1981
1982 if (json_variant_is_object(parameters) &&
e8aba093
VCS
1983 json_variant_elements(parameters) > 0) {
1984 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
1985
1986 r = json_build(&parameters_obj,
1987 JSON_BUILD_OBJECT(
1988 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters, 0)))));
1989 if (r < 0)
1990 return r;
1991
1992 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
1993 }
d41bd96f
LP
1994
1995 return -EINVAL;
1996}
1997
7466e94f
LP
1998int varlink_error_errno(Varlink *v, int error) {
1999 return varlink_errorb(
2000 v,
2001 VARLINK_ERROR_SYSTEM,
2002 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error)))));
2003}
2004
d41bd96f
LP
2005int varlink_notify(Varlink *v, JsonVariant *parameters) {
2006 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
2007 int r;
2008
2009 assert_return(v, -EINVAL);
2010
2011 if (v->state == VARLINK_DISCONNECTED)
db3d4222 2012 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
d41bd96f 2013 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
db3d4222 2014 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
d41bd96f
LP
2015
2016 r = varlink_sanitize_parameters(&parameters);
2017 if (r < 0)
db3d4222 2018 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
d41bd96f
LP
2019
2020 r = json_build(&m, JSON_BUILD_OBJECT(
2021 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
2022 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
2023 if (r < 0)
db3d4222 2024 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2025
2026 r = varlink_enqueue_json(v, m);
2027 if (r < 0)
db3d4222 2028 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
d41bd96f
LP
2029
2030 /* No state change, as more is coming */
2031 return 1;
2032}
2033
2034int varlink_notifyb(Varlink *v, ...) {
2035 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
2036 va_list ap;
2037 int r;
2038
2039 assert_return(v, -EINVAL);
2040
2041 va_start(ap, v);
2042 r = json_buildv(&parameters, ap);
2043 va_end(ap);
2044
2045 if (r < 0)
db3d4222 2046 return varlink_log_errno(v, r, "Failed to build json message: %m");
d41bd96f
LP
2047
2048 return varlink_notify(v, parameters);
2049}
2050
2051int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
2052 assert_return(v, -EINVAL);
2053
2054 if (callback && v->reply_callback && callback != v->reply_callback)
db3d4222 2055 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
2056
2057 v->reply_callback = callback;
2058
2059 return 0;
2060}
2061
2062void* varlink_set_userdata(Varlink *v, void *userdata) {
2063 void *old;
2064
2065 assert_return(v, NULL);
2066
2067 old = v->userdata;
2068 v->userdata = userdata;
2069
2070 return old;
2071}
2072
2073void* varlink_get_userdata(Varlink *v) {
2074 assert_return(v, NULL);
2075
2076 return v->userdata;
2077}
2078
2079static int varlink_acquire_ucred(Varlink *v) {
2080 int r;
2081
2082 assert(v);
2083
2084 if (v->ucred_acquired)
2085 return 0;
2086
2087 r = getpeercred(v->fd, &v->ucred);
2088 if (r < 0)
2089 return r;
2090
2091 v->ucred_acquired = true;
2092 return 0;
2093}
2094
2095int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
2096 int r;
2097
2098 assert_return(v, -EINVAL);
2099 assert_return(ret, -EINVAL);
2100
2101 r = varlink_acquire_ucred(v);
2102 if (r < 0)
db3d4222 2103 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2104
2105 if (!uid_is_valid(v->ucred.uid))
db3d4222 2106 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
2107
2108 *ret = v->ucred.uid;
2109 return 0;
2110}
2111
2112int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
2113 int r;
2114
2115 assert_return(v, -EINVAL);
2116 assert_return(ret, -EINVAL);
2117
2118 r = varlink_acquire_ucred(v);
2119 if (r < 0)
db3d4222 2120 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
d41bd96f
LP
2121
2122 if (!pid_is_valid(v->ucred.pid))
db3d4222 2123 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
d41bd96f
LP
2124
2125 *ret = v->ucred.pid;
2126 return 0;
2127}
2128
2129int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
2130 assert_return(v, -EINVAL);
2131 assert_return(timeout > 0, -EINVAL);
2132
2133 v->timeout = timeout;
2134 return 0;
2135}
2136
2137VarlinkServer *varlink_get_server(Varlink *v) {
2138 assert_return(v, NULL);
2139
2140 return v->server;
2141}
2142
2143int varlink_set_description(Varlink *v, const char *description) {
2144 assert_return(v, -EINVAL);
2145
2146 return free_and_strdup(&v->description, description);
2147}
2148
2149static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
99534007 2150 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2151
2152 assert(s);
d41bd96f
LP
2153
2154 handle_revents(v, revents);
2155 (void) varlink_process(v);
2156
2157 return 1;
2158}
2159
2160static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
99534007 2161 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2162
2163 assert(s);
d41bd96f
LP
2164
2165 (void) varlink_process(v);
2166 return 1;
2167}
2168
2169static int defer_callback(sd_event_source *s, void *userdata) {
99534007 2170 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2171
2172 assert(s);
d41bd96f
LP
2173
2174 (void) varlink_process(v);
2175 return 1;
2176}
2177
2178static int prepare_callback(sd_event_source *s, void *userdata) {
99534007 2179 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2180 int r, e;
2181 usec_t until;
f1194f5d 2182 bool have_timeout;
d41bd96f
LP
2183
2184 assert(s);
d41bd96f
LP
2185
2186 e = varlink_get_events(v);
2187 if (e < 0)
2188 return e;
2189
2190 r = sd_event_source_set_io_events(v->io_event_source, e);
2191 if (r < 0)
db3d4222 2192 return varlink_log_errno(v, r, "Failed to set source events: %m");
d41bd96f
LP
2193
2194 r = varlink_get_timeout(v, &until);
2195 if (r < 0)
2196 return r;
f1194f5d
LP
2197 have_timeout = r > 0;
2198
2199 if (have_timeout) {
d41bd96f
LP
2200 r = sd_event_source_set_time(v->time_event_source, until);
2201 if (r < 0)
db3d4222 2202 return varlink_log_errno(v, r, "Failed to set source time: %m");
d41bd96f
LP
2203 }
2204
f1194f5d 2205 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
d41bd96f 2206 if (r < 0)
db3d4222 2207 return varlink_log_errno(v, r, "Failed to enable event source: %m");
d41bd96f
LP
2208
2209 return 1;
2210}
2211
2212static int quit_callback(sd_event_source *event, void *userdata) {
99534007 2213 Varlink *v = ASSERT_PTR(userdata);
d41bd96f
LP
2214
2215 assert(event);
d41bd96f
LP
2216
2217 varlink_flush(v);
2218 varlink_close(v);
2219
2220 return 1;
2221}
2222
2223int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
2224 int r;
2225
2226 assert_return(v, -EINVAL);
2227 assert_return(!v->event, -EBUSY);
2228
2229 if (e)
2230 v->event = sd_event_ref(e);
2231 else {
2232 r = sd_event_default(&v->event);
2233 if (r < 0)
db3d4222 2234 return varlink_log_errno(v, r, "Failed to create event source: %m");
d41bd96f
LP
2235 }
2236
2237 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
2238 if (r < 0)
2239 goto fail;
2240
2241 r = sd_event_source_set_priority(v->time_event_source, priority);
2242 if (r < 0)
2243 goto fail;
2244
2245 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
2246
2247 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
2248 if (r < 0)
2249 goto fail;
2250
2251 r = sd_event_source_set_priority(v->quit_event_source, priority);
2252 if (r < 0)
2253 goto fail;
2254
2255 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
2256
2257 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
2258 if (r < 0)
2259 goto fail;
2260
2261 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
2262 if (r < 0)
2263 goto fail;
2264
2265 r = sd_event_source_set_priority(v->io_event_source, priority);
2266 if (r < 0)
2267 goto fail;
2268
2269 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
2270
2271 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
2272 if (r < 0)
2273 goto fail;
2274
2275 r = sd_event_source_set_priority(v->defer_event_source, priority);
2276 if (r < 0)
2277 goto fail;
2278
2279 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
2280
2281 return 0;
2282
2283fail:
db3d4222 2284 varlink_log_errno(v, r, "Failed to setup event source: %m");
d41bd96f
LP
2285 varlink_detach_event(v);
2286 return r;
2287}
2288
d41bd96f
LP
2289void varlink_detach_event(Varlink *v) {
2290 if (!v)
2291 return;
2292
2293 varlink_detach_event_sources(v);
2294
2295 v->event = sd_event_unref(v->event);
2296}
2297
2298sd_event *varlink_get_event(Varlink *v) {
2299 assert_return(v, NULL);
2300
2301 return v->event;
2302}
2303
d37cdac6
LP
2304int varlink_push_fd(Varlink *v, int fd) {
2305 int i;
2306
2307 assert_return(v, -EINVAL);
2308 assert_return(fd >= 0, -EBADF);
2309
2310 /* Takes an fd to send along with the *next* varlink message sent via this varlink connection. This
2311 * takes ownership of the specified fd. Use varlink_dup_fd() below to duplicate the fd first. */
2312
2313 if (!v->allow_fd_passing_output)
2314 return -EPERM;
2315
2316 if (v->n_pushed_fds >= INT_MAX)
2317 return -ENOMEM;
2318
2319 if (!GREEDY_REALLOC(v->pushed_fds, v->n_pushed_fds + 1))
2320 return -ENOMEM;
2321
2322 i = (int) v->n_pushed_fds;
2323 v->pushed_fds[v->n_pushed_fds++] = fd;
2324 return i;
2325}
2326
2327int varlink_dup_fd(Varlink *v, int fd) {
2328 _cleanup_close_ int dp = -1;
2329 int r;
2330
2331 assert_return(v, -EINVAL);
2332 assert_return(fd >= 0, -EBADF);
2333
2334 /* Like varlink_push_fd() but duplicates the specified fd instead of taking possession of it */
2335
2336 dp = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2337 if (dp < 0)
2338 return -errno;
2339
2340 r = varlink_push_fd(v, dp);
2341 if (r < 0)
2342 return r;
2343
2344 TAKE_FD(dp);
2345 return r;
2346}
2347
2348int varlink_reset_fds(Varlink *v) {
2349 assert_return(v, -EINVAL);
2350
2351 /* Closes all currently pending fds to send. This may be used whenever the caller is in the process
2352 * of putting together a message with fds, and then eventually something fails and they need to
2353 * rollback the fds. Note that this is implicitly called whenever an error reply is sent, see above. */
2354
2355 close_many(v->output_fds, v->n_output_fds);
2356 v->n_output_fds = 0;
2357 return 0;
2358}
2359
2360int varlink_peek_fd(Varlink *v, size_t i) {
2361 assert_return(v, -EINVAL);
2362
94d82b59 2363 /* Returns one of the file descriptors that were received along with the current message. This does
d37cdac6
LP
2364 * not duplicate the fd nor invalidate it, it hence remains in our possession. */
2365
2366 if (!v->allow_fd_passing_input)
2367 return -EPERM;
2368
2369 if (i >= v->n_input_fds)
2370 return -ENXIO;
2371
2372 return v->input_fds[i];
2373}
2374
2375int varlink_take_fd(Varlink *v, size_t i) {
2376 assert_return(v, -EINVAL);
2377
2378 /* Similar to varlink_peek_fd() but the file descriptor's ownership is passed to the caller, and
2379 * we'll invalidate the reference to it under our possession. If called twice in a row will return
2380 * -EBADF */
2381
2382 if (!v->allow_fd_passing_input)
2383 return -EPERM;
2384
2385 if (i >= v->n_input_fds)
2386 return -ENXIO;
2387
2388 return TAKE_FD(v->input_fds[i]);
2389}
2390
2391static int verify_unix_socket(Varlink *v) {
2392 assert(v);
2393
2394 if (v->af < 0) {
2395 struct stat st;
2396
2397 if (fstat(v->fd, &st) < 0)
2398 return -errno;
2399 if (!S_ISSOCK(st.st_mode)) {
2400 v->af = AF_UNSPEC;
2401 return -ENOTSOCK;
2402 }
2403
2404 v->af = socket_get_family(v->fd);
2405 if (v->af < 0)
2406 return v->af;
2407 }
2408
2409 return v->af == AF_UNIX ? 0 : -ENOMEDIUM;
2410}
2411
2412int varlink_set_allow_fd_passing_input(Varlink *v, bool b) {
2413 int r;
2414
2415 assert_return(v, -EINVAL);
2416
2417 if (v->allow_fd_passing_input == b)
2418 return 0;
2419
2420 if (!b) {
2421 v->allow_fd_passing_input = false;
2422 return 1;
2423 }
2424
2425 r = verify_unix_socket(v);
2426 if (r < 0)
2427 return r;
2428
2429 v->allow_fd_passing_input = true;
2430 return 0;
2431}
2432
2433int varlink_set_allow_fd_passing_output(Varlink *v, bool b) {
2434 int r;
2435
2436 assert_return(v, -EINVAL);
2437
2438 if (v->allow_fd_passing_output == b)
2439 return 0;
2440
2441 if (!b) {
2442 v->allow_fd_passing_output = false;
2443 return 1;
2444 }
2445
2446 r = verify_unix_socket(v);
2447 if (r < 0)
2448 return r;
2449
2450 v->allow_fd_passing_output = true;
2451 return 0;
2452}
2453
d41bd96f
LP
2454int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
2455 VarlinkServer *s;
2456
2457 assert_return(ret, -EINVAL);
2458 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
2459
2460 s = new(VarlinkServer, 1);
2461 if (!s)
db3d4222 2462 return log_oom_debug();
d41bd96f
LP
2463
2464 *s = (VarlinkServer) {
2465 .n_ref = 1,
2466 .flags = flags,
2467 .connections_max = varlink_server_connections_max(NULL),
2468 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
2469 };
2470
2471 *ret = s;
2472 return 0;
2473}
2474
2475static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
2476 char *m;
2477
2478 if (!s)
2479 return NULL;
2480
2481 varlink_server_shutdown(s);
2482
2483 while ((m = hashmap_steal_first_key(s->methods)))
2484 free(m);
2485
2486 hashmap_free(s->methods);
2487 hashmap_free(s->by_uid);
2488
2489 sd_event_unref(s->event);
2490
2491 free(s->description);
2492
2493 return mfree(s);
2494}
2495
2496DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
2497
2498static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
2499 int allowed = -1;
2500
2501 assert(server);
2502 assert(ucred);
2503
2504 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
2505 allowed = ucred->uid == 0;
2506
2507 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
2508 allowed = allowed > 0 || ucred->uid == getuid();
2509
2510 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
2511 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2512 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
2513 return 0;
2514 }
2515
2516 if (server->n_connections >= server->connections_max) {
2517 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
2518 return 0;
2519 }
2520
2521 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2522 unsigned c;
2523
2524 if (!uid_is_valid(ucred->uid)) {
2525 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
2526 return 0;
2527 }
2528
2529 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2530 if (c >= server->connections_per_uid_max) {
2531 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
2532 server->connections_per_uid_max);
2533 return 0;
2534 }
2535 }
2536
2537 return 1;
2538}
2539
678ca213 2540static int count_connection(VarlinkServer *server, const struct ucred *ucred) {
d41bd96f
LP
2541 unsigned c;
2542 int r;
2543
2544 assert(server);
2545 assert(ucred);
2546
2547 server->n_connections++;
2548
2549 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2550 r = hashmap_ensure_allocated(&server->by_uid, NULL);
2551 if (r < 0)
2552 return log_debug_errno(r, "Failed to allocate UID hash table: %m");
2553
2554 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2555
2556 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
2557 ucred->uid, c, server->connections_per_uid_max);
2558
2559 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
2560 if (r < 0)
2561 return log_debug_errno(r, "Failed to increment counter in UID hash table: %m");
2562 }
2563
2564 return 0;
2565}
2566
2567int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
2568 _cleanup_(varlink_unrefp) Varlink *v = NULL;
a995ce47 2569 struct ucred ucred = UCRED_INVALID;
d41bd96f 2570 bool ucred_acquired;
d41bd96f
LP
2571 int r;
2572
2573 assert_return(server, -EINVAL);
2574 assert_return(fd >= 0, -EBADF);
2575
2576 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
2577 r = getpeercred(fd, &ucred);
2578 if (r < 0)
2579 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2580
2581 ucred_acquired = true;
2582
2583 r = validate_connection(server, &ucred);
2584 if (r < 0)
2585 return r;
2586 if (r == 0)
2587 return -EPERM;
2588 } else
2589 ucred_acquired = false;
2590
2591 r = varlink_new(&v);
2592 if (r < 0)
2593 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
2594
2595 r = count_connection(server, &ucred);
2596 if (r < 0)
2597 return r;
2598
2599 v->fd = fd;
9807fdc1
LP
2600 if (server->flags & VARLINK_SERVER_INHERIT_USERDATA)
2601 v->userdata = server->userdata;
2602
d41bd96f
LP
2603 if (ucred_acquired) {
2604 v->ucred = ucred;
2605 v->ucred_acquired = true;
2606 }
2607
12619d0a
ZJS
2608 _cleanup_free_ char *desc = NULL;
2609 if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0)
2610 v->description = TAKE_PTR(desc);
d41bd96f
LP
2611
2612 /* Link up the server and the connection, and take reference in both directions. Note that the
2613 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2614 * which happens in varlink_close(), including in the event loop quit callback. */
2615 v->server = varlink_server_ref(server);
2616 varlink_ref(v);
2617
2618 varlink_set_state(v, VARLINK_IDLE_SERVER);
2619
7e69d90c
LP
2620 if (server->event) {
2621 r = varlink_attach_event(v, server->event, server->event_priority);
2622 if (r < 0) {
2623 varlink_log_errno(v, r, "Failed to attach new connection: %m");
254d1313 2624 v->fd = -EBADF; /* take the fd out of the connection again */
7e69d90c
LP
2625 varlink_close(v);
2626 return r;
2627 }
d41bd96f
LP
2628 }
2629
2630 if (ret)
2631 *ret = v;
2632
2633 return 0;
2634}
2635
c14e841f
AZ
2636static VarlinkServerSocket *varlink_server_socket_free(VarlinkServerSocket *ss) {
2637 if (!ss)
2638 return NULL;
2639
2640 free(ss->address);
2641 return mfree(ss);
2642}
2643
2644DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServerSocket *, varlink_server_socket_free);
2645
d41bd96f 2646static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
99534007 2647 VarlinkServerSocket *ss = ASSERT_PTR(userdata);
254d1313 2648 _cleanup_close_ int cfd = -EBADF;
d41bd96f
LP
2649 Varlink *v = NULL;
2650 int r;
2651
2652 assert(source);
d41bd96f
LP
2653
2654 varlink_server_log(ss->server, "New incoming connection.");
2655
2656 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2657 if (cfd < 0) {
2658 if (ERRNO_IS_ACCEPT_AGAIN(errno))
2659 return 0;
2660
2661 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
2662 }
2663
2664 r = varlink_server_add_connection(ss->server, cfd, &v);
2665 if (r < 0)
2666 return 0;
2667
2668 TAKE_FD(cfd);
2669
2670 if (ss->server->connect_callback) {
2671 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
2672 if (r < 0) {
2673 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
2674 varlink_close(v);
2675 return 0;
2676 }
2677 }
2678
2679 return 0;
2680}
2681
c14e841f
AZ
2682static int varlink_server_create_listen_fd_socket(VarlinkServer *s, int fd, VarlinkServerSocket **ret_ss) {
2683 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f
LP
2684 int r;
2685
c14e841f
AZ
2686 assert(s);
2687 assert(fd >= 0);
2688 assert(ret_ss);
d41bd96f
LP
2689
2690 r = fd_nonblock(fd, true);
2691 if (r < 0)
2692 return r;
2693
2694 ss = new(VarlinkServerSocket, 1);
2695 if (!ss)
db3d4222 2696 return log_oom_debug();
d41bd96f
LP
2697
2698 *ss = (VarlinkServerSocket) {
2699 .server = s,
2700 .fd = fd,
2701 };
2702
2703 if (s->event) {
8d91b220 2704 r = sd_event_add_io(s->event, &ss->event_source, fd, EPOLLIN, connect_callback, ss);
d41bd96f
LP
2705 if (r < 0)
2706 return r;
2707
2708 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
2709 if (r < 0)
2710 return r;
2711 }
2712
c14e841f
AZ
2713 *ret_ss = TAKE_PTR(ss);
2714 return 0;
2715}
2716
2717int varlink_server_listen_fd(VarlinkServer *s, int fd) {
2718 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
2719 int r;
2720
2721 assert_return(s, -EINVAL);
2722 assert_return(fd >= 0, -EBADF);
2723
2724 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
2725 if (r < 0)
2726 return r;
2727
d41bd96f
LP
2728 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
2729 return 0;
2730}
2731
2732int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
c14e841f 2733 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
d41bd96f 2734 union sockaddr_union sockaddr;
f36a9d59 2735 socklen_t sockaddr_len;
254d1313 2736 _cleanup_close_ int fd = -EBADF;
d41bd96f
LP
2737 int r;
2738
2739 assert_return(s, -EINVAL);
2740 assert_return(address, -EINVAL);
2741 assert_return((m & ~0777) == 0, -EINVAL);
2742
2743 r = sockaddr_un_set_path(&sockaddr.un, address);
2744 if (r < 0)
2745 return r;
f36a9d59 2746 sockaddr_len = r;
d41bd96f
LP
2747
2748 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2749 if (fd < 0)
2750 return -errno;
2751
a0c41de2
LP
2752 fd = fd_move_above_stdio(fd);
2753
d41bd96f
LP
2754 (void) sockaddr_un_unlink(&sockaddr.un);
2755
2053593f 2756 WITH_UMASK(~m & 0777) {
63e00ccd
CG
2757 r = mac_selinux_bind(fd, &sockaddr.sa, sockaddr_len);
2758 if (r < 0)
2759 return r;
2760 }
d41bd96f 2761
768fcd77 2762 if (listen(fd, SOMAXCONN_DELUXE) < 0)
d41bd96f
LP
2763 return -errno;
2764
c14e841f 2765 r = varlink_server_create_listen_fd_socket(s, fd, &ss);
d41bd96f
LP
2766 if (r < 0)
2767 return r;
2768
c14e841f
AZ
2769 r = free_and_strdup(&ss->address, address);
2770 if (r < 0)
2771 return r;
2772
2773 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
d41bd96f
LP
2774 TAKE_FD(fd);
2775 return 0;
2776}
2777
2778void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
2779 void *ret;
2780
2781 assert_return(s, NULL);
2782
2783 ret = s->userdata;
2784 s->userdata = userdata;
2785
2786 return ret;
2787}
2788
2789void* varlink_server_get_userdata(VarlinkServer *s) {
2790 assert_return(s, NULL);
2791
2792 return s->userdata;
2793}
2794
2795static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
2796 if (!ss)
2797 return NULL;
2798
2799 if (ss->server)
2800 LIST_REMOVE(sockets, ss->server->sockets, ss);
2801
1d3fe304 2802 sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
2803
2804 free(ss->address);
2805 safe_close(ss->fd);
2806
2807 return mfree(ss);
2808}
2809
2810int varlink_server_shutdown(VarlinkServer *s) {
2811 assert_return(s, -EINVAL);
2812
2813 while (s->sockets)
2814 varlink_server_socket_destroy(s->sockets);
2815
2816 return 0;
2817}
2818
536827e0
AZ
2819static int varlink_server_add_socket_event_source(VarlinkServer *s, VarlinkServerSocket *ss, int64_t priority) {
2820 _cleanup_(sd_event_source_unrefp) sd_event_source *es = NULL;
2821
2822 int r;
2823
2824 assert(s);
2825 assert(s->event);
2826 assert(ss);
2827 assert(ss->fd >= 0);
2828 assert(!ss->event_source);
2829
2830 r = sd_event_add_io(s->event, &es, ss->fd, EPOLLIN, connect_callback, ss);
2831 if (r < 0)
2832 return r;
2833
2834 r = sd_event_source_set_priority(es, priority);
2835 if (r < 0)
2836 return r;
2837
2838 ss->event_source = TAKE_PTR(es);
2839 return 0;
2840}
2841
d41bd96f 2842int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
d41bd96f
LP
2843 int r;
2844
2845 assert_return(s, -EINVAL);
2846 assert_return(!s->event, -EBUSY);
2847
2848 if (e)
2849 s->event = sd_event_ref(e);
2850 else {
2851 r = sd_event_default(&s->event);
2852 if (r < 0)
2853 return r;
2854 }
2855
2856 LIST_FOREACH(sockets, ss, s->sockets) {
536827e0 2857 r = varlink_server_add_socket_event_source(s, ss, priority);
d41bd96f
LP
2858 if (r < 0)
2859 goto fail;
2860 }
2861
2862 s->event_priority = priority;
2863 return 0;
2864
2865fail:
2866 varlink_server_detach_event(s);
2867 return r;
2868}
2869
2870int varlink_server_detach_event(VarlinkServer *s) {
d41bd96f
LP
2871 assert_return(s, -EINVAL);
2872
4f538d7b
LP
2873 LIST_FOREACH(sockets, ss, s->sockets)
2874 ss->event_source = sd_event_source_disable_unref(ss->event_source);
d41bd96f
LP
2875
2876 sd_event_unref(s->event);
2877 return 0;
2878}
2879
2880sd_event *varlink_server_get_event(VarlinkServer *s) {
2881 assert_return(s, NULL);
2882
2883 return s->event;
2884}
2885
2886int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
db3d4222 2887 _cleanup_free_ char *m = NULL;
d41bd96f
LP
2888 int r;
2889
2890 assert_return(s, -EINVAL);
2891 assert_return(method, -EINVAL);
2892 assert_return(callback, -EINVAL);
2893
2894 if (startswith(method, "org.varlink.service."))
db3d4222 2895 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST), "Cannot bind server to '%s'.", method);
d41bd96f 2896
d41bd96f
LP
2897 m = strdup(method);
2898 if (!m)
db3d4222 2899 return log_oom_debug();
d41bd96f 2900
1d2d1654
SS
2901 r = hashmap_ensure_put(&s->methods, &string_hash_ops, m, callback);
2902 if (r == -ENOMEM)
2903 return log_oom_debug();
db3d4222
ZJS
2904 if (r < 0)
2905 return log_debug_errno(r, "Failed to register callback: %m");
2906 if (r > 0)
2907 TAKE_PTR(m);
d41bd96f
LP
2908
2909 return 0;
2910}
2911
2912int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
2913 va_list ap;
e7b93f97 2914 int r = 0;
d41bd96f
LP
2915
2916 assert_return(s, -EINVAL);
2917
2918 va_start(ap, s);
2919 for (;;) {
2920 VarlinkMethod callback;
2921 const char *method;
2922
2923 method = va_arg(ap, const char *);
2924 if (!method)
2925 break;
2926
2927 callback = va_arg(ap, VarlinkMethod);
2928
2929 r = varlink_server_bind_method(s, method, callback);
2930 if (r < 0)
e7b93f97 2931 break;
d41bd96f 2932 }
e7b93f97 2933 va_end(ap);
d41bd96f 2934
e7b93f97 2935 return r;
d41bd96f
LP
2936}
2937
2938int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
2939 assert_return(s, -EINVAL);
2940
2941 if (callback && s->connect_callback && callback != s->connect_callback)
db3d4222 2942 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
d41bd96f
LP
2943
2944 s->connect_callback = callback;
2945 return 0;
2946}
2947
6d4d6002
LP
2948int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
2949 assert_return(s, -EINVAL);
2950
2951 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
db3d4222 2952 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
6d4d6002
LP
2953
2954 s->disconnect_callback = callback;
2955 return 0;
2956}
2957
d41bd96f 2958unsigned varlink_server_connections_max(VarlinkServer *s) {
88a36d36 2959 int dts;
d41bd96f
LP
2960
2961 /* If a server is specified, return the setting for that server, otherwise the default value */
2962 if (s)
2963 return s->connections_max;
2964
88a36d36
LP
2965 dts = getdtablesize();
2966 assert_se(dts > 0);
d41bd96f
LP
2967
2968 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
88a36d36
LP
2969 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
2970 return dts / 4 * 3;
d41bd96f
LP
2971
2972 return VARLINK_DEFAULT_CONNECTIONS_MAX;
2973}
2974
2975unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
2976 unsigned m;
2977
2978 if (s)
2979 return s->connections_per_uid_max;
2980
2981 /* Make sure to never use up more than ¾th of available connections for a single user */
2982 m = varlink_server_connections_max(NULL);
2983 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
2984 return m / 4 * 3;
2985
2986 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
2987}
2988
2989int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
2990 assert_return(s, -EINVAL);
2991 assert_return(m > 0, -EINVAL);
2992
2993 s->connections_per_uid_max = m;
2994 return 0;
2995}
2996
2997int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
2998 assert_return(s, -EINVAL);
2999 assert_return(m > 0, -EINVAL);
3000
3001 s->connections_max = m;
3002 return 0;
3003}
3004
c4f601f2
LP
3005unsigned varlink_server_current_connections(VarlinkServer *s) {
3006 assert_return(s, UINT_MAX);
3007
3008 return s->n_connections;
3009}
3010
d41bd96f
LP
3011int varlink_server_set_description(VarlinkServer *s, const char *description) {
3012 assert_return(s, -EINVAL);
3013
3014 return free_and_strdup(&s->description, description);
3015}
008798e9
AZ
3016
3017int varlink_server_serialize(VarlinkServer *s, FILE *f, FDSet *fds) {
3018 assert(f);
3019 assert(fds);
3020
3021 if (!s)
3022 return 0;
3023
3024 LIST_FOREACH(sockets, ss, s->sockets) {
3025 int copy;
3026
3027 assert(ss->address);
3028 assert(ss->fd >= 0);
3029
3030 fprintf(f, "varlink-server-socket-address=%s", ss->address);
3031
3032 /* If we fail to serialize the fd, it will be considered an error during deserialization */
3033 copy = fdset_put_dup(fds, ss->fd);
3034 if (copy < 0)
3035 return copy;
3036
3037 fprintf(f, " varlink-server-socket-fd=%i", copy);
3038
3039 fputc('\n', f);
3040 }
3041
3042 return 0;
3043}
3044
3045int varlink_server_deserialize_one(VarlinkServer *s, const char *value, FDSet *fds) {
3046 _cleanup_(varlink_server_socket_freep) VarlinkServerSocket *ss = NULL;
3047 _cleanup_free_ char *address = NULL;
3048 const char *v = ASSERT_PTR(value);
254d1313 3049 int r, fd = -EBADF;
008798e9
AZ
3050 char *buf;
3051 size_t n;
3052
3053 assert(s);
3054 assert(fds);
3055
3056 n = strcspn(v, " ");
3057 address = strndup(v, n);
3058 if (!address)
3059 return log_oom_debug();
3060
3061 if (v[n] != ' ')
3062 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
3063 "Failed to deserialize VarlinkServerSocket: %s: %m", value);
3064 v = startswith(v + n + 1, "varlink-server-socket-fd=");
3065 if (!v)
3066 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
3067 "Failed to deserialize VarlinkServerSocket fd %s: %m", value);
3068
3069 n = strcspn(v, " ");
3070 buf = strndupa_safe(v, n);
3071
e652663a 3072 fd = parse_fd(buf);
e652663a
DT
3073 if (fd < 0)
3074 return log_debug_errno(fd, "Unable to parse VarlinkServerSocket varlink-server-socket-fd=%s: %m", buf);
008798e9
AZ
3075 if (!fdset_contains(fds, fd))
3076 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
3077 "VarlinkServerSocket varlink-server-socket-fd= has unknown fd %d: %m", fd);
3078
3079 ss = new(VarlinkServerSocket, 1);
3080 if (!ss)
3081 return log_oom_debug();
3082
3083 *ss = (VarlinkServerSocket) {
3084 .server = s,
3085 .address = TAKE_PTR(address),
3086 .fd = fdset_remove(fds, fd),
3087 };
3088
3089 r = varlink_server_add_socket_event_source(s, ss, SD_EVENT_PRIORITY_NORMAL);
3090 if (r < 0)
3091 return log_debug_errno(r, "Failed to add VarlinkServerSocket event source to the event loop: %m");
3092
3093 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
3094 return 0;
3095}