Debian Codegraph @

src/shared/qmp-client.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-event.h"
4 #include "sd-future.h"
5 #include "sd-json.h"
6
7 #include "alloc-util.h"
8 #include "fd-util.h"
9 #include "hash-funcs.h"
10 #include "json-stream.h"
11 #include "json-util.h"
12 #include "qmp-client.h"
13 #include "set.h"
14 #include "siphash24.h"
15 #include "string-util.h"
16
17 typedef enum QmpClientState {
18 QMP_CLIENT_RUNNING, /* connection alive; qmp_capabilities may still be in flight */
19 QMP_CLIENT_DISCONNECTED, /* connection closed */
20 _QMP_CLIENT_STATE_MAX,
21 _QMP_CLIENT_STATE_INVALID = -EINVAL,
22 } QmpClientState;
23
24 struct QmpSlot {
25 unsigned n_ref;
26 QmpClient *client; /* NULL once disconnected (reply dispatched, cancelled, or client died) */
27 uint64_t id;
28 bool floating;
29 qmp_command_callback_t callback;
30 void *userdata;
31 };
32
33 struct QmpClient {
34 unsigned n_ref;
35
36 JsonStream stream;
37
38 sd_event_source *quit_event_source;
39 sd_event_source *defer_event_source;
40
41 uint64_t next_id;
42 Set *slots; /* QmpSlot* entries indexed by id, for async dispatch */
43
44 qmp_event_callback_t event_callback;
45 void *event_userdata;
46 qmp_disconnect_callback_t disconnect_callback;
47 void *disconnect_userdata;
48
49 uint64_t next_fdset_id; /* monotonic fdset-id allocator for add-fd */
50
51 QmpClientState state;
52 sd_json_variant *current; /* most recently parsed message, pending dispatch */
53
54 void *userdata;
55 };
56
57 static void qmp_slot_hash_func(const QmpSlot *p, struct siphash *state) {
58 siphash24_compress_typesafe(p->id, state);
59 }
60
61 static int qmp_slot_compare_func(const QmpSlot *a, const QmpSlot *b) {
62 return CMP(a->id, b->id);
63 }
64
65 DEFINE_PRIVATE_HASH_OPS(qmp_slot_hash_ops,
66 QmpSlot, qmp_slot_hash_func, qmp_slot_compare_func);
67
68 /* Break the slot's connection to the client: remove from the lookup set, drop whichever reference
69 * is implied by the slot's floating-ness. For floating slots, the set is the sole owner, so with
70 * unref=true we also drop the slot's n_ref (usually dropping it to zero and freeing). For
71 * non-floating slots, we release the back-reference the slot holds on the client.
72 *
73 * Safe to call multiple times: once slot->client is NULL, subsequent calls are no-ops. */
74 static void qmp_slot_disconnect(QmpSlot *slot, bool unref) {
75 assert(slot);
76
77 if (!slot->client)
78 return;
79
80 QmpClient *client = slot->client;
81
82 set_remove(client->slots, slot);
83 slot->client = NULL;
84
85 if (!slot->floating)
86 qmp_client_unref(client);
87 else if (unref)
88 /* May re-enter via qmp_slot_free→qmp_slot_disconnect(,false) if this drops the
89 * last ref, but the early return above makes that recursion a no-op. */
90 qmp_slot_unref(slot);
91 }
92
93 static QmpSlot* qmp_slot_free(QmpSlot *slot) {
94 if (!slot)
95 return NULL;
96
97 /* Idempotent: if the slot was already disconnected (reply dispatched, explicit cancel,
98 * or client-side teardown), this is a no-op. Otherwise it removes us from the set and
99 * drops our client reference (for non-floating slots). */
100 qmp_slot_disconnect(slot, /* unref= */ false);
101
102 return mfree(slot);
103 }
104
105 DEFINE_TRIVIAL_REF_UNREF_FUNC(QmpSlot, qmp_slot, qmp_slot_free);
106
107 QmpClient* qmp_slot_get_client(QmpSlot *slot) {
108 assert(slot);
109 return slot->client;
110 }
111
112 static int qmp_slot_new(
113 QmpClient *client,
114 bool floating,
115 uint64_t id,
116 qmp_command_callback_t callback,
117 void *userdata,
118 QmpSlot **ret) {
119
120 int r;
121
122 assert(client);
123 assert(ret);
124
125 _cleanup_(qmp_slot_unrefp) QmpSlot *slot = new(QmpSlot, 1);
126 if (!slot)
127 return -ENOMEM;
128
129 *slot = (QmpSlot) {
130 .n_ref = 1,
131 .client = NULL, /* wired up below, after set_put succeeds */
132 .id = id,
133 .floating = floating,
134 .callback = callback,
135 .userdata = userdata,
136 };
137
138 r = set_ensure_put(&client->slots, &qmp_slot_hash_ops, slot);
139 if (r < 0)
140 return r;
141 assert(r > 0);
142
143 slot->client = client;
144 if (!floating)
145 qmp_client_ref(client);
146
147 *ret = TAKE_PTR(slot);
148 return 0;
149 }
150
151 static void qmp_client_clear(QmpClient *c);
152
153 static QmpClient* qmp_client_free(QmpClient *c) {
154 if (!c)
155 return NULL;
156
157 qmp_client_clear(c);
158
159 return mfree(c);
160 }
161
162 DEFINE_TRIVIAL_REF_UNREF_FUNC(QmpClient, qmp_client, qmp_client_free);
163
164 static void qmp_client_clear_current(QmpClient *c) {
165 assert(c);
166
167 c->current = sd_json_variant_unref(c->current);
168 }
169
170 static void qmp_client_dispatch_event(QmpClient *c, sd_json_variant *v) {
171 int r;
172
173 assert(c);
174 assert(v);
175
176 if (!c->event_callback)
177 return;
178
179 struct {
180 const char *event;
181 sd_json_variant *data;
182 } p = {};
183
184 static const sd_json_dispatch_field table[] = {
185 { "event", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, event), SD_JSON_MANDATORY },
186 { "data", SD_JSON_VARIANT_OBJECT, sd_json_dispatch_variant_noref, voffsetof(p, data), 0 },
187 {},
188 };
189
190 r = sd_json_dispatch(v, table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG|SD_JSON_DEBUG, &p);
191 if (r < 0)
192 return;
193
194 r = c->event_callback(c, p.event, p.data, c->event_userdata);
195 if (r < 0)
196 json_stream_log_errno(&c->stream, r, "Event callback returned error, ignoring: %m");
197 }
198
199 /* QEMU's error "class" is effectively always "GenericError"; only "desc" carries useful info. */
200 static const char* qmp_extract_error_description(sd_json_variant *v) {
201 sd_json_variant *error = sd_json_variant_by_key(v, "error");
202 if (!error)
203 return NULL;
204 sd_json_variant *desc = sd_json_variant_by_key(error, "desc");
205 if (desc)
206 return sd_json_variant_string(desc);
207 return "unspecified error";
208 }
209
210 /* Returns 1 with id set; 0 if absent (e.g. pre-parse error responses); -EBADMSG on wrong type. */
211 static int qmp_extract_response_id(sd_json_variant *v, uint64_t *ret) {
212 sd_json_variant *id_variant;
213
214 assert(v);
215 assert(ret);
216
217 id_variant = sd_json_variant_by_key(v, "id");
218 if (!id_variant) {
219 *ret = 0;
220 return 0;
221 }
222 if (!sd_json_variant_is_unsigned(id_variant))
223 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
224 "QMP response 'id' field is not an unsigned integer.");
225
226 *ret = sd_json_variant_unsigned(id_variant);
227 return 1;
228 }
229
230 /* Returns 0 on success (ret_result = freshly reffed "return" value), -EIO on QMP error
231 * (ret_error_desc set to a freshly allocated string). Caller owns both outputs. */
232 static int qmp_parse_response(sd_json_variant *v, sd_json_variant **ret_result, char **reterr_error_desc) {
233 const char *desc;
234
235 desc = qmp_extract_error_description(v);
236 if (desc) {
237 if (reterr_error_desc) {
238 *reterr_error_desc = strdup(desc);
239 if (!*reterr_error_desc)
240 return -ENOMEM;
241 }
242 return -EIO;
243 }
244
245 if (ret_result)
246 *ret_result = sd_json_variant_ref(sd_json_variant_by_key(v, "return"));
247 return 0;
248 }
249
250 static int qmp_client_build_command(
251 QmpClient *c,
252 const char *command,
253 sd_json_variant *arguments,
254 sd_json_variant **ret,
255 uint64_t *ret_id) {
256
257 uint64_t id;
258 int r;
259
260 assert(c);
261 assert(command);
262 assert(ret);
263 assert(ret_id);
264
265 id = c->next_id++;
266
267 r = sd_json_buildo(
268 ret,
269 SD_JSON_BUILD_PAIR_STRING("execute", command),
270 SD_JSON_BUILD_PAIR_CONDITION(!!arguments, "arguments", SD_JSON_BUILD_VARIANT(arguments)),
271 SD_JSON_BUILD_PAIR_UNSIGNED("id", id));
272 if (r < 0)
273 return r;
274
275 *ret_id = id;
276 return 0;
277 }
278
279 /* Route c->current to event callback or matching async slot. Returns 1 on dispatch. */
280 static int qmp_client_dispatch(QmpClient *c) {
281 _cleanup_(sd_json_variant_unrefp) sd_json_variant *result = NULL;
282 _cleanup_free_ char *desc = NULL;
283 uint64_t id;
284 int error, r;
285
286 assert(c);
287
288 if (!c->current)
289 return 0;
290
291 /* Events have an "event" key */
292 if (sd_json_variant_by_key(c->current, "event")) {
293 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = TAKE_PTR(c->current);
294 qmp_client_dispatch_event(c, v);
295 return 1;
296 }
297
298 /* QEMU sends a one-shot greeting with a "QMP" key unsolicited on connect. We don't
299 * wait for it before sending qmp_capabilities (QEMU accepts commands the moment the
300 * socket is open), we detect it by the "QMP" key and drop it. */
301 if (sd_json_variant_by_key(c->current, "QMP")) {
302 qmp_client_clear_current(c);
303 return 1;
304 }
305
306 /* Command responses carry an "id" matching a request we sent */
307 r = qmp_extract_response_id(c->current, &id);
308 if (r < 0) {
309 qmp_client_clear_current(c);
310 return json_stream_log_errno(&c->stream, r, "Discarding QMP response with malformed id: %m");
311 }
312 if (r == 0) {
313 qmp_client_clear_current(c);
314 json_stream_log(&c->stream, "Discarding unrecognized QMP message");
315 return 1;
316 }
317
318 QmpSlot *slot = set_get(c->slots, &(QmpSlot) { .id = id });
319 if (!slot) {
320 qmp_client_clear_current(c);
321 json_stream_log(&c->stream, "Discarding QMP response with unknown id %" PRIu64, id);
322 return 1;
323 }
324
325 /* Synchronous slot (no callback): leave c->current pinned so qmp_client_call() can
326 * pick the reply up after its pump loop. The sync caller owns a ref on the slot and
327 * detects completion by observing slot->client turning NULL. */
328 if (!slot->callback) {
329 qmp_slot_disconnect(slot, /* unref= */ true);
330 return 1;
331 }
332
333 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = TAKE_PTR(c->current);
334 error = qmp_parse_response(v, &result, &desc);
335
336 /* Pin the slot across the callback regardless of floating-ness. For a floating slot,
337 * disconnect(unref=true) drops the set's implicit ref which would otherwise free it
338 * out from under the callback. */
339 qmp_slot_ref(slot);
340
341 r = slot->callback(c, result, desc, error, slot->userdata);
342 if (r < 0)
343 json_stream_log_errno(&c->stream, r, "Command callback returned error, ignoring: %m");
344
345 qmp_slot_disconnect(slot, /* unref= */ true);
346 qmp_slot_unref(slot);
347
348 return 1;
349 }
350
351 /* Fail all pending commands with the given error. Called on disconnect. */
352 static void qmp_client_fail_pending(QmpClient *c, int error) {
353 QmpSlot *slot;
354 int r;
355
356 assert(c);
357
358 while ((slot = set_first(c->slots))) {
359 /* Keep alive across the callback and past disconnect (which may unref it for
360 * floating slots). */
361 qmp_slot_ref(slot);
362
363 if (slot->callback) {
364 r = slot->callback(c, /* result= */ NULL, /* error_desc= */ NULL, error, slot->userdata);
365 if (r < 0)
366 json_stream_log_errno(&c->stream, r, "Command callback returned error, ignoring: %m");
367 }
368
369 qmp_slot_disconnect(slot, /* unref= */ true);
370 qmp_slot_unref(slot);
371 }
372 }
373
374 /* Synthetic SHUTDOWN on unexpected disconnect so subscribers learn the VM is gone. */
375 static void qmp_client_emit_synthetic_shutdown(QmpClient *c) {
376 _cleanup_(sd_json_variant_unrefp) sd_json_variant *data = NULL;
377 int r;
378
379 assert(c);
380
381 if (!c->event_callback)
382 return;
383
384 r = sd_json_buildo(
385 &data,
386 SD_JSON_BUILD_PAIR_BOOLEAN("guest", false),
387 SD_JSON_BUILD_PAIR_STRING("reason", "disconnected"));
388 if (r < 0) {
389 json_stream_log_errno(&c->stream, r, "Failed to build synthetic SHUTDOWN event data, skipping: %m");
390 return;
391 }
392
393 r = c->event_callback(c, "SHUTDOWN", data, c->event_userdata);
394 if (r < 0)
395 json_stream_log_errno(&c->stream, r, "Event callback returned error, ignoring: %m");
396 }
397
398 static bool qmp_client_handle_disconnect(QmpClient *c) {
399 assert(c);
400
401 if (c->state == QMP_CLIENT_DISCONNECTED)
402 return false;
403
404 c->state = QMP_CLIENT_DISCONNECTED;
405
406 /* Disable defer event source so we don't busy-loop on the EOF condition. */
407 if (c->defer_event_source)
408 (void) sd_event_source_set_enabled(c->defer_event_source, SD_EVENT_OFF);
409
410 qmp_client_fail_pending(c, -ECONNRESET);
411 qmp_client_emit_synthetic_shutdown(c);
412 if (c->disconnect_callback)
413 c->disconnect_callback(c, c->disconnect_userdata);
414
415 return true;
416 }
417
418 static bool qmp_client_test_disconnect(QmpClient *c) {
419 assert(c);
420
421 /* Already disconnected? */
422 if (c->state == QMP_CLIENT_DISCONNECTED)
423 return false;
424
425 if (!json_stream_should_disconnect(&c->stream))
426 return false;
427
428 return qmp_client_handle_disconnect(c);
429 }
430
431 /* Single step: write → dispatch → parse → read → disconnect. Matches sd_varlink_process(). */
432 int qmp_client_process(QmpClient *c) {
433 int r;
434
435 assert(c);
436
437 if (c->state < 0 || c->state == QMP_CLIENT_DISCONNECTED)
438 return -ENOTCONN;
439
440 /* Pin against a callback dropping the last ref mid-dispatch. Matches sd_varlink_process(). */
441 qmp_client_ref(c);
442
443 /* 1. Write — drain output buffer */
444 r = json_stream_write(&c->stream);
445 if (r < 0)
446 json_stream_log_errno(&c->stream, r, "Failed to write to QMP socket: %m");
447 if (r != 0)
448 goto finish;
449
450 /* 2. Dispatch — dispatch incoming messages to slots */
451 r = qmp_client_dispatch(c);
452 if (r < 0)
453 json_stream_log_errno(&c->stream, r, "Failed to dispatch QMP message: %m");
454 if (r != 0)
455 goto finish;
456
457 /* 3. Parse — extract one complete message into c->current */
458 if (!c->current) {
459 r = json_stream_parse(&c->stream, &c->current);
460 if (r < 0)
461 json_stream_log_errno(&c->stream, r, "Failed to parse QMP message: %m");
462 if (r != 0)
463 goto finish;
464 }
465
466 /* 4. Read — fill input buffer from fd */
467 if (!c->current) {
468 r = json_stream_read(&c->stream);
469 if (r < 0)
470 json_stream_log_errno(&c->stream, r, "Failed to read from QMP socket: %m");
471 if (r != 0)
472 goto finish;
473 }
474
475 /* 5. Test disconnect */
476 if (qmp_client_test_disconnect(c)) {
477 r = 1;
478 goto finish;
479 }
480
481 finish:
482 /* Re-arm defer source on progress so we get called again next iteration. */
483 if (r >= 0 && c->defer_event_source) {
484 int q;
485
486 q = sd_event_source_set_enabled(c->defer_event_source, r > 0 ? SD_EVENT_ON : SD_EVENT_OFF);
487 if (q < 0)
488 r = json_stream_log_errno(&c->stream, q, "Failed to enable deferred event source: %m");
489 }
490
491 /* -ENOBUFS is the buffered stream's 16 MiB cap, not a transport error — propagate without disconnecting. */
492 if (r < 0 && r != -ENOBUFS && c->state != QMP_CLIENT_DISCONNECTED)
493 qmp_client_handle_disconnect(c);
494
495 qmp_client_unref(c);
496 return r;
497 }
498
499 int qmp_client_wait(QmpClient *c, uint64_t timeout_usec) {
500 assert(c);
501
502 if (c->state == QMP_CLIENT_DISCONNECTED)
503 return -ENOTCONN;
504
505 return json_stream_wait(&c->stream, timeout_usec);
506 }
507
508 bool qmp_client_is_idle(QmpClient *c) {
509 assert(c);
510 return set_isempty(c->slots);
511 }
512
513 bool qmp_client_is_disconnected(QmpClient *c) {
514 assert(c);
515 return c->state == QMP_CLIENT_DISCONNECTED;
516 }
517
518 void* qmp_client_set_userdata(QmpClient *c, void *userdata) {
519 void *old;
520
521 assert(c);
522
523 old = c->userdata;
524 c->userdata = userdata;
525 return old;
526 }
527
528 void* qmp_client_get_userdata(QmpClient *c) {
529 assert(c);
530 return c->userdata;
531 }
532
533 /* Map our state to the transport phase used for POLLIN / salvage / timeout decisions. */
534 static JsonStreamPhase qmp_client_phase(void *userdata) {
535 QmpClient *c = ASSERT_PTR(userdata);
536
537 /* A parsed-but-undispatched message is mid-processing, not waiting on the wire. */
538 if (c->current)
539 return JSON_STREAM_PHASE_OTHER;
540
541 if (c->state != QMP_CLIENT_RUNNING)
542 return JSON_STREAM_PHASE_OTHER;
543
544 /* Pending slots (user commands or the initial qmp_capabilities) → awaiting reply.
545 * Otherwise we're idling for unsolicited events. */
546 return set_isempty(c->slots)
547 ? JSON_STREAM_PHASE_READING
548 : JSON_STREAM_PHASE_AWAITING_REPLY;
549 }
550
551 static int qmp_client_dispatch_cb(void *userdata) {
552 QmpClient *c = ASSERT_PTR(userdata);
553 return qmp_client_process(c);
554 }
555
556 static int qmp_client_defer_callback(sd_event_source *source, void *userdata) {
557 QmpClient *c = ASSERT_PTR(userdata);
558
559 assert(source);
560
561 (void) qmp_client_process(c);
562
563 return 1;
564 }
565
566 static void qmp_client_detach_event(QmpClient *c) {
567 if (!c)
568 return;
569
570 c->defer_event_source = sd_event_source_disable_unref(c->defer_event_source);
571 c->quit_event_source = sd_event_source_disable_unref(c->quit_event_source);
572 json_stream_detach_event(&c->stream);
573 }
574
575 static void qmp_client_clear(QmpClient *c) {
576 assert(c);
577
578 qmp_client_handle_disconnect(c);
579 qmp_client_detach_event(c);
580 qmp_client_clear_current(c);
581 json_stream_done(&c->stream);
582 /* qmp_client_handle_disconnect() above drained every entry via qmp_client_fail_pending();
583 * the set is borrow-only for non-floating slots, so set_free() can't safely run a
584 * destructor over leftovers — enforce the drain invariant instead. */
585 assert(set_isempty(c->slots));
586 c->slots = set_free(c->slots);
587 }
588
589 /* Blocks until output buffer is empty. Matches sd_varlink_flush(). */
590 static int qmp_client_flush(QmpClient *c) {
591 if (!c)
592 return 0;
593
594 if (c->state == QMP_CLIENT_DISCONNECTED)
595 return -ENOTCONN;
596
597 return json_stream_flush(&c->stream);
598 }
599
600 /* Notify callbacks, fire disconnect, detach sources, close fd. Matches sd_varlink_close(). */
601 static int qmp_client_close(QmpClient *c) {
602 if (!c)
603 return 0;
604
605 /* Take a temporary ref to prevent destruction mid-callback,
606 * matching sd_varlink_close()'s pattern. */
607 qmp_client_ref(c);
608 qmp_client_clear(c);
609 qmp_client_unref(c);
610
611 return 1;
612 }
613
614 static int qmp_client_quit_callback(sd_event_source *source, void *userdata) {
615 QmpClient *c = ASSERT_PTR(userdata);
616
617 assert(source);
618
619 qmp_client_flush(c);
620 qmp_client_close(c);
621
622 return 1;
623 }
624
625 static int qmp_client_send(
626 QmpClient *c,
627 const char *command,
628 QmpClientArgs *args,
629 qmp_command_callback_t callback,
630 void *userdata,
631 QmpSlot **ret_slot);
632
633 /* Reply callback for the eagerly-enqueued qmp_capabilities command. Success → we stay in
634 * RUNNING. Failure → negotiation is unrecoverable, force-disconnect so the next user op gets
635 * -ENOTCONN rather than hanging. */
636 static int qmp_client_capabilities_reply(
637 QmpClient *c,
638 sd_json_variant *result,
639 const char *error_desc,
640 int error,
641 void *userdata) {
642
643 /* qmp_client_handle_disconnect() below fails all pending slots, which re-enters this
644 * callback with -ECONNRESET on our own still-registered slot. Short-circuit that. */
645 if (c->state == QMP_CLIENT_DISCONNECTED)
646 return 0;
647
648 if (error >= 0)
649 return 0;
650
651 json_stream_log_errno(&c->stream, error, "qmp_capabilities failed: %s", strna(error_desc));
652 qmp_client_handle_disconnect(c);
653 return 0;
654 }
655
656 int qmp_client_connect_fd(QmpClient **ret, int fd) {
657 _cleanup_(qmp_client_unrefp) QmpClient *c = NULL;
658 int r;
659
660 assert(ret);
661 assert(fd >= 0);
662
663 c = new(QmpClient, 1);
664 if (!c)
665 return -ENOMEM;
666
667 *c = (QmpClient) {
668 .n_ref = 1,
669 .state = QMP_CLIENT_RUNNING,
670 .next_id = 1,
671 };
672
673 const JsonStreamParams params = {
674 .delimiter = "\r\n",
675 .phase = qmp_client_phase,
676 .dispatch = qmp_client_dispatch_cb,
677 .userdata = c,
678 };
679
680 r = json_stream_init(&c->stream, &params);
681 if (r < 0)
682 return r;
683
684 r = json_stream_connect_fd_pair(&c->stream, fd, fd);
685 if (r < 0)
686 return r;
687
688 /* Eagerly queue qmp_capabilities. QEMU accepts commands as soon as the socket opens
689 * — its greeting is informational and doesn't gate writes on our side. FIFO ordering
690 * of the output queue guarantees cap precedes any user command a later invoke()
691 * enqueues, which is all QEMU actually requires. */
692 r = qmp_client_send(c, "qmp_capabilities", /* args= */ NULL,
693 qmp_client_capabilities_reply, /* userdata= */ NULL,
694 /* ret_slot= */ NULL);
695 if (r < 0)
696 return r;
697
698 *ret = TAKE_PTR(c);
699 return 0;
700 }
701
702 int qmp_client_attach_event(QmpClient *c, sd_event *event, int64_t priority) {
703 int r;
704
705 assert(c);
706 assert(event);
707 assert(!json_stream_get_event(&c->stream));
708
709 r = json_stream_attach_event(&c->stream, event, priority);
710 if (r < 0)
711 return r;
712
713 sd_event *ev = json_stream_get_event(&c->stream);
714
715 r = sd_event_add_exit(ev, &c->quit_event_source, qmp_client_quit_callback, c);
716 if (r < 0)
717 goto fail;
718
719 r = sd_event_source_set_priority(c->quit_event_source, priority);
720 if (r < 0)
721 goto fail;
722
723 (void) sd_event_source_set_description(c->quit_event_source, "qmp-client-quit");
724
725 r = sd_event_add_defer(ev, &c->defer_event_source, qmp_client_defer_callback, c);
726 if (r < 0)
727 goto fail;
728
729 r = sd_event_source_set_priority(c->defer_event_source, priority);
730 if (r < 0)
731 goto fail;
732
733 r = sd_event_source_set_enabled(c->defer_event_source, SD_EVENT_OFF);
734 if (r < 0)
735 goto fail;
736
737 (void) sd_event_source_set_description(c->defer_event_source, "qmp-client-defer");
738
739 return 0;
740
741 fail:
742 qmp_client_detach_event(c);
743 return r;
744 }
745
746 /* Cleanup hook: closes any fds in *args not yet transferred to the stream. */
747 static QmpClientArgs* qmp_client_args_close_fds(QmpClientArgs *p) {
748 assert(p);
749 close_many_unset(p->fds_consume, p->n_fds);
750 return NULL;
751 }
752
753 DEFINE_TRIVIAL_CLEANUP_FUNC(QmpClientArgs*, qmp_client_args_close_fds);
754
755 /* Shared send path for qmp_client_invoke() and qmp_client_call(). A NULL callback registers
756 * a "synchronous" slot: dispatch_reply leaves c->current pinned on match instead of invoking
757 * a callback, so qmp_client_call() can pick the reply up after its pump loop. If ret_slot
758 * is NULL the slot is allocated as floating (owned by c->slots); otherwise a reference is
759 * handed back to the caller. */
760 static int qmp_client_send(
761 QmpClient *c,
762 const char *command,
763 QmpClientArgs *args,
764 qmp_command_callback_t callback,
765 void *userdata,
766 QmpSlot **ret_slot) {
767
768 _cleanup_(sd_json_variant_unrefp) sd_json_variant *cmd = NULL;
769 _cleanup_(qmp_slot_unrefp) QmpSlot *slot = NULL;
770 /* Closes any fds in args on every early-return path; TAKE_PTR()'d on the success path
771 * below once json_stream_enqueue_full() has taken ownership of them. */
772 _cleanup_(qmp_client_args_close_fdsp) QmpClientArgs *fds_owner = args;
773 uint64_t id;
774 int r;
775
776 assert(c);
777 assert(command);
778
779 if (c->state == QMP_CLIENT_DISCONNECTED)
780 return -ENOTCONN;
781
782 r = qmp_client_build_command(c, command, args ? args->arguments : NULL, &cmd, &id);
783 if (r < 0)
784 return r;
785
786 r = qmp_slot_new(c, /* floating= */ !ret_slot, id, callback, userdata, &slot);
787 if (r < 0)
788 return r;
789
790 r = json_stream_enqueue_full(&c->stream, cmd,
791 args ? args->fds_consume : NULL,
792 args ? args->n_fds : 0);
793 if (r < 0)
794 return r; /* slot cleanup disconnects it */
795
796 /* Arm defer so process() drains the output on the next iteration. */
797 if (c->defer_event_source)
798 (void) sd_event_source_set_enabled(c->defer_event_source, SD_EVENT_ON);
799
800 TAKE_PTR(fds_owner);
801
802 if (ret_slot)
803 *ret_slot = TAKE_PTR(slot);
804 else
805 TAKE_PTR(slot); /* floating: c->slots keeps it alive until dispatch */
806
807 return 0;
808 }
809
810 int qmp_client_invoke(
811 QmpClient *c,
812 QmpSlot **ret_slot,
813 const char *command,
814 QmpClientArgs *args,
815 qmp_command_callback_t callback,
816 void *userdata) {
817
818 assert(callback);
819 return qmp_client_send(c, command, args, callback, userdata, ret_slot);
820 }
821
822 typedef struct QmpFuture {
823 QmpSlot *slot; /* owned, non-floating; NULL once disconnected */
824 sd_json_variant *result;
825 char *error_desc;
826 } QmpFuture;
827
828 static void* qmp_future_alloc(void) {
829 return new0(QmpFuture, 1);
830 }
831
832 static void qmp_future_free(sd_future *f) {
833 QmpFuture *qf = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f)));
834 qmp_slot_unref(qf->slot);
835 sd_json_variant_unref(qf->result);
836 free(qf->error_desc);
837 free(qf);
838 }
839
840 static int qmp_future_cancel(sd_future *f) {
841 QmpFuture *qf = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f)));
842
843 /* Drop the pending slot so dispatch_reply won't try to fire our callback (and touch
844 * freed memory) when the reply eventually arrives. */
845 qf->slot = qmp_slot_unref(qf->slot);
846 return sd_future_resolve(f, -ECANCELED);
847 }
848
849 static const sd_future_ops qmp_call_future_ops = {
850 .size = sizeof(sd_future_ops),
851 .alloc = qmp_future_alloc,
852 .free = qmp_future_free,
853 .cancel = qmp_future_cancel,
854 };
855
856 static int qmp_future_callback(
857 QmpClient *c,
858 sd_json_variant *result,
859 const char *desc,
860 int error,
861 void *userdata) {
862
863 sd_future *f = ASSERT_PTR(userdata);
864 QmpFuture *qf = ASSERT_PTR(sd_future_get_private(f));
865 int r;
866
867 assert(result || desc || error);
868
869 if (result)
870 qf->result = sd_json_variant_ref(result);
871 if (desc) {
872 qf->error_desc = strdup(desc);
873 if (!qf->error_desc)
874 /* No usable reply payload to surface — propagate as transport-style
875 * failure so suspend() / sd_future_result() see the OOM. */
876 return sd_future_resolve(f, -ENOMEM);
877 }
878
879 /* Resolve with 0 on a success reply and -EIO on a QMP-level error (matching the synchronous
880 * path's errno for the desc-without-ret_error_desc case), so a caller awaiting the future
881 * learns about call failures from the resolution value alone. The reply payload itself
882 * (result or error_desc) is always stashed on the QmpFuture so future_get_qmp_reply() can
883 * hand the description string back on top of the bare -EIO. With no reply at all (transport
884 * failure, disconnect), resolve with the propagated transport errno; cancellation surfaces
885 * as -ECANCELED via qmp_future_cancel(). */
886 if (result)
887 r = 0;
888 else if (desc)
889 r = -EIO;
890 else
891 r = error;
892
893 return sd_future_resolve(f, r);
894 }
895
896 int qmp_client_call_future(
897 QmpClient *c,
898 const char *command,
899 QmpClientArgs *args,
900 sd_future **ret) {
901
902 int r;
903
904 assert(c);
905 assert(command);
906 assert(ret);
907
908 _cleanup_(sd_future_unrefp) sd_future *f = NULL;
909 r = sd_future_new(&qmp_call_future_ops, &f);
910 if (r < 0)
911 return r;
912
913 QmpFuture *qf = sd_future_get_private(f);
914
915 r = qmp_client_send(c, command, args, qmp_future_callback, f, &qf->slot);
916 if (r < 0)
917 return r;
918
919 *ret = TAKE_PTR(f);
920 return 0;
921 }
922
923 /* Extract the reply from a resolved qmp_client_call_future(). Returns 1 on success (with
924 * *ret_result a fresh reference the caller unrefs), -EIO on a QMP-level error (with the detail
925 * description copied into *ret_error_desc when the caller passed one to receive it), and the
926 * future's negative resume errno when no reply landed at all (transport failure / cancellation).
927 */
928 int future_get_qmp_reply(sd_future *f, sd_json_variant **ret_result, char **reterr_error_desc) {
929 assert(f);
930 assert(sd_future_get_ops(f) == &qmp_call_future_ops);
931 assert(sd_future_state(f) == SD_FUTURE_RESOLVED);
932
933 QmpFuture *qf = ASSERT_PTR(sd_future_get_private(f));
934
935 /* No reply at all: transport failure or cancellation — surface the future result. */
936 if (!qf->result && !qf->error_desc)
937 return sd_future_result(f);
938
939 if (qf->error_desc) {
940 if (reterr_error_desc) {
941 char *desc = strdup(qf->error_desc);
942 if (!desc)
943 return -ENOMEM;
944 *reterr_error_desc = desc;
945 }
946 return -EIO;
947 }
948
949 if (reterr_error_desc)
950 *reterr_error_desc = NULL;
951 if (ret_result)
952 *ret_result = sd_json_variant_ref(qf->result);
953
954 return 1;
955 }
956
957 static int qmp_client_call_suspend(
958 QmpClient *c,
959 const char *command,
960 QmpClientArgs *args,
961 sd_json_variant **ret_result,
962 char **ret_error_desc) {
963
964 int r;
965
966 assert(c);
967 assert(command);
968 assert(sd_fiber_is_running());
969
970 _cleanup_(sd_future_cancel_wait_unrefp) sd_future *call = NULL;
971 r = qmp_client_call_future(c, command, args, &call);
972 if (r < 0)
973 return r;
974
975 r = sd_fiber_suspend();
976
977 /* If the future isn't resolved, the suspend was interrupted before a reply arrived (fiber
978 * cancelled, fiber-wide SD_FIBER_TIMEOUT scope expired, …). There's no reply to extract,
979 * so surface the resume error directly. When the future is resolved, future_get_qmp_reply()
980 * already encodes success (1), QMP-level error (-EIO with the desc captured if asked for),
981 * and no-reply (negative future result) — pass it through. */
982 if (sd_future_state(call) != SD_FUTURE_RESOLVED)
983 return r;
984
985 return future_get_qmp_reply(call, ret_result, ret_error_desc);
986 }
987
988 int qmp_client_call(
989 QmpClient *c,
990 const char *command,
991 QmpClientArgs *args,
992 sd_json_variant **ret_result,
993 char **reterr_error_desc) {
994
995 _cleanup_(sd_json_variant_unrefp) sd_json_variant *result = NULL;
996 _cleanup_free_ char *desc = NULL;
997 int r;
998
999 assert_return(c, -EINVAL);
1000 assert_return(command, -EINVAL);
1001
1002 /* If we're on a fiber sharing the QMP client's event loop, use the async + suspend path so
1003 * multiple concurrent qmp_client_call() invocations across fibers don't deadlock each other
1004 * on the process+wait pump. */
1005 if (sd_fiber_is_running() && qmp_client_get_event(c) == sd_fiber_get_event())
1006 return qmp_client_call_suspend(c, command, args, ret_result, reterr_error_desc);
1007
1008 _cleanup_(qmp_slot_unrefp) QmpSlot *slot = NULL;
1009
1010 /* NULL callback marks this as a synchronous slot: dispatch_reply matches on id like
1011 * any other slot (so stray unknown-id replies still get logged and dropped), but
1012 * pins c->current for us instead of invoking a callback. The slot is non-floating so
1013 * we can observe dispatch by watching slot->client go NULL. */
1014 r = qmp_client_send(c, command, args, /* callback= */ NULL, /* userdata= */ NULL, &slot);
1015 if (r < 0)
1016 return r;
1017
1018 /* Pump the loop until our sync slot fires (disconnected by dispatch, c->current pinned). */
1019 for (;;) {
1020 if (c->state == QMP_CLIENT_DISCONNECTED)
1021 return -ECONNRESET;
1022
1023 if (!slot->client) {
1024 assert(c->current);
1025 break;
1026 }
1027
1028 r = qmp_client_process(c);
1029 if (r < 0)
1030 return r;
1031 if (r > 0)
1032 continue;
1033
1034 r = qmp_client_wait(c, USEC_INFINITY);
1035 if (r < 0)
1036 return r;
1037 }
1038
1039 _cleanup_(sd_json_variant_unrefp) sd_json_variant *current = TAKE_PTR(c->current);
1040 r = qmp_parse_response(current, &result, &desc);
1041 if (r < 0 && r != -EIO)
1042 return r;
1043
1044 /* QMP-level error: copy the description into *ret_error_desc when the caller asked for it,
1045 * and surface the failure via the return value (matching qmp_client_call_suspend() /
1046 * sd_bus_call()'s "negative on error" convention). */
1047 if (desc) {
1048 if (reterr_error_desc)
1049 *reterr_error_desc = TAKE_PTR(desc);
1050 return -EIO;
1051 }
1052
1053 if (ret_result)
1054 *ret_result = TAKE_PTR(result);
1055 if (reterr_error_desc)
1056 *reterr_error_desc = NULL;
1057
1058 return 1;
1059 }
1060
1061 void qmp_client_bind_event(QmpClient *c, qmp_event_callback_t callback, void *userdata) {
1062 assert(c);
1063 c->event_callback = callback;
1064 c->event_userdata = userdata;
1065 }
1066
1067 void qmp_client_bind_disconnect(QmpClient *c, qmp_disconnect_callback_t callback, void *userdata) {
1068 assert(c);
1069 c->disconnect_callback = callback;
1070 c->disconnect_userdata = userdata;
1071 }
1072
1073 int qmp_client_set_description(QmpClient *c, const char *description) {
1074 assert(c);
1075 return json_stream_set_description(&c->stream, description);
1076 }
1077
1078 sd_event* qmp_client_get_event(QmpClient *c) {
1079 assert(c);
1080 return json_stream_get_event(&c->stream);
1081 }
1082
1083 uint64_t qmp_client_next_fdset_id(QmpClient *c) {
1084 assert(c);
1085 return c->next_fdset_id++;
1086 }
1087
1088 bool qmp_schema_has_member(sd_json_variant *schema, const char *member_name) {
1089 sd_json_variant *entry;
1090
1091 assert(member_name);
1092
1093 if (!sd_json_variant_is_array(schema))
1094 return false;
1095
1096 JSON_VARIANT_ARRAY_FOREACH(entry, schema) {
1097 if (!sd_json_variant_is_object(entry))
1098 continue;
1099
1100 sd_json_variant *meta = sd_json_variant_by_key(entry, "meta-type");
1101 if (!meta || !streq_ptr(sd_json_variant_string(meta), "object"))
1102 continue;
1103
1104 sd_json_variant *members = sd_json_variant_by_key(entry, "members");
1105 if (!sd_json_variant_is_array(members))
1106 continue;
1107
1108 sd_json_variant *m;
1109 JSON_VARIANT_ARRAY_FOREACH(m, members) {
1110 if (!sd_json_variant_is_object(m))
1111 continue;
1112 sd_json_variant *mn = sd_json_variant_by_key(m, "name");
1113 if (mn && streq_ptr(sd_json_variant_string(mn), member_name))
1114 return true;
1115 }
1116 }
1117
1118 return false;
1119 }