virsocketaddr.c 31.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2009-2015 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14
 *
 * 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
15
 * License along with this library.  If not, see
O
Osier Yang 已提交
16
 * <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23 24 25 26
 *
 * Authors:
 *     Daniel Veillard <veillard@redhat.com>
 *     Laine Stump <laine@laine.org>
 *     Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include "virsocketaddr.h"
27
#include "virerror.h"
28
#include "virstring.h"
29
#include "viralloc.h"
30 31 32 33 34 35 36 37 38 39 40 41 42 43

#include <netdb.h>

#define VIR_FROM_THIS VIR_FROM_NONE

/*
 * Helpers to extract the IP arrays from the virSocketAddrPtr
 * That part is the less portable of the module
 */
typedef unsigned char virSocketAddrIPv4[4];
typedef virSocketAddrIPv4 *virSocketAddrIPv4Ptr;
typedef unsigned short virSocketAddrIPv6[8];
typedef virSocketAddrIPv6 *virSocketAddrIPv6Ptr;

44 45 46 47
static int
virSocketAddrGetIPv4Addr(const virSocketAddr *addr,
                         virSocketAddrIPv4Ptr tab)
{
48
    unsigned long val;
49
    size_t i;
50

51
    if (!addr || !tab || addr->data.stor.ss_family != AF_INET)
52
        return -1;
53 54 55

    val = ntohl(addr->data.inet4.sin_addr.s_addr);

56
    for (i = 0; i < 4; i++) {
57 58 59 60
        (*tab)[3 - i] = val & 0xFF;
        val >>= 8;
    }

61
    return 0;
62 63
}

64 65 66
static int
virSocketAddrGetIPv6Addr(const virSocketAddr *addr, virSocketAddrIPv6Ptr tab)
{
67
    size_t i;
68

69
    if (!addr || !tab || addr->data.stor.ss_family != AF_INET6)
70
        return -1;
71

72
    for (i = 0; i < 8; i++) {
73 74 75 76
        (*tab)[i] = ((addr->data.inet6.sin6_addr.s6_addr[2 * i] << 8) |
                     addr->data.inet6.sin6_addr.s6_addr[2 * i + 1]);
    }

77
    return 0;
78 79
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
static int
virSocketAddrParseInternal(struct addrinfo **res,
                           const char *val,
                           int family,
                           bool reportError)
{
    struct addrinfo hints;
    int err;

    if (val == NULL) {
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Missing address"));
        return -1;
    }

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_flags = AI_NUMERICHOST;
    if ((err = getaddrinfo(val, NULL, &hints, res)) != 0) {
        if (reportError)
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Cannot parse socket address '%s': %s"),
                           val, gai_strerror(err));

        return -1;
    }

    return 0;
}

109 110 111 112 113 114 115 116 117 118 119
/**
 * virSocketAddrParse:
 * @val: a numeric network address IPv4 or IPv6
 * @addr: where to store the return value, optional.
 * @family: address family to pass down to getaddrinfo
 *
 * Mostly a wrapper for getaddrinfo() extracting the address storage
 * from the numeric string like 1.2.3.4 or 2001:db8:85a3:0:0:8a2e:370:7334
 *
 * Returns the length of the network address or -1 in case of error.
 */
120 121
int virSocketAddrParse(virSocketAddrPtr addr, const char *val, int family)
{
122
    int len;
123
    struct addrinfo *res;
124

125
    if (virSocketAddrParseInternal(&res, val, family, true) < 0)
126 127 128
        return -1;

    if (res == NULL) {
129
        virReportError(VIR_ERR_SYSTEM_ERROR,
130 131 132 133 134 135 136 137 138 139 140 141
                       _("No socket addresses found for '%s'"),
                       val);
        return -1;
    }

    len = res->ai_addrlen;
    if (addr != NULL) {
        memcpy(&addr->data.stor, res->ai_addr, len);
        addr->len = res->ai_addrlen;
    }

    freeaddrinfo(res);
142
    return len;
143 144 145 146 147 148 149 150 151 152 153 154
}

/*
 * virSocketAddrParseIPv4:
 * @val: an IPv4 numeric address
 * @addr: the location to store the result
 *
 * Extract the address storage from an IPv4 numeric address
 *
 * Returns the length of the network address or -1 in case of error.
 */
int
155 156
virSocketAddrParseIPv4(virSocketAddrPtr addr, const char *val)
{
157 158 159 160 161 162 163 164 165 166 167 168 169
    return virSocketAddrParse(addr, val, AF_INET);
}

