esx_vi.c 93.4 KB
Newer Older
1 2 3 4

/*
 * esx_vi.c: client for the VMware VI API 2.5 to manage ESX hosts
 *
5
 * Copyright (C) 2010 Red Hat, Inc.
6
 * Copyright (C) 2009-2010 Matthias Bolte <matthias.bolte@googlemail.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include <libxml/parser.h>
#include <libxml/xpathInternals.h>

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "util.h"
#include "uuid.h"
34
#include "xml.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "esx_vi.h"
#include "esx_vi_methods.h"
#include "esx_util.h"

#define VIR_FROM_THIS VIR_FROM_ESX



#define ESX_VI__SOAP__RESPONSE_XPATH(_type)                                   \
    ((char *)"/soapenv:Envelope/soapenv:Body/"                                \
               "vim:"_type"Response/vim:returnval")



#define ESX_VI__TEMPLATE__ALLOC(_type)                                        \
    int                                                                       \
51
    esxVI_##_type##_Alloc(esxVI_##_type **ptrptr)                             \
52
    {                                                                         \
53
        return esxVI_Alloc((void **)ptrptr, sizeof(esxVI_##_type));           \
54 55
    }

56 57


58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#define ESX_VI__TEMPLATE__FREE(_type, _body)                                  \
    void                                                                      \
    esxVI_##_type##_Free(esxVI_##_type **ptrptr)                              \
    {                                                                         \
        esxVI_##_type *item = NULL;                                           \
                                                                              \
        if (ptrptr == NULL || *ptrptr == NULL) {                              \
            return;                                                           \
        }                                                                     \
                                                                              \
        item = *ptrptr;                                                       \
                                                                              \
        _body                                                                 \
                                                                              \
        VIR_FREE(*ptrptr);                                                    \
    }



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Context
 */

/* esxVI_Context_Alloc */
ESX_VI__TEMPLATE__ALLOC(Context);

/* esxVI_Context_Free */
ESX_VI__TEMPLATE__FREE(Context,
{
    VIR_FREE(item->url);
M
Matthias Bolte 已提交
88
    VIR_FREE(item->ipAddress);
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

    if (item->curl_handle != NULL) {
        curl_easy_cleanup(item->curl_handle);
    }

    if (item->curl_headers != NULL) {
        curl_slist_free_all(item->curl_headers);
    }

    virMutexDestroy(&item->curl_lock);

    VIR_FREE(item->username);
    VIR_FREE(item->password);
    esxVI_ServiceContent_Free(&item->service);
    esxVI_UserSession_Free(&item->session);
    esxVI_ManagedObjectReference_Free(&item->datacenter);
    esxVI_ManagedObjectReference_Free(&item->vmFolder);
    esxVI_ManagedObjectReference_Free(&item->hostFolder);
    esxVI_SelectionSpec_Free(&item->fullTraversalSpecList);
});

static size_t
M
Matthias Bolte 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
esxVI_CURL_ReadString(char *data, size_t size, size_t nmemb, void *ptrptr)
{
    const char *content = *(const char **)ptrptr;
    size_t available = 0;
    size_t requested = size * nmemb;

    if (content == NULL) {
        return 0;
    }

    available = strlen(content);

    if (available == 0) {
        return 0;
    }

    if (requested > available) {
        requested = available;
    }

    memcpy(data, content, requested);

    *(const char **)ptrptr = content + requested;

    return requested;
}

static size_t
esxVI_CURL_WriteBuffer(char *data, size_t size, size_t nmemb, void *buffer)
140 141 142 143 144 145 146 147 148 149 150 151 152 153
{
    if (buffer != NULL) {
        virBufferAdd((virBufferPtr) buffer, data, size * nmemb);

        return size * nmemb;
    }

    return 0;
}

#define ESX_VI__CURL__ENABLE_DEBUG_OUTPUT 0

#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
static int
M
Matthias Bolte 已提交
154 155
esxVI_CURL_Debug(CURL *curl ATTRIBUTE_UNUSED, curl_infotype type,
                 char *info, size_t size, void *data ATTRIBUTE_UNUSED)
156
{
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    char *buffer = NULL;

    /*
     * The libcurl documentation says:
     *
     *    The data pointed to by the char * passed to this function WILL NOT
     *    be zero terminated, but will be exactly of the size as told by the
     *    size_t argument.
     *
     * To handle this properly in order to pass the info string to VIR_DEBUG
     * a zero terminated copy of the info string has to be allocated.
     */
    if (VIR_ALLOC_N(buffer, size + 1) < 0) {
        return 0;
    }

    if (virStrncpy(buffer, info, size, size + 1) == NULL) {
        VIR_FREE(buffer);
        return 0;
    }

178 179
    switch (type) {
      case CURLINFO_TEXT:
180 181 182 183 184
        if (size > 0 && buffer[size - 1] == '\n') {
            buffer[size - 1] = '\0';
        }

        VIR_DEBUG("CURLINFO_TEXT [[[[%s]]]]", buffer);
185 186 187
        break;

      case CURLINFO_HEADER_IN:
188
        VIR_DEBUG("CURLINFO_HEADER_IN [[[[%s]]]]", buffer);
189 190 191
        break;

      case CURLINFO_HEADER_OUT:
192
        VIR_DEBUG("CURLINFO_HEADER_OUT [[[[%s]]]]", buffer);
193 194 195
        break;

      case CURLINFO_DATA_IN:
196
        VIR_DEBUG("CURLINFO_DATA_IN [[[[%s]]]]", buffer);
197 198 199
        break;

      case CURLINFO_DATA_OUT:
200
        VIR_DEBUG("CURLINFO_DATA_OUT [[[[%s]]]]", buffer);
201 202 203 204 205 206 207
        break;

      default:
        VIR_DEBUG0("unknown");
        break;
    }

208 209
    VIR_FREE(buffer);

210 211 212 213
    return 0;
}
#endif

214
static int
215
esxVI_CURL_Perform(esxVI_Context *ctx, const char *url)
216 217 218 219 220 221 222 223 224 225
{
    CURLcode errorCode;
    long responseCode = 0;
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
    const char *redirectUrl = NULL;
#endif

    errorCode = curl_easy_perform(ctx->curl_handle);

    if (errorCode != CURLE_OK) {
226
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
227
                     _("curl_easy_perform() returned an error: %s (%d) : %s"),
228
                     curl_easy_strerror(errorCode), errorCode, ctx->curl_error);
229 230 231 232 233 234 235
        return -1;
    }

    errorCode = curl_easy_getinfo(ctx->curl_handle, CURLINFO_RESPONSE_CODE,
                                  &responseCode);

    if (errorCode != CURLE_OK) {
236
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
237 238
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned an "
                       "error: %s (%d) : %s"), curl_easy_strerror(errorCode),
239
                     errorCode, ctx->curl_error);
240 241 242 243
        return -1;
    }

    if (responseCode < 0) {
244 245 246
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("curl_easy_getinfo(CURLINFO_RESPONSE_CODE) returned a "
                       "negative response code"));
247 248 249 250 251 252 253 254 255
        return -1;
    }

    if (responseCode == 301) {
#if LIBCURL_VERSION_NUM >= 0x071202 /* 7.18.2 */
        errorCode = curl_easy_getinfo(ctx->curl_handle, CURLINFO_REDIRECT_URL,
                                      &redirectUrl);

        if (errorCode != CURLE_OK) {
256
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
257 258 259
                         _("curl_easy_getinfo(CURLINFO_REDIRECT_URL) returned "
                           "an error: %s (%d) : %s"),
                         curl_easy_strerror(errorCode),
260
                         errorCode, ctx->curl_error);
261
        } else {
262
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
263
                         _("The server redirects from '%s' to '%s'"), url,
264 265 266
                         redirectUrl);
        }
#else
267
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
268
                     _("The server redirects from '%s'"), url);
269 270 271 272 273 274 275 276
#endif

        return -1;
    }

    return responseCode;
}

277
int
278
esxVI_Context_Connect(esxVI_Context *ctx, const char *url,
M
Matthias Bolte 已提交
279
                      const char *ipAddress, const char *username,
M
Matthias Bolte 已提交
280
                      const char *password, esxUtil_ParsedQuery *parsedQuery)
281
{
M
Matthias Bolte 已提交
282
    int result = -1;
283 284 285 286
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *datacenterList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

M
Matthias Bolte 已提交
287 288 289
    if (ctx == NULL || url == NULL || ipAddress == NULL || username == NULL ||
        password == NULL || ctx->url != NULL || ctx->service != NULL ||
        ctx->curl_handle != NULL || ctx->curl_headers != NULL) {
290
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
291
        return -1;
292 293
    }

294 295
    if (esxVI_String_DeepCopyValue(&ctx->url, url) < 0 ||
        esxVI_String_DeepCopyValue(&ctx->ipAddress, ipAddress) < 0) {
M
Matthias Bolte 已提交
296
        goto cleanup;
297 298 299 300 301
    }

    ctx->curl_handle = curl_easy_init();

    if (ctx->curl_handle == NULL) {
302 303
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL"));
M
Matthias Bolte 已提交
304
        goto cleanup;
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    }

    ctx->curl_headers = curl_slist_append(ctx->curl_headers, "Content-Type: "
                                          "text/xml; charset=UTF-8");

    /*
     * Add a dummy expect header to stop CURL from waiting for a response code
     * 100 (Continue) from the server before continuing the POST operation.
     * Waiting for this response would slowdown each communication with the
     * server by approx. 2 sec, because the server doesn't send the expected
     * 100 (Continue) response and the wait times out resulting in wasting
     * approx. 2 sec per POST operation.
     */
    ctx->curl_headers = curl_slist_append(ctx->curl_headers,
                                          "Expect: nothing");

    if (ctx->curl_headers == NULL) {
322 323
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not build CURL header list"));
M
Matthias Bolte 已提交
324
        goto cleanup;
325 326 327 328 329
    }

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, ctx->url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_USERAGENT, "libvirt-esx");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HEADER, 0);
330
    curl_easy_setopt(ctx->curl_handle, CURLOPT_FOLLOWLOCATION, 0);
M
Matthias Bolte 已提交
331 332 333 334
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYPEER,
                     parsedQuery->noVerify ? 0 : 1);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_SSL_VERIFYHOST,
                     parsedQuery->noVerify ? 0 : 2);
335 336
    curl_easy_setopt(ctx->curl_handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPHEADER, ctx->curl_headers);
M
Matthias Bolte 已提交
337 338
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READFUNCTION,
                     esxVI_CURL_ReadString);
339
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEFUNCTION,
M
Matthias Bolte 已提交
340
                     esxVI_CURL_WriteBuffer);
341 342
    curl_easy_setopt(ctx->curl_handle, CURLOPT_ERRORBUFFER,
                     ctx->curl_error);
343
#if ESX_VI__CURL__ENABLE_DEBUG_OUTPUT
344 345
    curl_easy_setopt(ctx->curl_handle, CURLOPT_DEBUGFUNCTION, esxVI_CURL_Debug);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_VERBOSE, 1);
346 347
#endif

M
Matthias Bolte 已提交
348 349 350 351 352 353 354 355 356
    if (parsedQuery->proxy) {
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXY,
                         parsedQuery->proxy_hostname);
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXYTYPE,
                         parsedQuery->proxy_type);
        curl_easy_setopt(ctx->curl_handle, CURLOPT_PROXYPORT,
                         parsedQuery->proxy_port);
    }

357
    if (virMutexInit(&ctx->curl_lock) < 0) {
358 359
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not initialize CURL mutex"));
M
Matthias Bolte 已提交
360
        goto cleanup;
361 362 363 364 365 366
    }

    ctx->username = strdup(username);
    ctx->password = strdup(password);

    if (ctx->username == NULL || ctx->password == NULL) {
367
        virReportOOMError();
M
Matthias Bolte 已提交
368
        goto cleanup;
369 370
    }

