virdbus.c 55.6 KB
Newer Older
1 2 3
/*
 * virdbus.c: helper for using DBus
 *
4
 * Copyright (C) 2012-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23
 *
 */

#include <config.h>

24
#define LIBVIRT_VIRDBUSPRIV_H_ALLOW
25
#include "virdbuspriv.h"
26
#include "viralloc.h"
27
#include "virerror.h"
28
#include "virlog.h"
29
#include "virthread.h"
30
#include "virstring.h"
31
#include "virprobe.h"
32 33 34

#define VIR_FROM_THIS VIR_FROM_DBUS

35 36
VIR_LOG_INIT("util.dbus");

37
#ifdef WITH_DBUS
38

39
static bool sharedBus = true;
40 41
static DBusConnection *systembus;
static DBusConnection *sessionbus;
42 43 44 45
static virOnceControl systemonce = VIR_ONCE_CONTROL_INITIALIZER;
static virOnceControl sessiononce = VIR_ONCE_CONTROL_INITIALIZER;
static DBusError systemdbuserr;
static DBusError sessiondbuserr;
46 47 48 49 50

static dbus_bool_t virDBusAddWatch(DBusWatch *watch, void *data);
static void virDBusRemoveWatch(DBusWatch *watch, void *data);
static void virDBusToggleWatch(DBusWatch *watch, void *data);

51 52 53 54 55
void virDBusSetSharedBus(bool shared)
{
    sharedBus = shared;
}

56
static DBusConnection *virDBusBusInit(DBusBusType type, DBusError *dbuserr)
57
{
58 59
    DBusConnection *bus;

60 61 62 63
    /* Allocate and initialize a new HAL context */
    dbus_connection_set_change_sigpipe(FALSE);
    dbus_threads_init_default();

64
    dbus_error_init(dbuserr);
65 66 67 68
    bus = sharedBus ?
        dbus_bus_get(type, dbuserr) :
        dbus_bus_get_private(type, dbuserr);
    if (!bus)
69
        return NULL;
70

71
    dbus_connection_set_exit_on_disconnect(bus, FALSE);
72 73

    /* Register dbus watch callbacks */
74
    if (!dbus_connection_set_watch_functions(bus,
75 76 77
                                             virDBusAddWatch,
                                             virDBusRemoveWatch,
                                             virDBusToggleWatch,
78 79
                                             bus, NULL)) {
        return NULL;
80
    }
81
    return bus;
82 83
}

84 85 86 87
static void virDBusSystemBusInit(void)
{
    systembus = virDBusBusInit(DBUS_BUS_SYSTEM, &systemdbuserr);
}
88

89 90
static DBusConnection *
virDBusGetSystemBusInternal(void)
91
{
92
    if (virOnce(&systemonce, virDBusSystemBusInit) < 0) {
93 94
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to run one time DBus initializer"));
95 96 97
        return NULL;
    }

98 99 100 101 102 103 104 105 106 107
    return systembus;
}


DBusConnection *
virDBusGetSystemBus(void)
{
    DBusConnection *bus;

    if (!(bus = virDBusGetSystemBusInternal())) {
108 109
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to get DBus system bus connection: %s"),
110
                       systemdbuserr.message ? systemdbuserr.message : "watch setup failed");
111 112 113
        return NULL;
    }

114 115 116 117
    return bus;
}


118 119 120 121 122 123 124 125 126 127
/**
 * virDBusHasSystemBus:
 *
 * Check if dbus system bus is running. This does not
 * imply that we have a connection. DBus might be running
 * and refusing connections due to its client limit. The
 * latter must be treated as a fatal error.
 *
 * Return false if dbus is not available, true if probably available.
 */
128 129 130 131 132 133
bool
virDBusHasSystemBus(void)
{
    if (virDBusGetSystemBusInternal())
        return true;

134 135 136 137 138 139 140
    if (systemdbuserr.name &&
        (STREQ(systemdbuserr.name, "org.freedesktop.DBus.Error.FileNotFound") ||
         STREQ(systemdbuserr.name, "org.freedesktop.DBus.Error.NoServer"))) {
        VIR_DEBUG("System DBus not available: %s", NULLSTR(systemdbuserr.message));
        return false;
    }
    return true;
141 142 143
}


144 145 146 147
void virDBusCloseSystemBus(void)
{
    if (systembus && !sharedBus) {
        dbus_connection_close(systembus);
148
        dbus_connection_unref(systembus);
149 150 151 152
        systembus = NULL;
    }
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
static void virDBusSessionBusInit(void)
{
    sessionbus = virDBusBusInit(DBUS_BUS_SESSION, &sessiondbuserr);
}

DBusConnection *virDBusGetSessionBus(void)
{
    if (virOnce(&sessiononce, virDBusSessionBusInit) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to run one time DBus initializer"));
        return NULL;
    }

    if (!sessionbus) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to get DBus session bus connection: %s"),
                       sessiondbuserr.message ? sessiondbuserr.message : "watch setup failed");
        return NULL;
    }

    return sessionbus;
}

struct virDBusWatch
{
    int watch;
    DBusConnection *bus;
};

J
Ján Tomko 已提交
182 183
static void virDBusWatchCallback(int fdatch G_GNUC_UNUSED,
                                 int fd G_GNUC_UNUSED,
184 185 186
                                 int events, void *opaque)
{
    DBusWatch *watch = opaque;
187
    struct virDBusWatch *info;
188 189
    int dbus_flags = 0;

190 191
    info = dbus_watch_get_data(watch);

192 193 194 195 196 197 198 199 200
    if (events & VIR_EVENT_HANDLE_READABLE)
        dbus_flags |= DBUS_WATCH_READABLE;
    if (events & VIR_EVENT_HANDLE_WRITABLE)
        dbus_flags |= DBUS_WATCH_WRITABLE;
    if (events & VIR_EVENT_HANDLE_ERROR)
        dbus_flags |= DBUS_WATCH_ERROR;
    if (events & VIR_EVENT_HANDLE_HANGUP)
        dbus_flags |= DBUS_WATCH_HANGUP;

201 202
    if (dbus_watch_handle(watch, dbus_flags) == FALSE)
        VIR_DEBUG("dbus_watch_handle() returned FALSE");
203

204
    dbus_connection_ref(info->bus);
205
    while (dbus_connection_dispatch(info->bus) == DBUS_DISPATCH_DATA_REMAINS)
206
        /* keep dispatching while data remains */;
207
    dbus_connection_unref(info->bus);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
}


static int virDBusTranslateWatchFlags(int dbus_flags)
{
    unsigned int flags = 0;
    if (dbus_flags & DBUS_WATCH_READABLE)
        flags |= VIR_EVENT_HANDLE_READABLE;
    if (dbus_flags & DBUS_WATCH_WRITABLE)
        flags |= VIR_EVENT_HANDLE_WRITABLE;
    if (dbus_flags & DBUS_WATCH_ERROR)
        flags |= VIR_EVENT_HANDLE_ERROR;
    if (dbus_flags & DBUS_WATCH_HANGUP)
        flags |= VIR_EVENT_HANDLE_HANGUP;
    return flags;
}


226 227
static void virDBusWatchFree(void *data)
{
228 229 230 231 232
    struct virDBusWatch *info = data;
    VIR_FREE(info);
}

static dbus_bool_t virDBusAddWatch(DBusWatch *watch,
233
                                   void *data)
