esx_util.c 22.6 KB
Newer Older
1 2

/*
3
 * esx_util.c: utility functions for the VMware ESX driver
4
 *
5
 * Copyright (C) 2010 Red Hat, Inc.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Copyright (C) 2009 Matthias Bolte <matthias.bolte@googlemail.com>
 * Copyright (C) 2009 Maximilian Wilhelm <max@rfc2324.org>
 *
 * 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>

27
#include <c-ctype.h>
28 29 30 31 32 33 34 35 36
#include <netdb.h>

#include "internal.h"
#include "datatypes.h"
#include "qparams.h"
#include "util.h"
#include "memory.h"
#include "logging.h"
#include "uuid.h"
37
#include "esx_private.h"
38 39 40 41
#include "esx_util.h"

#define VIR_FROM_THIS VIR_FROM_ESX

42

43

44
int
M
Matthias Bolte 已提交
45
esxUtil_ParseUri(esxUtil_ParsedUri **parsedUri, xmlURIPtr uri)
46
{
M
Matthias Bolte 已提交
47
    int result = -1;
48 49
    struct qparam_set *queryParamSet = NULL;
    struct qparam *queryParam = NULL;
50 51 52
    int i;
    int noVerify;
    int autoAnswer;
M
Matthias Bolte 已提交
53
    char *tmp;
M
Matthias Bolte 已提交
54
    char *saveptr;
55

M
Matthias Bolte 已提交
56
    if (parsedUri == NULL || *parsedUri != NULL) {
57 58
        ESX_VI_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
        return -1;
59 60
    }

M
Matthias Bolte 已提交
61
    if (VIR_ALLOC(*parsedUri) < 0) {
62 63
        virReportOOMError();
        return -1;
64 65
    }

66
#ifdef HAVE_XMLURI_QUERY_RAW
67
    queryParamSet = qparam_query_parse(uri->query_raw);
68
#else
69
    queryParamSet = qparam_query_parse(uri->query);
70 71 72
#endif

    if (queryParamSet == NULL) {
73
        goto cleanup;
74 75 76 77 78
    }

    for (i = 0; i < queryParamSet->n; i++) {
        queryParam = &queryParamSet->p[i];

79
        if (STRCASEEQ(queryParam->name, "transport")) {
M
Matthias Bolte 已提交
80
            VIR_FREE((*parsedUri)->transport);
81

M
Matthias Bolte 已提交
82
            (*parsedUri)->transport = strdup(queryParam->value);
83

M
Matthias Bolte 已提交
84
            if ((*parsedUri)->transport == NULL) {
85
                virReportOOMError();
M
Matthias Bolte 已提交
86
                goto cleanup;
87 88
            }

M
Matthias Bolte 已提交
89 90
            if (STRNEQ((*parsedUri)->transport, "http") &&
                STRNEQ((*parsedUri)->transport, "https")) {
91
                ESX_ERROR(VIR_ERR_INVALID_ARG,
92
                          _("Query parameter 'transport' has unexpected value "
93
                            "'%s' (should be http|https)"),
M
Matthias Bolte 已提交
94
                          (*parsedUri)->transport);
M
Matthias Bolte 已提交
95
                goto cleanup;
96
            }
97
        } else if (STRCASEEQ(queryParam->name, "vcenter")) {
M
Matthias Bolte 已提交
98
            VIR_FREE((*parsedUri)->vCenter);
99

M
Matthias Bolte 已提交
100
            (*parsedUri)->vCenter = strdup(queryParam->value);
101

M
Matthias Bolte 已提交
102
            if ((*parsedUri)->vCenter == NULL) {
103
                virReportOOMError();
M
Matthias Bolte 已提交
104
                goto cleanup;
105
            }
106
        } else if (STRCASEEQ(queryParam->name, "no_verify")) {
107 108
            if (virStrToLong_i(queryParam->value, NULL, 10, &noVerify) < 0 ||
                (noVerify != 0 && noVerify != 1)) {
109
                ESX_ERROR(VIR_ERR_INVALID_ARG,
110 111
                          _("Query parameter 'no_verify' has unexpected value "
                            "'%s' (should be 0 or 1)"), queryParam->value);
M
Matthias Bolte 已提交
112
                goto cleanup;
113
            }
114

M
Matthias Bolte 已提交
115
            (*parsedUri)->noVerify = noVerify != 0;
116 117 118
        } else if (STRCASEEQ(queryParam->name, "auto_answer")) {
            if (virStrToLong_i(queryParam->value, NULL, 10, &autoAnswer) < 0 ||
                (autoAnswer != 0 && autoAnswer != 1)) {
119
                ESX_ERROR(VIR_ERR_INVALID_ARG,
120 121
                          _("Query parameter 'auto_answer' has unexpected "
                            "value '%s' (should be 0 or 1)"), queryParam->value);
M
Matthias Bolte 已提交
122
                goto cleanup;
123
            }
124

M
Matthias Bolte 已提交
125
            (*parsedUri)->autoAnswer = autoAnswer != 0;
M
Matthias Bolte 已提交
126 127
        } else if (STRCASEEQ(queryParam->name, "proxy")) {
            /* Expected format: [<type>://]<hostname>[:<port>] */