371
    if (esxVI_RetrieveServiceContent(ctx, &ctx->service) < 0) {
M
Matthias Bolte 已提交
372
        goto cleanup;
373 374
    }

375 376 377
    if (STREQ(ctx->service->about->apiType, "HostAgent") ||
        STREQ(ctx->service->about->apiType, "VirtualCenter")) {
        if (STRPREFIX(ctx->service->about->apiVersion, "2.5")) {
378
            ctx->apiVersion = esxVI_APIVersion_25;
379
        } else if (STRPREFIX(ctx->service->about->apiVersion, "4.0")) {
380
            ctx->apiVersion = esxVI_APIVersion_40;
381
        } else {
382
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
383 384
                         _("Expecting VI API major/minor version '2.5' or '4.0' "
                           "but found '%s'"), ctx->service->about->apiVersion);
M
Matthias Bolte 已提交
385
            goto cleanup;
386
        }
387

388 389 390 391
        if (STREQ(ctx->service->about->productLineId, "gsx")) {
            if (STRPREFIX(ctx->service->about->version, "2.0")) {
                ctx->productVersion = esxVI_ProductVersion_GSX20;
            } else {
392
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
393 394
                             _("Expecting GSX major/minor version '2.0' but "
                               "found '%s'"), ctx->service->about->version);
M
Matthias Bolte 已提交
395
                goto cleanup;
396 397 398 399 400 401 402 403
            }
        } else if (STREQ(ctx->service->about->productLineId, "esx") ||
                   STREQ(ctx->service->about->productLineId, "embeddedEsx")) {
            if (STRPREFIX(ctx->service->about->version, "3.5")) {
                ctx->productVersion = esxVI_ProductVersion_ESX35;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_ESX40;
            } else {
404
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
405 406
                             _("Expecting ESX major/minor version '3.5' or "
                               "'4.0' but found '%s'"),
407
                             ctx->service->about->version);
M
Matthias Bolte 已提交
408
                goto cleanup;
409 410 411 412 413 414 415
            }
        } else if (STREQ(ctx->service->about->productLineId, "vpx")) {
            if (STRPREFIX(ctx->service->about->version, "2.5")) {
                ctx->productVersion = esxVI_ProductVersion_VPX25;
            } else if (STRPREFIX(ctx->service->about->version, "4.0")) {
                ctx->productVersion = esxVI_ProductVersion_VPX40;
            } else {
416
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
417 418
                             _("Expecting VPX major/minor version '2.5' or '4.0' "
                               "but found '%s'"), ctx->service->about->version);
M
Matthias Bolte 已提交
419
                goto cleanup;
420
            }
421
        } else {
422
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
423 424
                         _("Expecting product 'gsx' or 'esx' or 'embeddedEsx' "
                           "or 'vpx' but found '%s'"),
425
                         ctx->service->about->productLineId);
M
Matthias Bolte 已提交
426
            goto cleanup;
427 428
        }
    } else {
429
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
430 431
                     _("Expecting VI API type 'HostAgent' or 'VirtualCenter' "
                       "but found '%s'"), ctx->service->about->apiType);
M
Matthias Bolte 已提交
432
        goto cleanup;
433 434
    }

435
    if (esxVI_Login(ctx, username, password, NULL, &ctx->session) < 0) {
M
Matthias Bolte 已提交
436
        goto cleanup;
437 438
    }

439
    esxVI_BuildFullTraversalSpecList(&ctx->fullTraversalSpecList);
440

441
    if (esxVI_String_AppendValueListToList(&propertyNameList,
442 443
                                           "vmFolder\0"
                                           "hostFolder\0") < 0) {
M
Matthias Bolte 已提交
444
        goto cleanup;
445 446 447
    }

    /* Get pointer to Datacenter for later use */
448
    if (esxVI_LookupObjectContentByType(ctx, ctx->service->rootFolder,
449 450 451
                                        "Datacenter", propertyNameList,
                                        esxVI_Boolean_True,
                                        &datacenterList) < 0) {
M
Matthias Bolte 已提交
452
        goto cleanup;
453 454 455
    }

    if (datacenterList == NULL) {
456 457 458
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve the 'datacenter' object from the "
                       "VI host/center"));
M
Matthias Bolte 已提交
459
        goto cleanup;
460 461 462 463 464 465 466 467 468 469
    }

    ctx->datacenter = datacenterList->obj;
    datacenterList->obj = NULL;

    /* Get pointer to vmFolder and hostFolder for later use */
    for (dynamicProperty = datacenterList->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "vmFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
470
                  (dynamicProperty->val, &ctx->vmFolder)) {
M
Matthias Bolte 已提交
471
                goto cleanup;
472 473 474
            }
        } else if (STREQ(dynamicProperty->name, "hostFolder")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
475
                  (dynamicProperty->val, &ctx->hostFolder)) {
M
Matthias Bolte 已提交
476
                goto cleanup;
477 478 479 480 481 482 483
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (ctx->vmFolder == NULL || ctx->hostFolder == NULL) {
484 485 486
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("The 'datacenter' object is missing the "
                       "'vmFolder'/'hostFolder' property"));
M
Matthias Bolte 已提交
487
        goto cleanup;
488 489
    }

M
Matthias Bolte 已提交
490 491
    result = 0;

492 493 494 495 496 497 498 499
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&datacenterList);

    return result;
}

int
500
esxVI_Context_DownloadFile(esxVI_Context *ctx, const char *url, char **content)
501 502
{
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
503
    int responseCode = 0;
504 505

    if (content == NULL || *content != NULL) {
506
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
507
        return -1;
508 509 510 511 512 513
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &buffer);
M
Matthias Bolte 已提交
514
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
515 516
    curl_easy_setopt(ctx->curl_handle, CURLOPT_HTTPGET, 1);

517
    responseCode = esxVI_CURL_Perform(ctx, url);
518

519
    virMutexUnlock(&ctx->curl_lock);
520

521
    if (responseCode < 0) {
M
Matthias Bolte 已提交
522
        goto cleanup;
523
    } else if (responseCode != 200) {
524
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
525
                     _("HTTP response code %d for download from '%s'"),
526
                     responseCode, url);
M
Matthias Bolte 已提交
527
        goto cleanup;
528 529 530
    }

    if (virBufferError(&buffer)) {
531
        virReportOOMError();
M
Matthias Bolte 已提交
532
        goto cleanup;
533 534 535 536
    }

    *content = virBufferContentAndReset(&buffer);

M
Matthias Bolte 已提交
537 538 539 540 541
  cleanup:
    if (*content == NULL) {
        virBufferFreeAndReset(&buffer);
        return -1;
    }
542

M
Matthias Bolte 已提交
543
    return 0;
544 545
}

M
Matthias Bolte 已提交
546
int
547 548
esxVI_Context_UploadFile(esxVI_Context *ctx, const char *url,
                         const char *content)
M
Matthias Bolte 已提交
549
{
550
    int responseCode = 0;
M
Matthias Bolte 已提交
551 552

    if (content == NULL) {
553
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
554 555 556 557 558 559 560 561 562 563
        return -1;
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_READDATA, &content);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 1);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_INFILESIZE, strlen(content));

564
    responseCode = esxVI_CURL_Perform(ctx, url);
M
Matthias Bolte 已提交
565 566 567

    virMutexUnlock(&ctx->curl_lock);

568 569 570
    if (responseCode < 0) {
        return -1;
    } else if (responseCode != 200 && responseCode != 201) {
571
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
572
                     _("HTTP response code %d for upload to '%s'"),
573
                     responseCode, url);
M
Matthias Bolte 已提交
574 575 576 577 578 579
        return -1;
    }

    return 0;
}

580
int
581 582 583
esxVI_Context_Execute(esxVI_Context *ctx, const char *methodName,
                      const char *request, esxVI_Response **response,
                      esxVI_Occurrence occurrence)
584
{
M
Matthias Bolte 已提交
585
    int result = -1;
586 587
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_Fault *fault = NULL;
588 589 590
    char *xpathExpression = NULL;
    xmlXPathContextPtr xpathContext = NULL;
    xmlNodePtr responseNode = NULL;
591

592
    if (request == NULL || response == NULL || *response != NULL) {
593
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
594
        return -1;
595 596
    }

597
    if (esxVI_Response_Alloc(response) < 0) {
M
Matthias Bolte 已提交
598
        return -1;
599 600 601 602 603 604
    }

    virMutexLock(&ctx->curl_lock);

    curl_easy_setopt(ctx->curl_handle, CURLOPT_URL, ctx->url);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_WRITEDATA, &buffer);
M
Matthias Bolte 已提交
605
    curl_easy_setopt(ctx->curl_handle, CURLOPT_UPLOAD, 0);
606 607
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDS, request);
    curl_easy_setopt(ctx->curl_handle, CURLOPT_POSTFIELDSIZE, strlen(request));
608

609
    (*response)->responseCode = esxVI_CURL_Perform(ctx, ctx->url);
610

611
    virMutexUnlock(&ctx->curl_lock);
612

613
    if ((*response)->responseCode < 0) {
M
Matthias Bolte 已提交
614
        goto cleanup;
615 616 617
    }

    if (virBufferError(&buffer)) {
618
        virReportOOMError();
M
Matthias Bolte 已提交
619
        goto cleanup;
620 621
    }

622
    (*response)->content = virBufferContentAndReset(&buffer);
623

624
    if ((*response)->responseCode == 500 || (*response)->responseCode == 200) {
625 626
        (*response)->document = xmlReadDoc(BAD_CAST (*response)->content, "",
                                           NULL, XML_PARSE_NONET);
627

628
        if ((*response)->document == NULL) {
629
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
630
                         _("Response for call to '%s' could not be parsed"),
631
                         methodName);
M
Matthias Bolte 已提交
632
            goto cleanup;
633 634
        }

635
        if (xmlDocGetRootElement((*response)->document) == NULL) {
636
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
637
                         _("Response for call to '%s' is an empty XML document"),
638
                         methodName);
M
Matthias Bolte 已提交
639
            goto cleanup;
640 641
        }

642
        xpathContext = xmlXPathNewContext((*response)->document);
643

644
        if (xpathContext == NULL) {
645 646
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not create XPath context"));
M
Matthias Bolte 已提交
647
            goto cleanup;
648 649
        }

650
        xmlXPathRegisterNs(xpathContext, BAD_CAST "soapenv",
651
                           BAD_CAST "http://schemas.xmlsoap.org/soap/envelope/");
652
        xmlXPathRegisterNs(xpathContext, BAD_CAST "vim", BAD_CAST "urn:vim25");
653

654 655
        if ((*response)->responseCode == 500) {
            (*response)->node =
656
              virXPathNode("/soapenv:Envelope/soapenv:Body/soapenv:Fault",
657
                           xpathContext);
658

659
            if ((*response)->node == NULL) {
660
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
661 662
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, XPath evaluation failed"),
663
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
664
                goto cleanup;
665 666
            }

667 668
            if (esxVI_Fault_Deserialize((*response)->node, &fault) < 0) {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
669 670
                             _("HTTP response code %d for call to '%s'. "
                               "Fault is unknown, deserialization failed"),
671
                             (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
672
                goto cleanup;
673 674
            }

675
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
676 677
                         _("HTTP response code %d for call to '%s'. "
                           "Fault: %s - %s"), (*response)->responseCode,
678
                         methodName, fault->faultcode, fault->faultstring);
679 680 681 682 683 684

            /* FIXME: Dump raw response until detail part gets deserialized */
            VIR_DEBUG("HTTP response code %d for call to '%s' [[[[%s]]]]",
                      (*response)->responseCode, methodName,
                      (*response)->content);

M
Matthias Bolte 已提交
685
            goto cleanup;
686 687 688 689
        } else {
            if (virAsprintf(&xpathExpression,
                            "/soapenv:Envelope/soapenv:Body/vim:%sResponse",
                            methodName) < 0) {
690
                virReportOOMError();
M
Matthias Bolte 已提交
691
                goto cleanup;
692
            }
693

694
            responseNode = virXPathNode(xpathExpression, xpathContext);
695

696
            if (responseNode == NULL) {
697
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
698 699
                             _("XPath evaluation of response for call to '%s' "
                               "failed"), methodName);
M
Matthias Bolte 已提交
700
                goto cleanup;
701 702
            }

