1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <malloc.h>
4 #include <poll.h>
5
6 #include "alloc-util.h"
7 #include "errno-util.h"
8 #include "fd-util.h"
9 #include "hashmap.h"
10 #include "io-util.h"
11 #include "list.h"
12 #include "process-util.h"
13 #include "selinux-util.h"
14 #include "set.h"
15 #include "socket-util.h"
16 #include "string-table.h"
17 #include "string-util.h"
18 #include "strv.h"
19 #include "time-util.h"
20 #include "umask-util.h"
21 #include "user-util.h"
22 #include "varlink.h"
23
24 #define VARLINK_DEFAULT_CONNECTIONS_MAX 4096U
25 #define VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX 1024U
26
27 #define VARLINK_DEFAULT_TIMEOUT_USEC (45U*USEC_PER_SEC)
28 #define VARLINK_BUFFER_MAX (16U*1024U*1024U)
29 #define VARLINK_READ_SIZE (64U*1024U)
30
31 typedef enum VarlinkState {
32 /* Client side states */
33 VARLINK_IDLE_CLIENT,
34 VARLINK_AWAITING_REPLY,
35 VARLINK_AWAITING_REPLY_MORE,
36 VARLINK_CALLING,
37 VARLINK_CALLED,
38 VARLINK_PROCESSING_REPLY,
39
40 /* Server side states */
41 VARLINK_IDLE_SERVER,
42 VARLINK_PROCESSING_METHOD,
43 VARLINK_PROCESSING_METHOD_MORE,
44 VARLINK_PROCESSING_METHOD_ONEWAY,
45 VARLINK_PROCESSED_METHOD,
46 VARLINK_PENDING_METHOD,
47 VARLINK_PENDING_METHOD_MORE,
48
49 /* Common states (only during shutdown) */
50 VARLINK_PENDING_DISCONNECT,
51 VARLINK_PENDING_TIMEOUT,
52 VARLINK_PROCESSING_DISCONNECT,
53 VARLINK_PROCESSING_TIMEOUT,
54 VARLINK_PROCESSING_FAILURE,
55 VARLINK_DISCONNECTED,
56
57 _VARLINK_STATE_MAX,
58 _VARLINK_STATE_INVALID = -EINVAL,
59 } VarlinkState;
60
61 /* Tests whether we are not yet disconnected. Note that this is true during all states where the connection
62 * is still good for something, and false only when it's dead for good. This means: when we are
63 * asynchronously connecting to a peer and the connect() is still pending, then this will return 'true', as
64 * the connection is still good, and we are likely to be able to properly operate on it soon. */
65 #define VARLINK_STATE_IS_ALIVE(state) \
66 IN_SET(state, \
67 VARLINK_IDLE_CLIENT, \
68 VARLINK_AWAITING_REPLY, \
69 VARLINK_AWAITING_REPLY_MORE, \
70 VARLINK_CALLING, \
71 VARLINK_CALLED, \
72 VARLINK_PROCESSING_REPLY, \
73 VARLINK_IDLE_SERVER, \
74 VARLINK_PROCESSING_METHOD, \
75 VARLINK_PROCESSING_METHOD_MORE, \
76 VARLINK_PROCESSING_METHOD_ONEWAY, \
77 VARLINK_PROCESSED_METHOD, \
78 VARLINK_PENDING_METHOD, \
79 VARLINK_PENDING_METHOD_MORE)
80
81 struct Varlink {
82 unsigned n_ref;
83
84 VarlinkServer *server;
85
86 VarlinkState state;
87 bool connecting; /* This boolean indicates whether the socket fd we are operating on is currently
88 * processing an asynchronous connect(). In that state we watch the socket for
89 * EPOLLOUT, but we refrain from calling read() or write() on the socket as that
90 * will trigger ENOTCONN. Note that this boolean is kept separate from the
91 * VarlinkState above on purpose: while the connect() is still not complete we
92 * already want to allow queuing of messages and similar. Thus it's nice to keep
93 * these two state concepts separate: the VarlinkState encodes what our own view of
94 * the connection is, i.e. whether we think it's a server, a client, and has
95 * something queued already, while 'connecting' tells us a detail about the
96 * transport used below, that should have no effect on how we otherwise accept and
97 * process operations from the user.
98 *
99 * Or to say this differently: VARLINK_STATE_IS_ALIVE(state) tells you whether the
100 * connection is good to use, even if it might not be fully connected
101 * yet. connecting=true then informs you that actually we are still connecting, and
102 * the connection is actually not established yet and thus any requests you enqueue
103 * now will still work fine but will be queued only, not sent yet, but that
104 * shouldn't stop you from using the connection, since eventually whatever you queue
105 * *will* be sent.
106 *
107 * Or to say this even differently: 'state' is a high-level ("application layer"
108 * high, if you so will) state, while 'conecting' is a low-level ("transport layer"
109 * low, if you so will) state, and while they are not entirely unrelated and
110 * sometimes propagate effects to each other they are only asynchronously connected
111 * at most. */
112 unsigned n_pending;
113
114 int fd;
115
116 char *input_buffer; /* valid data starts at input_buffer_index, ends at input_buffer_index+input_buffer_size */
117 size_t input_buffer_index;
118 size_t input_buffer_size;
119 size_t input_buffer_unscanned;
120
121 char *output_buffer; /* valid data starts at output_buffer_index, ends at output_buffer_index+output_buffer_size */
122 size_t output_buffer_index;
123 size_t output_buffer_size;
124
125 VarlinkReply reply_callback;
126
127 JsonVariant *current;
128 JsonVariant *reply;
129
130 struct ucred ucred;
131 bool ucred_acquired:1;
132
133 bool write_disconnected:1;
134 bool read_disconnected:1;
135 bool prefer_read_write:1;
136 bool got_pollhup:1;
137
138 usec_t timestamp;
139 usec_t timeout;
140
141 void *userdata;
142 char *description;
143
144 sd_event *event;
145 sd_event_source *io_event_source;
146 sd_event_source *time_event_source;
147 sd_event_source *quit_event_source;
148 sd_event_source *defer_event_source;
149 };
150
151 typedef struct VarlinkServerSocket VarlinkServerSocket;
152
153 struct VarlinkServerSocket {
154 VarlinkServer *server;
155
156 int fd;
157 char *address;
158
159 sd_event_source *event_source;
160
161 LIST_FIELDS(VarlinkServerSocket, sockets);
162 };
163
164 struct VarlinkServer {
165 unsigned n_ref;
166 VarlinkServerFlags flags;
167
168 LIST_HEAD(VarlinkServerSocket, sockets);
169
170 Hashmap *methods;
171 VarlinkConnect connect_callback;
172 VarlinkDisconnect disconnect_callback;
173
174 sd_event *event;
175 int64_t event_priority;
176
177 unsigned n_connections;
178 Hashmap *by_uid;
179
180 void *userdata;
181 char *description;
182
183 unsigned connections_max;
184 unsigned connections_per_uid_max;
185 };
186
187 static const char* const varlink_state_table[_VARLINK_STATE_MAX] = {
188 [VARLINK_IDLE_CLIENT] = "idle-client",
189 [VARLINK_AWAITING_REPLY] = "awaiting-reply",
190 [VARLINK_AWAITING_REPLY_MORE] = "awaiting-reply-more",
191 [VARLINK_CALLING] = "calling",
192 [VARLINK_CALLED] = "called",
193 [VARLINK_PROCESSING_REPLY] = "processing-reply",
194 [VARLINK_IDLE_SERVER] = "idle-server",
195 [VARLINK_PROCESSING_METHOD] = "processing-method",
196 [VARLINK_PROCESSING_METHOD_MORE] = "processing-method-more",
197 [VARLINK_PROCESSING_METHOD_ONEWAY] = "processing-method-oneway",
198 [VARLINK_PROCESSED_METHOD] = "processed-method",
199 [VARLINK_PENDING_METHOD] = "pending-method",
200 [VARLINK_PENDING_METHOD_MORE] = "pending-method-more",
201 [VARLINK_PENDING_DISCONNECT] = "pending-disconnect",
202 [VARLINK_PENDING_TIMEOUT] = "pending-timeout",
203 [VARLINK_PROCESSING_DISCONNECT] = "processing-disconnect",
204 [VARLINK_PROCESSING_TIMEOUT] = "processing-timeout",
205 [VARLINK_PROCESSING_FAILURE] = "processing-failure",
206 [VARLINK_DISCONNECTED] = "disconnected",
207 };
208
209 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(varlink_state, VarlinkState);
210
211 #define varlink_log_errno(v, error, fmt, ...) \
212 log_debug_errno(error, "%s: " fmt, varlink_description(v), ##__VA_ARGS__)
213
214 #define varlink_log(v, fmt, ...) \
215 log_debug("%s: " fmt, varlink_description(v), ##__VA_ARGS__)
216
217 #define varlink_server_log_errno(s, error, fmt, ...) \
218 log_debug_errno(error, "%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
219
220 #define varlink_server_log(s, fmt, ...) \
221 log_debug("%s: " fmt, varlink_server_description(s), ##__VA_ARGS__)
222
varlink_description(Varlink * v)223 static inline const char *varlink_description(Varlink *v) {
224 return (v ? v->description : NULL) ?: "varlink";
225 }
226
varlink_server_description(VarlinkServer * s)227 static inline const char *varlink_server_description(VarlinkServer *s) {
228 return (s ? s->description : NULL) ?: "varlink";
229 }
230
varlink_set_state(Varlink * v,VarlinkState state)231 static void varlink_set_state(Varlink *v, VarlinkState state) {
232 assert(v);
233 assert(state >= 0 && state < _VARLINK_STATE_MAX);
234
235 if (v->state < 0)
236 varlink_log(v, "Setting state %s",
237 varlink_state_to_string(state));
238 else
239 varlink_log(v, "Changing state %s → %s",
240 varlink_state_to_string(v->state),
241 varlink_state_to_string(state));
242
243 v->state = state;
244 }
245
varlink_new(Varlink ** ret)246 static int varlink_new(Varlink **ret) {
247 Varlink *v;
248
249 assert(ret);
250
251 v = new(Varlink, 1);
252 if (!v)
253 return -ENOMEM;
254
255 *v = (Varlink) {
256 .n_ref = 1,
257 .fd = -1,
258
259 .state = _VARLINK_STATE_INVALID,
260
261 .ucred = UCRED_INVALID,
262
263 .timestamp = USEC_INFINITY,
264 .timeout = VARLINK_DEFAULT_TIMEOUT_USEC
265 };
266
267 *ret = v;
268 return 0;
269 }
270
varlink_connect_address(Varlink ** ret,const char * address)271 int varlink_connect_address(Varlink **ret, const char *address) {
272 _cleanup_(varlink_unrefp) Varlink *v = NULL;
273 union sockaddr_union sockaddr;
274 socklen_t sockaddr_len;
275 int r;
276
277 assert_return(ret, -EINVAL);
278 assert_return(address, -EINVAL);
279
280 r = sockaddr_un_set_path(&sockaddr.un, address);
281 if (r < 0)
282 return log_debug_errno(r, "Failed to set socket address '%s': %m", address);
283 sockaddr_len = r;
284
285 r = varlink_new(&v);
286 if (r < 0)
287 return log_debug_errno(r, "Failed to create varlink object: %m");
288
289 v->fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
290 if (v->fd < 0)
291 return log_debug_errno(errno, "Failed to create AF_UNIX socket: %m");
292
293 v->fd = fd_move_above_stdio(v->fd);
294
295 if (connect(v->fd, &sockaddr.sa, sockaddr_len) < 0) {
296 if (!IN_SET(errno, EAGAIN, EINPROGRESS))
297 return log_debug_errno(errno, "Failed to connect to %s: %m", address);
298
299 v->connecting = true; /* We are asynchronously connecting, i.e. the connect() is being
300 * processed in the background. As long as that's the case the socket
301 * is in a special state: it's there, we can poll it for EPOLLOUT, but
302 * if we attempt to write() to it before we see EPOLLOUT we'll get
303 * ENOTCONN (and not EAGAIN, like we would for a normal connected
304 * socket that isn't writable at the moment). Since ENOTCONN on write()
305 * hence can mean two different things (i.e. connection not complete
306 * yet vs. already disconnected again), we store as a boolean whether
307 * we are still in connect(). */
308 }
309
310 varlink_set_state(v, VARLINK_IDLE_CLIENT);
311
312 *ret = TAKE_PTR(v);
313 return 0;
314 }
315
varlink_connect_fd(Varlink ** ret,int fd)316 int varlink_connect_fd(Varlink **ret, int fd) {
317 Varlink *v;
318 int r;
319
320 assert_return(ret, -EINVAL);
321 assert_return(fd >= 0, -EBADF);
322
323 r = fd_nonblock(fd, true);
324 if (r < 0)
325 return log_debug_errno(r, "Failed to make fd %d nonblocking: %m", fd);
326
327 r = varlink_new(&v);
328 if (r < 0)
329 return log_debug_errno(r, "Failed to create varlink object: %m");
330
331 v->fd = fd;
332 varlink_set_state(v, VARLINK_IDLE_CLIENT);
333
334 /* Note that if this function is called we assume the passed socket (if it is one) is already
335 * properly connected, i.e. any asynchronous connect() done on it already completed. Because of that
336 * we'll not set the 'connecting' boolean here, i.e. we don't need to avoid write()ing to the socket
337 * until the connection is fully set up. Behaviour here is hence a bit different from
338 * varlink_connect_address() above, as there we do handle asynchronous connections ourselves and
339 * avoid doing write() on it before we saw EPOLLOUT for the first time. */
340
341 *ret = v;
342 return 0;
343 }
344
varlink_detach_event_sources(Varlink * v)345 static void varlink_detach_event_sources(Varlink *v) {
346 assert(v);
347
348 v->io_event_source = sd_event_source_disable_unref(v->io_event_source);
349 v->time_event_source = sd_event_source_disable_unref(v->time_event_source);
350 v->quit_event_source = sd_event_source_disable_unref(v->quit_event_source);
351 v->defer_event_source = sd_event_source_disable_unref(v->defer_event_source);
352 }
353
varlink_clear(Varlink * v)354 static void varlink_clear(Varlink *v) {
355 assert(v);
356
357 varlink_detach_event_sources(v);
358
359 v->fd = safe_close(v->fd);
360
361 v->input_buffer = mfree(v->input_buffer);
362 v->output_buffer = mfree(v->output_buffer);
363
364 v->current = json_variant_unref(v->current);
365 v->reply = json_variant_unref(v->reply);
366
367 v->event = sd_event_unref(v->event);
368 }
369
varlink_destroy(Varlink * v)370 static Varlink* varlink_destroy(Varlink *v) {
371 if (!v)
372 return NULL;
373
374 /* If this is called the server object must already been unreffed here. Why that? because when we
375 * linked up the varlink connection with the server object we took one ref in each direction */
376 assert(!v->server);
377
378 varlink_clear(v);
379
380 free(v->description);
381 return mfree(v);
382 }
383
384 DEFINE_TRIVIAL_REF_UNREF_FUNC(Varlink, varlink, varlink_destroy);
385
varlink_test_disconnect(Varlink * v)386 static int varlink_test_disconnect(Varlink *v) {
387 assert(v);
388
389 /* Tests whether we the connection has been terminated. We are careful to not stop processing it
390 * prematurely, since we want to handle half-open connections as well as possible and want to flush
391 * out and read data before we close down if we can. */
392
393 /* Already disconnected? */
394 if (!VARLINK_STATE_IS_ALIVE(v->state))
395 return 0;
396
397 /* Wait until connection setup is complete, i.e. until asynchronous connect() completes */
398 if (v->connecting)
399 return 0;
400
401 /* Still something to write and we can write? Stay around */
402 if (v->output_buffer_size > 0 && !v->write_disconnected)
403 return 0;
404
405 /* Both sides gone already? Then there's no need to stick around */
406 if (v->read_disconnected && v->write_disconnected)
407 goto disconnect;
408
409 /* If we are waiting for incoming data but the read side is shut down, disconnect. */
410 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER) && v->read_disconnected)
411 goto disconnect;
412
413 /* Similar, if are a client that hasn't written anything yet but the write side is dead, also
414 * disconnect. We also explicitly check for POLLHUP here since we likely won't notice the write side
415 * being down if we never wrote anything. */
416 if (IN_SET(v->state, VARLINK_IDLE_CLIENT) && (v->write_disconnected || v->got_pollhup))
417 goto disconnect;
418
419 /* We are on the server side and still want to send out more replies, but we saw POLLHUP already, and
420 * either got no buffered bytes to write anymore or already saw a write error. In that case we should
421 * shut down the varlink link. */
422 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE) && (v->write_disconnected || v->output_buffer_size == 0) && v->got_pollhup)
423 goto disconnect;
424
425 return 0;
426
427 disconnect:
428 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
429 return 1;
430 }
431
varlink_write(Varlink * v)432 static int varlink_write(Varlink *v) {
433 ssize_t n;
434
435 assert(v);
436
437 if (!VARLINK_STATE_IS_ALIVE(v->state))
438 return 0;
439 if (v->connecting) /* Writing while we are still wait for a non-blocking connect() to complete will
440 * result in ENOTCONN, hence exit early here */
441 return 0;
442 if (v->output_buffer_size == 0)
443 return 0;
444 if (v->write_disconnected)
445 return 0;
446
447 assert(v->fd >= 0);
448
449 /* We generally prefer recv()/send() (mostly because of MSG_NOSIGNAL) but also want to be compatible
450 * with non-socket IO, hence fall back automatically.
451 *
452 * Use a local variable to help gcc figure out that we set 'n' in all cases. */
453 bool prefer_write = v->prefer_read_write;
454 if (!prefer_write) {
455 n = send(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size, MSG_DONTWAIT|MSG_NOSIGNAL);
456 if (n < 0 && errno == ENOTSOCK)
457 prefer_write = v->prefer_read_write = true;
458 }
459 if (prefer_write)
460 n = write(v->fd, v->output_buffer + v->output_buffer_index, v->output_buffer_size);
461 if (n < 0) {
462 if (errno == EAGAIN)
463 return 0;
464
465 if (ERRNO_IS_DISCONNECT(errno)) {
466 /* If we get informed about a disconnect on write, then let's remember that, but not
467 * act on it just yet. Let's wait for read() to report the issue first. */
468 v->write_disconnected = true;
469 return 1;
470 }
471
472 return -errno;
473 }
474
475 v->output_buffer_size -= n;
476
477 if (v->output_buffer_size == 0)
478 v->output_buffer_index = 0;
479 else
480 v->output_buffer_index += n;
481
482 v->timestamp = now(CLOCK_MONOTONIC);
483 return 1;
484 }
485
varlink_read(Varlink * v)486 static int varlink_read(Varlink *v) {
487 size_t rs;
488 ssize_t n;
489
490 assert(v);
491
492 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER))
493 return 0;
494 if (v->connecting) /* read() on a socket while we are in connect() will fail with EINVAL, hence exit early here */
495 return 0;
496 if (v->current)
497 return 0;
498 if (v->input_buffer_unscanned > 0)
499 return 0;
500 if (v->read_disconnected)
501 return 0;
502
503 if (v->input_buffer_size >= VARLINK_BUFFER_MAX)
504 return -ENOBUFS;
505
506 assert(v->fd >= 0);
507
508 if (MALLOC_SIZEOF_SAFE(v->input_buffer) <= v->input_buffer_index + v->input_buffer_size) {
509 size_t add;
510
511 add = MIN(VARLINK_BUFFER_MAX - v->input_buffer_size, VARLINK_READ_SIZE);
512
513 if (v->input_buffer_index == 0) {
514
515 if (!GREEDY_REALLOC(v->input_buffer, v->input_buffer_size + add))
516 return -ENOMEM;
517
518 } else {
519 char *b;
520
521 b = new(char, v->input_buffer_size + add);
522 if (!b)
523 return -ENOMEM;
524
525 memcpy(b, v->input_buffer + v->input_buffer_index, v->input_buffer_size);
526
527 free_and_replace(v->input_buffer, b);
528 v->input_buffer_index = 0;
529 }
530 }
531
532 rs = MALLOC_SIZEOF_SAFE(v->input_buffer) - (v->input_buffer_index + v->input_buffer_size);
533
534 bool prefer_read = v->prefer_read_write;
535 if (!prefer_read) {
536 n = recv(v->fd, v->input_buffer + v->input_buffer_index + v->input_buffer_size, rs, MSG_DONTWAIT);
537 if (n < 0 && errno == ENOTSOCK)
538 prefer_read = v->prefer_read_write = true;
539 }
540 if (prefer_read)
541 n = read(v->fd, v->input_buffer + v->input_buffer_index + v->input_buffer_size, rs);
542 if (n < 0) {
543 if (errno == EAGAIN)
544 return 0;
545
546 if (ERRNO_IS_DISCONNECT(errno)) {
547 v->read_disconnected = true;
548 return 1;
549 }
550
551 return -errno;
552 }
553 if (n == 0) { /* EOF */
554 v->read_disconnected = true;
555 return 1;
556 }
557
558 v->input_buffer_size += n;
559 v->input_buffer_unscanned += n;
560
561 return 1;
562 }
563
varlink_parse_message(Varlink * v)564 static int varlink_parse_message(Varlink *v) {
565 const char *e, *begin;
566 size_t sz;
567 int r;
568
569 assert(v);
570
571 if (v->current)
572 return 0;
573 if (v->input_buffer_unscanned <= 0)
574 return 0;
575
576 assert(v->input_buffer_unscanned <= v->input_buffer_size);
577 assert(v->input_buffer_index + v->input_buffer_size <= MALLOC_SIZEOF_SAFE(v->input_buffer));
578
579 begin = v->input_buffer + v->input_buffer_index;
580
581 e = memchr(begin + v->input_buffer_size - v->input_buffer_unscanned, 0, v->input_buffer_unscanned);
582 if (!e) {
583 v->input_buffer_unscanned = 0;
584 return 0;
585 }
586
587 sz = e - begin + 1;
588
589 varlink_log(v, "New incoming message: %s", begin); /* FIXME: should we output the whole message here before validation?
590 * This may produce a non-printable journal entry if the message
591 * is invalid. We may also expose privileged information. */
592
593 r = json_parse(begin, 0, &v->current, NULL, NULL);
594 if (r < 0) {
595 /* If we encounter a parse failure flush all data. We cannot possibly recover from this,
596 * hence drop all buffered data now. */
597 v->input_buffer_index = v->input_buffer_size = v->input_buffer_unscanned = 0;
598 return varlink_log_errno(v, r, "Failed to parse JSON: %m");
599 }
600
601 v->input_buffer_size -= sz;
602
603 if (v->input_buffer_size == 0)
604 v->input_buffer_index = 0;
605 else
606 v->input_buffer_index += sz;
607
608 v->input_buffer_unscanned = v->input_buffer_size;
609 return 1;
610 }
611
varlink_test_timeout(Varlink * v)612 static int varlink_test_timeout(Varlink *v) {
613 assert(v);
614
615 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING))
616 return 0;
617 if (v->timeout == USEC_INFINITY)
618 return 0;
619
620 if (now(CLOCK_MONOTONIC) < usec_add(v->timestamp, v->timeout))
621 return 0;
622
623 varlink_set_state(v, VARLINK_PENDING_TIMEOUT);
624
625 return 1;
626 }
627
varlink_dispatch_local_error(Varlink * v,const char * error)628 static int varlink_dispatch_local_error(Varlink *v, const char *error) {
629 int r;
630
631 assert(v);
632 assert(error);
633
634 if (!v->reply_callback)
635 return 0;
636
637 r = v->reply_callback(v, NULL, error, VARLINK_REPLY_ERROR|VARLINK_REPLY_LOCAL, v->userdata);
638 if (r < 0)
639 log_debug_errno(r, "Reply callback returned error, ignoring: %m");
640
641 return 1;
642 }
643
varlink_dispatch_timeout(Varlink * v)644 static int varlink_dispatch_timeout(Varlink *v) {
645 assert(v);
646
647 if (v->state != VARLINK_PENDING_TIMEOUT)
648 return 0;
649
650 varlink_set_state(v, VARLINK_PROCESSING_TIMEOUT);
651 varlink_dispatch_local_error(v, VARLINK_ERROR_TIMEOUT);
652 varlink_close(v);
653
654 return 1;
655 }
656
varlink_dispatch_disconnect(Varlink * v)657 static int varlink_dispatch_disconnect(Varlink *v) {
658 assert(v);
659
660 if (v->state != VARLINK_PENDING_DISCONNECT)
661 return 0;
662
663 varlink_set_state(v, VARLINK_PROCESSING_DISCONNECT);
664 varlink_dispatch_local_error(v, VARLINK_ERROR_DISCONNECTED);
665 varlink_close(v);
666
667 return 1;
668 }
669
varlink_sanitize_parameters(JsonVariant ** v)670 static int varlink_sanitize_parameters(JsonVariant **v) {
671 assert(v);
672
673 /* Varlink always wants a parameters list, hence make one if the caller doesn't want any */
674 if (!*v)
675 return json_variant_new_object(v, NULL, 0);
676 else if (!json_variant_is_object(*v))
677 return -EINVAL;
678
679 return 0;
680 }
681
varlink_dispatch_reply(Varlink * v)682 static int varlink_dispatch_reply(Varlink *v) {
683 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
684 VarlinkReplyFlags flags = 0;
685 const char *error = NULL;
686 JsonVariant *e;
687 const char *k;
688 int r;
689
690 assert(v);
691
692 if (!IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING))
693 return 0;
694 if (!v->current)
695 return 0;
696
697 assert(v->n_pending > 0);
698
699 if (!json_variant_is_object(v->current))
700 goto invalid;
701
702 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
703
704 if (streq(k, "error")) {
705 if (error)
706 goto invalid;
707 if (!json_variant_is_string(e))
708 goto invalid;
709
710 error = json_variant_string(e);
711 flags |= VARLINK_REPLY_ERROR;
712
713 } else if (streq(k, "parameters")) {
714 if (parameters)
715 goto invalid;
716 if (!json_variant_is_object(e))
717 goto invalid;
718
719 parameters = json_variant_ref(e);
720
721 } else if (streq(k, "continues")) {
722 if (FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
723 goto invalid;
724
725 if (!json_variant_is_boolean(e))
726 goto invalid;
727
728 if (json_variant_boolean(e))
729 flags |= VARLINK_REPLY_CONTINUES;
730 } else
731 goto invalid;
732 }
733
734 /* Replies with 'continue' set are only OK if we set 'more' when the method call was initiated */
735 if (v->state != VARLINK_AWAITING_REPLY_MORE && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
736 goto invalid;
737
738 /* An error is final */
739 if (error && FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
740 goto invalid;
741
742 r = varlink_sanitize_parameters(¶meters);
743 if (r < 0)
744 goto invalid;
745
746 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE)) {
747 varlink_set_state(v, VARLINK_PROCESSING_REPLY);
748
749 if (v->reply_callback) {
750 r = v->reply_callback(v, parameters, error, flags, v->userdata);
751 if (r < 0)
752 log_debug_errno(r, "Reply callback returned error, ignoring: %m");
753 }
754
755 v->current = json_variant_unref(v->current);
756
757 if (v->state == VARLINK_PROCESSING_REPLY) {
758
759 assert(v->n_pending > 0);
760
761 if (!FLAGS_SET(flags, VARLINK_REPLY_CONTINUES))
762 v->n_pending--;
763
764 varlink_set_state(v,
765 FLAGS_SET(flags, VARLINK_REPLY_CONTINUES) ? VARLINK_AWAITING_REPLY_MORE :
766 v->n_pending == 0 ? VARLINK_IDLE_CLIENT : VARLINK_AWAITING_REPLY);
767 }
768 } else {
769 assert(v->state == VARLINK_CALLING);
770 varlink_set_state(v, VARLINK_CALLED);
771 }
772
773 return 1;
774
775 invalid:
776 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
777 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
778 varlink_close(v);
779
780 return 1;
781 }
782
varlink_dispatch_method(Varlink * v)783 static int varlink_dispatch_method(Varlink *v) {
784 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
785 VarlinkMethodFlags flags = 0;
786 const char *method = NULL, *error;
787 JsonVariant *e;
788 VarlinkMethod callback;
789 const char *k;
790 int r;
791
792 assert(v);
793
794 if (v->state != VARLINK_IDLE_SERVER)
795 return 0;
796 if (!v->current)
797 return 0;
798
799 if (!json_variant_is_object(v->current))
800 goto invalid;
801
802 JSON_VARIANT_OBJECT_FOREACH(k, e, v->current) {
803
804 if (streq(k, "method")) {
805 if (method)
806 goto invalid;
807 if (!json_variant_is_string(e))
808 goto invalid;
809
810 method = json_variant_string(e);
811
812 } else if (streq(k, "parameters")) {
813 if (parameters)
814 goto invalid;
815 if (!json_variant_is_object(e))
816 goto invalid;
817
818 parameters = json_variant_ref(e);
819
820 } else if (streq(k, "oneway")) {
821
822 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
823 goto invalid;
824
825 if (!json_variant_is_boolean(e))
826 goto invalid;
827
828 if (json_variant_boolean(e))
829 flags |= VARLINK_METHOD_ONEWAY;
830
831 } else if (streq(k, "more")) {
832
833 if ((flags & (VARLINK_METHOD_ONEWAY|VARLINK_METHOD_MORE)) != 0)
834 goto invalid;
835
836 if (!json_variant_is_boolean(e))
837 goto invalid;
838
839 if (json_variant_boolean(e))
840 flags |= VARLINK_METHOD_MORE;
841
842 } else
843 goto invalid;
844 }
845
846 if (!method)
847 goto invalid;
848
849 r = varlink_sanitize_parameters(¶meters);
850 if (r < 0)
851 goto fail;
852
853 varlink_set_state(v, (flags & VARLINK_METHOD_MORE) ? VARLINK_PROCESSING_METHOD_MORE :
854 (flags & VARLINK_METHOD_ONEWAY) ? VARLINK_PROCESSING_METHOD_ONEWAY :
855 VARLINK_PROCESSING_METHOD);
856
857 assert(v->server);
858
859 if (STR_IN_SET(method, "org.varlink.service.GetInfo", "org.varlink.service.GetInterface")) {
860 /* For now, we don't implement a single of varlink's own methods */
861 callback = NULL;
862 error = VARLINK_ERROR_METHOD_NOT_IMPLEMENTED;
863 } else if (startswith(method, "org.varlink.service.")) {
864 callback = NULL;
865 error = VARLINK_ERROR_METHOD_NOT_FOUND;
866 } else {
867 callback = hashmap_get(v->server->methods, method);
868 error = VARLINK_ERROR_METHOD_NOT_FOUND;
869 }
870
871 if (callback) {
872 r = callback(v, parameters, flags, v->userdata);
873 if (r < 0) {
874 log_debug_errno(r, "Callback for %s returned error: %m", method);
875
876 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
877 if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
878 r = varlink_error_errno(v, r);
879 if (r < 0)
880 return r;
881 }
882 }
883 } else if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
884 assert(error);
885
886 r = varlink_errorb(v, error, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method))));
887 if (r < 0)
888 return r;
889 }
890
891 switch (v->state) {
892
893 case VARLINK_PROCESSED_METHOD: /* Method call is fully processed */
894 case VARLINK_PROCESSING_METHOD_ONEWAY: /* ditto */
895 v->current = json_variant_unref(v->current);
896 varlink_set_state(v, VARLINK_IDLE_SERVER);
897 break;
898
899 case VARLINK_PROCESSING_METHOD: /* Method call wasn't replied to, will be replied to later */
900 varlink_set_state(v, VARLINK_PENDING_METHOD);
901 break;
902
903 case VARLINK_PROCESSING_METHOD_MORE: /* No reply for a "more" message was sent, more to come */
904 varlink_set_state(v, VARLINK_PENDING_METHOD_MORE);
905 break;
906
907 default:
908 assert_not_reached();
909
910 }
911
912 return r;
913
914 invalid:
915 r = -EINVAL;
916
917 fail:
918 varlink_set_state(v, VARLINK_PROCESSING_FAILURE);
919 varlink_dispatch_local_error(v, VARLINK_ERROR_PROTOCOL);
920 varlink_close(v);
921
922 return r;
923 }
924
varlink_process(Varlink * v)925 int varlink_process(Varlink *v) {
926 int r;
927
928 assert_return(v, -EINVAL);
929
930 if (v->state == VARLINK_DISCONNECTED)
931 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
932
933 varlink_ref(v);
934
935 r = varlink_write(v);
936 if (r < 0)
937 varlink_log_errno(v, r, "Write failed: %m");
938 if (r != 0)
939 goto finish;
940
941 r = varlink_dispatch_reply(v);
942 if (r < 0)
943 varlink_log_errno(v, r, "Reply dispatch failed: %m");
944 if (r != 0)
945 goto finish;
946
947 r = varlink_dispatch_method(v);
948 if (r < 0)
949 varlink_log_errno(v, r, "Method dispatch failed: %m");
950 if (r != 0)
951 goto finish;
952
953 r = varlink_parse_message(v);
954 if (r < 0)
955 varlink_log_errno(v, r, "Message parsing failed: %m");
956 if (r != 0)
957 goto finish;
958
959 r = varlink_read(v);
960 if (r < 0)
961 varlink_log_errno(v, r, "Read failed: %m");
962 if (r != 0)
963 goto finish;
964
965 r = varlink_test_disconnect(v);
966 assert(r >= 0);
967 if (r != 0)
968 goto finish;
969
970 r = varlink_dispatch_disconnect(v);
971 assert(r >= 0);
972 if (r != 0)
973 goto finish;
974
975 r = varlink_test_timeout(v);
976 assert(r >= 0);
977 if (r != 0)
978 goto finish;
979
980 r = varlink_dispatch_timeout(v);
981 assert(r >= 0);
982 if (r != 0)
983 goto finish;
984
985 finish:
986 if (r >= 0 && v->defer_event_source) {
987 int q;
988
989 /* If we did some processing, make sure we are called again soon */
990 q = sd_event_source_set_enabled(v->defer_event_source, r > 0 ? SD_EVENT_ON : SD_EVENT_OFF);
991 if (q < 0)
992 r = varlink_log_errno(v, q, "Failed to enable deferred event source: %m");
993 }
994
995 if (r < 0) {
996 if (VARLINK_STATE_IS_ALIVE(v->state))
997 /* Initiate disconnection */
998 varlink_set_state(v, VARLINK_PENDING_DISCONNECT);
999 else
1000 /* We failed while disconnecting, in that case close right away */
1001 varlink_close(v);
1002 }
1003
1004 varlink_unref(v);
1005 return r;
1006 }
1007
handle_revents(Varlink * v,int revents)1008 static void handle_revents(Varlink *v, int revents) {
1009 assert(v);
1010
1011 if (v->connecting) {
1012 /* If we have seen POLLOUT or POLLHUP on a socket we are asynchronously waiting a connect()
1013 * to complete on, we know we are ready. We don't read the connection error here though,
1014 * we'll get the error on the next read() or write(). */
1015 if ((revents & (POLLOUT|POLLHUP)) == 0)
1016 return;
1017
1018 varlink_log(v, "Anynchronous connection completed.");
1019 v->connecting = false;
1020 } else {
1021 /* Note that we don't care much about POLLIN/POLLOUT here, we'll just try reading and writing
1022 * what we can. However, we do care about POLLHUP to detect connection termination even if we
1023 * momentarily don't want to read nor write anything. */
1024
1025 if (!FLAGS_SET(revents, POLLHUP))
1026 return;
1027
1028 varlink_log(v, "Got POLLHUP from socket.");
1029 v->got_pollhup = true;
1030 }
1031 }
1032
varlink_wait(Varlink * v,usec_t timeout)1033 int varlink_wait(Varlink *v, usec_t timeout) {
1034 int r, fd, events;
1035 usec_t t;
1036
1037 assert_return(v, -EINVAL);
1038
1039 if (v->state == VARLINK_DISCONNECTED)
1040 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1041
1042 r = varlink_get_timeout(v, &t);
1043 if (r < 0)
1044 return r;
1045 if (t != USEC_INFINITY) {
1046 usec_t n;
1047
1048 n = now(CLOCK_MONOTONIC);
1049 if (t < n)
1050 t = 0;
1051 else
1052 t = usec_sub_unsigned(t, n);
1053 }
1054
1055 if (timeout != USEC_INFINITY &&
1056 (t == USEC_INFINITY || timeout < t))
1057 t = timeout;
1058
1059 fd = varlink_get_fd(v);
1060 if (fd < 0)
1061 return fd;
1062
1063 events = varlink_get_events(v);
1064 if (events < 0)
1065 return events;
1066
1067 r = fd_wait_for_event(fd, events, t);
1068 if (r <= 0)
1069 return r;
1070
1071 handle_revents(v, r);
1072 return 1;
1073 }
1074
varlink_get_fd(Varlink * v)1075 int varlink_get_fd(Varlink *v) {
1076
1077 assert_return(v, -EINVAL);
1078
1079 if (v->state == VARLINK_DISCONNECTED)
1080 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1081 if (v->fd < 0)
1082 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBADF), "No valid fd.");
1083
1084 return v->fd;
1085 }
1086
varlink_get_events(Varlink * v)1087 int varlink_get_events(Varlink *v) {
1088 int ret = 0;
1089
1090 assert_return(v, -EINVAL);
1091
1092 if (v->state == VARLINK_DISCONNECTED)
1093 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1094
1095 if (v->connecting) /* When processing an asynchronous connect(), we only wait for EPOLLOUT, which
1096 * tells us that the connection is now complete. Before that we should neither
1097 * write() or read() from the fd. */
1098 return EPOLLOUT;
1099
1100 if (!v->read_disconnected &&
1101 IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING, VARLINK_IDLE_SERVER) &&
1102 !v->current &&
1103 v->input_buffer_unscanned <= 0)
1104 ret |= EPOLLIN;
1105
1106 if (!v->write_disconnected &&
1107 v->output_buffer_size > 0)
1108 ret |= EPOLLOUT;
1109
1110 return ret;
1111 }
1112
varlink_get_timeout(Varlink * v,usec_t * ret)1113 int varlink_get_timeout(Varlink *v, usec_t *ret) {
1114 assert_return(v, -EINVAL);
1115
1116 if (v->state == VARLINK_DISCONNECTED)
1117 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1118
1119 if (IN_SET(v->state, VARLINK_AWAITING_REPLY, VARLINK_AWAITING_REPLY_MORE, VARLINK_CALLING) &&
1120 v->timeout != USEC_INFINITY) {
1121 if (ret)
1122 *ret = usec_add(v->timestamp, v->timeout);
1123 return 1;
1124 } else {
1125 if (ret)
1126 *ret = USEC_INFINITY;
1127 return 0;
1128 }
1129 }
1130
varlink_flush(Varlink * v)1131 int varlink_flush(Varlink *v) {
1132 int ret = 0, r;
1133
1134 assert_return(v, -EINVAL);
1135
1136 if (v->state == VARLINK_DISCONNECTED)
1137 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1138
1139 for (;;) {
1140 if (v->output_buffer_size == 0)
1141 break;
1142 if (v->write_disconnected)
1143 return -ECONNRESET;
1144
1145 r = varlink_write(v);
1146 if (r < 0)
1147 return r;
1148 if (r > 0) {
1149 ret = 1;
1150 continue;
1151 }
1152
1153 r = fd_wait_for_event(v->fd, POLLOUT, USEC_INFINITY);
1154 if (r < 0)
1155 return varlink_log_errno(v, r, "Poll failed on fd: %m");
1156
1157 assert(r != 0);
1158
1159 handle_revents(v, r);
1160 }
1161
1162 return ret;
1163 }
1164
varlink_detach_server(Varlink * v)1165 static void varlink_detach_server(Varlink *v) {
1166 VarlinkServer *saved_server;
1167 assert(v);
1168
1169 if (!v->server)
1170 return;
1171
1172 if (v->server->by_uid &&
1173 v->ucred_acquired &&
1174 uid_is_valid(v->ucred.uid)) {
1175 unsigned c;
1176
1177 c = PTR_TO_UINT(hashmap_get(v->server->by_uid, UID_TO_PTR(v->ucred.uid)));
1178 assert(c > 0);
1179
1180 if (c == 1)
1181 (void) hashmap_remove(v->server->by_uid, UID_TO_PTR(v->ucred.uid));
1182 else
1183 (void) hashmap_replace(v->server->by_uid, UID_TO_PTR(v->ucred.uid), UINT_TO_PTR(c - 1));
1184 }
1185
1186 assert(v->server->n_connections > 0);
1187 v->server->n_connections--;
1188
1189 /* If this is a connection associated to a server, then let's disconnect the server and the
1190 * connection from each other. This drops the dangling reference that connect_callback() set up. But
1191 * before we release the references, let's call the disconnection callback if it is defined. */
1192
1193 saved_server = TAKE_PTR(v->server);
1194
1195 if (saved_server->disconnect_callback)
1196 saved_server->disconnect_callback(saved_server, v, saved_server->userdata);
1197
1198 varlink_server_unref(saved_server);
1199 varlink_unref(v);
1200 }
1201
varlink_close(Varlink * v)1202 int varlink_close(Varlink *v) {
1203 assert_return(v, -EINVAL);
1204
1205 if (v->state == VARLINK_DISCONNECTED)
1206 return 0;
1207
1208 varlink_set_state(v, VARLINK_DISCONNECTED);
1209
1210 /* Let's take a reference first, since varlink_detach_server() might drop the final (dangling) ref
1211 * which would destroy us before we can call varlink_clear() */
1212 varlink_ref(v);
1213 varlink_detach_server(v);
1214 varlink_clear(v);
1215 varlink_unref(v);
1216
1217 return 1;
1218 }
1219
varlink_close_unref(Varlink * v)1220 Varlink* varlink_close_unref(Varlink *v) {
1221 if (!v)
1222 return NULL;
1223
1224 (void) varlink_close(v);
1225 return varlink_unref(v);
1226 }
1227
varlink_flush_close_unref(Varlink * v)1228 Varlink* varlink_flush_close_unref(Varlink *v) {
1229 if (!v)
1230 return NULL;
1231
1232 (void) varlink_flush(v);
1233 return varlink_close_unref(v);
1234 }
1235
varlink_enqueue_json(Varlink * v,JsonVariant * m)1236 static int varlink_enqueue_json(Varlink *v, JsonVariant *m) {
1237 _cleanup_free_ char *text = NULL;
1238 int r;
1239
1240 assert(v);
1241 assert(m);
1242
1243 r = json_variant_format(m, 0, &text);
1244 if (r < 0)
1245 return r;
1246 assert(text[r] == '\0');
1247
1248 if (v->output_buffer_size + r + 1 > VARLINK_BUFFER_MAX)
1249 return -ENOBUFS;
1250
1251 varlink_log(v, "Sending message: %s", text);
1252
1253 if (v->output_buffer_size == 0) {
1254
1255 free_and_replace(v->output_buffer, text);
1256
1257 v->output_buffer_size = r + 1;
1258 v->output_buffer_index = 0;
1259
1260 } else if (v->output_buffer_index == 0) {
1261
1262 if (!GREEDY_REALLOC(v->output_buffer, v->output_buffer_size + r + 1))
1263 return -ENOMEM;
1264
1265 memcpy(v->output_buffer + v->output_buffer_size, text, r + 1);
1266 v->output_buffer_size += r + 1;
1267
1268 } else {
1269 char *n;
1270 const size_t new_size = v->output_buffer_size + r + 1;
1271
1272 n = new(char, new_size);
1273 if (!n)
1274 return -ENOMEM;
1275
1276 memcpy(mempcpy(n, v->output_buffer + v->output_buffer_index, v->output_buffer_size), text, r + 1);
1277
1278 free_and_replace(v->output_buffer, n);
1279 v->output_buffer_size = new_size;
1280 v->output_buffer_index = 0;
1281 }
1282
1283 return 0;
1284 }
1285
varlink_send(Varlink * v,const char * method,JsonVariant * parameters)1286 int varlink_send(Varlink *v, const char *method, JsonVariant *parameters) {
1287 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1288 int r;
1289
1290 assert_return(v, -EINVAL);
1291 assert_return(method, -EINVAL);
1292
1293 if (v->state == VARLINK_DISCONNECTED)
1294 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1295
1296 /* We allow enqueuing multiple method calls at once! */
1297 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
1298 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1299
1300 r = varlink_sanitize_parameters(¶meters);
1301 if (r < 0)
1302 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1303
1304 r = json_build(&m, JSON_BUILD_OBJECT(
1305 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1306 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1307 JSON_BUILD_PAIR("oneway", JSON_BUILD_BOOLEAN(true))));
1308 if (r < 0)
1309 return varlink_log_errno(v, r, "Failed to build json message: %m");
1310
1311 r = varlink_enqueue_json(v, m);
1312 if (r < 0)
1313 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1314
1315 /* No state change here, this is one-way only after all */
1316 v->timestamp = now(CLOCK_MONOTONIC);
1317 return 0;
1318 }
1319
varlink_sendb(Varlink * v,const char * method,...)1320 int varlink_sendb(Varlink *v, const char *method, ...) {
1321 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1322 va_list ap;
1323 int r;
1324
1325 assert_return(v, -EINVAL);
1326
1327 va_start(ap, method);
1328 r = json_buildv(¶meters, ap);
1329 va_end(ap);
1330
1331 if (r < 0)
1332 return varlink_log_errno(v, r, "Failed to build json message: %m");
1333
1334 return varlink_send(v, method, parameters);
1335 }
1336
varlink_invoke(Varlink * v,const char * method,JsonVariant * parameters)1337 int varlink_invoke(Varlink *v, const char *method, JsonVariant *parameters) {
1338 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1339 int r;
1340
1341 assert_return(v, -EINVAL);
1342 assert_return(method, -EINVAL);
1343
1344 if (v->state == VARLINK_DISCONNECTED)
1345 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1346
1347 /* We allow enqueuing multiple method calls at once! */
1348 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT, VARLINK_AWAITING_REPLY))
1349 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1350
1351 r = varlink_sanitize_parameters(¶meters);
1352 if (r < 0)
1353 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1354
1355 r = json_build(&m, JSON_BUILD_OBJECT(
1356 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1357 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1358 if (r < 0)
1359 return varlink_log_errno(v, r, "Failed to build json message: %m");
1360
1361 r = varlink_enqueue_json(v, m);
1362 if (r < 0)
1363 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1364
1365 varlink_set_state(v, VARLINK_AWAITING_REPLY);
1366 v->n_pending++;
1367 v->timestamp = now(CLOCK_MONOTONIC);
1368
1369 return 0;
1370 }
1371
varlink_invokeb(Varlink * v,const char * method,...)1372 int varlink_invokeb(Varlink *v, const char *method, ...) {
1373 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1374 va_list ap;
1375 int r;
1376
1377 assert_return(v, -EINVAL);
1378
1379 va_start(ap, method);
1380 r = json_buildv(¶meters, ap);
1381 va_end(ap);
1382
1383 if (r < 0)
1384 return varlink_log_errno(v, r, "Failed to build json message: %m");
1385
1386 return varlink_invoke(v, method, parameters);
1387 }
1388
varlink_observe(Varlink * v,const char * method,JsonVariant * parameters)1389 int varlink_observe(Varlink *v, const char *method, JsonVariant *parameters) {
1390 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1391 int r;
1392
1393 assert_return(v, -EINVAL);
1394 assert_return(method, -EINVAL);
1395
1396 if (v->state == VARLINK_DISCONNECTED)
1397 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1398
1399 /* Note that we don't allow enqueuing multiple method calls when we are in more/continues mode! We
1400 * thus insist on an idle client here. */
1401 if (v->state != VARLINK_IDLE_CLIENT)
1402 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1403
1404 r = varlink_sanitize_parameters(¶meters);
1405 if (r < 0)
1406 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1407
1408 r = json_build(&m, JSON_BUILD_OBJECT(
1409 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1410 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1411 JSON_BUILD_PAIR("more", JSON_BUILD_BOOLEAN(true))));
1412 if (r < 0)
1413 return varlink_log_errno(v, r, "Failed to build json message: %m");
1414
1415 r = varlink_enqueue_json(v, m);
1416 if (r < 0)
1417 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1418
1419 varlink_set_state(v, VARLINK_AWAITING_REPLY_MORE);
1420 v->n_pending++;
1421 v->timestamp = now(CLOCK_MONOTONIC);
1422
1423 return 0;
1424 }
1425
varlink_observeb(Varlink * v,const char * method,...)1426 int varlink_observeb(Varlink *v, const char *method, ...) {
1427 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1428 va_list ap;
1429 int r;
1430
1431 assert_return(v, -EINVAL);
1432
1433 va_start(ap, method);
1434 r = json_buildv(¶meters, ap);
1435 va_end(ap);
1436
1437 if (r < 0)
1438 return varlink_log_errno(v, r, "Failed to build json message: %m");
1439
1440 return varlink_observe(v, method, parameters);
1441 }
1442
varlink_call(Varlink * v,const char * method,JsonVariant * parameters,JsonVariant ** ret_parameters,const char ** ret_error_id,VarlinkReplyFlags * ret_flags)1443 int varlink_call(
1444 Varlink *v,
1445 const char *method,
1446 JsonVariant *parameters,
1447 JsonVariant **ret_parameters,
1448 const char **ret_error_id,
1449 VarlinkReplyFlags *ret_flags) {
1450
1451 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1452 int r;
1453
1454 assert_return(v, -EINVAL);
1455 assert_return(method, -EINVAL);
1456
1457 if (v->state == VARLINK_DISCONNECTED)
1458 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1459 if (!IN_SET(v->state, VARLINK_IDLE_CLIENT))
1460 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1461
1462 assert(v->n_pending == 0); /* n_pending can't be > 0 if we are in VARLINK_IDLE_CLIENT state */
1463
1464 r = varlink_sanitize_parameters(¶meters);
1465 if (r < 0)
1466 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1467
1468 r = json_build(&m, JSON_BUILD_OBJECT(
1469 JSON_BUILD_PAIR("method", JSON_BUILD_STRING(method)),
1470 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1471 if (r < 0)
1472 return varlink_log_errno(v, r, "Failed to build json message: %m");
1473
1474 r = varlink_enqueue_json(v, m);
1475 if (r < 0)
1476 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1477
1478 varlink_set_state(v, VARLINK_CALLING);
1479 v->n_pending++;
1480 v->timestamp = now(CLOCK_MONOTONIC);
1481
1482 while (v->state == VARLINK_CALLING) {
1483
1484 r = varlink_process(v);
1485 if (r < 0)
1486 return r;
1487 if (r > 0)
1488 continue;
1489
1490 r = varlink_wait(v, USEC_INFINITY);
1491 if (r < 0)
1492 return r;
1493 }
1494
1495 switch (v->state) {
1496
1497 case VARLINK_CALLED:
1498 assert(v->current);
1499
1500 json_variant_unref(v->reply);
1501 v->reply = TAKE_PTR(v->current);
1502
1503 varlink_set_state(v, VARLINK_IDLE_CLIENT);
1504 assert(v->n_pending == 1);
1505 v->n_pending--;
1506
1507 if (ret_parameters)
1508 *ret_parameters = json_variant_by_key(v->reply, "parameters");
1509 if (ret_error_id)
1510 *ret_error_id = json_variant_string(json_variant_by_key(v->reply, "error"));
1511 if (ret_flags)
1512 *ret_flags = 0;
1513
1514 return 1;
1515
1516 case VARLINK_PENDING_DISCONNECT:
1517 case VARLINK_DISCONNECTED:
1518 return varlink_log_errno(v, SYNTHETIC_ERRNO(ECONNRESET), "Connection was closed.");
1519
1520 case VARLINK_PENDING_TIMEOUT:
1521 return varlink_log_errno(v, SYNTHETIC_ERRNO(ETIME), "Connection timed out.");
1522
1523 default:
1524 assert_not_reached();
1525 }
1526 }
1527
varlink_callb(Varlink * v,const char * method,JsonVariant ** ret_parameters,const char ** ret_error_id,VarlinkReplyFlags * ret_flags,...)1528 int varlink_callb(
1529 Varlink *v,
1530 const char *method,
1531 JsonVariant **ret_parameters,
1532 const char **ret_error_id,
1533 VarlinkReplyFlags *ret_flags, ...) {
1534
1535 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1536 va_list ap;
1537 int r;
1538
1539 assert_return(v, -EINVAL);
1540
1541 va_start(ap, ret_flags);
1542 r = json_buildv(¶meters, ap);
1543 va_end(ap);
1544
1545 if (r < 0)
1546 return varlink_log_errno(v, r, "Failed to build json message: %m");
1547
1548 return varlink_call(v, method, parameters, ret_parameters, ret_error_id, ret_flags);
1549 }
1550
varlink_reply(Varlink * v,JsonVariant * parameters)1551 int varlink_reply(Varlink *v, JsonVariant *parameters) {
1552 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1553 int r;
1554
1555 assert_return(v, -EINVAL);
1556
1557 if (v->state == VARLINK_DISCONNECTED)
1558 return -ENOTCONN;
1559 if (!IN_SET(v->state,
1560 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1561 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1562 return -EBUSY;
1563
1564 r = varlink_sanitize_parameters(¶meters);
1565 if (r < 0)
1566 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1567
1568 r = json_build(&m, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1569 if (r < 0)
1570 return varlink_log_errno(v, r, "Failed to build json message: %m");
1571
1572 r = varlink_enqueue_json(v, m);
1573 if (r < 0)
1574 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1575
1576 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1577 /* We just replied to a method call that was let hanging for a while (i.e. we were outside of
1578 * the varlink_dispatch_method() stack frame), which means with this reply we are ready to
1579 * process further messages. */
1580 v->current = json_variant_unref(v->current);
1581 varlink_set_state(v, VARLINK_IDLE_SERVER);
1582 } else
1583 /* We replied to a method call from within the varlink_dispatch_method() stack frame), which
1584 * means we should it handle the rest of the state engine. */
1585 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1586
1587 return 1;
1588 }
1589
varlink_replyb(Varlink * v,...)1590 int varlink_replyb(Varlink *v, ...) {
1591 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1592 va_list ap;
1593 int r;
1594
1595 assert_return(v, -EINVAL);
1596
1597 va_start(ap, v);
1598 r = json_buildv(¶meters, ap);
1599 va_end(ap);
1600
1601 if (r < 0)
1602 return r;
1603
1604 return varlink_reply(v, parameters);
1605 }
1606
varlink_error(Varlink * v,const char * error_id,JsonVariant * parameters)1607 int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
1608 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1609 int r;
1610
1611 assert_return(v, -EINVAL);
1612 assert_return(error_id, -EINVAL);
1613
1614 if (v->state == VARLINK_DISCONNECTED)
1615 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1616 if (!IN_SET(v->state,
1617 VARLINK_PROCESSING_METHOD, VARLINK_PROCESSING_METHOD_MORE,
1618 VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE))
1619 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1620
1621 r = varlink_sanitize_parameters(¶meters);
1622 if (r < 0)
1623 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1624
1625 r = json_build(&m, JSON_BUILD_OBJECT(
1626 JSON_BUILD_PAIR("error", JSON_BUILD_STRING(error_id)),
1627 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters))));
1628 if (r < 0)
1629 return varlink_log_errno(v, r, "Failed to build json message: %m");
1630
1631 r = varlink_enqueue_json(v, m);
1632 if (r < 0)
1633 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1634
1635 if (IN_SET(v->state, VARLINK_PENDING_METHOD, VARLINK_PENDING_METHOD_MORE)) {
1636 v->current = json_variant_unref(v->current);
1637 varlink_set_state(v, VARLINK_IDLE_SERVER);
1638 } else
1639 varlink_set_state(v, VARLINK_PROCESSED_METHOD);
1640
1641 return 1;
1642 }
1643
varlink_errorb(Varlink * v,const char * error_id,...)1644 int varlink_errorb(Varlink *v, const char *error_id, ...) {
1645 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1646 va_list ap;
1647 int r;
1648
1649 assert_return(v, -EINVAL);
1650 assert_return(error_id, -EINVAL);
1651
1652 va_start(ap, error_id);
1653 r = json_buildv(¶meters, ap);
1654 va_end(ap);
1655
1656 if (r < 0)
1657 return varlink_log_errno(v, r, "Failed to build json message: %m");
1658
1659 return varlink_error(v, error_id, parameters);
1660 }
1661
varlink_error_invalid_parameter(Varlink * v,JsonVariant * parameters)1662 int varlink_error_invalid_parameter(Varlink *v, JsonVariant *parameters) {
1663 int r;
1664
1665 assert_return(v, -EINVAL);
1666 assert_return(parameters, -EINVAL);
1667
1668 /* We expect to be called in one of two ways: the 'parameters' argument is a string variant in which
1669 * case it is the parameter key name that is invalid. Or the 'parameters' argument is an object
1670 * variant in which case we'll pull out the first key. The latter mode is useful in functions that
1671 * don't expect any arguments. */
1672
1673 /* varlink_error(...) expects a json object as the third parameter. Passing a string variant causes
1674 * parameter sanitization to fail, and it returns -EINVAL. */
1675
1676 if (json_variant_is_string(parameters)) {
1677 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
1678
1679 r = json_build(¶meters_obj,
1680 JSON_BUILD_OBJECT(
1681 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(parameters))));
1682 if (r < 0)
1683 return r;
1684
1685 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
1686 }
1687
1688 if (json_variant_is_object(parameters) &&
1689 json_variant_elements(parameters) > 0) {
1690 _cleanup_(json_variant_unrefp) JsonVariant *parameters_obj = NULL;
1691
1692 r = json_build(¶meters_obj,
1693 JSON_BUILD_OBJECT(
1694 JSON_BUILD_PAIR("parameter", JSON_BUILD_VARIANT(json_variant_by_index(parameters, 0)))));
1695 if (r < 0)
1696 return r;
1697
1698 return varlink_error(v, VARLINK_ERROR_INVALID_PARAMETER, parameters_obj);
1699 }
1700
1701 return -EINVAL;
1702 }
1703
varlink_error_errno(Varlink * v,int error)1704 int varlink_error_errno(Varlink *v, int error) {
1705 return varlink_errorb(
1706 v,
1707 VARLINK_ERROR_SYSTEM,
1708 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("errno", JSON_BUILD_INTEGER(abs(error)))));
1709 }
1710
varlink_notify(Varlink * v,JsonVariant * parameters)1711 int varlink_notify(Varlink *v, JsonVariant *parameters) {
1712 _cleanup_(json_variant_unrefp) JsonVariant *m = NULL;
1713 int r;
1714
1715 assert_return(v, -EINVAL);
1716
1717 if (v->state == VARLINK_DISCONNECTED)
1718 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
1719 if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
1720 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
1721
1722 r = varlink_sanitize_parameters(¶meters);
1723 if (r < 0)
1724 return varlink_log_errno(v, r, "Failed to sanitize parameters: %m");
1725
1726 r = json_build(&m, JSON_BUILD_OBJECT(
1727 JSON_BUILD_PAIR("parameters", JSON_BUILD_VARIANT(parameters)),
1728 JSON_BUILD_PAIR("continues", JSON_BUILD_BOOLEAN(true))));
1729 if (r < 0)
1730 return varlink_log_errno(v, r, "Failed to build json message: %m");
1731
1732 r = varlink_enqueue_json(v, m);
1733 if (r < 0)
1734 return varlink_log_errno(v, r, "Failed to enqueue json message: %m");
1735
1736 /* No state change, as more is coming */
1737 return 1;
1738 }
1739
varlink_notifyb(Varlink * v,...)1740 int varlink_notifyb(Varlink *v, ...) {
1741 _cleanup_(json_variant_unrefp) JsonVariant *parameters = NULL;
1742 va_list ap;
1743 int r;
1744
1745 assert_return(v, -EINVAL);
1746
1747 va_start(ap, v);
1748 r = json_buildv(¶meters, ap);
1749 va_end(ap);
1750
1751 if (r < 0)
1752 return varlink_log_errno(v, r, "Failed to build json message: %m");
1753
1754 return varlink_notify(v, parameters);
1755 }
1756
varlink_bind_reply(Varlink * v,VarlinkReply callback)1757 int varlink_bind_reply(Varlink *v, VarlinkReply callback) {
1758 assert_return(v, -EINVAL);
1759
1760 if (callback && v->reply_callback && callback != v->reply_callback)
1761 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
1762
1763 v->reply_callback = callback;
1764
1765 return 0;
1766 }
1767
varlink_set_userdata(Varlink * v,void * userdata)1768 void* varlink_set_userdata(Varlink *v, void *userdata) {
1769 void *old;
1770
1771 assert_return(v, NULL);
1772
1773 old = v->userdata;
1774 v->userdata = userdata;
1775
1776 return old;
1777 }
1778
varlink_get_userdata(Varlink * v)1779 void* varlink_get_userdata(Varlink *v) {
1780 assert_return(v, NULL);
1781
1782 return v->userdata;
1783 }
1784
varlink_acquire_ucred(Varlink * v)1785 static int varlink_acquire_ucred(Varlink *v) {
1786 int r;
1787
1788 assert(v);
1789
1790 if (v->ucred_acquired)
1791 return 0;
1792
1793 r = getpeercred(v->fd, &v->ucred);
1794 if (r < 0)
1795 return r;
1796
1797 v->ucred_acquired = true;
1798 return 0;
1799 }
1800
varlink_get_peer_uid(Varlink * v,uid_t * ret)1801 int varlink_get_peer_uid(Varlink *v, uid_t *ret) {
1802 int r;
1803
1804 assert_return(v, -EINVAL);
1805 assert_return(ret, -EINVAL);
1806
1807 r = varlink_acquire_ucred(v);
1808 if (r < 0)
1809 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
1810
1811 if (!uid_is_valid(v->ucred.uid))
1812 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
1813
1814 *ret = v->ucred.uid;
1815 return 0;
1816 }
1817
varlink_get_peer_pid(Varlink * v,pid_t * ret)1818 int varlink_get_peer_pid(Varlink *v, pid_t *ret) {
1819 int r;
1820
1821 assert_return(v, -EINVAL);
1822 assert_return(ret, -EINVAL);
1823
1824 r = varlink_acquire_ucred(v);
1825 if (r < 0)
1826 return varlink_log_errno(v, r, "Failed to acquire credentials: %m");
1827
1828 if (!pid_is_valid(v->ucred.pid))
1829 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENODATA), "Peer uid is invalid.");
1830
1831 *ret = v->ucred.pid;
1832 return 0;
1833 }
1834
varlink_set_relative_timeout(Varlink * v,usec_t timeout)1835 int varlink_set_relative_timeout(Varlink *v, usec_t timeout) {
1836 assert_return(v, -EINVAL);
1837 assert_return(timeout > 0, -EINVAL);
1838
1839 v->timeout = timeout;
1840 return 0;
1841 }
1842
varlink_get_server(Varlink * v)1843 VarlinkServer *varlink_get_server(Varlink *v) {
1844 assert_return(v, NULL);
1845
1846 return v->server;
1847 }
1848
varlink_set_description(Varlink * v,const char * description)1849 int varlink_set_description(Varlink *v, const char *description) {
1850 assert_return(v, -EINVAL);
1851
1852 return free_and_strdup(&v->description, description);
1853 }
1854
io_callback(sd_event_source * s,int fd,uint32_t revents,void * userdata)1855 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1856 Varlink *v = userdata;
1857
1858 assert(s);
1859 assert(v);
1860
1861 handle_revents(v, revents);
1862 (void) varlink_process(v);
1863
1864 return 1;
1865 }
1866
time_callback(sd_event_source * s,uint64_t usec,void * userdata)1867 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1868 Varlink *v = userdata;
1869
1870 assert(s);
1871 assert(v);
1872
1873 (void) varlink_process(v);
1874 return 1;
1875 }
1876
defer_callback(sd_event_source * s,void * userdata)1877 static int defer_callback(sd_event_source *s, void *userdata) {
1878 Varlink *v = userdata;
1879
1880 assert(s);
1881 assert(v);
1882
1883 (void) varlink_process(v);
1884 return 1;
1885 }
1886
prepare_callback(sd_event_source * s,void * userdata)1887 static int prepare_callback(sd_event_source *s, void *userdata) {
1888 Varlink *v = userdata;
1889 int r, e;
1890 usec_t until;
1891 bool have_timeout;
1892
1893 assert(s);
1894 assert(v);
1895
1896 e = varlink_get_events(v);
1897 if (e < 0)
1898 return e;
1899
1900 r = sd_event_source_set_io_events(v->io_event_source, e);
1901 if (r < 0)
1902 return varlink_log_errno(v, r, "Failed to set source events: %m");
1903
1904 r = varlink_get_timeout(v, &until);
1905 if (r < 0)
1906 return r;
1907 have_timeout = r > 0;
1908
1909 if (have_timeout) {
1910 r = sd_event_source_set_time(v->time_event_source, until);
1911 if (r < 0)
1912 return varlink_log_errno(v, r, "Failed to set source time: %m");
1913 }
1914
1915 r = sd_event_source_set_enabled(v->time_event_source, have_timeout ? SD_EVENT_ON : SD_EVENT_OFF);
1916 if (r < 0)
1917 return varlink_log_errno(v, r, "Failed to enable event source: %m");
1918
1919 return 1;
1920 }
1921
quit_callback(sd_event_source * event,void * userdata)1922 static int quit_callback(sd_event_source *event, void *userdata) {
1923 Varlink *v = userdata;
1924
1925 assert(event);
1926 assert(v);
1927
1928 varlink_flush(v);
1929 varlink_close(v);
1930
1931 return 1;
1932 }
1933
varlink_attach_event(Varlink * v,sd_event * e,int64_t priority)1934 int varlink_attach_event(Varlink *v, sd_event *e, int64_t priority) {
1935 int r;
1936
1937 assert_return(v, -EINVAL);
1938 assert_return(!v->event, -EBUSY);
1939
1940 if (e)
1941 v->event = sd_event_ref(e);
1942 else {
1943 r = sd_event_default(&v->event);
1944 if (r < 0)
1945 return varlink_log_errno(v, r, "Failed to create event source: %m");
1946 }
1947
1948 r = sd_event_add_time(v->event, &v->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, v);
1949 if (r < 0)
1950 goto fail;
1951
1952 r = sd_event_source_set_priority(v->time_event_source, priority);
1953 if (r < 0)
1954 goto fail;
1955
1956 (void) sd_event_source_set_description(v->time_event_source, "varlink-time");
1957
1958 r = sd_event_add_exit(v->event, &v->quit_event_source, quit_callback, v);
1959 if (r < 0)
1960 goto fail;
1961
1962 r = sd_event_source_set_priority(v->quit_event_source, priority);
1963 if (r < 0)
1964 goto fail;
1965
1966 (void) sd_event_source_set_description(v->quit_event_source, "varlink-quit");
1967
1968 r = sd_event_add_io(v->event, &v->io_event_source, v->fd, 0, io_callback, v);
1969 if (r < 0)
1970 goto fail;
1971
1972 r = sd_event_source_set_prepare(v->io_event_source, prepare_callback);
1973 if (r < 0)
1974 goto fail;
1975
1976 r = sd_event_source_set_priority(v->io_event_source, priority);
1977 if (r < 0)
1978 goto fail;
1979
1980 (void) sd_event_source_set_description(v->io_event_source, "varlink-io");
1981
1982 r = sd_event_add_defer(v->event, &v->defer_event_source, defer_callback, v);
1983 if (r < 0)
1984 goto fail;
1985
1986 r = sd_event_source_set_priority(v->defer_event_source, priority);
1987 if (r < 0)
1988 goto fail;
1989
1990 (void) sd_event_source_set_description(v->defer_event_source, "varlink-defer");
1991
1992 return 0;
1993
1994 fail:
1995 varlink_log_errno(v, r, "Failed to setup event source: %m");
1996 varlink_detach_event(v);
1997 return r;
1998 }
1999
varlink_detach_event(Varlink * v)2000 void varlink_detach_event(Varlink *v) {
2001 if (!v)
2002 return;
2003
2004 varlink_detach_event_sources(v);
2005
2006 v->event = sd_event_unref(v->event);
2007 }
2008
varlink_get_event(Varlink * v)2009 sd_event *varlink_get_event(Varlink *v) {
2010 assert_return(v, NULL);
2011
2012 return v->event;
2013 }
2014
varlink_server_new(VarlinkServer ** ret,VarlinkServerFlags flags)2015 int varlink_server_new(VarlinkServer **ret, VarlinkServerFlags flags) {
2016 VarlinkServer *s;
2017
2018 assert_return(ret, -EINVAL);
2019 assert_return((flags & ~_VARLINK_SERVER_FLAGS_ALL) == 0, -EINVAL);
2020
2021 s = new(VarlinkServer, 1);
2022 if (!s)
2023 return log_oom_debug();
2024
2025 *s = (VarlinkServer) {
2026 .n_ref = 1,
2027 .flags = flags,
2028 .connections_max = varlink_server_connections_max(NULL),
2029 .connections_per_uid_max = varlink_server_connections_per_uid_max(NULL),
2030 };
2031
2032 *ret = s;
2033 return 0;
2034 }
2035
varlink_server_destroy(VarlinkServer * s)2036 static VarlinkServer* varlink_server_destroy(VarlinkServer *s) {
2037 char *m;
2038
2039 if (!s)
2040 return NULL;
2041
2042 varlink_server_shutdown(s);
2043
2044 while ((m = hashmap_steal_first_key(s->methods)))
2045 free(m);
2046
2047 hashmap_free(s->methods);
2048 hashmap_free(s->by_uid);
2049
2050 sd_event_unref(s->event);
2051
2052 free(s->description);
2053
2054 return mfree(s);
2055 }
2056
2057 DEFINE_TRIVIAL_REF_UNREF_FUNC(VarlinkServer, varlink_server, varlink_server_destroy);
2058
validate_connection(VarlinkServer * server,const struct ucred * ucred)2059 static int validate_connection(VarlinkServer *server, const struct ucred *ucred) {
2060 int allowed = -1;
2061
2062 assert(server);
2063 assert(ucred);
2064
2065 if (FLAGS_SET(server->flags, VARLINK_SERVER_ROOT_ONLY))
2066 allowed = ucred->uid == 0;
2067
2068 if (FLAGS_SET(server->flags, VARLINK_SERVER_MYSELF_ONLY))
2069 allowed = allowed > 0 || ucred->uid == getuid();
2070
2071 if (allowed == 0) { /* Allow access when it is explicitly allowed or when neither
2072 * VARLINK_SERVER_ROOT_ONLY nor VARLINK_SERVER_MYSELF_ONLY are specified. */
2073 varlink_server_log(server, "Unprivileged client attempted connection, refusing.");
2074 return 0;
2075 }
2076
2077 if (server->n_connections >= server->connections_max) {
2078 varlink_server_log(server, "Connection limit of %u reached, refusing.", server->connections_max);
2079 return 0;
2080 }
2081
2082 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2083 unsigned c;
2084
2085 if (!uid_is_valid(ucred->uid)) {
2086 varlink_server_log(server, "Client with invalid UID attempted connection, refusing.");
2087 return 0;
2088 }
2089
2090 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2091 if (c >= server->connections_per_uid_max) {
2092 varlink_server_log(server, "Per-UID connection limit of %u reached, refusing.",
2093 server->connections_per_uid_max);
2094 return 0;
2095 }
2096 }
2097
2098 return 1;
2099 }
2100
count_connection(VarlinkServer * server,const struct ucred * ucred)2101 static int count_connection(VarlinkServer *server, const struct ucred *ucred) {
2102 unsigned c;
2103 int r;
2104
2105 assert(server);
2106 assert(ucred);
2107
2108 server->n_connections++;
2109
2110 if (FLAGS_SET(server->flags, VARLINK_SERVER_ACCOUNT_UID)) {
2111 r = hashmap_ensure_allocated(&server->by_uid, NULL);
2112 if (r < 0)
2113 return log_debug_errno(r, "Failed to allocate UID hash table: %m");
2114
2115 c = PTR_TO_UINT(hashmap_get(server->by_uid, UID_TO_PTR(ucred->uid)));
2116
2117 varlink_server_log(server, "Connections of user " UID_FMT ": %u (of %u max)",
2118 ucred->uid, c, server->connections_per_uid_max);
2119
2120 r = hashmap_replace(server->by_uid, UID_TO_PTR(ucred->uid), UINT_TO_PTR(c + 1));
2121 if (r < 0)
2122 return log_debug_errno(r, "Failed to increment counter in UID hash table: %m");
2123 }
2124
2125 return 0;
2126 }
2127
varlink_server_add_connection(VarlinkServer * server,int fd,Varlink ** ret)2128 int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret) {
2129 _cleanup_(varlink_unrefp) Varlink *v = NULL;
2130 struct ucred ucred = UCRED_INVALID;
2131 bool ucred_acquired;
2132 int r;
2133
2134 assert_return(server, -EINVAL);
2135 assert_return(fd >= 0, -EBADF);
2136
2137 if ((server->flags & (VARLINK_SERVER_ROOT_ONLY|VARLINK_SERVER_ACCOUNT_UID)) != 0) {
2138 r = getpeercred(fd, &ucred);
2139 if (r < 0)
2140 return varlink_server_log_errno(server, r, "Failed to acquire peer credentials of incoming socket, refusing: %m");
2141
2142 ucred_acquired = true;
2143
2144 r = validate_connection(server, &ucred);
2145 if (r < 0)
2146 return r;
2147 if (r == 0)
2148 return -EPERM;
2149 } else
2150 ucred_acquired = false;
2151
2152 r = varlink_new(&v);
2153 if (r < 0)
2154 return varlink_server_log_errno(server, r, "Failed to allocate connection object: %m");
2155
2156 r = count_connection(server, &ucred);
2157 if (r < 0)
2158 return r;
2159
2160 v->fd = fd;
2161 if (server->flags & VARLINK_SERVER_INHERIT_USERDATA)
2162 v->userdata = server->userdata;
2163
2164 if (ucred_acquired) {
2165 v->ucred = ucred;
2166 v->ucred_acquired = true;
2167 }
2168
2169 _cleanup_free_ char *desc = NULL;
2170 if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0)
2171 v->description = TAKE_PTR(desc);
2172
2173 /* Link up the server and the connection, and take reference in both directions. Note that the
2174 * reference on the connection is left dangling. It will be dropped when the connection is closed,
2175 * which happens in varlink_close(), including in the event loop quit callback. */
2176 v->server = varlink_server_ref(server);
2177 varlink_ref(v);
2178
2179 varlink_set_state(v, VARLINK_IDLE_SERVER);
2180
2181 if (server->event) {
2182 r = varlink_attach_event(v, server->event, server->event_priority);
2183 if (r < 0) {
2184 varlink_log_errno(v, r, "Failed to attach new connection: %m");
2185 v->fd = -1; /* take the fd out of the connection again */
2186 varlink_close(v);
2187 return r;
2188 }
2189 }
2190
2191 if (ret)
2192 *ret = v;
2193
2194 return 0;
2195 }
2196
connect_callback(sd_event_source * source,int fd,uint32_t revents,void * userdata)2197 static int connect_callback(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2198 VarlinkServerSocket *ss = userdata;
2199 _cleanup_close_ int cfd = -1;
2200 Varlink *v = NULL;
2201 int r;
2202
2203 assert(source);
2204 assert(ss);
2205
2206 varlink_server_log(ss->server, "New incoming connection.");
2207
2208 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2209 if (cfd < 0) {
2210 if (ERRNO_IS_ACCEPT_AGAIN(errno))
2211 return 0;
2212
2213 return varlink_server_log_errno(ss->server, errno, "Failed to accept incoming socket: %m");
2214 }
2215
2216 r = varlink_server_add_connection(ss->server, cfd, &v);
2217 if (r < 0)
2218 return 0;
2219
2220 TAKE_FD(cfd);
2221
2222 if (ss->server->connect_callback) {
2223 r = ss->server->connect_callback(ss->server, v, ss->server->userdata);
2224 if (r < 0) {
2225 varlink_log_errno(v, r, "Connection callback returned error, disconnecting client: %m");
2226 varlink_close(v);
2227 return 0;
2228 }
2229 }
2230
2231 return 0;
2232 }
2233
varlink_server_listen_fd(VarlinkServer * s,int fd)2234 int varlink_server_listen_fd(VarlinkServer *s, int fd) {
2235 _cleanup_free_ VarlinkServerSocket *ss = NULL;
2236 int r;
2237
2238 assert_return(s, -EINVAL);
2239 assert_return(fd >= 0, -EBADF);
2240
2241 r = fd_nonblock(fd, true);
2242 if (r < 0)
2243 return r;
2244
2245 ss = new(VarlinkServerSocket, 1);
2246 if (!ss)
2247 return log_oom_debug();
2248
2249 *ss = (VarlinkServerSocket) {
2250 .server = s,
2251 .fd = fd,
2252 };
2253
2254 if (s->event) {
2255 r = sd_event_add_io(s->event, &ss->event_source, fd, EPOLLIN, connect_callback, ss);
2256 if (r < 0)
2257 return r;
2258
2259 r = sd_event_source_set_priority(ss->event_source, s->event_priority);
2260 if (r < 0)
2261 return r;
2262 }
2263
2264 LIST_PREPEND(sockets, s->sockets, TAKE_PTR(ss));
2265 return 0;
2266 }
2267
varlink_server_listen_address(VarlinkServer * s,const char * address,mode_t m)2268 int varlink_server_listen_address(VarlinkServer *s, const char *address, mode_t m) {
2269 union sockaddr_union sockaddr;
2270 socklen_t sockaddr_len;
2271 _cleanup_close_ int fd = -1;
2272 int r;
2273
2274 assert_return(s, -EINVAL);
2275 assert_return(address, -EINVAL);
2276 assert_return((m & ~0777) == 0, -EINVAL);
2277
2278 r = sockaddr_un_set_path(&sockaddr.un, address);
2279 if (r < 0)
2280 return r;
2281 sockaddr_len = r;
2282
2283 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2284 if (fd < 0)
2285 return -errno;
2286
2287 fd = fd_move_above_stdio(fd);
2288
2289 (void) sockaddr_un_unlink(&sockaddr.un);
2290
2291 RUN_WITH_UMASK(~m & 0777) {
2292 r = mac_selinux_bind(fd, &sockaddr.sa, sockaddr_len);
2293 if (r < 0)
2294 return r;
2295 }
2296
2297 if (listen(fd, SOMAXCONN) < 0)
2298 return -errno;
2299
2300 r = varlink_server_listen_fd(s, fd);
2301 if (r < 0)
2302 return r;
2303
2304 TAKE_FD(fd);
2305 return 0;
2306 }
2307
varlink_server_set_userdata(VarlinkServer * s,void * userdata)2308 void* varlink_server_set_userdata(VarlinkServer *s, void *userdata) {
2309 void *ret;
2310
2311 assert_return(s, NULL);
2312
2313 ret = s->userdata;
2314 s->userdata = userdata;
2315
2316 return ret;
2317 }
2318
varlink_server_get_userdata(VarlinkServer * s)2319 void* varlink_server_get_userdata(VarlinkServer *s) {
2320 assert_return(s, NULL);
2321
2322 return s->userdata;
2323 }
2324
varlink_server_socket_destroy(VarlinkServerSocket * ss)2325 static VarlinkServerSocket* varlink_server_socket_destroy(VarlinkServerSocket *ss) {
2326 if (!ss)
2327 return NULL;
2328
2329 if (ss->server)
2330 LIST_REMOVE(sockets, ss->server->sockets, ss);
2331
2332 sd_event_source_disable_unref(ss->event_source);
2333
2334 free(ss->address);
2335 safe_close(ss->fd);
2336
2337 return mfree(ss);
2338 }
2339
varlink_server_shutdown(VarlinkServer * s)2340 int varlink_server_shutdown(VarlinkServer *s) {
2341 assert_return(s, -EINVAL);
2342
2343 while (s->sockets)
2344 varlink_server_socket_destroy(s->sockets);
2345
2346 return 0;
2347 }
2348
varlink_server_attach_event(VarlinkServer * s,sd_event * e,int64_t priority)2349 int varlink_server_attach_event(VarlinkServer *s, sd_event *e, int64_t priority) {
2350 int r;
2351
2352 assert_return(s, -EINVAL);
2353 assert_return(!s->event, -EBUSY);
2354
2355 if (e)
2356 s->event = sd_event_ref(e);
2357 else {
2358 r = sd_event_default(&s->event);
2359 if (r < 0)
2360 return r;
2361 }
2362
2363 LIST_FOREACH(sockets, ss, s->sockets) {
2364 assert(!ss->event_source);
2365
2366 r = sd_event_add_io(s->event, &ss->event_source, ss->fd, EPOLLIN, connect_callback, ss);
2367 if (r < 0)
2368 goto fail;
2369
2370 r = sd_event_source_set_priority(ss->event_source, priority);
2371 if (r < 0)
2372 goto fail;
2373 }
2374
2375 s->event_priority = priority;
2376 return 0;
2377
2378 fail:
2379 varlink_server_detach_event(s);
2380 return r;
2381 }
2382
varlink_server_detach_event(VarlinkServer * s)2383 int varlink_server_detach_event(VarlinkServer *s) {
2384 assert_return(s, -EINVAL);
2385
2386 LIST_FOREACH(sockets, ss, s->sockets)
2387 ss->event_source = sd_event_source_disable_unref(ss->event_source);
2388
2389 sd_event_unref(s->event);
2390 return 0;
2391 }
2392
varlink_server_get_event(VarlinkServer * s)2393 sd_event *varlink_server_get_event(VarlinkServer *s) {
2394 assert_return(s, NULL);
2395
2396 return s->event;
2397 }
2398
varlink_server_bind_method(VarlinkServer * s,const char * method,VarlinkMethod callback)2399 int varlink_server_bind_method(VarlinkServer *s, const char *method, VarlinkMethod callback) {
2400 _cleanup_free_ char *m = NULL;
2401 int r;
2402
2403 assert_return(s, -EINVAL);
2404 assert_return(method, -EINVAL);
2405 assert_return(callback, -EINVAL);
2406
2407 if (startswith(method, "org.varlink.service."))
2408 return log_debug_errno(SYNTHETIC_ERRNO(EEXIST), "Cannot bind server to '%s'.", method);
2409
2410 m = strdup(method);
2411 if (!m)
2412 return log_oom_debug();
2413
2414 r = hashmap_ensure_put(&s->methods, &string_hash_ops, m, callback);
2415 if (r == -ENOMEM)
2416 return log_oom_debug();
2417 if (r < 0)
2418 return log_debug_errno(r, "Failed to register callback: %m");
2419 if (r > 0)
2420 TAKE_PTR(m);
2421
2422 return 0;
2423 }
2424
varlink_server_bind_method_many_internal(VarlinkServer * s,...)2425 int varlink_server_bind_method_many_internal(VarlinkServer *s, ...) {
2426 va_list ap;
2427 int r = 0;
2428
2429 assert_return(s, -EINVAL);
2430
2431 va_start(ap, s);
2432 for (;;) {
2433 VarlinkMethod callback;
2434 const char *method;
2435
2436 method = va_arg(ap, const char *);
2437 if (!method)
2438 break;
2439
2440 callback = va_arg(ap, VarlinkMethod);
2441
2442 r = varlink_server_bind_method(s, method, callback);
2443 if (r < 0)
2444 break;
2445 }
2446 va_end(ap);
2447
2448 return r;
2449 }
2450
varlink_server_bind_connect(VarlinkServer * s,VarlinkConnect callback)2451 int varlink_server_bind_connect(VarlinkServer *s, VarlinkConnect callback) {
2452 assert_return(s, -EINVAL);
2453
2454 if (callback && s->connect_callback && callback != s->connect_callback)
2455 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
2456
2457 s->connect_callback = callback;
2458 return 0;
2459 }
2460
varlink_server_bind_disconnect(VarlinkServer * s,VarlinkDisconnect callback)2461 int varlink_server_bind_disconnect(VarlinkServer *s, VarlinkDisconnect callback) {
2462 assert_return(s, -EINVAL);
2463
2464 if (callback && s->disconnect_callback && callback != s->disconnect_callback)
2465 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "A different callback was already set.");
2466
2467 s->disconnect_callback = callback;
2468 return 0;
2469 }
2470
varlink_server_connections_max(VarlinkServer * s)2471 unsigned varlink_server_connections_max(VarlinkServer *s) {
2472 int dts;
2473
2474 /* If a server is specified, return the setting for that server, otherwise the default value */
2475 if (s)
2476 return s->connections_max;
2477
2478 dts = getdtablesize();
2479 assert_se(dts > 0);
2480
2481 /* Make sure we never use up more than ¾th of RLIMIT_NOFILE for IPC */
2482 if (VARLINK_DEFAULT_CONNECTIONS_MAX > (unsigned) dts / 4 * 3)
2483 return dts / 4 * 3;
2484
2485 return VARLINK_DEFAULT_CONNECTIONS_MAX;
2486 }
2487
varlink_server_connections_per_uid_max(VarlinkServer * s)2488 unsigned varlink_server_connections_per_uid_max(VarlinkServer *s) {
2489 unsigned m;
2490
2491 if (s)
2492 return s->connections_per_uid_max;
2493
2494 /* Make sure to never use up more than ¾th of available connections for a single user */
2495 m = varlink_server_connections_max(NULL);
2496 if (VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX > m)
2497 return m / 4 * 3;
2498
2499 return VARLINK_DEFAULT_CONNECTIONS_PER_UID_MAX;
2500 }
2501
varlink_server_set_connections_per_uid_max(VarlinkServer * s,unsigned m)2502 int varlink_server_set_connections_per_uid_max(VarlinkServer *s, unsigned m) {
2503 assert_return(s, -EINVAL);
2504 assert_return(m > 0, -EINVAL);
2505
2506 s->connections_per_uid_max = m;
2507 return 0;
2508 }
2509
varlink_server_set_connections_max(VarlinkServer * s,unsigned m)2510 int varlink_server_set_connections_max(VarlinkServer *s, unsigned m) {
2511 assert_return(s, -EINVAL);
2512 assert_return(m > 0, -EINVAL);
2513
2514 s->connections_max = m;
2515 return 0;
2516 }
2517
varlink_server_current_connections(VarlinkServer * s)2518 unsigned varlink_server_current_connections(VarlinkServer *s) {
2519 assert_return(s, UINT_MAX);
2520
2521 return s->n_connections;
2522 }
2523
varlink_server_set_description(VarlinkServer * s,const char * description)2524 int varlink_server_set_description(VarlinkServer *s, const char *description) {
2525 assert_return(s, -EINVAL);
2526
2527 return free_and_strdup(&s->description, description);
2528 }
2529