234 235 236 237 238 239
{
    int flags = 0;
    int fd;
    struct virDBusWatch *info;

    if (VIR_ALLOC(info) < 0)
240
        return FALSE;
241 242 243 244 245 246 247 248 249

    if (dbus_watch_get_enabled(watch))
        flags = virDBusTranslateWatchFlags(dbus_watch_get_flags(watch));

# if HAVE_DBUS_WATCH_GET_UNIX_FD
    fd = dbus_watch_get_unix_fd(watch);
# else
    fd = dbus_watch_get_fd(watch);
# endif
250
    dbus_watch_set_data(watch, info, virDBusWatchFree);
251
    info->bus = (DBusConnection *)data;
252 253 254 255
    info->watch = virEventAddHandle(fd, flags,
                                    virDBusWatchCallback,
                                    watch, NULL);
    if (info->watch < 0) {
256
        dbus_watch_set_data(watch, NULL, NULL);
257
        return FALSE;
258 259
    }

260
    return TRUE;
261 262 263 264
}


static void virDBusRemoveWatch(DBusWatch *watch,
J
Ján Tomko 已提交
265
                               void *data G_GNUC_UNUSED)
266 267 268 269 270 271 272 273 274 275
{
    struct virDBusWatch *info;

    info = dbus_watch_get_data(watch);

    (void)virEventRemoveHandle(info->watch);
}


static void virDBusToggleWatch(DBusWatch *watch,
J
Ján Tomko 已提交
276
                               void *data G_GNUC_UNUSED)
277 278 279 280 281 282 283 284 285 286 287 288
{
    int flags = 0;
    struct virDBusWatch *info;

    if (dbus_watch_get_enabled(watch))
        flags = virDBusTranslateWatchFlags(dbus_watch_get_flags(watch));

    info = dbus_watch_get_data(watch);

    (void)virEventUpdateHandle(info->watch, flags);
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
# define VIR_DBUS_TYPE_STACK_MAX_DEPTH 32

static const char virDBusBasicTypes[] = {
    DBUS_TYPE_BYTE,
    DBUS_TYPE_BOOLEAN,
    DBUS_TYPE_INT16,
    DBUS_TYPE_UINT16,
    DBUS_TYPE_INT32,
    DBUS_TYPE_UINT32,
    DBUS_TYPE_INT64,
    DBUS_TYPE_UINT64,
    DBUS_TYPE_DOUBLE,
    DBUS_TYPE_STRING,
    DBUS_TYPE_OBJECT_PATH,
    DBUS_TYPE_SIGNATURE,
};

306 307
static bool virDBusIsBasicType(char c)
{
308
    return !!memchr(virDBusBasicTypes, c, G_N_ELEMENTS(virDBusBasicTypes));
309 310 311 312 313 314 315 316 317 318 319 320 321
}

/*
 * All code related to virDBusMessageIterEncode and
 * virDBusMessageIterDecode is derived from systemd
 * bus_message_append_ap()/message_read_ap() in
 * bus-message.c under the terms of the LGPLv2+
 */
static int
virDBusSignatureLengthInternal(const char *s,
                               bool allowDict,
                               unsigned arrayDepth,
                               unsigned structDepth,
322 323
                               size_t *skiplen,
                               size_t *siglen)
324 325
{
    if (virDBusIsBasicType(*s) || *s == DBUS_TYPE_VARIANT) {
326
        *skiplen = *siglen = 1;
327 328 329 330
        return 0;
    }

    if (*s == DBUS_TYPE_ARRAY) {
331 332 333
        size_t skiplencont;
        size_t siglencont;
        bool arrayref = false;
334 335 336 337 338 339 340 341

        if (arrayDepth >= VIR_DBUS_TYPE_STACK_MAX_DEPTH) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Signature '%s' too deeply nested"),
                           s);
            return -1;
        }

342 343 344 345 346
        if (*(s + 1) == '&') {
            arrayref = true;
            s++;
        }

347 348 349 350
        if (virDBusSignatureLengthInternal(s + 1,
                                           true,
                                           arrayDepth + 1,
                                           structDepth,
351 352
                                           &skiplencont,
                                           &siglencont) < 0)
353 354
            return -1;

355 356 357 358
        *skiplen = skiplencont + 1;
        *siglen = siglencont + 1;
        if (arrayref)
            (*skiplen)++;
359 360 361 362 363 364 365 366 367 368 369 370 371
        return 0;
    }

    if (*s == DBUS_STRUCT_BEGIN_CHAR) {
        const char *p = s + 1;

        if (structDepth >= VIR_DBUS_TYPE_STACK_MAX_DEPTH) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Signature '%s' too deeply nested"),
                           s);
            return -1;
        }

372 373
        *skiplen = *siglen = 2;

374
        while (*p != DBUS_STRUCT_END_CHAR) {
375 376
            size_t skiplencont;
            size_t siglencont;
377 378 379 380 381

            if (virDBusSignatureLengthInternal(p,
                                               false,
                                               arrayDepth,
                                               structDepth + 1,
382 383
                                               &skiplencont,
                                               &siglencont) < 0)
384 385
                return -1;

386 387 388
            p += skiplencont;
            *skiplen += skiplencont;
            *siglen += siglencont;
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        }

        return 0;
    }

    if (*s == DBUS_DICT_ENTRY_BEGIN_CHAR && allowDict) {
        const char *p = s + 1;
        unsigned n = 0;
        if (structDepth >= VIR_DBUS_TYPE_STACK_MAX_DEPTH) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Signature '%s' too deeply nested"),
                           s);
            return -1;
        }

404 405
        *skiplen = *siglen = 2;

406
        while (*p != DBUS_DICT_ENTRY_END_CHAR) {
407 408
            size_t skiplencont;
            size_t siglencont;
409 410 411 412 413 414 415 416 417 418 419 420

            if (n == 0 && !virDBusIsBasicType(*p)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Dict entry in signature '%s' must be a basic type"),
                               s);
                return -1;
            }

            if (virDBusSignatureLengthInternal(p,
                                               false,
                                               arrayDepth,
                                               structDepth + 1,
421 422
                                               &skiplencont,
                                               &siglencont) < 0)
423 424
                return -1;

425 426 427
            p += skiplencont;
            *skiplen += skiplencont;
            *siglen += siglencont;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
            n++;
        }

        if (n != 2) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Dict entry in signature '%s' is wrong size"),
                           s);
            return -1;
        }

        return 0;
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unexpected signature '%s'"), s);
    return -1;
}


447
static int virDBusSignatureLength(const char *s, size_t *skiplen, size_t *siglen)
448
{
449
    return virDBusSignatureLengthInternal(s, true, 0, 0, skiplen, siglen);
450 451 452
}


453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
static char *virDBusCopyContainerSignature(const char *sig,
                                           size_t *skiplen,
                                           size_t *siglen)
{
    size_t i, j;
    char *contsig;
    bool isGroup;

    isGroup = (sig[0] == DBUS_STRUCT_BEGIN_CHAR ||
               sig[0] == DBUS_DICT_ENTRY_BEGIN_CHAR);

    if (virDBusSignatureLength(isGroup ? sig : sig + 1, skiplen, siglen) < 0)
        return NULL;

    if (VIR_ALLOC_N(contsig, *siglen + 1) < 0)
        return NULL;

    for (i = 0, j = 0; i < *skiplen && j < *siglen; i++) {
        if (sig[i + 1] == '&')
            continue;
        contsig[j] = sig[i + 1];
        j++;
    }
    contsig[*siglen] = '\0';
    VIR_DEBUG("Extracted '%s' from '%s'", contsig, sig);
    return contsig;
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

/* Ideally, we'd just call ourselves recursively on every
 * complex type. However, the state of a va_list that is
 * passed to a function is undefined after that function
 * returns. This means we need to decode the va_list linearly
 * in a single stackframe. We hence implement our own
 * home-grown stack in an array. */

typedef struct _virDBusTypeStack virDBusTypeStack;
struct _virDBusTypeStack {
    const char *types;
    size_t nstruct;
    size_t narray;
    DBusMessageIter *iter;
};

static int virDBusTypeStackPush(virDBusTypeStack **stack,
                                size_t *nstack,
                                DBusMessageIter *iter,
                                const char *types,
                                size_t nstruct,
                                size_t narray)
{
    if (*nstack >= VIR_DBUS_TYPE_STACK_MAX_DEPTH) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("DBus type too deeply nested"));
        return -1;
    }

    if (VIR_EXPAND_N(*stack, *nstack, 1) < 0)
        return -1;

    (*stack)[(*nstack) - 1].iter = iter;
    (*stack)[(*nstack) - 1].types = types;
    (*stack)[(*nstack) - 1].nstruct = nstruct;
    (*stack)[(*nstack) - 1].narray = narray;