703
            xpathContext->node = responseNode;
704
            (*response)->node = virXPathNode("./vim:returnval", xpathContext);
705

706 707
            switch (occurrence) {
              case esxVI_Occurrence_RequiredItem:
708 709
                if ((*response)->node == NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
710 711
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
712
                    goto cleanup;
713 714
                } else if ((*response)->node->next != NULL) {
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
715 716
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
717
                    goto cleanup;
718 719 720 721 722
                }

                break;

              case esxVI_Occurrence_RequiredList:
723
                if ((*response)->node == NULL) {
724
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
725 726
                                 _("Call to '%s' returned an empty result, "
                                   "expecting a non-empty result"), methodName);
M
Matthias Bolte 已提交
727
                    goto cleanup;
728 729 730 731 732 733 734
                }

                break;

              case esxVI_Occurrence_OptionalItem:
                if ((*response)->node != NULL &&
                    (*response)->node->next != NULL) {
735
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
736 737
                                 _("Call to '%s' returned a list, expecting "
                                   "exactly one item"), methodName);
M
Matthias Bolte 已提交
738
                    goto cleanup;
739 740 741 742
                }

                break;

743
              case esxVI_Occurrence_OptionalList:
744 745 746 747 748
                /* Any amount of items is valid */
                break;

              case esxVI_Occurrence_None:
                if ((*response)->node != NULL) {
749
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
750 751
                                 _("Call to '%s' returned something, expecting "
                                   "an empty result"), methodName);
M
Matthias Bolte 已提交
752
                    goto cleanup;
753 754 755 756 757
                }

                break;

              default:
758 759
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Invalid argument (occurrence)"));
M
Matthias Bolte 已提交
760
                goto cleanup;
761
            }
762
        }
763
    } else {
764
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
765
                     _("HTTP response code %d for call to '%s'"),
766
                     (*response)->responseCode, methodName);
M
Matthias Bolte 已提交
767
        goto cleanup;
768 769
    }

M
Matthias Bolte 已提交
770 771
    result = 0;

772
  cleanup:
M
Matthias Bolte 已提交
773 774 775 776 777 778
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
        esxVI_Response_Free(response);
        esxVI_Fault_Free(&fault);
    }

779 780 781 782
    VIR_FREE(xpathExpression);
    xmlXPathFreeContext(xpathContext);

    return result;
783 784 785 786 787
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
788
 * Response
789 790
 */

791 792
/* esxVI_Response_Alloc */
ESX_VI__TEMPLATE__ALLOC(Response);
793

794 795
/* esxVI_Response_Free */
ESX_VI__TEMPLATE__FREE(Response,
796
{
797
    VIR_FREE(item->content);
798 799 800 801 802 803 804 805 806 807 808 809 810

    if (item->document != NULL) {
        xmlFreeDoc(item->document);
    }
});



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Enumeration
 */

int
811
esxVI_Enumeration_CastFromAnyType(const esxVI_Enumeration *enumeration,
812 813 814 815 816
                                  esxVI_AnyType *anyType, int *value)
{
    int i;

    if (anyType == NULL || value == NULL) {
817
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
818 819 820 821 822
        return -1;
    }

    *value = 0; /* undefined */

823
    if (anyType->type != enumeration->type) {
824
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
825
                     _("Expecting type '%s' but found '%s'"),
826 827
                     esxVI_Type_ToString(enumeration->type),
                     esxVI_Type_ToString(anyType->type));
828 829 830 831 832 833 834 835 836 837
        return -1;
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(anyType->value, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
            return 0;
        }
    }

838
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
839
                 _("Unknown value '%s' for %s"), anyType->value,
840
                 esxVI_Type_ToString(enumeration->type));
841 842 843 844 845

    return -1;
}

int
846
esxVI_Enumeration_Serialize(const esxVI_Enumeration *enumeration,
847
                            int value, const char *element, virBufferPtr output)
848 849 850 851 852
{
    int i;
    const char *name = NULL;

    if (element == NULL || output == NULL) {
853
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
854 855 856 857
        return -1;
    }

    if (value == 0) { /* undefined */
858
        return 0;
859 860 861 862 863 864 865 866 867 868
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (value == enumeration->values[i].value) {
            name = enumeration->values[i].name;
            break;
        }
    }

    if (name == NULL) {
869
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
870 871 872
        return -1;
    }

873 874
    ESV_VI__XML_TAG__OPEN(output, element,
                          esxVI_Type_ToString(enumeration->type));
875 876 877 878 879 880 881 882 883

    virBufferAdd(output, name, -1);

    ESV_VI__XML_TAG__CLOSE(output, element);

    return 0;
}

int
884
esxVI_Enumeration_Deserialize(const esxVI_Enumeration *enumeration,
885 886 887
                              xmlNodePtr node, int *value)
{
    int i;
M
Matthias Bolte 已提交
888
    int result = -1;
889 890 891
    char *name = NULL;

    if (value == NULL) {
892
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
893
        return -1;
894 895 896 897
    }

    *value = 0; /* undefined */

898
    if (esxVI_String_DeserializeValue(node, &name) < 0) {
M
Matthias Bolte 已提交
899
        return -1;
900 901 902 903 904
    }

    for (i = 0; enumeration->values[i].name != NULL; ++i) {
        if (STREQ(name, enumeration->values[i].name)) {
            *value = enumeration->values[i].value;
M
Matthias Bolte 已提交
905 906
            result = 0;
            break;
907 908 909
        }
    }

M
Matthias Bolte 已提交
910 911 912 913
    if (result < 0) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, _("Unknown value '%s' for %s"),
                     name, esxVI_Type_ToString(enumeration->type));
    }
914 915 916 917 918 919 920 921 922 923 924 925 926

    VIR_FREE(name);

    return result;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * List
 */

int
927
esxVI_List_Append(esxVI_List **list, esxVI_List *item)
928 929 930 931
{
    esxVI_List *next = NULL;

    if (list == NULL || item == NULL) {
932
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
        return -1;
    }

    if (*list == NULL) {
        *list = item;
        return 0;
    }

    next = *list;

    while (next->_next != NULL) {
        next = next->_next;
    }

    next->_next = item;

    return 0;
}

int
953
esxVI_List_DeepCopy(esxVI_List **destList, esxVI_List *srcList,
954 955 956 957 958 959 960
                    esxVI_List_DeepCopyFunc deepCopyFunc,
                    esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *dest = NULL;
    esxVI_List *src = NULL;

    if (destList == NULL || *destList != NULL) {
961
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
962
        return -1;
963 964 965
    }

    for (src = srcList; src != NULL; src = src->_next) {
966 967
        if (deepCopyFunc(&dest, src) < 0 ||
            esxVI_List_Append(destList, dest) < 0) {
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
            goto failure;
        }

        dest = NULL;
    }

    return 0;

  failure:
    freeFunc(&dest);
    freeFunc(destList);

    return -1;
}

983
int
984
esxVI_List_CastFromAnyType(esxVI_AnyType *anyType, esxVI_List **list,
985 986 987
                           esxVI_List_CastFromAnyTypeFunc castFromAnyTypeFunc,
                           esxVI_List_FreeFunc freeFunc)
{
M
Matthias Bolte 已提交
988
    int result = -1;
989 990 991 992 993 994
    xmlNodePtr childNode = NULL;
    esxVI_AnyType *childAnyType = NULL;
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        castFromAnyTypeFunc == NULL || freeFunc == NULL) {
995
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
996
        return -1;
997 998 999 1000 1001 1002 1003
    }

    if (anyType == NULL) {
        return 0;
    }

    if (! STRPREFIX(anyType->other, "ArrayOf")) {
1004
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1005
                     _("Expecting type to begin with 'ArrayOf' but found '%s'"),
1006
                     anyType->other);
1007
        return -1;
1008 1009
    }

1010
    for (childNode = anyType->node->children; childNode != NULL;
1011 1012
         childNode = childNode->next) {
        if (childNode->type != XML_ELEMENT_NODE) {
1013
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1014
                         _("Wrong XML element type %d"), childNode->type);
M
Matthias Bolte 已提交
1015
            goto cleanup;
1016 1017 1018 1019
        }

        esxVI_AnyType_Free(&childAnyType);

1020 1021 1022
        if (esxVI_AnyType_Deserialize(childNode, &childAnyType) < 0 ||
            castFromAnyTypeFunc(childAnyType, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
M
Matthias Bolte 已提交
1023
            goto cleanup;
1024 1025 1026 1027 1028
        }

        item = NULL;
    }

M
Matthias Bolte 已提交
1029 1030
    result = 0;

1031
  cleanup:
M
Matthias Bolte 已提交
1032 1033 1034 1035 1036
    if (result < 0) {
        freeFunc(&item);
        freeFunc(list);
    }

1037 1038 1039 1040 1041
    esxVI_AnyType_Free(&childAnyType);

    return result;
}

1042
int
1043
esxVI_List_Serialize(esxVI_List *list, const char *element,
1044
                     virBufferPtr output,
1045 1046 1047 1048 1049
                     esxVI_List_SerializeFunc serializeFunc)
{
    esxVI_List *item = NULL;

    if (element == NULL || output == NULL || serializeFunc == NULL) {
1050
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1051 1052 1053 1054
        return -1;
    }

    if (list == NULL) {
1055
        return 0;
1056 1057 1058
    }

    for (item = list; item != NULL; item = item->_next) {
1059
        if (serializeFunc(item, element, output) < 0) {
1060 1061 1062 1063 1064 1065 1066 1067
            return -1;
        }
    }

    return 0;
}

int
1068
esxVI_List_Deserialize(xmlNodePtr node, esxVI_List **list,
1069 1070 1071 1072 1073 1074 1075
                       esxVI_List_DeserializeFunc deserializeFunc,
                       esxVI_List_FreeFunc freeFunc)
{
    esxVI_List *item = NULL;

    if (list == NULL || *list != NULL ||
        deserializeFunc == NULL || freeFunc == NULL) {
1076
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1077 1078 1079 1080 1081 1082 1083 1084 1085
        return -1;
    }

    if (node == NULL) {
        return 0;
    }

    for (; node != NULL; node = node->next) {
        if (node->type != XML_ELEMENT_NODE) {
1086
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1087
                         _("Wrong XML element type %d"), node->type);
1088 1089 1090
            goto failure;
        }

1091 1092
        if (deserializeFunc(node, &item) < 0 ||
            esxVI_List_Append(list, item) < 0) {
1093 1094 1095
            goto failure;
        }

1096
        item = NULL;
1097 1098 1099 1100 1101
    }

    return 0;

  failure:
1102
    freeFunc(&item);
1103 1104 1105 1106 1107 1108 1109 1110 1111
    freeFunc(list);

    return -1;
}



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Utility and Convenience Functions
1112 1113 1114 1115
 *
 * Function naming scheme:
 *  - 'lookup' functions query the ESX or vCenter for information
 *  - 'get' functions get information from a local object
1116 1117 1118
 */

int
1119
esxVI_Alloc(void **ptrptr, size_t size)
1120 1121
{
    if (ptrptr == NULL || *ptrptr != NULL) {
1122
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1123 1124 1125 1126
        return -1;
    }

    if (virAllocN(ptrptr, size, 1) < 0) {
1127
        virReportOOMError();
1128 1129 1130 1131 1132 1133
        return -1;
    }

    return 0;
}

1134 1135