M
Matthias Bolte 已提交
128 129 130 131
            (*parsedUri)->proxy = true;
            (*parsedUri)->proxy_type = CURLPROXY_HTTP;
            VIR_FREE((*parsedUri)->proxy_hostname);
            (*parsedUri)->proxy_port = 1080;
M
Matthias Bolte 已提交
132 133

            if ((tmp = STRSKIP(queryParam->value, "http://")) != NULL) {
M
Matthias Bolte 已提交
134
                (*parsedUri)->proxy_type = CURLPROXY_HTTP;
M
Matthias Bolte 已提交
135 136
            } else if ((tmp = STRSKIP(queryParam->value, "socks://")) != NULL ||
                       (tmp = STRSKIP(queryParam->value, "socks5://")) != NULL) {
M
Matthias Bolte 已提交
137
                (*parsedUri)->proxy_type = CURLPROXY_SOCKS5;
M
Matthias Bolte 已提交
138
            } else if ((tmp = STRSKIP(queryParam->value, "socks4://")) != NULL) {
M
Matthias Bolte 已提交
139
                (*parsedUri)->proxy_type = CURLPROXY_SOCKS4;
M
Matthias Bolte 已提交
140
            } else if ((tmp = STRSKIP(queryParam->value, "socks4a://")) != NULL) {
M
Matthias Bolte 已提交
141
                (*parsedUri)->proxy_type = CURLPROXY_SOCKS4A;
M
Matthias Bolte 已提交
142 143 144 145 146 147 148 149 150 151 152 153
            } else if ((tmp = strstr(queryParam->value, "://")) != NULL) {
                *tmp = '\0';

                ESX_ERROR(VIR_ERR_INVALID_ARG,
                          _("Query parameter 'proxy' contains unexpected "
                            "type '%s' (should be (http|socks(|4|4a|5))"),
                          queryParam->value);
                goto cleanup;
            } else {
                tmp = queryParam->value;
            }

M
Matthias Bolte 已提交
154
            (*parsedUri)->proxy_hostname = strdup(tmp);
M
Matthias Bolte 已提交
155

M
Matthias Bolte 已提交
156
            if ((*parsedUri)->proxy_hostname == NULL) {
M
Matthias Bolte 已提交
157 158 159 160
                virReportOOMError();
                goto cleanup;
            }

M
Matthias Bolte 已提交
161 162
            if ((tmp = strchr((*parsedUri)->proxy_hostname, ':')) != NULL) {
                if (tmp == (*parsedUri)->proxy_hostname) {
M
Matthias Bolte 已提交
163 164 165 166 167 168 169 170 171
                    ESX_ERROR(VIR_ERR_INVALID_ARG, "%s",
                              _("Query parameter 'proxy' doesn't contain a "
                                "hostname"));
                    goto cleanup;
                }

                *tmp++ = '\0';

                if (virStrToLong_i(tmp, NULL, 10,
M
Matthias Bolte 已提交
172 173 174
                                   &(*parsedUri)->proxy_port) < 0 ||
                    (*parsedUri)->proxy_port < 1 ||
                    (*parsedUri)->proxy_port > 65535) {
M
Matthias Bolte 已提交
175 176 177 178 179 180
                    ESX_ERROR(VIR_ERR_INVALID_ARG,
                              _("Query parameter 'proxy' has unexpected port"
                                "value '%s' (should be [1..65535])"), tmp);
                    goto cleanup;
                }
            }