/*
 * virSocketAddrParseIPv6:
 * @val: an IPv6 numeric address
 * @addr: the location to store the result
 *
 * Extract the address storage from an IPv6 numeric address
 *
 * Returns the length of the network address or -1 in case of error.
 */
int
170 171
virSocketAddrParseIPv6(virSocketAddrPtr addr, const char *val)
{
172 173 174
    return virSocketAddrParse(addr, val, AF_INET6);
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
/*
 * virSocketAddrSetIPv4AddrNetOrder:
 * @addr: the location to store the result
 * @val: the 32bit integer in network byte order representing the IPv4 address
 *
 * Set the IPv4 address given an integer in network order. This function does not
 * touch any previously set port.
 */
void
virSocketAddrSetIPv4AddrNetOrder(virSocketAddrPtr addr, uint32_t val)
{
    addr->data.stor.ss_family = AF_INET;
    addr->data.inet4.sin_addr.s_addr = val;
    addr->len = sizeof(struct sockaddr_in);
}

191 192 193 194 195 196 197 198 199 200 201
/*
 * virSocketAddrSetIPv4Addr:
 * @addr: the location to store the result
 * @val: the 32bit integer in host byte order representing the IPv4 address
 *
 * Set the IPv4 address given an integer in host order. This function does not
 * touch any previously set port.
 */
void
virSocketAddrSetIPv4Addr(virSocketAddrPtr addr, uint32_t val)
{
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    virSocketAddrSetIPv4AddrNetOrder(addr, htonl(val));
}

/*
 * virSocketAddrSetIPv6AddrNetOrder:
 * @addr: the location to store the result
 * @val: the 128bit integer in network byte order representing the IPv6 address
 *
 * Set the IPv6 address given an integer in network order. This function does not
 * touch any previously set port.
 */
void virSocketAddrSetIPv6AddrNetOrder(virSocketAddrPtr addr, uint32_t val[4])
{
    addr->data.stor.ss_family = AF_INET6;
    memcpy(addr->data.inet6.sin6_addr.s6_addr, val, 4 * sizeof(*val));
    addr->len = sizeof(struct sockaddr_in6);
218 219
}

220 221 222 223 224 225 226 227 228 229
/*
 * virSocketAddrSetIPv6Addr:
 * @addr: the location to store the result
 * @val: the 128bit integer in host byte order representing the IPv6 address
 *
 * Set the IPv6 address given an integer in host order. This function does not
 * touch any previously set port.
 */
void virSocketAddrSetIPv6Addr(virSocketAddrPtr addr, uint32_t val[4])
{
230 231 232 233 234 235 236
    size_t i = 0;
    uint32_t host_val[4];

    for (i = 0; i < 4; i++)
        host_val[i] = htonl(val[i]);

    virSocketAddrSetIPv6AddrNetOrder(addr, host_val);
237 238
}

239 240 241 242 243 244 245 246 247
/*
 * virSocketAddrEqual:
 * @s1: the location of the one IP address
 * @s2: the location of the other IP address
 *
 * Compare two IP addresses for equality. Two addresses are equal
 * if their IP addresses and ports are equal.
 */
bool
248
virSocketAddrEqual(const virSocketAddr *s1, const virSocketAddr *s2)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
{
    if (s1->data.stor.ss_family != s2->data.stor.ss_family)
        return false;

    switch (s1->data.stor.ss_family) {
    case AF_INET:
        return (memcmp(&s1->data.inet4.sin_addr.s_addr,
                       &s2->data.inet4.sin_addr.s_addr,
                       sizeof(s1->data.inet4.sin_addr.s_addr)) == 0 &&
                s1->data.inet4.sin_port == s2->data.inet4.sin_port);
    case AF_INET6:
        return (memcmp(&s1->data.inet6.sin6_addr.s6_addr,
                       &s2->data.inet6.sin6_addr.s6_addr,
                       sizeof(s1->data.inet6.sin6_addr.s6_addr)) == 0 &&
                s1->data.inet6.sin6_port == s2->data.inet6.sin6_port);
    }
265 266 267 268 269 270 271 272 273
    return false;
}

/*
 * virSocketAddrIsPrivate:
 * @s: the location of the IP address
 *
 * Return true if this address is in its family's defined
 * "private/local" address space. For IPv4, private addresses are in
274
 * the range of 192.168.0.0/16, 172.16.0.0/12, or 10.0.0.0/8.  For
275 276 277 278 279 280
 * IPv6, local addresses are in the range of FC00::/7 or FEC0::/10
 * (that last one is deprecated, but still in use).
 *
 * See RFC1918, RFC3484, and RFC4193 for details.
 */
bool
281
virSocketAddrIsPrivate(const virSocketAddr *addr)
282 283 284 285 286 287 288 289
{
    unsigned long val;

    switch (addr->data.stor.ss_family) {
    case AF_INET:
       val = ntohl(addr->data.inet4.sin_addr.s_addr);

       return ((val & 0xFFFF0000) == ((192L << 24) + (168 << 16)) ||
290
               (val & 0xFFF00000) == ((172L << 24) + (16  << 16)) ||
291 292 293 294 295 296 297
               (val & 0xFF000000) == ((10L  << 24)));

    case AF_INET6:
        return ((addr->data.inet6.sin6_addr.s6_addr[0] & 0xFE) == 0xFC ||
                ((addr->data.inet6.sin6_addr.s6_addr[0] & 0xFF) == 0xFE &&
                 (addr->data.inet6.sin6_addr.s6_addr[1] & 0xC0) == 0xC0));
    }
298 299 300
    return false;
}

301 302 303 304 305 306 307
/*
 * virSocketAddrIsWildcard:
 * @addr: address to check
 *
 * Check if passed address is a variant of ANYCAST address.
 */
bool
308
virSocketAddrIsWildcard(const virSocketAddr *addr)
309
{
310
    struct in_addr tmp = { .s_addr = INADDR_ANY };
311 312
    switch (addr->data.stor.ss_family) {
    case AF_INET:
313
        return memcmp(&addr->data.inet4.sin_addr.s_addr, &tmp.s_addr,
314 315
                      sizeof(addr->data.inet4.sin_addr.s_addr)) == 0;
    case AF_INET6:
316
        return IN6_IS_ADDR_UNSPECIFIED(&addr->data.inet6.sin6_addr);
317 318 319 320
    }
    return false;
}

321 322 323 324 325 326 327 328 329
/*
 * virSocketAddrFormat:
 * @addr: an initialized virSocketAddrPtr
 *
 * Returns a string representation of the given address
 * Returns NULL on any error
 * Caller must free the returned string
 */
char *
330 331
virSocketAddrFormat(const virSocketAddr *addr)
{
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    return virSocketAddrFormatFull(addr, false, NULL);
}


/*
 * virSocketAddrFormatFull:
 * @addr: an initialized virSocketAddrPtr
 * @withService: if true, then service info is appended
 * @separator: separator between hostname & service.
 *
 * Returns a string representation of the given address
 * Returns NULL on any error
 * Caller must free the returned string
 */
char *
347
virSocketAddrFormatFull(const virSocketAddr *addr,
348 349 350 351 352 353 354 355
                        bool withService,
                        const char *separator)
{
    char host[NI_MAXHOST], port[NI_MAXSERV];
    char *addrstr;
    int err;

    if (addr == NULL) {
356
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("Missing address"));
357 358 359 360 361 362 363 364 365
        return NULL;
    }

    /* Short-circuit since getnameinfo doesn't work
     * nicely for UNIX sockets */
    if (addr->data.sa.sa_family == AF_UNIX) {
        if (withService) {
            if (virAsprintf(&addrstr, "127.0.0.1%s0",
                            separator ? separator : ":") < 0)
366
                goto error;
367
        } else {
368 369
            if (VIR_STRDUP(addrstr, "127.0.0.1") < 0)
                goto error;
370 371 372 373 374 375 376 377 378
        }
        return addrstr;
    }

    if ((err = getnameinfo(&addr->data.sa,
                           addr->len,
                           host, sizeof(host),
                           port, sizeof(port),
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
379
        virReportError(VIR_ERR_SYSTEM_ERROR,
380 381 382 383 384 385 386
                       _("Cannot convert socket address to string: %s"),
                       gai_strerror(err));
        return NULL;
    }

    if (withService) {
        if (virAsprintf(&addrstr, "%s%s%s", host, separator, port) == -1)
387
            goto error;
388
    } else {
389 390
        if (VIR_STRDUP(addrstr, host) < 0)
            goto error;
391 392 393 394
    }

    return addrstr;

395
 error:
396 397 398 399 400 401 402 403 404 405 406 407 408 409
    return NULL;
}


/*
 * virSocketAddrSetPort:
 * @addr: an initialized virSocketAddrPtr
 * @port: the port number to set
 *
 * Set the transport layer port of the given virtSocketAddr
 *
 * Returns 0 on success, -1 on failure
 */
int
410 411
virSocketAddrSetPort(virSocketAddrPtr addr, int port)
{
412 413 414 415 416
    if (addr == NULL)
        return -1;

    port = htons(port);

417
    if (addr->data.stor.ss_family == AF_INET) {
418
        addr->data.inet4.sin_port = port;
419
    } else if (addr->data.stor.ss_family == AF_INET6) {
420
        addr->data.inet6.sin6_port = port;
421
    } else {
422 423 424 425 426 427 428 429 430 431 432 433 434 435
        return -1;
    }

    return 0;
}

/*
 * virSocketGetPort:
 * @addr: an initialized virSocketAddrPtr
 *
 * Returns the transport layer port of the given virtSocketAddr
 * Returns -1 if @addr is invalid
 */
int
436 437
virSocketAddrGetPort(virSocketAddrPtr addr)
{
438 439 440
    if (addr == NULL)
        return -1;

441
    if (addr->data.stor.ss_family == AF_INET) {
442
        return ntohs(addr->data.inet4.sin_port);
443
    } else if (addr->data.stor.ss_family == AF_INET6) {
444 445 446 447 448 449 450 451 452 453 454 455 456 457
        return ntohs(addr->data.inet6.sin6_port);
    }

    return -1;
}

/**
 * virSocketAddrIsNetmask:
 * @netmask: the netmask address
 *
 * Check that @netmask is a proper network mask
 *
 * Returns 0 in case of success and -1 in case of error
 */
458 459
int virSocketAddrIsNetmask(virSocketAddrPtr netmask)
{
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    int n = virSocketAddrGetNumNetmaskBits(netmask);
    if (n < 0)
        return -1;
    return 0;
}

/**
 * virSocketAddrMask:
 * @addr: address that needs to be masked
 * @netmask: the netmask address
 * @network: where to store the result, can be same as @addr
 *
 * Mask off the host bits of @addr according to @netmask, turning it
 * into a network address.
 *
 * Returns 0 in case of success, or -1 on error.
 */
int
478 479 480
virSocketAddrMask(const virSocketAddr *addr,
                  const virSocketAddr *netmask,
                  virSocketAddrPtr network)
481
{
482
    memset(network, 0, sizeof(*network));
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    if (addr->data.stor.ss_family != netmask->data.stor.ss_family) {
        network->data.stor.ss_family = AF_UNSPEC;
        return -1;
    }

    if (addr->data.stor.ss_family == AF_INET) {
        network->data.inet4.sin_addr.s_addr
            = (addr->data.inet4.sin_addr.s_addr
               & netmask->data.inet4.sin_addr.s_addr);
        network->data.inet4.sin_port = 0;
        network->data.stor.ss_family = AF_INET;
        network->len = addr->len;
        return 0;
    }
    if (addr->data.stor.ss_family == AF_INET6) {
498 499 500 501 502
        size_t i;
        for (i = 0; i < 16; i++) {
            network->data.inet6.sin6_addr.s6_addr[i]
                = (addr->data.inet6.sin6_addr.s6_addr[i]
                   & netmask->data.inet6.sin6_addr.s6_addr[i]);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        }
        network->data.inet6.sin6_port = 0;
        network->data.stor.ss_family = AF_INET6;
        network->len = addr->len;
        return 0;
    }
    network->data.stor.ss_family = AF_UNSPEC;
    return -1;
}

/**
 * virSocketAddrMaskByPrefix:
 * @addr: address that needs to be masked
 * @prefix: prefix (# of 1 bits) of netmask to apply
 * @network: where to store the result, can be same as @addr
 *
 * Mask off the host bits of @addr according to @prefix, turning it
 * into a network address.
 *
 * Returns 0 in case of success, or -1 on error.
 */
int
525 526 527
virSocketAddrMaskByPrefix(const virSocketAddr *addr,
                          unsigned int prefix,
                          virSocketAddrPtr network)
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
{
    virSocketAddr netmask;

    if (virSocketAddrPrefixToNetmask(prefix, &netmask,
                                     addr->data.stor.ss_family) < 0) {
        network->data.stor.ss_family = AF_UNSPEC;
        return -1;
    }

    return virSocketAddrMask(addr, &netmask, network);
}

/**
 * virSocketAddrBroadcast:
 * @addr: address that needs to be turned into broadcast address (IPv4 only)
 * @netmask: the netmask address
J
Ján Tomko 已提交
544
 * @broadcast: virSocketAddr to receive the broadcast address
545 546 547 548 549 550 551
 *
 * Mask ON the host bits of @addr according to @netmask, turning it
 * into a broadcast address.
 *
 * Returns 0 in case of success, or -1 on error.
 */
int
552 553 554
virSocketAddrBroadcast(const virSocketAddr *addr,
                       const virSocketAddr *netmask,
                       virSocketAddrPtr broadcast)
555
{
556 557
    memset(broadcast, 0, sizeof(*broadcast));

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    if ((addr->data.stor.ss_family != AF_INET) ||
        (netmask->data.stor.ss_family != AF_INET)) {
        broadcast->data.stor.ss_family = AF_UNSPEC;
        return -1;
    }

    broadcast->data.stor.ss_family = AF_INET;
    broadcast->len = addr->len;
    broadcast->data.inet4.sin_addr.s_addr
        = (addr->data.inet4.sin_addr.s_addr
           | ~netmask->data.inet4.sin_addr.s_addr);
    return 0;
}

/**
 * virSocketAddrBroadcastByPrefix:
 * @addr: address that needs to be turned into broadcast address (IPv4 only)
 * @prefix: prefix (# of 1 bits) of netmask to apply
J
Ján Tomko 已提交
576
 * @broadcast: virSocketAddr to receive the broadcast address
577 578 579 580 581 582 583
 *
 * Mask off the host bits of @addr according to @prefix, turning it
 * into a network address.
 *
 * Returns 0 in case of success, or -1 on error.
 */
int
584 585 586
virSocketAddrBroadcastByPrefix(const virSocketAddr *addr,
                               unsigned int prefix,
                               virSocketAddrPtr broadcast)
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
{
    virSocketAddr netmask;

    if (virSocketAddrPrefixToNetmask(prefix, &netmask,
                                     addr->data.stor.ss_family) < 0)
        return -1;

    return virSocketAddrBroadcast(addr, &netmask, broadcast);
}

/**
 * virSocketCheckNetmask:
 * @addr1: a first network address
 * @addr2: a second network address
 * @netmask: the netmask address
 *
 * Check that @addr1 and @addr2 pertain to the same @netmask address
 * range and returns the size of the range
 *
 * Returns 1 in case of success and 0 in case of failure and
 *         -1 in case of error
 */
int virSocketAddrCheckNetmask(virSocketAddrPtr addr1, virSocketAddrPtr addr2,
610 611
                              virSocketAddrPtr netmask)
{
612
    size_t i;
613 614

    if ((addr1 == NULL) || (addr2 == NULL) || (netmask == NULL))
615
        return -1;
616 617
    if ((addr1->data.stor.ss_family != addr2->data.stor.ss_family) ||
        (addr1->data.stor.ss_family != netmask->data.stor.ss_family))
618
        return -1;
619 620

    if (virSocketAddrIsNetmask(netmask) != 0)
621
        return -1;
622 623 624 625 626 627 628

    if (addr1->data.stor.ss_family == AF_INET) {
        virSocketAddrIPv4 t1, t2, tm;

        if ((virSocketAddrGetIPv4Addr(addr1, &t1) < 0) ||
            (virSocketAddrGetIPv4Addr(addr2, &t2) < 0) ||
            (virSocketAddrGetIPv4Addr(netmask, &tm) < 0))
629
            return -1;
630

631
        for (i = 0; i < 4; i++) {
632
            if ((t1[i] & tm[i]) != (t2[i] & tm[i]))
633
                return 0;
634 635 636 637 638 639 640 641
        }

    } else if (addr1->data.stor.ss_family == AF_INET6) {
        virSocketAddrIPv6 t1, t2, tm;

        if ((virSocketAddrGetIPv6Addr(addr1, &t1) < 0) ||
            (virSocketAddrGetIPv6Addr(addr2, &t2) < 0) ||
            (virSocketAddrGetIPv6Addr(netmask, &tm) < 0))
642
            return -1;
643

644
        for (i = 0; i < 8; i++) {
645
            if ((t1[i] & tm[i]) != (t2[i] & tm[i]))
646
                return 0;
647 648 649
        }

    } else {
650
        return -1;
651
    }
652
    return 1;
653 654 655 656 657 658
}

/**
 * virSocketGetRange:
 * @start: start of an IP range
 * @end: end of an IP range
659 660
 * @network: IP address of network that should completely contain this range
 * @prefix: prefix of the network
661
 *
662 663 664 665 666
 * Check the order of the 2 addresses and compute the range, this will
 * return 1 for identical addresses. Errors can come from incompatible
 * addresses type, excessive range (>= 2^^16) where the two addresses
 * are unrelated, inverted start and end, or a range that is not
 * within network/prefix.
667 668 669
 *
 * Returns the size of the range or -1 in case of failure
 */
670 671 672
int
virSocketAddrGetRange(virSocketAddrPtr start, virSocketAddrPtr end,
                      virSocketAddrPtr network, int prefix)
673
{
674 675
    int ret = 0;
    size_t i;
676
    virSocketAddr netmask;
677
    char *startStr = NULL, *endStr = NULL, *netStr = NULL;
678

679
    if (start == NULL || end == NULL) {
680
        virReportError(VIR_ERR_INTERNAL_ERROR,
681
                       _("NULL argument - %p %p"), start, end);
682 683 684 685 686
        goto error;
    }

    startStr = virSocketAddrFormat(start);
    endStr = virSocketAddrFormat(end);
687
    if (!startStr || !endStr)
688
        goto error; /*error already reported */
689

690
    if (VIR_SOCKET_ADDR_FAMILY(start) != VIR_SOCKET_ADDR_FAMILY(end)) {
691
        virReportError(VIR_ERR_INTERNAL_ERROR,
692 693
                       _("mismatch of address family in range %s - %s"),
                       startStr, endStr);
694 695
        goto error;
    }
696

697 698 699 700 701 702
    if (network) {
        /* some checks can only be done if we have details of the
         * network the range should be within
         */
        if (!(netStr = virSocketAddrFormat(network)))
            goto error;
703

704
        if (VIR_SOCKET_ADDR_FAMILY(start) != VIR_SOCKET_ADDR_FAMILY(network)) {
705
            virReportError(VIR_ERR_INTERNAL_ERROR,
706 707 708
                           _("mismatch of address family in "
                             "range %s - %s for network %s"),
                           startStr, endStr, netStr);
709 710
            goto error;
        }
711

712 713 714
        if (prefix < 0 ||
            virSocketAddrPrefixToNetmask(prefix, &netmask,
                                         VIR_SOCKET_ADDR_FAMILY(network)) < 0) {
715
            virReportError(VIR_ERR_INTERNAL_ERROR,
716 717 718
                           _("bad prefix %d for network %s when "
                             " checking range %s - %s"),
                           prefix, netStr, startStr, endStr);
719 720 721
            goto error;
        }

722 723 724
        /* both start and end of range need to be within network */
        if (virSocketAddrCheckNetmask(start, network, &netmask) <= 0 ||
            virSocketAddrCheckNetmask(end, network, &netmask) <= 0) {
725
            virReportError(VIR_ERR_INTERNAL_ERROR,
726 727
                           _("range %s - %s is not entirely within "
                             "network %s/%d"),
728 729 730
                           startStr, endStr, netStr, prefix);
            goto error;
        }
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
        if (VIR_SOCKET_ADDR_IS_FAMILY(start, AF_INET)) {
            virSocketAddr netaddr, broadcast;

            if (virSocketAddrBroadcast(network, &netmask, &broadcast) < 0 ||
                virSocketAddrMask(network, &netmask, &netaddr) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("failed to construct broadcast or network "
                                 "address for network %s/%d"),
                               netStr, prefix);
                goto error;
            }

            /* Don't allow the start of the range to be the network
             * address (usually "...0") or the end of the range to be the
             * broadcast address (usually "...255"). (the opposite also
             * isn't allowed, but checking for that is implicit in all the
             * other combined checks) (IPv6 doesn't have broadcast and
             * network addresses, so this check is only done for IPv4)
             */
            if (virSocketAddrEqual(start, &netaddr)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("start of range %s - %s in network %s/%d "
                                 "is the network address"),
                               startStr, endStr, netStr, prefix);
                goto error;
            }

            if (virSocketAddrEqual(end, &broadcast)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("end of range %s - %s in network %s/%d "
                                 "is the broadcast address"),
                               startStr, endStr, netStr, prefix);
                goto error;
            }
        }
    }

    if (VIR_SOCKET_ADDR_IS_FAMILY(start, AF_INET)) {
        virSocketAddrIPv4 t1, t2;

        if (virSocketAddrGetIPv4Addr(start, &t1) < 0 ||
            virSocketAddrGetIPv4Addr(end, &t2) < 0) {
774 775
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to get IPv4 address "
776 777
                             "for start or end of range %s - %s"),
                           startStr, endStr);