1136
int
1137
esxVI_BuildFullTraversalSpecItem(esxVI_SelectionSpec **fullTraversalSpecList,
1138 1139 1140 1141 1142 1143 1144 1145
                                 const char *name, const char *type,
                                 const char *path, const char *selectSetNames)
{
    esxVI_TraversalSpec *traversalSpec = NULL;
    esxVI_SelectionSpec *selectionSpec = NULL;
    const char *currentSelectSetName = NULL;

    if (fullTraversalSpecList == NULL) {
1146
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1147 1148 1149
        return -1;
    }

1150
    if (esxVI_TraversalSpec_Alloc(&traversalSpec) < 0 ||
1151
        esxVI_String_DeepCopyValue(&traversalSpec->name, name) < 0 ||
1152 1153
        esxVI_String_DeepCopyValue(&traversalSpec->type, type) < 0 ||
        esxVI_String_DeepCopyValue(&traversalSpec->path, path) < 0) {
1154 1155 1156 1157 1158 1159 1160 1161 1162
        goto failure;
    }

    traversalSpec->skip = esxVI_Boolean_False;

    if (selectSetNames != NULL) {
        currentSelectSetName = selectSetNames;

        while (currentSelectSetName != NULL && *currentSelectSetName != '\0') {
1163 1164
            if (esxVI_SelectionSpec_Alloc(&selectionSpec) < 0 ||
                esxVI_String_DeepCopyValue(&selectionSpec->name,
1165
                                           currentSelectSetName) < 0 ||
1166
                esxVI_SelectionSpec_AppendToList(&traversalSpec->selectSet,
1167 1168 1169 1170
                                                 selectionSpec) < 0) {
                goto failure;
            }

1171
            selectionSpec = NULL;
1172 1173 1174 1175
            currentSelectSetName += strlen(currentSelectSetName) + 1;
        }
    }

1176
    if (esxVI_SelectionSpec_AppendToList(fullTraversalSpecList,
1177 1178
                                         esxVI_SelectionSpec_DynamicCast
                                           (traversalSpec)) < 0) {
1179 1180 1181 1182 1183 1184 1185
        goto failure;
    }

    return 0;

  failure:
    esxVI_TraversalSpec_Free(&traversalSpec);
1186
    esxVI_SelectionSpec_Free(&selectionSpec);
1187 1188 1189 1190 1191 1192 1193

    return -1;
}



int
1194
esxVI_BuildFullTraversalSpecList(esxVI_SelectionSpec **fullTraversalSpecList)
1195 1196
{
    if (fullTraversalSpecList == NULL || *fullTraversalSpecList != NULL) {
1197
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1198 1199 1200
        return -1;
    }

1201
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1202 1203 1204
                                         "visitFolders",
                                         "Folder", "childEntity",
                                         "visitFolders\0"
M
Matthias Bolte 已提交
1205
                                         "datacenterToDatastore\0"
1206 1207 1208 1209
                                         "datacenterToVmFolder\0"
                                         "datacenterToHostFolder\0"
                                         "computeResourceToHost\0"
                                         "computeResourceToResourcePool\0"
M
Matthias Bolte 已提交
1210
                                         "hostSystemToVm\0"
1211 1212 1213 1214
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

M
Matthias Bolte 已提交
1215
    /* Traversal through datastore branch */
1216
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1217 1218 1219 1220 1221 1222
                                         "datacenterToDatastore",
                                         "Datacenter", "datastore",
                                         NULL) < 0) {
        goto failure;
    }

1223
    /* Traversal through vmFolder branch */
1224
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1225 1226 1227 1228 1229 1230 1231
                                         "datacenterToVmFolder",
                                         "Datacenter", "vmFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through hostFolder branch  */
1232
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1233 1234 1235 1236 1237 1238 1239
                                         "datacenterToHostFolder",
                                         "Datacenter", "hostFolder",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Traversal through host branch  */
1240
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1241 1242 1243 1244 1245 1246 1247
                                         "computeResourceToHost",
                                         "ComputeResource", "host",
                                         NULL) < 0) {
        goto failure;
    }

    /* Traversal through resourcePool branch */
1248
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1249 1250 1251 1252 1253 1254 1255 1256
                                         "computeResourceToResourcePool",
                                         "ComputeResource", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1257
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1258 1259 1260 1261 1262 1263 1264 1265
                                         "resourcePoolToResourcePool",
                                         "ResourcePool", "resourcePool",
                                         "resourcePoolToResourcePool\0"
                                         "resourcePoolToVm\0") < 0) {
        goto failure;
    }

    /* Recurse through all hosts */
1266
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
M
Matthias Bolte 已提交
1267
                                         "hostSystemToVm",
1268 1269 1270 1271 1272 1273
                                         "HostSystem", "vm",
                                         "visitFolders\0") < 0) {
        goto failure;
    }

    /* Recurse through all resource pools */
1274
    if (esxVI_BuildFullTraversalSpecItem(fullTraversalSpecList,
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
                                         "resourcePoolToVm",
                                         "ResourcePool", "vm", NULL) < 0) {
        goto failure;
    }

    return 0;

  failure:
    esxVI_SelectionSpec_Free(fullTraversalSpecList);

    return -1;
}



/*
 * Can't use the SessionIsActive() function here, because at least
 * 'ESX Server 3.5.0 build-64607' returns an 'method not implemented' fault if
 * you try to call it. Query the session manager for the current session of
 * this connection instead and re-login if there is no current session for this
 * connection.
1296 1297
 *
 * Update: 'ESX 4.0.0 build-171294' doesn't implement this method.
1298 1299 1300 1301
 */
#define ESX_VI_USE_SESSION_IS_ACTIVE 0

int
1302
esxVI_EnsureSession(esxVI_Context *ctx)
1303 1304 1305 1306
{
#if ESX_VI_USE_SESSION_IS_ACTIVE
    esxVI_Boolean active = esxVI_Boolean_Undefined;
#else
M
Matthias Bolte 已提交
1307
    int result = -1;
1308 1309 1310 1311 1312 1313 1314
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *sessionManager = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_UserSession *currentSession = NULL;
#endif

    if (ctx->session == NULL) {
1315
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1316 1317 1318 1319
        return -1;
    }

#if ESX_VI_USE_SESSION_IS_ACTIVE
1320 1321
    if (esxVI_SessionIsActive(ctx, ctx->session->key, ctx->session->userName,
                              &active) < 0) {
1322 1323 1324 1325 1326 1327
        return -1;
    }

    if (active != esxVI_Boolean_True) {
        esxVI_UserSession_Free(&ctx->session);

1328
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
1329 1330 1331 1332
                        &ctx->session) < 0) {
            return -1;
        }
    }
1333 1334

    return 0;
1335
#else
1336
    if (esxVI_String_AppendValueToList(&propertyNameList,
1337
                                       "currentSession") < 0 ||
1338
        esxVI_LookupObjectContentByType(ctx, ctx->service->sessionManager,
1339 1340 1341
                                        "SessionManager", propertyNameList,
                                        esxVI_Boolean_False,
                                        &sessionManager) < 0) {
M
Matthias Bolte 已提交
1342
        goto cleanup;
1343 1344 1345 1346 1347
    }

    for (dynamicProperty = sessionManager->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "currentSession")) {
1348
            if (esxVI_UserSession_CastFromAnyType(dynamicProperty->val,
1349
                                                  &currentSession) < 0) {
M
Matthias Bolte 已提交
1350
                goto cleanup;
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSession == NULL) {
        esxVI_UserSession_Free(&ctx->session);

1362 1363
        if (esxVI_Login(ctx, ctx->username, ctx->password, NULL,
                        &ctx->session) < 0) {
M
Matthias Bolte 已提交
1364
            goto cleanup;
1365 1366
        }
    } else if (STRNEQ(ctx->session->key, currentSession->key)) {
1367 1368 1369
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Key of the current session differs from the key at "
                       "last login"));
M
Matthias Bolte 已提交
1370
        goto cleanup;
1371 1372
    }

M
Matthias Bolte 已提交
1373 1374
    result = 0;

1375 1376 1377 1378 1379 1380
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&sessionManager);
    esxVI_UserSession_Free(&currentSession);

    return result;
1381
#endif
1382 1383 1384 1385 1386
}



int
1387
esxVI_LookupObjectContentByType(esxVI_Context *ctx,
1388 1389 1390 1391 1392
                                esxVI_ManagedObjectReference *root,
                                const char *type,
                                esxVI_String *propertyNameList,
                                esxVI_Boolean recurse,
                                esxVI_ObjectContent **objectContentList)
1393
{
M
Matthias Bolte 已提交
1394
    int result = -1;
1395 1396 1397 1398 1399
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;

    if (ctx->fullTraversalSpecList == NULL) {
1400
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid call"));
1401 1402 1403
        return -1;
    }

1404
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
1405
        return -1;
1406 1407 1408 1409 1410 1411 1412 1413 1414
    }

    objectSpec->obj = root;
    objectSpec->skip = esxVI_Boolean_False;

    if (recurse == esxVI_Boolean_True) {
        objectSpec->selectSet = ctx->fullTraversalSpecList;
    }

1415
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
1416
        goto cleanup;
1417 1418 1419 1420 1421
    }

    propertySpec->type = (char *)type;
    propertySpec->pathSet = propertyNameList;

1422 1423
    if (esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
1424
                                        propertySpec) < 0 ||
1425
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
1426
                                      objectSpec) < 0) {
M
Matthias Bolte 已提交
1427
        goto cleanup;
1428 1429
    }

1430
    result = esxVI_RetrieveProperties(ctx, propertyFilterSpec,
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
                                      objectContentList);

  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
    if (objectSpec != NULL) {
        objectSpec->obj = NULL;
        objectSpec->selectSet = NULL;
    }

    if (propertySpec != NULL) {
        propertySpec->type = NULL;
        propertySpec->pathSet = NULL;
    }

    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);

    return result;
}



1455
int
1456
esxVI_GetManagedEntityStatus(esxVI_ObjectContent *objectContent,
1457 1458 1459 1460 1461 1462 1463 1464 1465
                             const char *propertyName,
                             esxVI_ManagedEntityStatus *managedEntityStatus)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            return esxVI_ManagedEntityStatus_CastFromAnyType
1466
                     (dynamicProperty->val, managedEntityStatus);
1467 1468 1469
        }
    }

1470
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1471 1472
                 _("Missing '%s' property while looking for "
                   "ManagedEntityStatus"), propertyName);
1473 1474 1475 1476 1477 1478

    return -1;
}



1479
int
1480
esxVI_GetVirtualMachinePowerState(esxVI_ObjectContent *virtualMachine,
1481 1482 1483 1484 1485 1486 1487 1488
                                  esxVI_VirtualMachinePowerState *powerState)
{
    esxVI_DynamicProperty *dynamicProperty;

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.powerState")) {
            return esxVI_VirtualMachinePowerState_CastFromAnyType
1489
                     (dynamicProperty->val, powerState);
1490 1491 1492
        }
    }

1493 1494
    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Missing 'runtime.powerState' property"));
1495 1496 1497 1498 1499 1500

    return -1;
}



1501 1502
int
esxVI_GetVirtualMachineQuestionInfo
1503
  (esxVI_ObjectContent *virtualMachine,
1504 1505 1506 1507 1508
   esxVI_VirtualMachineQuestionInfo **questionInfo)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (questionInfo == NULL || *questionInfo != NULL) {
1509
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1510 1511 1512 1513 1514 1515 1516
        return -1;
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "runtime.question")) {
            if (esxVI_VirtualMachineQuestionInfo_CastFromAnyType
1517
                  (dynamicProperty->val, questionInfo) < 0) {
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
                return -1;
            }
        }
    }

    return 0;
}