181 182 183 184 185 186
        } else {
            VIR_WARN("Ignoring unexpected query parameter '%s'",
                     queryParam->name);
        }
    }

M
Matthias Bolte 已提交
187 188 189
    /* Expected format: [/]<datacenter>/<computeresource>[/<hostsystem>] */
    if (uri->path != NULL) {
        tmp = strdup(uri->path);
190

M
Matthias Bolte 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        if (tmp == NULL) {
            virReportOOMError();
            goto cleanup;
        }

        if (esxVI_String_DeepCopyValue(&(*parsedUri)->path_datacenter,
                                       strtok_r(tmp, "/", &saveptr)) < 0 ||
            esxVI_String_DeepCopyValue(&(*parsedUri)->path_computeResource,
                                       strtok_r(NULL, "/", &saveptr)) < 0 ||
            esxVI_String_DeepCopyValue(&(*parsedUri)->path_hostSystem,
                                       strtok_r(NULL, "", &saveptr)) < 0) {
            VIR_FREE(tmp);
            goto cleanup;
        }

        VIR_FREE(tmp);
    }

    if ((*parsedUri)->transport == NULL) {
        (*parsedUri)->transport = strdup("https");

        if ((*parsedUri)->transport == NULL) {
213
            virReportOOMError();
M
Matthias Bolte 已提交
214
            goto cleanup;
215 216 217
        }
    }

M
Matthias Bolte 已提交
218
    result = 0;
219

M
Matthias Bolte 已提交
220 221
  cleanup:
    if (result < 0) {
M
Matthias Bolte 已提交
222
        esxUtil_FreeParsedUri(parsedUri);
223 224
    }

M
Matthias Bolte 已提交
225 226
    if (queryParamSet != NULL) {
        free_qparam_set(queryParamSet);
227 228
    }

M
Matthias Bolte 已提交
229
    return result;
230 231 232 233
}



234 235

void
M
Matthias Bolte 已提交
236
esxUtil_FreeParsedUri(esxUtil_ParsedUri **parsedUri)
237
{
M
Matthias Bolte 已提交
238
    if (parsedUri == NULL || *parsedUri == NULL) {
239 240 241
        return;
    }

M
Matthias Bolte 已提交
242 243 244 245 246 247
    VIR_FREE((*parsedUri)->transport);
    VIR_FREE((*parsedUri)->vCenter);
    VIR_FREE((*parsedUri)->proxy_hostname);
    VIR_FREE((*parsedUri)->path_datacenter);
    VIR_FREE((*parsedUri)->path_computeResource);
    VIR_FREE((*parsedUri)->path_hostSystem);
248

M
Matthias Bolte 已提交
249
    VIR_FREE(*parsedUri);
250 251 252 253
}



254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
int
esxUtil_ParseVirtualMachineIDString(const char *id_string, int *id)
{
    /* Try to parse an integer from the complete string. */
    if (virStrToLong_i(id_string, NULL, 10, id) == 0) {
        return 0;
    }

    /*
     * If that fails try to parse an integer from the string tail
     * assuming the naming scheme Virtual Center seems to use.
     */
    if (STRPREFIX(id_string, "vm-")) {
        if (virStrToLong_i(id_string + 3, NULL, 10, id) == 0) {
            return 0;
        }
    }

    return -1;
}



M
Matthias Bolte 已提交
277
int
278
esxUtil_ParseDatastorePath(const char *datastorePath, char **datastoreName,
279
                           char **directoryName, char **directoryAndFileName)