778 779
            goto error;
        }
780

781 782
        /* legacy check that everything except the last two bytes
         * are the same
783
         */
784
        for (i = 0; i < 2; i++) {
785 786
            if (t1[i] != t2[i]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
787 788
                           _("range %s - %s is too large (> 65535)"),
                           startStr, endStr);
789 790
            goto error;
            }
791 792
        }
        ret = (t2[2] - t1[2]) * 256 + (t2[3] - t1[3]);
793 794
        if (ret < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
795 796
                           _("range %s - %s is reversed "),
                           startStr, endStr);
797 798
            goto error;
        }
799
        ret++;
800
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(start, AF_INET6)) {
801 802
        virSocketAddrIPv6 t1, t2;

803 804
        if (virSocketAddrGetIPv6Addr(start, &t1) < 0 ||
            virSocketAddrGetIPv6Addr(end, &t2) < 0) {
805 806
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("failed to get IPv6 address "
807 808
                             "for start or end of range %s - %s"),
                           startStr, endStr);
809 810
            goto error;
        }
811

812 813 814
        /* legacy check that everything except the last two bytes are
         * the same
         */
815
        for (i = 0; i < 7; i++) {
816 817
            if (t1[i] != t2[i]) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
818 819
                               _("range %s - %s is too large (> 65535)"),
                               startStr, endStr);