517 518
    VIR_DEBUG("Pushed types='%s' nstruct=%zu narray=%zd",
              types, nstruct, (ssize_t)narray);
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    return 0;
}


static int virDBusTypeStackPop(virDBusTypeStack **stack,
                               size_t *nstack,
                               DBusMessageIter **iter,
                               const char **types,
                               size_t *nstruct,
                               size_t *narray)
{
    if (*nstack == 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("DBus type stack is empty"));
        return -1;
    }

    *iter = (*stack)[(*nstack) - 1].iter;
    *types = (*stack)[(*nstack) - 1].types;
    *nstruct = (*stack)[(*nstack) - 1].nstruct;
    *narray = (*stack)[(*nstack) - 1].narray;
540 541
    VIR_DEBUG("Popped types='%s' nstruct=%zu narray=%zd",
              *types, *nstruct, (ssize_t)*narray);
542 543 544 545 546 547 548 549 550 551
    VIR_SHRINK_N(*stack, *nstack, 1);

    return 0;
}


static void virDBusTypeStackFree(virDBusTypeStack **stack,
                                 size_t *nstack)
{
    size_t i;
J
John Ferlan 已提交
552 553 554 555

    if (!*stack)
        return;

556 557 558
    /* The iter in the first level of the stack is the
     * root iter which must not be freed
     */
559
    for (i = 1; i < *nstack; i++)
560 561 562 563 564
        VIR_FREE((*stack)[i].iter);
    VIR_FREE(*stack);
}


565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
static bool
virDBusIsAllowedRefType(const char *sig)
{
    if (*sig == '{') {
        if (strlen(sig) != 4)
            return false;
        if (!virDBusIsBasicType(sig[1]) ||
            !virDBusIsBasicType(sig[2]) ||
            sig[1] != sig[2])
            return false;
        if (sig[3] != '}')
            return false;
    } else {
        if (strlen(sig) != 1)
            return false;
        if (!virDBusIsBasicType(sig[0]))
            return false;
    }
    return true;
}


587 588 589 590 591 592 593 594 595 596 597 598 599
# define SET_NEXT_VAL(dbustype, vargtype, arrtype, sigtype, fmt) \
    do { \
        dbustype x; \
        if (arrayref) { \
            arrtype valarray = arrayptr; \
            x = (dbustype)*valarray; \
            valarray++; \
            arrayptr = valarray; \
        } else { \
            x = (dbustype)va_arg(args, vargtype); \
        } \
        if (!dbus_message_iter_append_basic(iter, sigtype, &x)) { \
            virReportError(VIR_ERR_INTERNAL_ERROR, \
600
                           _("Cannot append basic type %s"), #vargtype);\
601 602
            goto cleanup; \
        } \
603
        VIR_DEBUG("Appended basic type '" #dbustype "' varg '" #vargtype\
604
                  "' sig '%c' val '" fmt "'", sigtype, (vargtype)x); \
605 606
    } while (0)

607

608 609 610 611 612 613 614 615
static int
virDBusMessageIterEncode(DBusMessageIter *rootiter,
                         const char *types,
                         va_list args)
{
    int ret = -1;
    size_t narray;
    size_t nstruct;
616 617
    bool arrayref = false;
    void *arrayptr = NULL;
618 619 620
    virDBusTypeStack *stack = NULL;
    size_t nstack = 0;
    size_t siglen;
621
    size_t skiplen;
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    char *contsig = NULL;
    const char *vsig;
    DBusMessageIter *newiter = NULL;
    DBusMessageIter *iter = rootiter;

    VIR_DEBUG("rootiter=%p types=%s", rootiter, types);

    if (!types)
        return 0;

    narray = (size_t)-1;
    nstruct = strlen(types);

    for (;;) {
        const char *t;

638 639
        VIR_DEBUG("Loop nstack=%zu narray=%zd nstruct=%zu types='%s'",
                  nstack, (ssize_t)narray, nstruct, types);
640 641 642 643
        if (narray == 0 ||
            (narray == (size_t)-1 &&
             nstruct == 0)) {
            DBusMessageIter *thisiter = iter;
644 645 646 647 648
            if (*types != '}') {
                VIR_DEBUG("Reset array ref");
                arrayref = false;
                arrayptr = NULL;
            }
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
            VIR_DEBUG("Popping iter=%p", iter);
            if (nstack == 0)
                break;
            if (virDBusTypeStackPop(&stack, &nstack, &iter,
                                    &types, &nstruct, &narray) < 0)
                goto cleanup;
            VIR_DEBUG("Popped iter=%p", iter);

            if (!dbus_message_iter_close_container(iter, thisiter)) {
                if (thisiter != rootiter)
                    VIR_FREE(thisiter);
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Cannot close container iterator"));
                goto cleanup;
            }
            if (thisiter != rootiter)
                VIR_FREE(thisiter);
            continue;
        }

        t = types;
        if (narray != (size_t)-1) {
            narray--;
        } else {
            types++;
            nstruct--;
        }

        switch (*t) {
        case DBUS_TYPE_BYTE:
E
Eric Blake 已提交
679
            SET_NEXT_VAL(unsigned char, int, unsigned char *, *t, "%d");
680 681 682
            break;

        case DBUS_TYPE_BOOLEAN:
E
Eric Blake 已提交
683
            SET_NEXT_VAL(dbus_bool_t, int, bool *, *t, "%d");
684 685 686
            break;

        case DBUS_TYPE_INT16:
E
Eric Blake 已提交
687
            SET_NEXT_VAL(dbus_int16_t, int, short *, *t, "%d");
688 689 690
            break;

        case DBUS_TYPE_UINT16:
E
Eric Blake 已提交
691 692
            SET_NEXT_VAL(dbus_uint16_t, unsigned int, unsigned short *,
                         *t, "%d");
693 694 695
            break;

        case DBUS_TYPE_INT32:
E
Eric Blake 已提交
696
            SET_NEXT_VAL(dbus_int32_t, int, int *, *t, "%d");
697 698 699
            break;

        case DBUS_TYPE_UINT32:
E
Eric Blake 已提交
700 701
            SET_NEXT_VAL(dbus_uint32_t, unsigned int, unsigned int *,
                         *t, "%u");
702 703 704
            break;

        case DBUS_TYPE_INT64:
E
Eric Blake 已提交
705
            SET_NEXT_VAL(dbus_int64_t, long long, long long *, *t, "%lld");
706 707 708
            break;

        case DBUS_TYPE_UINT64:
E
Eric Blake 已提交
709 710
            SET_NEXT_VAL(dbus_uint64_t, unsigned long long,
                         unsigned long long *, *t, "%llu");
711 712 713
            break;

        case DBUS_TYPE_DOUBLE:
E
Eric Blake 已提交
714
            SET_NEXT_VAL(double, double, double *, *t, "%lf");
715 716 717 718 719
            break;

        case DBUS_TYPE_STRING:
        case DBUS_TYPE_OBJECT_PATH:
        case DBUS_TYPE_SIGNATURE:
E
Eric Blake 已提交
720
            SET_NEXT_VAL(char *, char *, char **, *t, "%s");
721 722 723
            break;

        case DBUS_TYPE_ARRAY:
724 725 726 727 728 729 730 731 732 733 734 735
            arrayptr = NULL;
            if (t[1] == '&') {
                VIR_DEBUG("Got array ref");
                t++;
                types++;
                nstruct--;
                arrayref = true;
            } else {
                VIR_DEBUG("Got array non-ref");
                arrayref = false;
            }

736
            if (!(contsig = virDBusCopyContainerSignature(t, &skiplen, &siglen)))
737 738
                goto cleanup;

739
            if (arrayref && !virDBusIsAllowedRefType(contsig)) {
740
                virReportError(VIR_ERR_INTERNAL_ERROR,
741 742
                               _("Got array ref but '%s' is not a single basic type "
                                 "or dict with matching key+value type"),
743 744 745 746
                               contsig);
                goto cleanup;
            }

747
            if (narray == (size_t)-1) {
748 749
                types += skiplen;
                nstruct -= skiplen;
750 751 752 753
            }

            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
754
            VIR_DEBUG("Contsig '%s' skip='%zu' len='%zu'", contsig, skiplen, siglen);
755 756 757 758 759
            if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
                                                  contsig, newiter))
                goto cleanup;
            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
760 761
                                     nstruct, narray) < 0) {
                VIR_FREE(newiter);
762
                goto cleanup;
763
            }