M
Matthias Bolte 已提交
280
{
M
Matthias Bolte 已提交
281
    int result = -1;
282
    char *copyOfDatastorePath = NULL;
283 284 285
    char *tmp = NULL;
    char *saveptr = NULL;
    char *preliminaryDatastoreName = NULL;
286 287
    char *preliminaryDirectoryAndFileName = NULL;
    char *preliminaryFileName = NULL;
M
Matthias Bolte 已提交
288

289 290 291
    if ((datastoreName != NULL && *datastoreName != NULL) ||
        (directoryName != NULL && *directoryName != NULL) ||
        (directoryAndFileName != NULL && *directoryAndFileName != NULL)) {
292
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR, "%s", _("Invalid argument"));
293
        return -1;
M
Matthias Bolte 已提交
294 295
    }

296
    if (esxVI_String_DeepCopyValue(&copyOfDatastorePath, datastorePath) < 0) {
M
Matthias Bolte 已提交
297
        goto cleanup;
298 299
    }

300 301 302
    /* Expected format: '[<datastore>] <path>' where <path> is optional */
    if ((tmp = STRSKIP(copyOfDatastorePath, "[")) == NULL || *tmp == ']' ||
        (preliminaryDatastoreName = strtok_r(tmp, "]", &saveptr)) == NULL) {
303
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
304 305
                  _("Datastore path '%s' doesn't have expected format "
                    "'[<datastore>] <path>'"), datastorePath);
M
Matthias Bolte 已提交
306
        goto cleanup;
M
Matthias Bolte 已提交
307 308
    }

309 310
    if (datastoreName != NULL &&
        esxVI_String_DeepCopyValue(datastoreName,
311
                                   preliminaryDatastoreName) < 0) {
M
Matthias Bolte 已提交
312
        goto cleanup;
313 314
    }

315
    preliminaryDirectoryAndFileName = strtok_r(NULL, "", &saveptr);
316

317 318 319 320 321 322
    if (preliminaryDirectoryAndFileName == NULL) {
        preliminaryDirectoryAndFileName = (char *)"";
    } else {
        preliminaryDirectoryAndFileName +=
          strspn(preliminaryDirectoryAndFileName, " ");
    }
M
Matthias Bolte 已提交
323

324 325 326 327 328
    if (directoryAndFileName != NULL &&
        esxVI_String_DeepCopyValue(directoryAndFileName,
                                   preliminaryDirectoryAndFileName) < 0) {
        goto cleanup;
    }
M
Matthias Bolte 已提交
329

330 331 332 333 334 335
    if (directoryName != NULL) {
        /* Split <path> into <directory>/<file> */
        preliminaryFileName = strrchr(preliminaryDirectoryAndFileName, '/');

        if (preliminaryFileName != NULL) {
            *preliminaryFileName++ = '\0';
M
Matthias Bolte 已提交
336 337
        }

338
        if (esxVI_String_DeepCopyValue(directoryName,
339
                                       preliminaryDirectoryAndFileName) < 0) {
M
Matthias Bolte 已提交
340
            goto cleanup;
341
        }
M
Matthias Bolte 已提交
342 343
    }

M
Matthias Bolte 已提交
344 345
    result = 0;

M
Matthias Bolte 已提交
346
  cleanup:
M
Matthias Bolte 已提交
347
    if (result < 0) {
348 349 350 351 352 353 354 355 356 357 358
        if (datastoreName != NULL) {
            VIR_FREE(*datastoreName);
        }

        if (directoryName != NULL) {
            VIR_FREE(*directoryName);
        }

        if (directoryAndFileName != NULL) {
            VIR_FREE(*directoryAndFileName);
        }
M
Matthias Bolte 已提交
359 360
    }

361
    VIR_FREE(copyOfDatastorePath);
M
Matthias Bolte 已提交
362 363 364 365 366 367

    return result;
}



368
int
369
esxUtil_ResolveHostname(const char *hostname,
M
Matthias Bolte 已提交
370
                        char *ipAddress, size_t ipAddress_length)