820 821
                goto error;
            }
822 823
        }
        ret = t2[7] - t1[7];
824 825
        if (ret < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
826 827
                           _("range %s - %s start larger than end"),
                           startStr, endStr);
828 829
            goto error;
        }
830 831
        ret++;
    } else {
832 833
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported address family "
834 835
                         "for range %s - %s, must be ipv4 or ipv6"),
                       startStr, endStr);
836
        goto error;
837
    }
838

839 840 841 842
 cleanup:
    VIR_FREE(startStr);
    VIR_FREE(endStr);
    VIR_FREE(netStr);
843
    return ret;
844 845 846 847

 error:
    ret = -1;
    goto cleanup;
848 849 850 851 852 853 854 855 856 857 858 859
}


/**
 * virSocketAddrGetNumNetmaskBits
 * @netmask: the presumed netmask
 *
 * Get the number of netmask bits in a netmask.
 *
 * Returns the number of bits in the netmask or -1 if an error occurred
 * or the netmask is invalid.
 */
860
int virSocketAddrGetNumNetmaskBits(const virSocketAddr *netmask)
861
{
862
    size_t i, j;
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    int c = 0;

    if (netmask->data.stor.ss_family == AF_INET) {
        virSocketAddrIPv4 tm;
        uint8_t bit;

        if (virSocketAddrGetIPv4Addr(netmask, &tm) < 0)
            return -1;

        for (i = 0; i < 4; i++)
            if (tm[i] == 0xff)
                c += 8;
            else
                break;

        if (c == 8 * 4)
            return c;

        j = i << 3;
        while (j < (8 * 4)) {
            bit = 1 << (7 - (j & 7));
884
            if ((tm[j >> 3] & bit))
885
                c++;
886
            else
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
                break;
            j++;
        }

        while (j < (8 * 4)) {
            bit = 1 << (7 - (j & 7));
            if ((tm[j >> 3] & bit))
                return -1;
            j++;
        }

        return c;
    } else if (netmask->data.stor.ss_family == AF_INET6) {
        virSocketAddrIPv6 tm;
        uint16_t bit;

        if (virSocketAddrGetIPv6Addr(netmask, &tm) < 0)
            return -1;

        for (i = 0; i < 8; i++)
            if (tm[i] == 0xffff)
                c += 16;
            else
                break;

        if (c == 16 * 8)
            return c;

        j = i << 4;
        while (j < (16 * 8)) {
            bit = 1 << (15 - (j & 0xf));
918
            if ((tm[j >> 4] & bit))
919
                c++;
920
            else
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
                break;
            j++;
        }

        while (j < (16 * 8)) {
            bit = 1 << (15 - (j & 0xf));
            if ((tm[j >> 4]) & bit)
                return -1;
            j++;
        }

        return c;
    }
    return -1;
}