764
            VIR_FREE(contsig);
765
            iter = g_steal_pointer(&newiter);
766
            types = t + 1;
767
            nstruct = skiplen;
768 769 770
            narray = (size_t)va_arg(args, int);
            if (arrayref)
                arrayptr = va_arg(args, void *);
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
            break;

        case DBUS_TYPE_VARIANT:
            vsig = va_arg(args, const char *);
            if (!vsig) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing variant type signature"));
                goto cleanup;
            }
            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
            if (!dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
                                                  vsig, newiter))
                goto cleanup;
            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
787 788
                                     nstruct, narray) < 0) {
                VIR_FREE(newiter);
789
                goto cleanup;
790
            }
791
            iter = g_steal_pointer(&newiter);
792 793 794 795 796 797 798
            types = vsig;
            nstruct = strlen(types);
            narray = (size_t)-1;
            break;

        case DBUS_STRUCT_BEGIN_CHAR:
        case DBUS_DICT_ENTRY_BEGIN_CHAR:
799
            if (!(contsig = virDBusCopyContainerSignature(t, &skiplen, &siglen)))
800 801 802 803
                goto cleanup;

            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
804
            VIR_DEBUG("Contsig '%s' skip='%zu' len='%zu'", contsig, skiplen, siglen);
805 806 807 808 809 810
            if (!dbus_message_iter_open_container(iter,
                                                  *t == DBUS_STRUCT_BEGIN_CHAR ?
                                                  DBUS_TYPE_STRUCT : DBUS_TYPE_DICT_ENTRY,
                                                  NULL, newiter))
                goto cleanup;
            if (narray == (size_t)-1) {
811 812
                types += skiplen - 1;
                nstruct -= skiplen - 1;
813 814 815 816
            }

            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
817 818
                                     nstruct, narray) < 0) {
                VIR_FREE(newiter);
819
                goto cleanup;
820
            }
821
            VIR_FREE(contsig);
822
            iter = g_steal_pointer(&newiter);
823
            types = t + 1;
824
            nstruct = skiplen - 2;
825 826 827 828 829 830
            narray = (size_t)-1;

            break;

        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
831 832
                           _("Unknown type '%x' in signature '%s'"),
                           (int)*t, types);
833
            goto cleanup;
834 835 836 837 838
        }
    }

    ret = 0;

839
 cleanup:
840 841 842 843 844 845 846 847 848 849 850
    while (nstack > 0) {
        DBusMessageIter *thisiter = iter;
        VIR_DEBUG("Popping iter=%p", iter);
        ignore_value(virDBusTypeStackPop(&stack, &nstack, &iter,
                                         &types, &nstruct, &narray));
        VIR_DEBUG("Popped iter=%p", iter);

        if (thisiter != rootiter)
            VIR_FREE(thisiter);
    }

851 852 853 854 855 856 857 858
    virDBusTypeStackFree(&stack, &nstack);
    VIR_FREE(contsig);
    VIR_FREE(newiter);
    return ret;
}
# undef SET_NEXT_VAL


859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
# define GET_NEXT_VAL(dbustype, member, vargtype, fmt) \
    do { \
        DBusBasicValue v; \
        dbustype *x = (dbustype *)&v.member; \
        vargtype *y; \
        if (arrayref) { \
            VIR_DEBUG("Use arrayref"); \
            vargtype **xptrptr = arrayptr; \
            if (VIR_EXPAND_N(*xptrptr, *narrayptr, 1) < 0) \
                goto cleanup; \
            y = (*xptrptr + (*narrayptr - 1)); \
            VIR_DEBUG("Expanded to %zu", *narrayptr); \
        } else { \
            y = va_arg(args, vargtype *); \
        } \
        dbus_message_iter_get_basic(iter, x); \
        *y = *x; \
        VIR_DEBUG("Read basic type '" #dbustype "' varg '" #vargtype \
                  "' val '" fmt "'", (vargtype)*y); \
878 879 880 881 882 883 884 885 886 887 888
    } while (0)


