network.c 17.4 KB
Newer Older
1 2 3
/*
 * network.c: network helper APIs for libvirt
 *
4
 * Copyright (C) 2009-2011 Red Hat, Inc.
5 6 7 8 9 10 11
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
 */

#include <config.h>
M
Matthew Booth 已提交
12
#include <arpa/inet.h>
13 14 15

#include "memory.h"
#include "network.h"
16 17 18 19 20 21 22
#include "util.h"
#include "virterror_internal.h"

#define VIR_FROM_THIS VIR_FROM_NONE
#define virSocketError(code, ...)                                       \
    virReportErrorHelper(NULL, VIR_FROM_THIS, code, __FILE__,           \
                         __FUNCTION__, __LINE__, __VA_ARGS__)
23 24 25 26 27 28 29 30 31 32 33 34 35 36

/*
 * Helpers to extract the IP arrays from the virSocketAddrPtr
 * That part is the less portable of the module
 */
typedef unsigned char virIPv4Addr[4];
typedef virIPv4Addr *virIPv4AddrPtr;
typedef unsigned short virIPv6Addr[8];
typedef virIPv6Addr *virIPv6AddrPtr;

static int getIPv4Addr(virSocketAddrPtr addr, virIPv4AddrPtr tab) {
    unsigned long val;
    int i;

37
    if ((addr == NULL) || (tab == NULL) || (addr->data.stor.ss_family != AF_INET))
38 39
        return(-1);

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

    for (i = 0;i < 4;i++) {
43
        (*tab)[3 - i] = val & 0xFF;
44 45 46 47 48 49 50 51 52
        val >>= 8;
    }

    return(0);
}

static int getIPv6Addr(virSocketAddrPtr addr, virIPv6AddrPtr tab) {
    int i;

53
    if ((addr == NULL) || (tab == NULL) || (addr->data.stor.ss_family != AF_INET6))
54 55 56
        return(-1);

    for (i = 0;i < 8;i++) {
57 58
        (*tab)[i] = ((addr->data.inet6.sin6_addr.s6_addr[2 * i] << 8) |
                     addr->data.inet6.sin6_addr.s6_addr[2 * i + 1]);
59 60 61 62 63 64 65 66
    }

    return(0);
}

/**
 * virSocketParseAddr:
 * @val: a numeric network address IPv4 or IPv6
67
 * @addr: where to store the return value, optional.
68
 * @family: address family to pass down to getaddrinfo
69 70 71 72
 *
 * 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
 *
M
Matthew Booth 已提交
73
 * Returns the length of the network address or -1 in case of error.
74 75
 */
int
76
virSocketParseAddr(const char *val, virSocketAddrPtr addr, int family) {
77 78 79
    int len;
    struct addrinfo hints;
    struct addrinfo *res = NULL;
80
    int err;
81

82
    if (val == NULL) {
83
        virSocketError(VIR_ERR_INVALID_ARG, "%s", _("Missing address"));
84 85
        return -1;
    }
86 87

    memset(&hints, 0, sizeof(hints));
88 89
    hints.ai_family = family;
    hints.ai_flags = AI_NUMERICHOST;
90 91 92 93 94 95 96 97 98 99 100 101
    if ((err = getaddrinfo(val, NULL, &hints, &res)) != 0) {
        virSocketError(VIR_ERR_SYSTEM_ERROR,
                       _("Cannot parse socket address '%s': %s"),
                       val, gai_strerror(err));
        return -1;
    }

    if (res == NULL) {
        virSocketError(VIR_ERR_SYSTEM_ERROR,
                       _("No socket addresses found for '%s'"),
                       val);
        return -1;
102 103 104
    }

    len = res->ai_addrlen;
105 106 107 108
    if (addr != NULL) {
        memcpy(&addr->data.stor, res->ai_addr, len);
        addr->len = res->ai_addrlen;
    }
109 110 111 112 113 114 115 116

    freeaddrinfo(res);
    return(len);
}

/*
 * virSocketParseIpv4Addr:
 * @val: an IPv4 numeric address
117
 * @addr: the location to store the result
118 119 120
 *
 * Extract the address storage from an IPv4 numeric address
 *
121
 * Returns the length of the network address or -1 in case of error.
122 123 124 125 126 127 128 129 130
 */