/**
 * virSocketPrefixToNetmask:
 * @prefix: number of 1 bits to put in the netmask
 * @netmask: address to fill in with the desired netmask
 * @family: family of the address (AF_INET or AF_INET6 only)
 *
 * given @prefix and @family, fill in @netmask with a netmask
 * (eg 255.255.255.0).
 *
 * Returns 0 on success or -1 on error.
 */

int
virSocketAddrPrefixToNetmask(unsigned int prefix,
                             virSocketAddrPtr netmask,
                             int family)
{
    int result = -1;

    netmask->data.stor.ss_family = AF_UNSPEC; /* assume failure */

    if (family == AF_INET) {
        int ip;

        if (prefix > 32)
            goto error;

        ip = prefix ? ~((1 << (32 - prefix)) - 1) : 0;
        netmask->data.inet4.sin_addr.s_addr = htonl(ip);
        netmask->data.stor.ss_family = AF_INET;
        result = 0;

    } else if (family == AF_INET6) {
970
        size_t i = 0;
971 972 973 974 975 976

        if (prefix > 128)
            goto error;

        while (prefix >= 8) {
            /* do as much as possible an entire byte at a time */
977
            netmask->data.inet6.sin6_addr.s6_addr[i++] = 0xff;
978 979 980 981
            prefix -= 8;
        }
        if (prefix > 0) {
            /* final partial byte */
982
            netmask->data.inet6.sin6_addr.s6_addr[i++]
983 984
                = ~((1 << (8 - prefix)) -1);
        }
985
        while (i < 16) {
986
            /* zerofill remainder in case it wasn't initialized */
987
            netmask->data.inet6.sin6_addr.s6_addr[i++] = 0;
988 989 990 991 992
        }
        netmask->data.stor.ss_family = AF_INET6;
        result = 0;
    }

993
 error:
994
    return result;
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
 }