static int
virDBusMessageIterDecode(DBusMessageIter *rootiter,
                         const char *types,
                         va_list args)
{
    int ret = -1;
    size_t narray;
    size_t nstruct;
889 890 891
    bool arrayref = false;
    void *arrayptr = NULL;
    size_t *narrayptr = 0;
892 893
    virDBusTypeStack *stack = NULL;
    size_t nstack = 0;
894
    size_t skiplen;
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    size_t siglen;
    char *contsig = NULL;
    const char *vsig;
    DBusMessageIter *newiter = NULL;
    DBusMessageIter *iter = rootiter;

    VIR_DEBUG("rootiter=%p types=%s", rootiter, types);

    if (!types)
        return 0;

    narray = (size_t)-1;
    nstruct = strlen(types);

    for (;;) {
        const char *t;
        bool advanceiter = true;

913 914
        VIR_DEBUG("Loop nstack=%zu narray=%zd nstruct=%zu type='%s'",
                  nstack, (ssize_t)narray, nstruct, types);
915 916 917 918 919 920 921 922 923 924 925
        if (narray == 0 ||
            (narray == (size_t)-1 &&
             nstruct == 0)) {
            DBusMessageIter *thisiter = iter;
            VIR_DEBUG("Popping iter=%p", iter);
            if (nstack == 0)
                break;
            if (virDBusTypeStackPop(&stack, &nstack, &iter,
                                    &types, &nstruct, &narray) < 0)
                goto cleanup;
            VIR_DEBUG("Popped iter=%p types=%s", iter, types);
926 927 928 929 930
            if (strchr(types, '}') == NULL) {
                arrayref = false;
                arrayptr = NULL;
                VIR_DEBUG("Clear array ref flag");
            }
931 932
            if (thisiter != rootiter)
                VIR_FREE(thisiter);
933 934 935 936 937 938 939
            if (arrayref) {
                if (!dbus_message_iter_has_next(iter))
                    narray = 0;
                else
                    narray = 1;
                VIR_DEBUG("Pop set narray=%zd", (ssize_t)narray);
            }
940 941 942 943 944 945 946 947 948 949 950 951 952
            if (!(narray == 0 ||
                  (narray == (size_t)-1 &&
                   nstruct == 0)) &&
                !dbus_message_iter_next(iter)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Not enough fields in message for signature"));
                goto cleanup;
            }
            continue;
        }

        t = types;
        if (narray != (size_t)-1) {
953 954
            if (!arrayref)
                narray--;
955 956 957 958 959 960 961
        } else {
            types++;
            nstruct--;
        }

        switch (*t) {
        case DBUS_TYPE_BYTE:
962
            GET_NEXT_VAL(unsigned char, byt, unsigned char, "%d");
963 964 965
            break;

        case DBUS_TYPE_BOOLEAN:
966
            GET_NEXT_VAL(dbus_bool_t, bool_val, bool, "%d");
967 968 969
            break;

        case DBUS_TYPE_INT16:
970
            GET_NEXT_VAL(dbus_int16_t, i16, short, "%d");
971 972 973
            break;

        case DBUS_TYPE_UINT16:
974
            GET_NEXT_VAL(dbus_uint16_t, u16, unsigned short, "%d");
975 976 977
            break;

        case DBUS_TYPE_INT32:
978
            GET_NEXT_VAL(dbus_uint32_t, i32, int, "%d");
979 980 981
            break;

        case DBUS_TYPE_UINT32:
982
            GET_NEXT_VAL(dbus_uint32_t, u32, unsigned int, "%u");
983 984 985
            break;

        case DBUS_TYPE_INT64:
986
            GET_NEXT_VAL(dbus_uint64_t, i64, long long, "%lld");
987 988 989
            break;

        case DBUS_TYPE_UINT64:
990
            GET_NEXT_VAL(dbus_uint64_t, u64, unsigned long long, "%llu");
991 992 993
            break;

        case DBUS_TYPE_DOUBLE:
994
            GET_NEXT_VAL(double, dbl, double, "%lf");
995 996 997 998 999 1000
            break;

        case DBUS_TYPE_STRING:
        case DBUS_TYPE_OBJECT_PATH:
        case DBUS_TYPE_SIGNATURE:
            do {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
                char **x;
                if (arrayref) {
                    char ***xptrptr = arrayptr;
                    if (VIR_EXPAND_N(*xptrptr, *narrayptr, 1) < 0)
                        goto cleanup;
                    x = (char **)(*xptrptr + (*narrayptr - 1));
                    VIR_DEBUG("Expanded to %zu", *narrayptr);
                } else {
                    x = (char **)va_arg(args, char **);
                }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
                char *s;
                dbus_message_iter_get_basic(iter, &s);
                if (VIR_STRDUP(*x, s) < 0)
                    goto cleanup;
                VIR_DEBUG("Read basic type 'char *' varg 'char **'"
                          "' val '%s'", *x);
            } while (0);
            break;

        case DBUS_TYPE_ARRAY:
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            arrayptr = NULL;
            if (t[1] == '&') {
                VIR_DEBUG("Got array ref");
                t++;
                types++;
                nstruct--;
                arrayref = true;
            } else {
                VIR_DEBUG("Got array non-ref");
                arrayref = false;
            }

1033
            advanceiter = false;
1034
            if (!(contsig = virDBusCopyContainerSignature(t, &skiplen, &siglen)))
1035 1036
                goto cleanup;

1037
            if (arrayref && !virDBusIsAllowedRefType(contsig)) {
1038
                virReportError(VIR_ERR_INTERNAL_ERROR,
1039
                               _("Got array ref but '%s' is not a single basic type / dict"),
1040 1041 1042 1043
                               contsig);
                goto cleanup;
            }

1044
            if (narray == (size_t)-1) {
1045 1046
                types += skiplen;
                nstruct -= skiplen;
1047 1048 1049 1050
            }

            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
1051 1052
            VIR_DEBUG("Array contsig='%s' skip=%'zu' len='%zu' types='%s'",
                      contsig, skiplen, siglen, types);
1053 1054 1055 1056 1057 1058
            dbus_message_iter_recurse(iter, newiter);
            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
                                     nstruct, narray) < 0)
                goto cleanup;
            VIR_FREE(contsig);
1059
            iter = g_steal_pointer(&newiter);
1060
            types = t + 1;
1061
            nstruct = skiplen;
1062 1063 1064 1065 1066 1067 1068 1069
            if (arrayref) {
                narrayptr = va_arg(args, size_t *);
                arrayptr = va_arg(args, void *);
                *narrayptr = 0;
                *(char **)arrayptr = NULL;
            } else {
                narray = va_arg(args, int);
            }
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
            break;

        case DBUS_TYPE_VARIANT:
            advanceiter = false;
            vsig = va_arg(args, const char *);
            if (!vsig) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Missing variant type signature"));
                goto cleanup;
            }
            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
            dbus_message_iter_recurse(iter, newiter);
            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
                                     nstruct, narray) < 0) {
                VIR_DEBUG("Push failed");
                goto cleanup;
            }
1089
            iter = g_steal_pointer(&newiter);
1090 1091 1092 1093 1094 1095 1096 1097
            types = vsig;
            nstruct = strlen(types);
            narray = (size_t)-1;
            break;

        case DBUS_STRUCT_BEGIN_CHAR:
        case DBUS_DICT_ENTRY_BEGIN_CHAR:
            advanceiter = false;
1098
            if (!(contsig = virDBusCopyContainerSignature(t, &skiplen, &siglen)))
1099 1100 1101 1102
                goto cleanup;

            if (VIR_ALLOC(newiter) < 0)
                goto cleanup;
1103 1104
            VIR_DEBUG("Dict/struct contsig='%s' skip='%zu' len='%zu' types='%s'",
                      contsig, skiplen, siglen, types);
1105 1106
            dbus_message_iter_recurse(iter, newiter);
            if (narray == (size_t)-1) {
1107 1108
                types += skiplen - 1;
                nstruct -= skiplen - 1;
1109 1110 1111 1112 1113 1114 1115
            }

            if (virDBusTypeStackPush(&stack, &nstack,
                                     iter, types,
                                     nstruct, narray) < 0)
                goto cleanup;
            VIR_FREE(contsig);
1116
            iter = g_steal_pointer(&newiter);
1117
            types = t + 1;
1118
            nstruct = skiplen - 2;
1119 1120 1121 1122 1123 1124
            narray = (size_t)-1;

            break;

        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
1125 1126 1127 1128 1129
                           _("Unknown type '%c' in signature '%s'"),
                           *t, types);
            goto cleanup;
        }

1130 1131 1132
        VIR_DEBUG("After nstack=%zu narray=%zd nstruct=%zu types='%s'",
                  nstack, (ssize_t)narray, nstruct, types);

1133
        if (arrayref) {
1134
            if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_INVALID) {
1135
                narray = 0;
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
            } else {
                if (advanceiter)
                    dbus_message_iter_next(iter);
                if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_INVALID) {
                    narray = 0;
                } else {
                    narray = 1;
                }
            }
            VIR_DEBUG("Set narray=%zd", (ssize_t)narray);
        } else {
            if (advanceiter &&
                !(narray == 0 ||
                  (narray == (size_t)-1 &&
                   nstruct == 0)) &&
                !dbus_message_iter_next(iter)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Not enough fields in message for signature"));
                goto cleanup;
            }
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        }
    }

    if (dbus_message_iter_has_next(iter)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Too many fields in message for signature"));
        goto cleanup;
    }

    ret = 0;