371 372 373 374 375
{
    struct addrinfo hints;
    struct addrinfo *result = NULL;
    int errcode;

M
Matthias Bolte 已提交
376
    memset(&hints, 0, sizeof (hints));
377 378 379 380 381 382 383 384 385

    hints.ai_flags = AI_ADDRCONFIG;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

    errcode = getaddrinfo(hostname, NULL, &hints, &result);

    if (errcode != 0) {
386
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
387
                  _("IP address lookup for host '%s' failed: %s"), hostname,
388 389 390 391 392
                  gai_strerror(errcode));
        return -1;
    }

    if (result == NULL) {
393
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
394
                  _("No IP address for host '%s' found: %s"), hostname,
395 396 397 398
                  gai_strerror(errcode));
        return -1;
    }

M
Matthias Bolte 已提交
399 400
    errcode = getnameinfo(result->ai_addr, result->ai_addrlen, ipAddress,
                          ipAddress_length, NULL, 0, NI_NUMERICHOST);
401 402

    if (errcode != 0) {
403
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
404
                  _("Formating IP address for host '%s' failed: %s"), hostname,
405 406 407 408 409 410 411 412 413 414 415 416 417
                  gai_strerror(errcode));
        freeaddrinfo(result);
        return -1;
    }

    freeaddrinfo(result);

    return 0;
}



int
418
esxUtil_GetConfigString(virConfPtr conf, const char *name, char **string,
419
                        bool optional)
420 421 422 423 424 425 426 427 428 429 430
{
    virConfValuePtr value;

    *string = NULL;
    value = virConfGetValue(conf, name);

    if (value == NULL) {
        if (optional) {
            return 0;
        }

431
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
432
                  _("Missing essential config entry '%s'"), name);
433 434 435 436
        return -1;
    }

    if (value->type != VIR_CONF_STRING) {
437
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
438
                  _("Config entry '%s' must be a string"), name);
439 440 441 442 443 444 445 446
        return -1;
    }

    if (value->str == NULL) {
        if (optional) {
            return 0;
        }

447
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
448
                  _("Missing essential config entry '%s'"), name);
449 450 451 452 453 454
        return -1;
    }

    *string = strdup(value->str);

    if (*string == NULL) {
455
        virReportOOMError();
456 457 458 459 460 461 462 463 464
        return -1;
    }

    return 0;
}



int
465
esxUtil_GetConfigUUID(virConfPtr conf, const char *name, unsigned char *uuid,
466
                      bool optional)
467 468 469 470 471 472 473 474 475
{
    virConfValuePtr value;

    value = virConfGetValue(conf, name);

    if (value == NULL) {
        if (optional) {
            return 0;
        } else {
476
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
477
                      _("Missing essential config entry '%s'"), name);
478 479 480 481 482
            return -1;
        }
    }

    if (value->type != VIR_CONF_STRING) {
483
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
484
                  _("Config entry '%s' must be a string"), name);
485 486 487 488 489 490 491
        return -1;
    }

    if (value->str == NULL) {
        if (optional) {
            return 0;
        } else {
492
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
493
                      _("Missing essential config entry '%s'"), name);
494 495 496 497
            return -1;
        }
    }

498
    if (virUUIDParse(value->str, uuid) < 0) {
499
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
500
                  _("Could not parse UUID from string '%s'"), value->str);
501 502
        return -1;
    }
503 504 505 506 507 508 509

    return 0;
}



int
510
esxUtil_GetConfigLong(virConfPtr conf, const char *name, long long *number,
511
                      long long default_, bool optional)
512 513 514 515 516 517 518 519 520 521
{
    virConfValuePtr value;

    *number = default_;
    value = virConfGetValue(conf, name);

    if (value == NULL) {
        if (optional) {
            return 0;
        } else {
522
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
523
                      _("Missing essential config entry '%s'"), name);
524 525 526 527 528 529 530 531 532
            return -1;
        }
    }

    if (value->type == VIR_CONF_STRING) {
        if (value->str == NULL) {
            if (optional) {
                return 0;
            } else {
533
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
534
                          _("Missing essential config entry '%s'"), name);
535 536 537 538 539 540 541
                return -1;
            }
        }

        if (STREQ(value->str, "unlimited")) {
            *number = -1;
        } else if (virStrToLong_ll(value->str, NULL, 10, number) < 0) {
542
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
543
                      _("Config entry '%s' must represent an integer value"),
544 545 546 547
                      name);
            return -1;
        }
    } else {
548
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
549
                  _("Config entry '%s' must be a string"), name);