1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
int
esxVI_GetBoolean(esxVI_ObjectContent *objectContent, const char *propertyName,
                 esxVI_Boolean *value, esxVI_Occurrence occurence)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != esxVI_Boolean_Undefined) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_Boolean) < 0) {
                return -1;
            }

            *value = dynamicProperty->val->boolean;
            break;
        }
    }

    if (*value == esxVI_Boolean_Undefined &&
        occurence == esxVI_Occurrence_RequiredItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



int
esxVI_GetStringValue(esxVI_ObjectContent *objectContent,
                     const char *propertyName,
                     char **value, esxVI_Occurrence occurence)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_AnyType_ExpectType(dynamicProperty->val,
                                         esxVI_Type_String) < 0) {
                return -1;
            }

            *value = dynamicProperty->val->string;
            break;
        }
    }

    if (*value == NULL && occurence == esxVI_Occurrence_RequiredItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



int
esxVI_GetManagedObjectReference(esxVI_ObjectContent *objectContent,
                                const char *propertyName,
                                esxVI_ManagedObjectReference **value,
                                esxVI_Occurrence occurence)
{
    esxVI_DynamicProperty *dynamicProperty;

    if (value == NULL || *value != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, propertyName)) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, value) < 0) {
                return -1;
            }

            break;
        }
    }

    if (*value == NULL && occurence == esxVI_Occurrence_RequiredItem) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Missing '%s' property"), propertyName);
        return -1;
    }

    return 0;
}



1636
int
1637
esxVI_LookupNumberOfDomainsByPowerState(esxVI_Context *ctx,
1638 1639
                                        esxVI_VirtualMachinePowerState powerState,
                                        esxVI_Boolean inverse)
1640
{
M
Matthias Bolte 已提交
1641
    bool success = false;
1642 1643 1644 1645 1646
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_VirtualMachinePowerState powerState_;
M
Matthias Bolte 已提交
1647
    int count = 0;
1648

1649
    if (esxVI_String_AppendValueToList(&propertyNameList,
1650
                                       "runtime.powerState") < 0 ||
1651 1652
        esxVI_LookupObjectContentByType(ctx, ctx->vmFolder, "VirtualMachine",
                                        propertyNameList, esxVI_Boolean_True,
1653
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
1654
        goto cleanup;
1655 1656 1657 1658 1659 1660 1661 1662 1663
    }

    for (virtualMachine = virtualMachineList; virtualMachine != NULL;
         virtualMachine = virtualMachine->_next) {
        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "runtime.powerState")) {
                if (esxVI_VirtualMachinePowerState_CastFromAnyType
1664
                      (dynamicProperty->val, &powerState_) < 0) {
M
Matthias Bolte 已提交
1665
                    goto cleanup;
1666 1667 1668 1669 1670 1671
                }

                if ((inverse != esxVI_Boolean_True &&
                     powerState_ == powerState) ||
                    (inverse == esxVI_Boolean_True &&
                     powerState_ != powerState)) {
M
Matthias Bolte 已提交
1672
                    count++;
1673 1674 1675 1676 1677 1678 1679
                }
            } else {
                VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
            }
        }
    }

M
Matthias Bolte 已提交
1680 1681
    success = true;

1682 1683 1684 1685
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);

M
Matthias Bolte 已提交
1686
    return success ? count : -1;
1687 1688 1689 1690 1691
}



int
1692
esxVI_GetVirtualMachineIdentity(esxVI_ObjectContent *virtualMachine,
1693 1694 1695 1696
                                int *id, char **name, unsigned char *uuid)
{
    const char *uuid_string = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
1697
    esxVI_ManagedEntityStatus configStatus = esxVI_ManagedEntityStatus_Undefined;
1698 1699

    if (STRNEQ(virtualMachine->obj->type, "VirtualMachine")) {
1700 1701
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("ObjectContent does not reference a virtual machine"));
1702 1703 1704 1705 1706 1707
        return -1;
    }

    if (id != NULL) {
        if (esxUtil_ParseVirtualMachineIDString
              (virtualMachine->obj->value, id) < 0 || *id <= 0) {
1708
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1709
                         _("Could not parse positive integer from '%s'"),
1710 1711 1712 1713 1714 1715 1716
                         virtualMachine->obj->value);
            goto failure;
        }
    }

    if (name != NULL) {
        if (*name != NULL) {
1717
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
1718 1719 1720 1721 1722 1723 1724
            goto failure;
        }

        for (dynamicProperty = virtualMachine->propSet;
             dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
            if (STREQ(dynamicProperty->name, "name")) {
1725
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1726 1727 1728 1729 1730 1731 1732
                                             esxVI_Type_String) < 0) {
                    goto failure;
                }

                *name = strdup(dynamicProperty->val->string);

                if (*name == NULL) {
1733
                    virReportOOMError();
1734 1735 1736 1737 1738 1739 1740 1741
                    goto failure;
                }

                break;
            }
        }

        if (*name == NULL) {
1742 1743
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Could not get name of virtual machine"));
1744 1745 1746 1747 1748
            goto failure;
        }
    }

    if (uuid != NULL) {
1749
        if (esxVI_GetManagedEntityStatus(virtualMachine, "configStatus",
1750 1751 1752 1753 1754 1755 1756 1757 1758
                                         &configStatus) < 0) {
            goto failure;
        }

        if (configStatus == esxVI_ManagedEntityStatus_Green) {
            for (dynamicProperty = virtualMachine->propSet;
                 dynamicProperty != NULL;
                 dynamicProperty = dynamicProperty->_next) {
                if (STREQ(dynamicProperty->name, "config.uuid")) {
1759
                    if (esxVI_AnyType_ExpectType(dynamicProperty->val,
1760 1761 1762 1763 1764 1765
                                                 esxVI_Type_String) < 0) {
                        goto failure;
                    }

                    uuid_string = dynamicProperty->val->string;
                    break;
1766
                }
1767
            }
1768

1769
            if (uuid_string == NULL) {
1770 1771
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("Could not get UUID of virtual machine"));
1772
                goto failure;
1773 1774
            }

1775
            if (virUUIDParse(uuid_string, uuid) < 0) {
1776
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
1777
                             _("Could not parse UUID from string '%s'"),
1778 1779 1780 1781 1782
                             uuid_string);
                goto failure;
            }
        } else {
            memset(uuid, 0, VIR_UUID_BUFLEN);
1783

1784 1785
            VIR_WARN0("Cannot access UUID, because 'configStatus' property "
                      "indicates a config problem");
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
        }
    }

    return 0;

  failure:
    if (name != NULL) {
        VIR_FREE(*name);
    }

    return -1;
}



1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
int
esxVI_GetNumberOfSnapshotTrees
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList)
{
    int count = 0;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList; snapshotTree != NULL;
         snapshotTree = snapshotTree->_next) {
        count += 1 + esxVI_GetNumberOfSnapshotTrees
                       (snapshotTree->childSnapshotList);
    }

    return count;
}



int
esxVI_GetSnapshotTreeNames(esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
                           char **names, int nameslen)
{
    int count = 0;
    int result;
    int i;
    esxVI_VirtualMachineSnapshotTree *snapshotTree;

    for (snapshotTree = snapshotTreeList;
         snapshotTree != NULL && count < nameslen;
         snapshotTree = snapshotTree->_next) {
        names[count] = strdup(snapshotTree->name);

        if (names[count] == NULL) {
            virReportOOMError();
            goto failure;
        }

        count++;

        if (count >= nameslen) {
            break;
        }

        result = esxVI_GetSnapshotTreeNames(snapshotTree->childSnapshotList,
                                            names + count, nameslen - count);

        if (result < 0) {
            goto failure;
        }

        count += result;
    }

    return count;

  failure:
    for (i = 0; i < count; ++i) {
        VIR_FREE(names[i]);
    }

    return -1;
}



int
esxVI_GetSnapshotTreeByName
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList, const char *name,
   esxVI_VirtualMachineSnapshotTree **snapshotTree,
   esxVI_VirtualMachineSnapshotTree **snapshotTreeParent,
   esxVI_Occurrence occurrence)
{
    esxVI_VirtualMachineSnapshotTree *candidate;

    if (snapshotTree == NULL || *snapshotTree != NULL ||
        snapshotTreeParent == NULL || *snapshotTreeParent != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (candidate = snapshotTreeList; candidate != NULL;
         candidate = candidate->_next) {
        if (STREQ(candidate->name, name)) {
            *snapshotTree = candidate;
            *snapshotTreeParent = NULL;
            return 1;
        }

        if (esxVI_GetSnapshotTreeByName(candidate->childSnapshotList, name,
                                        snapshotTree, snapshotTreeParent,
                                        occurrence) > 0) {
            if (*snapshotTreeParent == NULL) {
                *snapshotTreeParent = candidate;
            }

            return 1;
        }
    }

    if (occurrence == esxVI_Occurrence_OptionalItem) {
        return 0;
    } else {
        ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                     _("Could not find snapshot with name '%s'"), name);

        return -1;
    }
}



int
esxVI_GetSnapshotTreeBySnapshot
  (esxVI_VirtualMachineSnapshotTree *snapshotTreeList,
   esxVI_ManagedObjectReference *snapshot,
   esxVI_VirtualMachineSnapshotTree **snapshotTree)
{
    esxVI_VirtualMachineSnapshotTree *candidate;

    if (snapshotTree == NULL || *snapshotTree != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    for (candidate = snapshotTreeList; candidate != NULL;
         candidate = candidate->_next) {
        if (STREQ(candidate->snapshot->value, snapshot->value)) {
            *snapshotTree = candidate;
            return 0;
        }

        if (esxVI_GetSnapshotTreeBySnapshot(candidate->childSnapshotList,
                                            snapshot, snapshotTree) >= 0) {
            return 0;
        }
    }

    ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                 _("Could not find domain snapshot with internal name '%s'"),
                 snapshot->value);

    return -1;
}



1947 1948
int
esxVI_LookupResourcePoolByHostSystem
1949
  (esxVI_Context *ctx, esxVI_ObjectContent *hostSystem,
1950
   esxVI_ManagedObjectReference **resourcePool)
M
Matthias Bolte 已提交
1951
{
M
Matthias Bolte 已提交
1952
    int result = -1;
M
Matthias Bolte 已提交
1953 1954 1955 1956 1957 1958
    esxVI_String *propertyNameList = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
    esxVI_ObjectContent *computeResource = NULL;

    if (resourcePool == NULL || *resourcePool != NULL) {
1959
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
1960 1961 1962 1963 1964 1965 1966
        return -1;
    }

    for (dynamicProperty = hostSystem->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "parent")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
1967
                  (dynamicProperty->val, &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
1968
                goto cleanup;
M
Matthias Bolte 已提交
1969 1970 1971 1972 1973 1974 1975 1976 1977
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (managedObjectReference == NULL) {
1978 1979
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource of host system"));
M
Matthias Bolte 已提交
1980
        goto cleanup;
M
Matthias Bolte 已提交
1981 1982
    }

1983 1984
    if (esxVI_String_AppendValueToList(&propertyNameList, "resourcePool") < 0 ||
        esxVI_LookupObjectContentByType(ctx, managedObjectReference,
1985 1986 1987
                                        "ComputeResource", propertyNameList,
                                        esxVI_Boolean_False,
                                        &computeResource) < 0) {
M
Matthias Bolte 已提交
1988
        goto cleanup;
M
Matthias Bolte 已提交
1989 1990 1991
    }

    if (computeResource == NULL) {
1992 1993
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve compute resource of host system"));
M
Matthias Bolte 已提交
1994
        goto cleanup;
M
Matthias Bolte 已提交
1995 1996 1997 1998 1999 2000
    }

    for (dynamicProperty = computeResource->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "resourcePool")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
2001
                  (dynamicProperty->val, resourcePool) < 0) {
M
Matthias Bolte 已提交
2002
                goto cleanup;
M
Matthias Bolte 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if ((*resourcePool) == NULL) {
2012 2013
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not retrieve resource pool of compute resource"));
M
Matthias Bolte 已提交
2014
        goto cleanup;
M
Matthias Bolte 已提交
2015 2016
    }

M
Matthias Bolte 已提交
2017 2018
    result = 0;

M
Matthias Bolte 已提交
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&managedObjectReference);
    esxVI_ObjectContent_Free(&computeResource);

    return result;
}