1167
 cleanup:
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    virDBusTypeStackFree(&stack, &nstack);
    VIR_FREE(contsig);
    VIR_FREE(newiter);
    return ret;
}
# undef GET_NEXT_VAL

int
virDBusMessageEncodeArgs(DBusMessage* msg,
                         const char *types,
                         va_list args)
{
    DBusMessageIter iter;
    int ret = -1;

    memset(&iter, 0, sizeof(iter));

    dbus_message_iter_init_append(msg, &iter);

    ret = virDBusMessageIterEncode(&iter, types, args);

    return ret;
}


int virDBusMessageDecodeArgs(DBusMessage* msg,
                             const char *types,
                             va_list args)
{
    DBusMessageIter iter;
    int ret = -1;

    if (!dbus_message_iter_init(msg, &iter)) {
        if (*types != '\0') {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("No args present for signature %s"),
                           types);
        } else {
            ret = 0;
        }
        goto cleanup;
    }

    ret = virDBusMessageIterDecode(&iter, types, args);

1213
 cleanup:
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    return ret;
}


int virDBusMessageEncode(DBusMessage* msg,
                         const char *types,
                         ...)
{
    int ret;
    va_list args;
    va_start(args, types);
    ret = virDBusMessageEncodeArgs(msg, types, args);
    va_end(args);
    return ret;
}


1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
/**
 * virDBusMessageDecode:
 * @msg: the reply to decode
 * @types: type signature for following return values
 * @...: pointers in which to store return values
 *
 * The @types type signature is the same format as
 * that used for the virDBusCallMethod. The difference
 * is that each variadic parameter must be a pointer to
 * be filled with the values. eg instead of passing an
 * 'int', pass an 'int *'.
 *
 */
int
virDBusMessageDecode(DBusMessage* msg,
                     const char *types,
                     ...)
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
{
    int ret;
    va_list args;
    va_start(args, types);
    ret = virDBusMessageDecodeArgs(msg, types, args);
    va_end(args);
    return ret;
}

# define VIR_DBUS_METHOD_CALL_TIMEOUT_MILLIS 30 * 1000

/**
1260 1261
 * virDBusCreateMethodV:
 * @call: pointer to be filled with a method call message
1262 1263
 * @destination: bus identifier of the target service
 * @path: object path of the target service
E
Eric Blake 已提交
1264
 * @iface: the interface of the object
1265 1266
 * @member: the name of the method in the interface
 * @types: type signature for following method arguments
1267
 * @args: method arguments
1268
 *
1269 1270
 * This creates a DBus method call message and saves a
 * pointer to it in @call. The @destination, @path, @iface
1271 1272
 * and @member parameters identify the object method to
 * be invoked. The optional @replyout parameter will be
1273 1274
 * filled with any reply to the method call. The method
 * can be later invoked using virDBusCall.
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
 *
 * The @types parameter is a DBus signature describing
 * the method call parameters which will be provided
 * as variadic args. Each character in @types must
 * correspond to one of the following DBus codes for
 * basic types:
 *
 * 'y' - 8-bit byte, promoted to an 'int'
 * 'b' - bool value, promoted to an 'int'
 * 'n' - 16-bit signed integer, promoted to an 'int'
 * 'q' - 16-bit unsigned integer, promoted to an 'int'
 * 'i' - 32-bit signed integer, passed as an 'int'
 * 'u' - 32-bit unsigned integer, passed as an 'int'
 * 'x' - 64-bit signed integer, passed as a 'long long'
 * 't' - 64-bit unsigned integer, passed as an 'unsigned long long'
 * 'd' - 8-byte floating point, passed as a 'double'
 * 's' - NUL-terminated string, in UTF-8
 * 'o' - NUL-terminated string, representing a valid object path
 * 'g' - NUL-terminated string, representing a valid type signature
 *
 * or use one of the compound types
 *
 * 'a' - array of values
 * 'v' - a variadic type.
 * '(' - start of a struct
 * ')' - end of a struct
 * '{' - start of a dictionary entry (pair of types)
 * '}' - start of a dictionary entry (pair of types)
 *
E
Eric Blake 已提交
1304 1305 1306
 * At this time, there is no support for Unix fd's ('h'), which only
 * newer DBus supports.
 *
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
 * Passing values in variadic args for basic types is
 * simple, the value is just passed directly using the
 * corresponding C type listed against the type code
 * above. Note how any integer value smaller than an
 * 'int' is promoted to an 'int' by the C rules for
 * variadic args.
 *
 * Passing values in variadic args for compound types
 * requires a little further explanation.
 *
 * - Variant: the first arg is a string containing
 *   the type signature for the values to be stored
 *   inside the variant. This is then followed by
 *   the values corresponding to the type signature
 *   in the normal manner.
 *
 * - Array: when 'a' appears in a type signature, it
 *   must be followed by a single type describing the
 *   array element type. For example 'as' is an array
 *   of strings. 'a(is)' is an array of structs, each
 *   struct containing an int and a string.
 *
 *   The first variadic arg for an array, is an 'int'
 *   specifying the number of elements in the array.
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
 *   This is then followed by additional variadic args,
 *   one for each element of the array.
 *
 * - Array reference: when 'a' appears in a type signature,
 *   followed by '&', this signifies an array passed by
 *   reference.
 *
 *   Array references may only be used when the
 *   element values are basic types, or a dict
 *   entry where both keys and values are using
 *   the same basic type.
 *
 *   The first variadic arg for an array, is an 'int'
 *   specifying the number of elements in the array.
 *   When the element is a basic type, the second
 *   variadic arg is a pointer to an array containing
 *   the element values. When the element is a dict
 *   entry, the second variadic arg is a pointer to
 *   an array containing the dict keys, and the
 *   third variadic arg is a pointer to an array
 *   containing the dict values.
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
 *
 * - Struct: when a '(' appears in a type signature,
 *   it must be followed by one or more types describing
 *   the elements in the array, terminated by a ')'.
 *
 * - Dict entry: when a '{' appears in a type signature it
 *   must be followed by exactly two types, one describing
 *   the type of the hash key, the other describing the
 *   type of the hash entry. The hash key type must be
 *   a basic type, not a compound type.
 *
 * Example signatures, with their corresponding variadic
 * args:
 *
 * - "biiss" - some basic types
 *
 *     (true, 7, 42, "hello", "world")
 *
 * - "as" - an array with a basic type element
 *
 *     (3, "one", "two", "three")
 *
 * - "a(is)" - an array with a struct element
 *
 *     (3, 1, "one", 2, "two", 3, "three")
 *
 * - "svs" - some basic types with a variant as an int
 *
 *     ("hello", "i", 3, "world")
 *
 * - "svs" - some basic types with a variant as an array of ints
 *
 *     ("hello", "ai", 4, 1, 2, 3, 4, "world")
 *
 * - "a{ss}" - a hash table (aka array + dict entry)
 *
 *     (3, "title", "Mr", "forename", "Joe", "surname", "Bloggs")
 *
 * - "a{sv}" - a hash table (aka array + dict entry)
 *
 *     (3, "email", "s", "joe@blogs.com", "age", "i", 35,
 *      "address", "as", 3, "Some house", "Some road", "some city")
 */