550 551 552 553 554 555 556 557 558
        return -1;
    }

    return 0;
}



int
559 560
esxUtil_GetConfigBoolean(virConfPtr conf, const char *name, bool *boolean_,
                         bool default_, bool optional)
561 562 563
{
    virConfValuePtr value;

M
Matthias Bolte 已提交
564
    *boolean_ = default_;
565 566 567 568 569 570
    value = virConfGetValue(conf, name);

    if (value == NULL) {
        if (optional) {
            return 0;
        } else {
571
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
572
                      _("Missing essential config entry '%s'"), name);
573 574 575 576 577 578 579 580 581
            return -1;
        }
    }

    if (value->type == VIR_CONF_STRING) {
        if (value->str == NULL) {
            if (optional) {
                return 0;
            } else {
582
                ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
583
                          _("Missing essential config entry '%s'"), name);
584 585 586 587 588
                return -1;
            }
        }

        if (STRCASEEQ(value->str, "true")) {
M
Matthias Bolte 已提交
589
            *boolean_ = 1;
590
        } else if (STRCASEEQ(value->str, "false")) {
M
Matthias Bolte 已提交
591
            *boolean_ = 0;
592
        } else {
593
            ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
594 595
                      _("Config entry '%s' must represent a boolean value "
                        "(true|false)"), name);
596 597 598
            return -1;
        }
    } else {
599
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
600
                  _("Config entry '%s' must be a string"), name);
601 602 603 604 605
        return -1;
    }

    return 0;
}
606 607 608 609 610 611 612 613 614



int
esxUtil_ReformatUuid(const char *input, char *output)
{
    unsigned char uuid[VIR_UUID_BUFLEN];

    if (virUUIDParse(input, uuid) < 0) {
615 616 617
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not parse UUID from string '%s'"),
                  input);
618 619 620 621 622 623 624
        return -1;
    }

    virUUIDFormat(uuid, output);

    return 0;
}
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821



char *
esxUtil_EscapeHex(const char *string, char escape, const char *special)
{
    char *escaped = NULL;
    size_t length = 1; /* 1 byte for termination */
    const char *tmp1 = string;
    char *tmp2;

    /* Calculate length of escaped string */
    while (*tmp1 != '\0') {
        if (*tmp1 == escape || strspn(tmp1, special) > 0) {
            length += 2;
        }

        ++tmp1;
        ++length;
    }

    if (VIR_ALLOC_N(escaped, length) < 0) {
        virReportOOMError();
        return NULL;
    }

    tmp1 = string; /* reading from this one */
    tmp2 = escaped; /* writing to this one */

    /* Escape to 'cXX' where c is the escape char and X is a hex digit */
    while (*tmp1 != '\0') {
        if (*tmp1 == escape || strspn(tmp1, special) > 0) {
            *tmp2++ = escape;

            snprintf(tmp2, 3, "%02x", (unsigned int)*tmp1);

            tmp2 += 2;
        } else {
            *tmp2++ = *tmp1;
        }

        ++tmp1;
    }

    *tmp2 = '\0';

    return escaped;
}



int
esxUtil_UnescapeHex(char *string, char escape)
{
    char *tmp1 = string; /* reading from this one */
    char *tmp2 = string; /* writing to this one */

    /* Unescape from 'cXX' where c is the escape char and X is a hex digit */
    while (*tmp1 != '\0') {
        if (*tmp1 == escape) {
            if (!c_isxdigit(tmp1[1]) || !c_isxdigit(tmp1[2])) {
                return -1;
            }

            *tmp2++ = virHexToBin(tmp1[1]) * 16 + virHexToBin(tmp1[2]);
            tmp1 += 3;
        } else {
            *tmp2++ = *tmp1++;
        }
    }

    *tmp2 = '\0';

    return 0;
}