2029
int
2030
esxVI_LookupHostSystemByIp(esxVI_Context *ctx, const char *ipAddress,
M
Matthias Bolte 已提交
2031
                           esxVI_String *propertyNameList,
2032 2033
                           esxVI_ObjectContent **hostSystem)
{
M
Matthias Bolte 已提交
2034
    int result = -1;
2035 2036 2037
    esxVI_ManagedObjectReference *managedObjectReference = NULL;

    if (hostSystem == NULL || *hostSystem != NULL) {
2038
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2039 2040 2041
        return -1;
    }

2042 2043
    if (esxVI_FindByIp(ctx, ctx->datacenter, ipAddress, esxVI_Boolean_False,
                       &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2044
        return -1;
2045 2046
    }

2047 2048 2049 2050
    if (managedObjectReference == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                     _("Could not find host system with IP address '%s'"),
                     ipAddress);
M
Matthias Bolte 已提交
2051
        goto cleanup;
2052 2053
    }

2054
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2055 2056
                                        "HostSystem", propertyNameList,
                                        esxVI_Boolean_False, hostSystem) < 0) {
M
Matthias Bolte 已提交
2057
        goto cleanup;
2058 2059
    }

M
Matthias Bolte 已提交
2060 2061
    result = 0;

2062 2063 2064 2065 2066 2067 2068 2069 2070
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
}



int
2071
esxVI_LookupVirtualMachineByUuid(esxVI_Context *ctx, const unsigned char *uuid,
2072
                                 esxVI_String *propertyNameList,
2073
                                 esxVI_ObjectContent **virtualMachine,
M
Matthias Bolte 已提交
2074
                                 esxVI_Occurrence occurrence)
2075
{
M
Matthias Bolte 已提交
2076
    int result = -1;
2077
    esxVI_ManagedObjectReference *managedObjectReference = NULL;
2078
    char uuid_string[VIR_UUID_STRING_BUFLEN] = "";
2079 2080

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2081
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2082 2083 2084
        return -1;
    }

2085 2086 2087
    virUUIDFormat(uuid, uuid_string);

    if (esxVI_FindByUuid(ctx, ctx->datacenter, uuid_string, esxVI_Boolean_True,
2088
                         &managedObjectReference) < 0) {
M
Matthias Bolte 已提交
2089
        return -1;
2090 2091
    }

2092
    if (managedObjectReference == NULL) {
M
Matthias Bolte 已提交
2093
        if (occurrence == esxVI_Occurrence_OptionalItem) {
2094 2095
            return 0;
        } else {
2096
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2097 2098
                         _("Could not find domain with UUID '%s'"),
                         uuid_string);
M
Matthias Bolte 已提交
2099
            goto cleanup;
2100 2101 2102
        }
    }

2103
    if (esxVI_LookupObjectContentByType(ctx, managedObjectReference,
2104 2105 2106
                                        "VirtualMachine", propertyNameList,
                                        esxVI_Boolean_False,
                                        virtualMachine) < 0) {
M
Matthias Bolte 已提交
2107
        goto cleanup;
2108 2109
    }

M
Matthias Bolte 已提交
2110 2111
    result = 0;

2112 2113 2114 2115
  cleanup:
    esxVI_ManagedObjectReference_Free(&managedObjectReference);

    return result;
M
Matthias Bolte 已提交
2116 2117 2118 2119
}



2120 2121 2122 2123 2124 2125
int
esxVI_LookupVirtualMachineByName(esxVI_Context *ctx, const char *name,
                                 esxVI_String *propertyNameList,
                                 esxVI_ObjectContent **virtualMachine,
                                 esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2126
    int result = -1;
2127 2128 2129 2130 2131 2132
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *virtualMachineList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    char *name_candidate = NULL;

    if (virtualMachine == NULL || *virtualMachine != NULL) {
2133
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
        return -1;
    }

    if (esxVI_String_DeepCopyList(&completePropertyNameList,
                                  propertyNameList) < 0 ||
        esxVI_String_AppendValueToList(&completePropertyNameList, "name") < 0 ||
        esxVI_LookupObjectContentByType(ctx, ctx->vmFolder, "VirtualMachine",
                                        completePropertyNameList,
                                        esxVI_Boolean_True,
                                        &virtualMachineList) < 0) {
M
Matthias Bolte 已提交
2144
        goto cleanup;
2145 2146 2147 2148 2149 2150 2151 2152
    }

    for (candidate = virtualMachineList; candidate != NULL;
         candidate = candidate->_next) {
        VIR_FREE(name_candidate);

        if (esxVI_GetVirtualMachineIdentity(candidate, NULL, &name_candidate,
                                            NULL) < 0) {
M
Matthias Bolte 已提交
2153
            goto cleanup;
2154 2155 2156 2157 2158 2159 2160
        }

        if (STRNEQ(name, name_candidate)) {
            continue;
        }

        if (esxVI_ObjectContent_DeepCopy(virtualMachine, candidate) < 0) {
M
Matthias Bolte 已提交
2161
            goto cleanup;
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
        }

        break;
    }

    if (*virtualMachine == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            return 0;
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN,
2172
                         _("Could not find domain with name '%s'"), name);
M
Matthias Bolte 已提交
2173
            goto cleanup;
2174 2175 2176
        }
    }

M
Matthias Bolte 已提交
2177 2178
    result = 0;

2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&virtualMachineList);
    VIR_FREE(name_candidate);

    return result;
}



2189 2190
int
esxVI_LookupVirtualMachineByUuidAndPrepareForTask
2191
  (esxVI_Context *ctx, const unsigned char *uuid,
2192 2193 2194
   esxVI_String *propertyNameList, esxVI_ObjectContent **virtualMachine,
   esxVI_Boolean autoAnswer)
{
M
Matthias Bolte 已提交
2195
    int result = -1;
2196 2197 2198 2199
    esxVI_String *completePropertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;
    esxVI_TaskInfo *pendingTaskInfoList = NULL;

2200
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
2201
                                  propertyNameList) < 0 ||
2202
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2203 2204
                                           "runtime.question\0"
                                           "recentTask\0") < 0 ||
2205
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, completePropertyNameList,
2206
                                         virtualMachine,
M
Matthias Bolte 已提交
2207
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2208
        esxVI_GetVirtualMachineQuestionInfo(*virtualMachine,
2209 2210
                                            &questionInfo) < 0 ||
        esxVI_LookupPendingTaskInfoListByVirtualMachine
2211
           (ctx, *virtualMachine, &pendingTaskInfoList) < 0) {
M
Matthias Bolte 已提交
2212
        goto cleanup;
2213 2214 2215
    }

    if (questionInfo != NULL &&
2216
        esxVI_HandleVirtualMachineQuestion(ctx, (*virtualMachine)->obj,
2217
                                           questionInfo, autoAnswer) < 0) {
M
Matthias Bolte 已提交
2218
        goto cleanup;
2219 2220 2221
    }

    if (pendingTaskInfoList != NULL) {
2222 2223
        ESX_VI_ERROR(VIR_ERR_OPERATION_INVALID, "%s",
                     _("Other tasks are pending for this domain"));
M
Matthias Bolte 已提交
2224
        goto cleanup;
2225 2226
    }

M
Matthias Bolte 已提交
2227 2228
    result = 0;

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);
    esxVI_TaskInfo_Free(&pendingTaskInfoList);

    return result;
}



M
Matthias Bolte 已提交
2239
int
2240 2241
esxVI_LookupDatastoreByName(esxVI_Context *ctx, const char *name,
                            esxVI_String *propertyNameList,
M
Matthias Bolte 已提交
2242
                            esxVI_ObjectContent **datastore,
M
Matthias Bolte 已提交
2243
                            esxVI_Occurrence occurrence)
M
Matthias Bolte 已提交
2244
{
M
Matthias Bolte 已提交
2245
    int result = -1;
M
Matthias Bolte 已提交
2246 2247 2248 2249
    esxVI_String *completePropertyNameList = NULL;
    esxVI_ObjectContent *datastoreList = NULL;
    esxVI_ObjectContent *candidate = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
2250
    esxVI_Boolean accessible = esxVI_Boolean_Undefined;
2251
    size_t offset = 14; /* = strlen("/vmfs/volumes/") */
2252
    int numInaccessibleDatastores = 0;
M
Matthias Bolte 已提交
2253 2254

    if (datastore == NULL || *datastore != NULL) {
2255
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
M
Matthias Bolte 已提交
2256 2257 2258 2259
        return -1;
    }

    /* Get all datastores */
2260
    if (esxVI_String_DeepCopyList(&completePropertyNameList,
M
Matthias Bolte 已提交
2261
                                  propertyNameList) < 0 ||
2262
        esxVI_String_AppendValueListToList(&completePropertyNameList,
2263 2264 2265
                                           "summary.accessible\0"
                                           "summary.name\0"
                                           "summary.url\0") < 0) {
M
Matthias Bolte 已提交
2266
        goto cleanup;
M
Matthias Bolte 已提交
2267 2268
    }

2269 2270
    if (esxVI_LookupObjectContentByType(ctx, ctx->datacenter, "Datastore",
                                        completePropertyNameList,
2271 2272
                                        esxVI_Boolean_True,
                                        &datastoreList) < 0) {
M
Matthias Bolte 已提交
2273
        goto cleanup;
M
Matthias Bolte 已提交
2274 2275 2276
    }

    if (datastoreList == NULL) {
M
Matthias Bolte 已提交
2277
        if (occurrence == esxVI_Occurrence_OptionalItem) {
M
Matthias Bolte 已提交
2278
            goto success;
M
Matthias Bolte 已提交
2279
        } else {
2280 2281
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("No datastores available"));
M
Matthias Bolte 已提交
2282
            goto cleanup;
M
Matthias Bolte 已提交
2283 2284 2285 2286 2287 2288
        }
    }

    /* Search for a matching datastore */
    for (candidate = datastoreList; candidate != NULL;
         candidate = candidate->_next) {
2289 2290
        accessible = esxVI_Boolean_Undefined;

M
Matthias Bolte 已提交
2291 2292
        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2293
            if (STREQ(dynamicProperty->name, "summary.accessible")) {
2294
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
2295
                                             esxVI_Type_Boolean) < 0) {
M
Matthias Bolte 已提交
2296
                    goto cleanup;
2297 2298 2299 2300 2301 2302 2303 2304
                }

                accessible = dynamicProperty->val->boolean;
                break;
            }
        }

        if (accessible == esxVI_Boolean_Undefined) {
2305 2306 2307
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                         _("Got incomplete response while querying for the "
                           "datastore 'summary.accessible' property"));
M
Matthias Bolte 已提交
2308
            goto cleanup;
2309 2310 2311 2312 2313 2314 2315 2316
        }

        if (accessible == esxVI_Boolean_False) {
            ++numInaccessibleDatastores;
        }

        for (dynamicProperty = candidate->propSet; dynamicProperty != NULL;
             dynamicProperty = dynamicProperty->_next) {
2317
            if (STREQ(dynamicProperty->name, "summary.name")) {
2318
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2319
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2320
                    goto cleanup;
M
Matthias Bolte 已提交
2321 2322 2323
                }

                if (STREQ(dynamicProperty->val->string, name)) {
2324
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2325
                                                     candidate) < 0) {
M
Matthias Bolte 已提交
2326
                        goto cleanup;
M
Matthias Bolte 已提交
2327 2328 2329
                    }

                    /* Found datastore with matching name */
M
Matthias Bolte 已提交
2330
                    goto success;
M
Matthias Bolte 已提交
2331
                }