1395 1396 1397 1398 1399 1400 1401
int virDBusCreateMethodV(DBusMessage **call,
                         const char *destination,
                         const char *path,
                         const char *iface,
                         const char *member,
                         const char *types,
                         va_list args)
1402 1403 1404
{
    int ret = -1;

1405 1406 1407 1408
    if (!(*call = dbus_message_new_method_call(destination,
                                               path,
                                               iface,
                                               member))) {
1409 1410 1411 1412
        virReportOOMError();
        goto cleanup;
    }

1413
    if (virDBusMessageEncodeArgs(*call, types, args) < 0) {
1414
        virDBusMessageUnref(*call);
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
        *call = NULL;
        goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}


/**
 * virDBusCreateMethod:
 * @call: pointer to be filled with a method call message
 * @destination: bus identifier of the target service
 * @path: object path of the target service
 * @iface: the interface of the object
 * @member: the name of the method in the interface
 * @types: type signature for following method arguments
 * @...: method arguments
 *
 * See virDBusCreateMethodV for a description of the
 * behaviour of this method.
 */
int virDBusCreateMethod(DBusMessage **call,
                        const char *destination,
                        const char *path,
                        const char *iface,
                        const char *member,
                        const char *types, ...)
{
    va_list args;
    int ret;

1448
    va_start(args, types);
1449 1450
    ret = virDBusCreateMethodV(call, destination, path,
                               iface, member, types, args);
1451 1452
    va_end(args);

1453 1454 1455 1456
    return ret;
}


1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
/**
 * virDBusCreateReplyV:
 * @reply: pointer to be filled with a method reply message
 * @types: type signature for following method arguments
 * @args: method arguments
 *
 * This creates a DBus method reply message and saves a
 * pointer to it in @reply.
 *
 * The @types parameter is a DBus signature describing
 * the method call parameters which will be provided
 * as variadic args. See virDBusCreateMethodV for a
 * description of this parameter.
 */
1471
int virDBusCreateReplyV(DBusMessage **reply,
1472 1473 1474 1475 1476
                        const char *types,
                        va_list args)
{
    int ret = -1;

1477
    if (!(*reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN))) {
1478 1479 1480 1481 1482
        virReportOOMError();
        goto cleanup;
    }

    if (virDBusMessageEncodeArgs(*reply, types, args) < 0) {
1483
        virDBusMessageUnref(*reply);
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
        *reply = NULL;
        goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}


/**
 * virDBusCreateReply:
 * @reply: pointer to be filled with a method reply message
 * @types: type signature for following method arguments
 * @...: method arguments
 *
 * See virDBusCreateReplyV for a description of the
 * behaviour of this method.
 */
1503
int virDBusCreateReply(DBusMessage **reply,
1504 1505 1506 1507 1508 1509
                       const char *types, ...)
{
    va_list args;
    int ret;

    va_start(args, types);
1510
    ret = virDBusCreateReplyV(reply, types, args);
1511 1512 1513 1514 1515 1516
    va_end(args);

    return ret;
}


1517 1518 1519 1520 1521
/**
 * virDBusCall:
 * @conn: a DBus connection
 * @call: pointer to a message to send
 * @replyout: pointer to receive reply message, or NULL
1522
 * @error: pointer to receive error message
1523 1524 1525 1526 1527 1528 1529
 *
 * This invokes a method encoded in @call on a remote
 * service on the DBus bus @conn. The optional @replyout
 * parameter will be filled with any reply to the method
 * call. The virDBusMethodReply method can be used to
 * decode the return values.
 *
1530 1531 1532 1533 1534 1535
 * If @error is NULL then a libvirt error will be raised
 * when a DBus error is received and the return value will
 * be -1. If @error is non-NULL then any DBus error will
 * be saved into that object and the return value will
 * be 0.
 *
1536 1537
 * Returns 0 on success, or -1 upon error
 */
C
Cole Robinson 已提交
1538 1539 1540 1541
static int
virDBusCall(DBusConnection *conn,
            DBusMessage *call,
            DBusMessage **replyout,
1542
            virErrorPtr error)
1543

1544 1545
{
    DBusMessage *reply = NULL;
1546
    DBusError localerror;
1547
    int ret = -1;
1548
    const char *iface, *member, *path, *dest;
1549

1550 1551 1552
    dbus_error_init(&localerror);
    if (error)
        memset(error, 0, sizeof(*error));
1553

1554 1555 1556 1557 1558 1559 1560 1561 1562
    iface = dbus_message_get_interface(call);
    member = dbus_message_get_member(call);
    path = dbus_message_get_path(call);
    dest = dbus_message_get_destination(call);

    PROBE(DBUS_METHOD_CALL,
          "'%s.%s' on '%s' at '%s'",
          iface, member, path, dest);

1563 1564 1565
    if (!(reply = dbus_connection_send_with_reply_and_block(conn,
                                                            call,
                                                            VIR_DBUS_METHOD_CALL_TIMEOUT_MILLIS,
1566
                                                            &localerror))) {
1567 1568 1569
        PROBE(DBUS_METHOD_ERROR,
              "'%s.%s' on '%s' at '%s' error %s: %s",
              iface, member, path, dest,
1570 1571
              localerror.name,
              localerror.message);
1572
        if (error) {
1573 1574 1575 1576 1577 1578 1579
            error->level = VIR_ERR_ERROR;
            error->code = VIR_ERR_DBUS_SERVICE;
            error->domain = VIR_FROM_DBUS;
            if (VIR_STRDUP(error->message, localerror.message) < 0)
                goto cleanup;
            if (VIR_STRDUP(error->str1, localerror.name) < 0)
                goto cleanup;
1580
            ret = 0;
1581
        } else {
1582
            virReportError(VIR_ERR_DBUS_SERVICE, _("%s: %s"), member,
1583
                           localerror.message ? : _("unknown error"));
1584
        }
1585 1586 1587
        goto cleanup;
    }

1588 1589 1590 1591
    PROBE(DBUS_METHOD_REPLY,
          "'%s.%s' on '%s' at '%s'",
          iface, member, path, dest);

1592 1593
    ret = 0;

1594
 cleanup:
1595 1596 1597
    if (ret < 0 && error)
        virResetError(error);
    dbus_error_free(&localerror);
1598 1599 1600 1601
    if (reply) {
        if (ret == 0 && replyout)
            *replyout = reply;
        else
1602
            virDBusMessageUnref(reply);
1603 1604 1605 1606 1607
    }
    return ret;
}


1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
/**
 * virDBusCallMethod:
 * @conn: a DBus connection
 * @replyout: pointer to receive reply message, or NULL
 * @destination: bus identifier of the target service
 * @path: object path of the target service
 * @iface: the interface of the object
 * @member: the name of the method in the interface
 * @types: type signature for following method arguments
 * @...: method arguments
 *
 * This invokes a method on a remote service on the
 * DBus bus @conn. The @destination, @path, @iface
 * and @member parameters identify the object method to
 * be invoked. The optional @replyout parameter will be
 * filled with any reply to the method call. The
 * virDBusMethodReply method can be used to decode the
 * return values.
 *
 * The @types parameter is a DBus signature describing
 * the method call parameters which will be provided
 * as variadic args. See virDBusCreateMethodV for a
 * description of this parameter.
 *
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
 *
 * If @error is NULL then a libvirt error will be raised
 * when a DBus error is received and the return value will
 * be -1. If @error is non-NULL then any DBus error will
 * be saved into that object and the return value will
 * be 0. If an error occurs while encoding method args
 * the return value will always be -1 regardless of whether
 * @error is set.
 *
 * Returns 0 on success, or -1 upon error
1642 1643 1644
 */
int virDBusCallMethod(DBusConnection *conn,
                      DBusMessage **replyout,
1645
                      virErrorPtr error,
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                      const char *destination,
                      const char *path,
                      const char *iface,
                      const char *member,
                      const char *types, ...)
{
    DBusMessage *call = NULL;
    int ret = -1;
    va_list args;

    va_start(args, types);
    ret = virDBusCreateMethodV(&call, destination, path,
                               iface, member, types, args);
    va_end(args);
    if (ret < 0)
        goto cleanup;

1663
    ret = virDBusCall(conn, call, replyout, error);
1664 1665

 cleanup:
1666
    virDBusMessageUnref(call);
1667 1668 1669 1670
    return ret;
}


1671
static int virDBusIsServiceInList(const char *listMethod, const char *name)
1672 1673 1674 1675 1676 1677 1678 1679 1680
{
    DBusConnection *conn;
    DBusMessage *reply = NULL;
    DBusMessageIter iter, sub;
    int ret = -1;

    if (!virDBusHasSystemBus())
        return -2;

1681 1682
    if (!(conn = virDBusGetSystemBus()))
        return -1;
1683 1684 1685

    if (virDBusCallMethod(conn,
                          &reply,
1686
                          NULL,
1687 1688 1689
                          "org.freedesktop.DBus",
                          "/org/freedesktop/DBus",
                          "org.freedesktop.DBus",
1690
                          listMethod,
C
Cédric Bosdonnat 已提交
1691
                          NULL) < 0)
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
        return ret;

    if (!dbus_message_iter_init(reply, &iter) ||
        dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Reply message incorrect"));
        goto cleanup;
    }

    ret = -2;
    dbus_message_iter_recurse(&iter, &sub);
    while (dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING) {
        const char *service = NULL;

        dbus_message_iter_get_basic(&sub, &service);
        dbus_message_iter_next(&sub);

        if (STREQ(service, name)) {
            ret = 0;
            break;
        }
    }

 cleanup:
1716
    virDBusMessageUnref(reply);
1717 1718 1719
    return ret;
}

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
/**
 * virDBusIsServiceEnabled:
 * @name: service name
 *
 * Returns 0 if service is available, -1 on fatal error, or -2 if service is not available
 */
int virDBusIsServiceEnabled(const char *name)
{
    int ret = virDBusIsServiceInList("ListActivatableNames", name);

    VIR_DEBUG("Service %s is %s", name, ret ? "unavailable" : "available");

    return ret;
}
1734

1735 1736 1737 1738
/**
 * virDBusIsServiceRegistered
 * @name: service name
 *
N
Nitesh Konkar 已提交
1739
 * Returns 0 if service is registered, -1 on fatal error, or -2 if service is not registered
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
 */
int virDBusIsServiceRegistered(const char *name)
{
    int ret = virDBusIsServiceInList("ListNames", name);

    VIR_DEBUG("Service %s is %s", name, ret ? "not registered" : "registered");

    return ret;
}

1750 1751
void virDBusMessageUnref(DBusMessage *msg)
{
1752 1753
    if (msg)
        dbus_message_unref(msg);
1754 1755
}

1756
#else /* ! WITH_DBUS */
J
Ján Tomko 已提交
1757
void virDBusSetSharedBus(bool shared G_GNUC_UNUSED)
1758 1759 1760 1761
{
    /* nothing */
}

1762 1763
DBusConnection *virDBusGetSystemBus(void)
{
1764 1765
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
1766 1767 1768
    return NULL;
}

1769 1770 1771 1772 1773 1774 1775 1776

bool
virDBusHasSystemBus(void)
{
    VIR_DEBUG("DBus support not compiled into this binary");
    return false;
}

1777 1778 1779 1780
void virDBusCloseSystemBus(void)
{
    /* nothing */
}
1781

1782 1783 1784 1785 1786 1787
DBusConnection *virDBusGetSessionBus(void)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return NULL;
}
1788