int
virSocketParseIpv4Addr(const char *val, virSocketAddrPtr addr) {
    return(virSocketParseAddr(val, addr, AF_INET));
}

/*
 * virSocketParseIpv6Addr:
 * @val: an IPv6 numeric address
131
 * @addr: the location to store the result
132 133 134
 *
 * Extract the address storage from an IPv6 numeric address
 *
135
 * Returns the length of the network address or -1 in case of error.
136 137 138 139 140 141
 */
int
virSocketParseIpv6Addr(const char *val, virSocketAddrPtr addr) {
    return(virSocketParseAddr(val, addr, AF_INET6));
}

M
Matthew Booth 已提交
142 143
/*
 * virSocketFormatAddr:
E
Eric Blake 已提交
144
 * @addr: an initialized virSocketAddrPtr
M
Matthew Booth 已提交
145 146 147 148 149 150 151
 *
 * Returns a string representation of the given address
 * Returns NULL on any error
 * Caller must free the returned string
 */
char *
virSocketFormatAddr(virSocketAddrPtr addr) {
152 153
    return virSocketFormatAddrFull(addr, false, NULL);
}
M
Matthew Booth 已提交
154 155


156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
/*
 * virSocketFormatAddrFull:
 * @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 *
virSocketFormatAddrFull(virSocketAddrPtr addr,
                        bool withService,
                        const char *separator)
{
    char host[NI_MAXHOST], port[NI_MAXSERV];
    char *addrstr;
    int err;

    if (addr == NULL) {
176
        virSocketError(VIR_ERR_INVALID_ARG, "%s", _("Missing address"));
177
        return NULL;
M
Matthew Booth 已提交
178 179
    }

180 181 182 183 184 185 186 187 188 189 190 191
    /* 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)
                goto no_memory;
        } else {
            if (!(addrstr = strdup("127.0.0.1")))
                goto no_memory;
        }
        return addrstr;
M
Matthew Booth 已提交
192 193
    }

194 195 196 197 198 199 200 201
    if ((err = getnameinfo(&addr->data.sa,
                           addr->len,
                           host, sizeof(host),
                           port, sizeof(port),
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
        virSocketError(VIR_ERR_SYSTEM_ERROR,
                       _("Cannot convert socket address to string: %s"),
                       gai_strerror(err));
M
Matthew Booth 已提交
202 203 204
        return NULL;
    }

205 206 207 208 209 210
    if (withService) {
        if (virAsprintf(&addrstr, "%s%s%s", host, separator, port) == -1)
            goto no_memory;
    } else {
        if (!(addrstr = strdup(host)))
            goto no_memory;
M
Matthew Booth 已提交
211 212
    }

213 214 215 216 217
    return addrstr;

no_memory:
    virReportOOMError();
    return NULL;
M
Matthew Booth 已提交
218 219
}

220

M
Matthew Booth 已提交
221 222
/*
 * virSocketSetPort:
E
Eric Blake 已提交
223
 * @addr: an initialized virSocketAddrPtr
M
Matthew Booth 已提交
224 225 226 227 228 229 230 231 232 233 234
 * @port: the port number to set
 *
 * Set the transport layer port of the given virtSocketAddr
 *
 * Returns 0 on success, -1 on failure
 */
int
virSocketSetPort(virSocketAddrPtr addr, int port) {
    if (addr == NULL)
        return -1;

235 236
    port = htons(port);

237 238
    if(addr->data.stor.ss_family == AF_INET) {
        addr->data.inet4.sin_port = port;
M
Matthew Booth 已提交
239 240
    }

241 242
    else if(addr->data.stor.ss_family == AF_INET6) {
        addr->data.inet6.sin6_port = port;
M
Matthew Booth 已提交
243 244 245 246 247 248 249 250 251 252 253
    }

    else {
        return -1;
    }

    return 0;
}

/*
 * virSocketGetPort:
E
Eric Blake 已提交
254
 * @addr: an initialized virSocketAddrPtr
M
Matthew Booth 已提交
255 256 257 258 259 260 261 262 263
 *
 * Returns the transport layer port of the given virtSocketAddr
 * Returns -1 if @addr is invalid
 */
int
virSocketGetPort(virSocketAddrPtr addr) {
    if (addr == NULL)
        return -1;

264 265
    if(addr->data.stor.ss_family == AF_INET) {
        return ntohs(addr->data.inet4.sin_port);
M
Matthew Booth 已提交
266 267
    }

268 269
    else if(addr->data.stor.ss_family == AF_INET6) {
        return ntohs(addr->data.inet6.sin6_port);
M
Matthew Booth 已提交
270 271 272 273 274
    }

    return -1;
}

