viruri.c 2.3 KB
Newer Older
M
Martin Kletzander 已提交
1 2 3 4 5 6 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 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 88 89 90 91 92 93
/*
 * viruri.c: URI parsing wrappers for libxml2 functions
 *
 * Copyright (C) 2012 Red Hat, Inc.
 *
 * See COPYING.LIB for the License of this software
 */

#include <config.h>

#include "viruri.h"

#include "memory.h"
#include "util.h"

/**
 * virURIParse:
 * @uri: URI to parse
 *
 * Wrapper for xmlParseURI
 *
 * Unfortunately there are few things that should be managed after
 * parsing the URI. Fortunately there is only one thing now and its
 * removing of square brackets around IPv6 addresses.
 *
 * @returns the parsed uri object with some fixes
 */
virURIPtr
virURIParse(const char *uri)
{
    virURIPtr ret = xmlParseURI(uri);

    /* First check: does it even make sense to jump inside */
    if (ret != NULL &&
        ret->server != NULL &&
        ret->server[0] == '[') {
        size_t length = strlen(ret->server);

        /* We want to modify the server string only if there are
         * square brackets on both ends and inside there is IPv6
         * address. Otherwise we could make a mistake by modifying
         * something other than an IPv6 address. */
        if (ret->server[length - 1] == ']' && strchr(ret->server, ':')) {
            memmove(&ret->server[0], &ret->server[1], length - 2);
            ret->server[length - 2] = '\0';
        }
        /* Even after such modification, it is completely ok to free
         * the uri with xmlFreeURI() */
    }

    return ret;
}

/**
 * virURIFormat:
 * @uri: URI to format
 *
 * Wrapper for xmlSaveUri
 *
 * This function constructs back everything that @ref virURIParse
 * changes after parsing
 *
 * @returns the constructed uri as a string
 */
char *
virURIFormat(xmlURIPtr uri)
{
    char *backupserver = NULL;
    char *tmpserver = NULL;
    char *ret;

    /* First check: does it make sense to do anything */
    if (uri != NULL &&
        uri->server != NULL &&
        strchr(uri->server, ':') != NULL) {

        backupserver = uri->server;
        if (virAsprintf(&tmpserver, "[%s]", uri->server) < 0)
            return NULL;

        uri->server = tmpserver;
    }

    ret = (char *) xmlSaveUri(uri);

    /* Put the fixed version back */
    if (tmpserver) {
        uri->server = backupserver;
        VIR_FREE(tmpserver);
    }

    return ret;
}
94 95 96 97 98 99 100 101 102 103 104 105


/**
 * virURIFree:
 * @uri: uri to free
 *
 * Frees the URI
 */
void virURIFree(virURIPtr uri)
{
    xmlFreeURI(uri);
}