/**
 * virSocketAddrGetIpPrefix:
 * @address: network address
 * @netmask: netmask for this network
 * @prefix: prefix if specified instead of netmask
 *
 * Returns prefix value on success or -1 on error.
 */

int
1007 1008
virSocketAddrGetIpPrefix(const virSocketAddr *address,
                         const virSocketAddr *netmask,
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
                         int prefix)
{
    if (prefix > 0) {
        return prefix;
    } else if (VIR_SOCKET_ADDR_VALID(netmask)) {
        return virSocketAddrGetNumNetmaskBits(netmask);
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(address, AF_INET)) {
        /* Return the natural prefix for the network's ip address.
         * On Linux we could use the IN_CLASSx() macros, but those
         * aren't guaranteed on all platforms, so we just deal with
         * the bits ourselves.
         */
        unsigned char octet
            = ntohl(address->data.inet4.sin_addr.s_addr) >> 24;
1023 1024 1025 1026 1027 1028

        /* If address is 0.0.0.0, we surely want to have 0 prefix for
         * the default route. */
        if (address->data.inet4.sin_addr.s_addr == 0)
            return 0;

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        if ((octet & 0x80) == 0) {
            /* Class A network */
            return 8;
        } else if ((octet & 0xC0) == 0x80) {
            /* Class B network */
            return 16;
        } else if ((octet & 0xE0) == 0xC0) {
            /* Class C network */
            return 24;
        }
        return -1;
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(address, AF_INET6)) {
1041
        if (virSocketAddrIsWildcard(address))
1042
            return 0;
1043 1044 1045 1046 1047 1048 1049 1050 1051
        return 64;
    }

    /* When none of the three (address/netmask/prefix) is given, 0 is
     * returned rather than error, because this is a valid
     * expectation, e.g. for the address/prefix used for a default
     * route (the destination of a default route is 0.0.0.0/0).
     */
    return 0;
1052
}
1053 1054