char *
esxUtil_EscapeBase64(const char *string)
{
    /* 'normal' characters don't get base64 encoded */
    static const char *normal =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),. _-";

    /* VMware uses ',' instead of the path separator '/' in the base64 alphabet */
    static const char *base64 =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";

    virBuffer buffer = VIR_BUFFER_INITIALIZER;
    const char *tmp1 = string;
    size_t length;
    unsigned char c1, c2, c3;

    /* Escape sequences of non-'normal' characters as base64 without padding */
    while (*tmp1 != '\0') {
        length = strspn(tmp1, normal);

        if (length > 0) {
            virBufferAdd(&buffer, tmp1, length);

            tmp1 += length;
        } else {
            length = strcspn(tmp1, normal);

            virBufferAddChar(&buffer, '+');

            while (length > 0) {
                c1 = *tmp1++;
                c2 = length > 1 ? *tmp1++ : 0;
                c3 = length > 2 ? *tmp1++ : 0;

                virBufferAddChar(&buffer, base64[(c1 >> 2) & 0x3f]);
                virBufferAddChar(&buffer, base64[((c1 << 4) + (c2 >> 4)) & 0x3f]);

                if (length > 1) {
                    virBufferAddChar(&buffer, base64[((c2 << 2) + (c3 >> 6)) & 0x3f]);
                }

                if (length > 2) {
                    virBufferAddChar(&buffer, base64[c3 & 0x3f]);
                }

                length -= length > 3 ? 3 : length;
            }

            if (*tmp1 != '\0') {
                virBufferAddChar(&buffer, '-');
            }
        }
    }

    if (virBufferError(&buffer)) {
        virReportOOMError();
        virBufferFreeAndReset(&buffer);

        return NULL;
    }

    return virBufferContentAndReset(&buffer);
}



void
esxUtil_ReplaceSpecialWindowsPathChars(char *string)
{
    /* '/' and '\\' are missing on purpose */
    static const char *specials = "\"*<>:|?";

    char *tmp = string;
    size_t length;

    while (*tmp != '\0') {
        length = strspn(tmp, specials);

        while (length > 0) {
            *tmp++ = '_';
            --length;
        }

        if (*tmp != '\0') {
            ++tmp;
        }
    }
}



char *
esxUtil_EscapeDatastoreItem(const char *string)
{
    char *replaced = strdup(string);
    char *escaped1;
    char *escaped2 = NULL;

    if (replaced == NULL) {
        virReportOOMError();
        return NULL;
    }

    esxUtil_ReplaceSpecialWindowsPathChars(replaced);

    escaped1 = esxUtil_EscapeHexPercent(replaced);

    if (escaped1 == NULL) {
        goto cleanup;
    }

    escaped2 = esxUtil_EscapeBase64(escaped1);

  cleanup:
    VIR_FREE(replaced);
    VIR_FREE(escaped1);

    return escaped2;
}
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859



char *
esxUtil_ConvertToUTF8(const char *encoding, const char *string)
{
    char *result = NULL;
    xmlCharEncodingHandlerPtr handler;
    xmlBufferPtr input;
    xmlBufferPtr utf8;

    handler = xmlFindCharEncodingHandler(encoding);

    if (handler == NULL) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("libxml2 doesn't handle %s encoding"), encoding);
        return NULL;
    }

    input = xmlBufferCreateStatic((char *)string, strlen(string));
    utf8 = xmlBufferCreate();

    if (xmlCharEncInFunc(handler, utf8, input) < 0) {
        ESX_ERROR(VIR_ERR_INTERNAL_ERROR,
                  _("Could not convert from %s to UTF-8 encoding"), encoding);
        goto cleanup;
    }

    result = (char *)utf8->content;
    utf8->content = NULL;

  cleanup:
    xmlCharEncCloseFunc(handler);
    xmlBufferFree(input);
    xmlBufferFree(utf8);

    return result;
}