275 276 277 278 279 280 281 282 283
/**
 * 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
 */
int virSocketAddrIsNetmask(virSocketAddrPtr netmask) {
284 285 286 287
    int n = virSocketGetNumNetmaskBits(netmask);
    if (n < 0)
        return -1;
    return 0;
288 289
}

L
Laine Stump 已提交
290 291 292 293
/**
 * virSocketAddrMask:
 * @addr: address that needs to be masked
 * @netmask: the netmask address
294
 * @network: where to store the result, can be same as @addr
L
Laine Stump 已提交
295 296 297 298 299 300 301
 *
 * 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
302 303 304
virSocketAddrMask(const virSocketAddrPtr addr,
                  const virSocketAddrPtr netmask,
                  virSocketAddrPtr       network)
L
Laine Stump 已提交
305
{
306 307
    if (addr->data.stor.ss_family != netmask->data.stor.ss_family) {
        network->data.stor.ss_family = AF_UNSPEC;
L
Laine Stump 已提交
308
        return -1;
309
    }
L
Laine Stump 已提交
310 311

    if (addr->data.stor.ss_family == AF_INET) {
312 313 314
        network->data.inet4.sin_addr.s_addr
            = (addr->data.inet4.sin_addr.s_addr
               & netmask->data.inet4.sin_addr.s_addr);
315
        network->data.inet4.sin_port = 0;
316 317
        network->data.stor.ss_family = AF_INET;
        network->len = addr->len;
L
Laine Stump 已提交
318 319 320 321
        return 0;
    }
    if (addr->data.stor.ss_family == AF_INET6) {
        int ii;
322 323 324 325 326
        for (ii = 0; ii < 16; ii++) {
            network->data.inet6.sin6_addr.s6_addr[ii]
                = (addr->data.inet6.sin6_addr.s6_addr[ii]
                   & netmask->data.inet6.sin6_addr.s6_addr[ii]);
        }
327
        network->data.inet6.sin6_port = 0;
328 329
        network->data.stor.ss_family = AF_INET6;
        network->len = addr->len;
L
Laine Stump 已提交
330 331
        return 0;
    }
332
    network->data.stor.ss_family = AF_UNSPEC;
L
Laine Stump 已提交
333 334 335 336 337 338 339
    return -1;
}

/**
 * virSocketAddrMaskByPrefix:
 * @addr: address that needs to be masked
 * @prefix: prefix (# of 1 bits) of netmask to apply
340
 * @network: where to store the result, can be same as @addr
L
Laine Stump 已提交
341 342 343 344 345 346 347
 *
 * 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
348 349 350
virSocketAddrMaskByPrefix(const virSocketAddrPtr addr,
                          unsigned int           prefix,
                          virSocketAddrPtr       network)
L
Laine Stump 已提交
351 352 353 354
{
    virSocketAddr netmask;

    if (virSocketAddrPrefixToNetmask(prefix, &netmask,
355 356
                                     addr->data.stor.ss_family) < 0) {
        network->data.stor.ss_family = AF_UNSPEC;
L
Laine Stump 已提交
357
        return -1;
358
    }
L
Laine Stump 已提交
359

360
    return virSocketAddrMask(addr, &netmask, network);
L
Laine Stump 已提交
361 362
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
/**
 * virSocketAddrBroadcast:
 * @addr: address that needs to be turned into broadcast address (IPv4 only)
 * @netmask: the netmask address
 * @broadcast: virSocketAddr to recieve the broadcast address
 *
 * 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
virSocketAddrBroadcast(const virSocketAddrPtr addr,
                       const virSocketAddrPtr netmask,
                       virSocketAddrPtr       broadcast)
{
    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
 * @broadcast: virSocketAddr to recieve the broadcast address
 *
 * 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
virSocketAddrBroadcastByPrefix(const virSocketAddrPtr addr,
                               unsigned int           prefix,
                               virSocketAddrPtr       broadcast)
{
    virSocketAddr netmask;

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

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

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/**
 * 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 virSocketCheckNetmask(virSocketAddrPtr addr1, virSocketAddrPtr addr2,
                          virSocketAddrPtr netmask) {
    int i;

    if ((addr1 == NULL) || (addr2 == NULL) || (netmask == NULL))
        return(-1);
436 437
    if ((addr1->data.stor.ss_family != addr2->data.stor.ss_family) ||
        (addr1->data.stor.ss_family != netmask->data.stor.ss_family))
438 439 440 441 442
        return(-1);

    if (virSocketAddrIsNetmask(netmask) != 0)
        return(-1);

443
    if (addr1->data.stor.ss_family == AF_INET) {
444 445 446 447 448 449 450 451 452 453 454 455
        virIPv4Addr t1, t2, tm;

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

        for (i = 0;i < 4;i++) {
            if ((t1[i] & tm[i]) != (t2[i] & tm[i]))
                return(0);
        }

456
    } else if (addr1->data.stor.ss_family == AF_INET6) {
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
        virIPv6Addr t1, t2, tm;

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

        for (i = 0;i < 8;i++) {
            if ((t1[i] & tm[i]) != (t2[i] & tm[i]))
                return(0);
        }

    } else {
        return(-1);
    }
    return(1);
}

/**
 * virSocketGetRange:
 * @start: start of an IP range
 * @end: end of an IP range
 *
 * 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 or inverted start and end.
 *
 * Returns the size of the range or -1 in case of failure
 */