2332 2333
            } else if (STREQ(dynamicProperty->name, "summary.url") &&
                       ctx->productVersion & esxVI_ProductVersion_ESX) {
2334 2335 2336 2337 2338 2339 2340 2341
                if (accessible == esxVI_Boolean_False) {
                    /*
                     * The 'summary.url' property of an inaccessible datastore
                     * is invalid and cannot be used to identify the datastore.
                     */
                    continue;
                }

2342
                if (esxVI_AnyType_ExpectType(dynamicProperty->val,
M
Matthias Bolte 已提交
2343
                                             esxVI_Type_String) < 0) {
M
Matthias Bolte 已提交
2344
                    goto cleanup;
M
Matthias Bolte 已提交
2345 2346 2347 2348
                }

                if (! STRPREFIX(dynamicProperty->val->string,
                                "/vmfs/volumes/")) {
2349
                    ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2350 2351
                                 _("Datastore URL '%s' has unexpected prefix, "
                                   "expecting '/vmfs/volumes/' prefix"),
M
Matthias Bolte 已提交
2352
                                 dynamicProperty->val->string);
M
Matthias Bolte 已提交
2353
                    goto cleanup;
M
Matthias Bolte 已提交
2354 2355 2356
                }

                if (STREQ(dynamicProperty->val->string + offset, name)) {
2357
                    if (esxVI_ObjectContent_DeepCopy(datastore,
M
Matthias Bolte 已提交
2358
                                                     candidate) < 0) {
M
Matthias Bolte 已提交
2359
                        goto cleanup;
M
Matthias Bolte 已提交
2360 2361 2362
                    }

                    /* Found datastore with matching URL suffix */
M
Matthias Bolte 已提交
2363
                    goto success;
M
Matthias Bolte 已提交
2364 2365 2366 2367 2368
                }
            }
        }
    }

M
Matthias Bolte 已提交
2369
    if (occurrence != esxVI_Occurrence_OptionalItem) {
2370
        if (numInaccessibleDatastores > 0) {
2371
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2372 2373
                         _("Could not find datastore '%s', maybe it's "
                           "inaccessible"), name);
2374
        } else {
2375
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2376
                         _("Could not find datastore '%s'"), name);
2377 2378
        }

M
Matthias Bolte 已提交
2379
        goto cleanup;
M
Matthias Bolte 已提交
2380 2381
    }

M
Matthias Bolte 已提交
2382 2383 2384
  success:
    result = 0;

M
Matthias Bolte 已提交
2385 2386 2387 2388 2389
  cleanup:
    esxVI_String_Free(&completePropertyNameList);
    esxVI_ObjectContent_Free(&datastoreList);

    return result;
2390 2391 2392 2393
}



2394 2395 2396 2397
int
esxVI_LookupTaskInfoByTask(esxVI_Context *ctx,
                           esxVI_ManagedObjectReference *task,
                           esxVI_TaskInfo **taskInfo)
2398
{
M
Matthias Bolte 已提交
2399
    int result = -1;
2400 2401 2402 2403 2404
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *objectContent = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (taskInfo == NULL || *taskInfo != NULL) {
2405
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2406 2407 2408
        return -1;
    }

2409 2410 2411
    if (esxVI_String_AppendValueToList(&propertyNameList, "info") < 0 ||
        esxVI_LookupObjectContentByType(ctx, task, "Task", propertyNameList,
                                        esxVI_Boolean_False,
2412
                                        &objectContent) < 0) {
M
Matthias Bolte 已提交
2413
        goto cleanup;
2414 2415 2416 2417 2418
    }

    for (dynamicProperty = objectContent->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "info")) {
2419
            if (esxVI_TaskInfo_CastFromAnyType(dynamicProperty->val,
2420
                                               taskInfo) < 0) {
M
Matthias Bolte 已提交
2421
                goto cleanup;
2422 2423 2424 2425 2426 2427 2428 2429
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

M
Matthias Bolte 已提交
2430 2431
    result = 0;

2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&objectContent);

    return result;
}



int
esxVI_LookupPendingTaskInfoListByVirtualMachine
2443
  (esxVI_Context *ctx, esxVI_ObjectContent *virtualMachine,
2444 2445
   esxVI_TaskInfo **pendingTaskInfoList)
{
M
Matthias Bolte 已提交
2446
    int result = -1;
2447 2448 2449 2450 2451 2452 2453
    esxVI_String *propertyNameList = NULL;
    esxVI_ManagedObjectReference *recentTaskList = NULL;
    esxVI_ManagedObjectReference *recentTask = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_TaskInfo *taskInfo = NULL;

    if (pendingTaskInfoList == NULL || *pendingTaskInfoList != NULL) {
2454
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
2455 2456 2457 2458 2459 2460 2461 2462
        return -1;
    }

    /* Get list of recent tasks */
    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "recentTask")) {
            if (esxVI_ManagedObjectReference_CastListFromAnyType
2463
                  (dynamicProperty->val, &recentTaskList) < 0) {
M
Matthias Bolte 已提交
2464
                goto cleanup;
2465 2466 2467 2468 2469 2470 2471 2472 2473
            }

            break;
        }
    }

    /* Lookup task info for each task */
    for (recentTask = recentTaskList; recentTask != NULL;
         recentTask = recentTask->_next) {
2474
        if (esxVI_LookupTaskInfoByTask(ctx, recentTask, &taskInfo) < 0) {
M
Matthias Bolte 已提交
2475
            goto cleanup;
2476 2477 2478 2479
        }

        if (taskInfo->state == esxVI_TaskInfoState_Queued ||
            taskInfo->state == esxVI_TaskInfoState_Running) {
2480
            if (esxVI_TaskInfo_AppendToList(pendingTaskInfoList,
2481
                                            taskInfo) < 0) {
M
Matthias Bolte 已提交
2482
                goto cleanup;
2483 2484 2485 2486 2487 2488 2489 2490
            }

            taskInfo = NULL;
        } else {
            esxVI_TaskInfo_Free(&taskInfo);
        }
    }

M
Matthias Bolte 已提交
2491 2492
    result = 0;

2493
  cleanup:
M
Matthias Bolte 已提交
2494 2495 2496 2497
    if (result < 0) {
        esxVI_TaskInfo_Free(pendingTaskInfoList);
    }

2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    esxVI_String_Free(&propertyNameList);
    esxVI_ManagedObjectReference_Free(&recentTaskList);
    esxVI_TaskInfo_Free(&taskInfo);

    return result;
}



int
2508
esxVI_LookupAndHandleVirtualMachineQuestion(esxVI_Context *ctx,
2509 2510 2511
                                            const unsigned char *uuid,
                                            esxVI_Boolean autoAnswer)
{
M
Matthias Bolte 已提交
2512
    int result = -1;
2513 2514 2515 2516
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_String *propertyNameList = NULL;
    esxVI_VirtualMachineQuestionInfo *questionInfo = NULL;

2517
    if (esxVI_String_AppendValueToList(&propertyNameList,
2518
                                       "runtime.question") < 0 ||
2519
        esxVI_LookupVirtualMachineByUuid(ctx, uuid, propertyNameList,
2520
                                         &virtualMachine,
M
Matthias Bolte 已提交
2521
                                         esxVI_Occurrence_RequiredItem) < 0 ||
2522
        esxVI_GetVirtualMachineQuestionInfo(virtualMachine,
2523
                                            &questionInfo) < 0) {
M
Matthias Bolte 已提交
2524
        goto cleanup;
2525 2526 2527
    }

    if (questionInfo != NULL &&
2528
        esxVI_HandleVirtualMachineQuestion(ctx, virtualMachine->obj,
2529
                                           questionInfo, autoAnswer) < 0) {
M
Matthias Bolte 已提交
2530
        goto cleanup;
2531 2532
    }

M
Matthias Bolte 已提交
2533 2534
    result = 0;

2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
  cleanup:
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_String_Free(&propertyNameList);
    esxVI_VirtualMachineQuestionInfo_Free(&questionInfo);

    return result;
}



2545 2546 2547 2548 2549
int
esxVI_LookupRootSnapshotTreeList
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **rootSnapshotTreeList)
{
M
Matthias Bolte 已提交
2550
    int result = -1;
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;

    if (rootSnapshotTreeList == NULL || *rootSnapshotTreeList != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueToList(&propertyNameList,
                                       "snapshot.rootSnapshotList") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2565
        goto cleanup;
2566 2567 2568 2569 2570 2571 2572
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
2573
                goto cleanup;
2574 2575 2576 2577 2578 2579 2580 2581
            }

            break;
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

M
Matthias Bolte 已提交
2582 2583
    result = 0;

2584
  cleanup:
M
Matthias Bolte 已提交
2585 2586 2587 2588
    if (result < 0) {
        esxVI_VirtualMachineSnapshotTree_Free(rootSnapshotTreeList);
    }

2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);

    return result;
}



int
esxVI_LookupCurrentSnapshotTree
  (esxVI_Context *ctx, const unsigned char *virtualMachineUuid,
   esxVI_VirtualMachineSnapshotTree **currentSnapshotTree,
   esxVI_Occurrence occurrence)
{
M
Matthias Bolte 已提交
2603
    int result = -1;
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
    esxVI_String *propertyNameList = NULL;
    esxVI_ObjectContent *virtualMachine = NULL;
    esxVI_DynamicProperty *dynamicProperty = NULL;
    esxVI_ManagedObjectReference *currentSnapshot = NULL;
    esxVI_VirtualMachineSnapshotTree *rootSnapshotTreeList = NULL;
    esxVI_VirtualMachineSnapshotTree *snapshotTree = NULL;

    if (currentSnapshotTree == NULL || *currentSnapshotTree != NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
    }

    if (esxVI_String_AppendValueListToList(&propertyNameList,
                                           "snapshot.currentSnapshot\0"
                                           "snapshot.rootSnapshotList\0") < 0 ||
        esxVI_LookupVirtualMachineByUuid(ctx, virtualMachineUuid,
                                         propertyNameList, &virtualMachine,
                                         esxVI_Occurrence_RequiredItem) < 0) {
M
Matthias Bolte 已提交
2622
        goto cleanup;
2623 2624 2625 2626 2627 2628 2629
    }

    for (dynamicProperty = virtualMachine->propSet; dynamicProperty != NULL;
         dynamicProperty = dynamicProperty->_next) {
        if (STREQ(dynamicProperty->name, "snapshot.currentSnapshot")) {
            if (esxVI_ManagedObjectReference_CastFromAnyType
                  (dynamicProperty->val, &currentSnapshot) < 0) {
M
Matthias Bolte 已提交
2630
                goto cleanup;
2631 2632 2633 2634
            }
        } else if (STREQ(dynamicProperty->name, "snapshot.rootSnapshotList")) {
            if (esxVI_VirtualMachineSnapshotTree_CastListFromAnyType
                  (dynamicProperty->val, &rootSnapshotTreeList) < 0) {
M
Matthias Bolte 已提交
2635
                goto cleanup;
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
            }
        } else {
            VIR_WARN("Unexpected '%s' property", dynamicProperty->name);
        }
    }

    if (currentSnapshot == NULL) {
        if (occurrence == esxVI_Occurrence_OptionalItem) {
            return 0;
        } else {
            ESX_VI_ERROR(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                         _("Domain has no current snapshot"));
M
Matthias Bolte 已提交
2648
            goto cleanup;
2649 2650 2651 2652 2653 2654
        }
    }

    if (rootSnapshotTreeList == NULL) {
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("Could not lookup root snapshot list"));
M
Matthias Bolte 已提交
2655
        goto cleanup;
2656 2657 2658 2659 2660 2661
    }

    if (esxVI_GetSnapshotTreeBySnapshot(rootSnapshotTreeList, currentSnapshot,
                                        &snapshotTree) < 0 ||
        esxVI_VirtualMachineSnapshotTree_DeepCopy(currentSnapshotTree,
                                                  snapshotTree) < 0) {
M
Matthias Bolte 已提交
2662
        goto cleanup;
2663 2664
    }

M
Matthias Bolte 已提交
2665 2666
    result = 0;

2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
  cleanup:
    esxVI_String_Free(&propertyNameList);
    esxVI_ObjectContent_Free(&virtualMachine);
    esxVI_ManagedObjectReference_Free(&currentSnapshot);
    esxVI_VirtualMachineSnapshotTree_Free(&rootSnapshotTreeList);

    return result;
}