/**
1055
 * virSocketAddrNumericFamily:
1056 1057
 * @address: address to check
 *
1058
 * Check if passed address is an IP address in numeric format.
1059
 *
1060 1061
 * Returns: AF_INET or AF_INET6 if @address is an numeric IP address,
 *          -1 otherwise.
1062
 */
1063 1064
int
virSocketAddrNumericFamily(const char *address)
1065 1066 1067 1068 1069
{
    struct addrinfo *res;
    unsigned short family;

    if (virSocketAddrParseInternal(&res, address, AF_UNSPEC, false) < 0)
1070
        return -1;
1071 1072 1073

    family = res->ai_addr->sa_family;
    freeaddrinfo(res);
1074
    return family;
1075
}
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

/**
 * virSocketAddrIsNumericLocalhost:
 * @address: address to check
 *
 * Check if passed address is a numeric 'localhost' address.
 *
 * Returns: true if @address is a numeric 'localhost' address,
 *          false otherwise
 */
bool
virSocketAddrIsNumericLocalhost(const char *addr)
{
R
Roman Bogorodskiy 已提交
1089
    virSocketAddr res;
1090 1091
    struct in_addr tmp = { .s_addr = htonl(INADDR_LOOPBACK) };

R
Roman Bogorodskiy 已提交
1092 1093
    if (virSocketAddrParse(&res, addr, AF_UNSPEC) < 0)
        return false;
1094

R
Roman Bogorodskiy 已提交
1095
    switch (res.data.stor.ss_family) {
1096
    case AF_INET:
R
Roman Bogorodskiy 已提交
1097 1098
        return memcmp(&res.data.inet4.sin_addr.s_addr, &tmp.s_addr,
                     sizeof(res.data.inet4.sin_addr.s_addr)) == 0;
1099
    case AF_INET6:
R
Roman Bogorodskiy 已提交
1100
        return IN6_IS_ADDR_LOOPBACK(&res.data.inet6.sin6_addr);
1101
    }
1102

R
Roman Bogorodskiy 已提交
1103
    return false;
1104
}