int virSocketGetRange(virSocketAddrPtr start, virSocketAddrPtr end) {
    int ret = 0, i;

    if ((start == NULL) || (end == NULL))
        return(-1);
492
    if (start->data.stor.ss_family != end->data.stor.ss_family)
493 494
        return(-1);

495
    if (start->data.stor.ss_family == AF_INET) {
496 497 498 499 500 501 502 503 504 505 506 507 508 509
        virIPv4Addr t1, t2;

        if ((getIPv4Addr(start, &t1) < 0) ||
            (getIPv4Addr(end, &t2) < 0))
            return(-1);

        for (i = 0;i < 2;i++) {
            if (t1[i] != t2[i])
                return(-1);
        }
        ret = (t2[2] - t1[2]) * 256 + (t2[3] - t1[3]);
        if (ret < 0)
            return(-1);
        ret++;
510
    } else if (start->data.stor.ss_family == AF_INET6) {
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        virIPv6Addr t1, t2;

        if ((getIPv6Addr(start, &t1) < 0) ||
            (getIPv6Addr(end, &t2) < 0))
            return(-1);

        for (i = 0;i < 7;i++) {
            if (t1[i] != t2[i])
                return(-1);
        }
        ret = t2[7] - t1[7];
        if (ret < 0)
            return(-1);
        ret++;
    } else {
        return(-1);
    }
    return(ret);
}
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545


/**
 * virGetNumNetmaskBits
 * @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.
 */
int virSocketGetNumNetmaskBits(const virSocketAddrPtr netmask)
{
    int i, j;
    int c = 0;

546
    if (netmask->data.stor.ss_family == AF_INET) {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
        virIPv4Addr tm;
        uint8_t bit;

        if (getIPv4Addr(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));
            if ((tm[j >> 3] & bit)) {
                c++;
            } else
                break;
            j++;
        }

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

        return c;
580
    } else if (netmask->data.stor.ss_family == AF_INET6) {
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        virIPv6Addr tm;
        uint16_t bit;

        if (getIPv6Addr(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));
            if ((tm[j >> 4] & bit)) {
                c++;
            } else
                break;
            j++;
        }

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

        return c;
    }
    return -1;
}
L
Laine Stump 已提交
617 618 619 620 621 622 623 624 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

/**
 * 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) {
        int ii = 0;

        if (prefix > 128)
            goto error;

        while (prefix >= 8) {
            /* do as much as possible an entire byte at a time */
            netmask->data.inet6.sin6_addr.s6_addr[ii++] = 0xff;
            prefix -= 8;
        }
        if (prefix > 0) {
            /* final partial byte */
            netmask->data.inet6.sin6_addr.s6_addr[ii++]
                = ~((1 << (8 - prefix)) -1);
        }
        while (ii < 16) {
            /* zerofill remainder in case it wasn't initialized */
            netmask->data.inet6.sin6_addr.s6_addr[ii++] = 0;
        }
        netmask->data.stor.ss_family = AF_INET6;
        result = 0;
    }

error:
    return result;
}