J
Ján Tomko 已提交
1789 1790 1791 1792 1793 1794
int virDBusCreateMethod(DBusMessage **call G_GNUC_UNUSED,
                        const char *destination G_GNUC_UNUSED,
                        const char *path G_GNUC_UNUSED,
                        const char *iface G_GNUC_UNUSED,
                        const char *member G_GNUC_UNUSED,
                        const char *types G_GNUC_UNUSED, ...)
1795 1796 1797 1798 1799 1800
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1801 1802 1803 1804 1805 1806 1807
int virDBusCreateMethodV(DBusMessage **call G_GNUC_UNUSED,
                         const char *destination G_GNUC_UNUSED,
                         const char *path G_GNUC_UNUSED,
                         const char *iface G_GNUC_UNUSED,
                         const char *member G_GNUC_UNUSED,
                         const char *types G_GNUC_UNUSED,
                         va_list args G_GNUC_UNUSED)
1808 1809 1810 1811 1812 1813
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1814 1815 1816
int virDBusCreateReplyV(DBusMessage **reply G_GNUC_UNUSED,
                        const char *types G_GNUC_UNUSED,
                        va_list args G_GNUC_UNUSED)
1817 1818 1819 1820 1821 1822
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1823 1824
int virDBusCreateReply(DBusMessage **reply G_GNUC_UNUSED,
                       const char *types G_GNUC_UNUSED, ...)
1825 1826 1827 1828 1829 1830
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1831 1832 1833 1834 1835 1836 1837 1838
int virDBusCallMethod(DBusConnection *conn G_GNUC_UNUSED,
                      DBusMessage **reply G_GNUC_UNUSED,
                      virErrorPtr error G_GNUC_UNUSED,
                      const char *destination G_GNUC_UNUSED,
                      const char *path G_GNUC_UNUSED,
                      const char *iface G_GNUC_UNUSED,
                      const char *member G_GNUC_UNUSED,
                      const char *types G_GNUC_UNUSED, ...)
1839 1840 1841 1842 1843 1844 1845
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}


J
Ján Tomko 已提交
1846 1847
int virDBusMessageEncode(DBusMessage* msg G_GNUC_UNUSED,
                         const char *types G_GNUC_UNUSED,
1848 1849 1850 1851 1852 1853 1854
                         ...)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1855 1856
int virDBusMessageDecode(DBusMessage* msg G_GNUC_UNUSED,
                         const char *types G_GNUC_UNUSED,
1857 1858 1859 1860 1861 1862 1863
                         ...)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("DBus support not compiled into this binary"));
    return -1;
}

J
Ján Tomko 已提交
1864
int virDBusIsServiceEnabled(const char *name G_GNUC_UNUSED)
1865 1866 1867 1868 1869
{
    VIR_DEBUG("DBus support not compiled into this binary");
    return -2;
}

J
Ján Tomko 已提交
1870
int virDBusIsServiceRegistered(const char *name G_GNUC_UNUSED)
1871 1872 1873 1874 1875
{
    VIR_DEBUG("DBus support not compiled into this binary");
    return -2;
}

J
Ján Tomko 已提交
1876
void virDBusMessageUnref(DBusMessage *msg G_GNUC_UNUSED)
1877 1878 1879
{
    /* nothing */
}
1880
#endif /* ! WITH_DBUS */
1881 1882 1883 1884 1885 1886 1887 1888 1889

bool virDBusErrorIsUnknownMethod(virErrorPtr err)
{
    return err->domain == VIR_FROM_DBUS &&
        err->code == VIR_ERR_DBUS_SERVICE &&
        err->level == VIR_ERR_ERROR &&
        STREQ_NULLABLE("org.freedesktop.DBus.Error.UnknownMethod",
                       err->str1);
}