2678 2679
int
esxVI_HandleVirtualMachineQuestion
2680
  (esxVI_Context *ctx, esxVI_ManagedObjectReference *virtualMachine,
2681 2682 2683
   esxVI_VirtualMachineQuestionInfo *questionInfo,
   esxVI_Boolean autoAnswer)
{
M
Matthias Bolte 已提交
2684
    int result = -1;
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
    esxVI_ElementDescription *elementDescription = NULL;
    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    esxVI_ElementDescription *answerChoice = NULL;
    int answerIndex = 0;
    char *possibleAnswers = NULL;

    if (questionInfo->choice->choiceInfo != NULL) {
        for (elementDescription = questionInfo->choice->choiceInfo;
             elementDescription != NULL;
             elementDescription = elementDescription->_next) {
            virBufferVSprintf(&buffer, "'%s'", elementDescription->label);

            if (elementDescription->_next != NULL) {
                virBufferAddLit(&buffer, ", ");
            }

            if (answerChoice == NULL &&
                questionInfo->choice->defaultIndex != NULL &&
                questionInfo->choice->defaultIndex->value == answerIndex) {
                answerChoice = elementDescription;
            }

            ++answerIndex;
        }

        if (virBufferError(&buffer)) {
2711
            virReportOOMError();
M
Matthias Bolte 已提交
2712
            goto cleanup;
2713 2714 2715 2716 2717 2718 2719
        }

        possibleAnswers = virBufferContentAndReset(&buffer);
    }

    if (autoAnswer == esxVI_Boolean_True) {
        if (possibleAnswers == NULL) {
2720
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2721 2722
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
2723
                         questionInfo->text);
M
Matthias Bolte 已提交
2724
            goto cleanup;
2725
        } else if (answerChoice == NULL) {
2726
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2727 2728 2729
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s, but no "
                           "default answer is specified"), questionInfo->text,
2730
                         possibleAnswers);
M
Matthias Bolte 已提交
2731
            goto cleanup;
2732 2733 2734 2735 2736 2737 2738
        }

        VIR_INFO("Pending question blocks virtual machine execution, "
                 "question is '%s', possible answers are %s, responding "
                 "with default answer '%s'", questionInfo->text,
                 possibleAnswers, answerChoice->label);

2739
        if (esxVI_AnswerVM(ctx, virtualMachine, questionInfo->id,
2740
                           answerChoice->key) < 0) {
M
Matthias Bolte 已提交
2741
            goto cleanup;
2742 2743 2744
        }
    } else {
        if (possibleAnswers != NULL) {
2745
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2746 2747
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', possible answers are %s"),
2748 2749
                         questionInfo->text, possibleAnswers);
        } else {
2750
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
2751 2752
                         _("Pending question blocks virtual machine execution, "
                           "question is '%s', no possible answers"),
2753 2754 2755
                         questionInfo->text);
        }

M
Matthias Bolte 已提交
2756
        goto cleanup;
2757 2758
    }

M
Matthias Bolte 已提交
2759 2760
    result = 0;

2761
  cleanup:
M
Matthias Bolte 已提交
2762 2763 2764 2765
    if (result < 0) {
        virBufferFreeAndReset(&buffer);
    }

2766 2767 2768 2769 2770 2771 2772
    VIR_FREE(possibleAnswers);

    return result;
}



2773
int
2774
esxVI_WaitForTaskCompletion(esxVI_Context *ctx,
2775
                            esxVI_ManagedObjectReference *task,
2776 2777
                            const unsigned char *virtualMachineUuid,
                            esxVI_Boolean autoAnswer,
2778 2779
                            esxVI_TaskInfoState *finalState)
{
M
Matthias Bolte 已提交
2780
    int result = -1;
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
    esxVI_ObjectSpec *objectSpec = NULL;
    esxVI_PropertySpec *propertySpec = NULL;
    esxVI_PropertyFilterSpec *propertyFilterSpec = NULL;
    esxVI_ManagedObjectReference *propertyFilter = NULL;
    char *version = NULL;
    esxVI_UpdateSet *updateSet = NULL;
    esxVI_PropertyFilterUpdate *propertyFilterUpdate = NULL;
    esxVI_ObjectUpdate *objectUpdate = NULL;
    esxVI_PropertyChange *propertyChange = NULL;
    esxVI_AnyType *propertyValue = NULL;
    esxVI_TaskInfoState state = esxVI_TaskInfoState_Undefined;
2792
    esxVI_TaskInfo *taskInfo = NULL;
2793 2794 2795 2796

    version = strdup("");

    if (version == NULL) {
2797
        virReportOOMError();
M
Matthias Bolte 已提交
2798
        return -1;
2799 2800
    }

2801
    if (esxVI_ObjectSpec_Alloc(&objectSpec) < 0) {
M
Matthias Bolte 已提交
2802
        goto cleanup;
2803 2804 2805 2806 2807
    }

    objectSpec->obj = task;
    objectSpec->skip = esxVI_Boolean_False;

2808
    if (esxVI_PropertySpec_Alloc(&propertySpec) < 0) {
M
Matthias Bolte 已提交
2809
        goto cleanup;
2810 2811 2812 2813
    }

    propertySpec->type = task->type;

2814
    if (esxVI_String_AppendValueToList(&propertySpec->pathSet,
2815
                                       "info.state") < 0 ||
2816 2817
        esxVI_PropertyFilterSpec_Alloc(&propertyFilterSpec) < 0 ||
        esxVI_PropertySpec_AppendToList(&propertyFilterSpec->propSet,
2818
                                        propertySpec) < 0 ||
2819
        esxVI_ObjectSpec_AppendToList(&propertyFilterSpec->objectSet,
2820
                                      objectSpec) < 0 ||
2821
        esxVI_CreateFilter(ctx, propertyFilterSpec, esxVI_Boolean_True,
2822
                           &propertyFilter) < 0) {
M
Matthias Bolte 已提交
2823
        goto cleanup;
2824 2825 2826 2827 2828 2829
    }

    while (state != esxVI_TaskInfoState_Success &&
           state != esxVI_TaskInfoState_Error) {
        esxVI_UpdateSet_Free(&updateSet);

2830 2831
        if (virtualMachineUuid != NULL) {
            if (esxVI_LookupAndHandleVirtualMachineQuestion
2832
                  (ctx, virtualMachineUuid, autoAnswer) < 0) {
2833 2834 2835 2836 2837
                /*
                 * FIXME: Disable error reporting here, so possible errors from
                 *        esxVI_LookupTaskInfoByTask() and esxVI_CancelTask()
                 *        don't overwrite the actual error
                 */
2838
                if (esxVI_LookupTaskInfoByTask(ctx, task, &taskInfo)) {
M
Matthias Bolte 已提交
2839
                    goto cleanup;
2840 2841 2842
                }

                if (taskInfo->cancelable == esxVI_Boolean_True) {
2843
                    if (esxVI_CancelTask(ctx, task) < 0) {
2844 2845 2846
                        VIR_ERROR0(_("Cancelable task is blocked by an "
                                     "unanswered question but cancelation "
                                     "failed"));
2847 2848
                    }
                } else {
2849 2850
                    VIR_ERROR0(_("Non-cancelable task is blocked by an "
                                 "unanswered question"));
2851 2852 2853 2854
                }

                /* FIXME: Enable error reporting here again */

M
Matthias Bolte 已提交
2855
                goto cleanup;
2856 2857 2858
            }
        }

2859
        if (esxVI_WaitForUpdates(ctx, version, &updateSet) < 0) {
M
Matthias Bolte 已提交
2860
            goto cleanup;
2861 2862 2863 2864 2865 2866
        }

        VIR_FREE(version);
        version = strdup(updateSet->version);

        if (version == NULL) {
2867
            virReportOOMError();
M
Matthias Bolte 已提交
2868
            goto cleanup;
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
        }

        if (updateSet->filterSet == NULL) {
            continue;
        }

        for (propertyFilterUpdate = updateSet->filterSet;
             propertyFilterUpdate != NULL;
             propertyFilterUpdate = propertyFilterUpdate->_next) {
            for (objectUpdate = propertyFilterUpdate->objectSet;
                 objectUpdate != NULL; objectUpdate = objectUpdate->_next) {
                for (propertyChange = objectUpdate->changeSet;
                     propertyChange != NULL;
                     propertyChange = propertyChange->_next) {
                    if (STREQ(propertyChange->name, "info.state")) {
                        if (propertyChange->op == esxVI_PropertyChangeOp_Add ||
                            propertyChange->op == esxVI_PropertyChangeOp_Assign) {
                            propertyValue = propertyChange->val;
                        } else {
                            propertyValue = NULL;
                        }
                    }
                }
            }
        }

        if (propertyValue == NULL) {
            continue;
        }

2899
        if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, &state) < 0) {
M
Matthias Bolte 已提交
2900
            goto cleanup;
2901 2902 2903
        }
    }

2904
    if (esxVI_DestroyPropertyFilter(ctx, propertyFilter) < 0) {
2905 2906 2907
        VIR_DEBUG0("DestroyPropertyFilter failed");
    }

2908
    if (esxVI_TaskInfoState_CastFromAnyType(propertyValue, finalState) < 0) {
M
Matthias Bolte 已提交
2909
        goto cleanup;
2910 2911
    }

M
Matthias Bolte 已提交
2912 2913
    result = 0;

2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930
  cleanup:
    /*
     * Remove values given by the caller from the data structures to prevent
     * them from being freed by the call to esxVI_PropertyFilterSpec_Free().
     */
    if (objectSpec != NULL) {
        objectSpec->obj = NULL;
    }

    if (propertySpec != NULL) {
        propertySpec->type = NULL;
    }

    esxVI_PropertyFilterSpec_Free(&propertyFilterSpec);
    esxVI_ManagedObjectReference_Free(&propertyFilter);
    VIR_FREE(version);
    esxVI_UpdateSet_Free(&updateSet);
2931
    esxVI_TaskInfo_Free(&taskInfo);
2932 2933 2934

    return result;
}
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958



int
esxVI_ParseHostCpuIdInfo(esxVI_ParsedHostCpuIdInfo *parsedHostCpuIdInfo,
                         esxVI_HostCpuIdInfo *hostCpuIdInfo)
{
    int expectedLength = 39; /* = strlen("----:----:----:----:----:----:----:----"); */
    char *input[4] = { hostCpuIdInfo->eax, hostCpuIdInfo->ebx,
                       hostCpuIdInfo->ecx, hostCpuIdInfo->edx };
    char *output[4] = { parsedHostCpuIdInfo->eax, parsedHostCpuIdInfo->ebx,
                        parsedHostCpuIdInfo->ecx, parsedHostCpuIdInfo->edx };
    const char *name[4] = { "eax", "ebx", "ecx", "edx" };
    int r, i, o;

    memset(parsedHostCpuIdInfo, 0, sizeof (*parsedHostCpuIdInfo));

    parsedHostCpuIdInfo->level = hostCpuIdInfo->level->value;

    for (r = 0; r < 4; ++r) {
        if (strlen(input[r]) != expectedLength) {
            ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                         _("HostCpuIdInfo register '%s' has an unexpected length"),
                         name[r]);
M
Matthias Bolte 已提交
2959
            return -1;
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
        }

        /* Strip the ':' and invert the "bit" order from 31..0 to 0..31 */
        for (i = 0, o = 31; i < expectedLength; i += 5, o -= 4) {
            output[r][o] = input[r][i];
            output[r][o - 1] = input[r][i + 1];
            output[r][o - 2] = input[r][i + 2];
            output[r][o - 3] = input[r][i + 3];

            if (i + 4 < expectedLength && input[r][i + 4] != ':') {
                ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR,
                             _("HostCpuIdInfo register '%s' has an unexpected format"),
                             name[r]);
M
Matthias Bolte 已提交
2973
                return -1;
2974 2975 2976 2977 2978 2979
            }
        }
    }

    return 0;
}