tcp_address.cpp 26.9 KB
Newer Older
1
/*
2
    Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
3

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
5

6 7 8
    libzmq is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
9 10
    (at your option) any later version.

11 12 13 14 15 16 17 18 19 20 21 22 23 24
    As a special exception, the Contributors give you permission to link
    this library with independent modules to produce an executable,
    regardless of the license terms of these independent modules, and to
    copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the
    terms and conditions of the license of that module. An independent
    module is a module which is not derived from or based on this library.
    If you modify this library, you must extend this exception to your
    version of the library.

    libzmq 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.
25 26 27 28 29

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

30
#include "precompiled.hpp"
31
#include <string>
32
#include <sstream>
33

34
#include "macros.hpp"
35
#include "tcp_address.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
36
#include "stdint.hpp"
37
#include "err.hpp"
38
#include "ip.hpp"
39

40
#ifndef ZMQ_HAVE_WINDOWS
41 42 43
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
44
#include <net/if.h>
45
#include <netdb.h>
46
#include <ctype.h>
47 48
#include <unistd.h>
#include <stdlib.h>
49 50
#endif

Martin Hurton's avatar
Martin Hurton committed
51
#ifdef ZMQ_HAVE_SOLARIS
52 53 54
#include <sys/sockio.h>

//  On Solaris platform, network interface name can be queried by ioctl.
55
int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_)
56 57
{
    //  TODO: Unused parameter, IPv6 support not implemented for Solaris.
58
    LIBZMQ_UNUSED (ipv6_);
59 60

    //  Create a socket.
Martin Hurton's avatar
Martin Hurton committed
61
    const int fd = open_socket (AF_INET, SOCK_DGRAM, 0);
62
    errno_assert (fd != -1);
63 64 65 66 67 68

    //  Retrieve number of interfaces.
    lifnum ifn;
    ifn.lifn_family = AF_INET;
    ifn.lifn_flags = 0;
    int rc = ioctl (fd, SIOCGLIFNUM, (char*) &ifn);
69
    errno_assert (rc != -1);
70 71

    //  Allocate memory to get interface names.
Martin Hurton's avatar
Martin Hurton committed
72
    const size_t ifr_size = sizeof (struct lifreq) * ifn.lifn_count;
73 74
    char *ifr = (char*) malloc (ifr_size);
    alloc_assert (ifr);
75

76 77 78 79 80 81 82
    //  Retrieve interface names.
    lifconf ifc;
    ifc.lifc_family = AF_INET;
    ifc.lifc_flags = 0;
    ifc.lifc_len = ifr_size;
    ifc.lifc_buf = ifr;
    rc = ioctl (fd, SIOCGLIFCONF, (char*) &ifc);
83
    errno_assert (rc != -1);
84 85 86 87

    //  Find the interface with the specified name and AF_INET family.
    bool found = false;
    lifreq *ifrp = ifc.lifc_req;
88
    for (int n = 0; n < (int) (ifc.lifc_len / sizeof (lifreq));
89
          n ++, ifrp ++) {
90
        if (!strcmp (nic_, ifrp->lifr_name)) {
91
            rc = ioctl (fd, SIOCGLIFADDR, (char*) ifrp);
92
            errno_assert (rc != -1);
93
            if (ifrp->lifr_addr.ss_family == AF_INET) {
Martin Hurton's avatar
Martin Hurton committed
94
                if (is_src_)
95
                    source_address.ipv4 = *(sockaddr_in*) &ifrp->lifr_addr;
Martin Hurton's avatar
Martin Hurton committed
96 97
                else
                    address.ipv4 = *(sockaddr_in*) &ifrp->lifr_addr;
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
                found = true;
                break;
            }
        }
    }

    //  Clean-up.
    free (ifr);
    close (fd);

    if (!found) {
        errno = ENODEV;
        return -1;
    }
    return 0;
}

115
#elif defined ZMQ_HAVE_AIX || defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_ANDROID
116 117
#include <sys/ioctl.h>

118
int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_)
119
{
120 121 122 123 124 125 126 127
#if defined ZMQ_HAVE_AIX || defined ZMQ_HAVE_HPUX
    // IPv6 support not implemented for AIX or HP/UX.
    if (ipv6_)
    {
        errno = ENODEV;
        return -1;
    }
#endif
128 129

    //  Create a socket.
130
    const int sd = open_socket (ipv6_ ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
131
    errno_assert (sd != -1);
132

133
    struct ifreq ifr;
134 135

    //  Copy interface name for ioctl get.
136
    strncpy (ifr.ifr_name, nic_, sizeof (ifr.ifr_name) );
137 138

    //  Fetch interface address.
139
    const int rc = ioctl (sd, SIOCGIFADDR, (caddr_t) &ifr, sizeof (ifr) );
140 141 142 143 144 145 146 147

    //  Clean up.
    close (sd);

    if (rc == -1) {
        errno = ENODEV;
        return -1;
    }
148 149

    const int family = ifr.ifr_addr.sa_family;
150
    if (family == (ipv6_ ? AF_INET6 : AF_INET)
151 152 153 154 155 156 157 158 159 160 161
        && !strcmp (nic_, ifr.ifr_name))
    {
        if (is_src_)
            memcpy (&source_address, &ifr.ifr_addr,
                    (family == AF_INET) ? sizeof (struct sockaddr_in)
                                        : sizeof (struct sockaddr_in6));
        else
            memcpy (&address, &ifr.ifr_addr,
                    (family == AF_INET) ? sizeof (struct sockaddr_in)
                                        : sizeof (struct sockaddr_in6));
    }
Martin Hurton's avatar
Martin Hurton committed
162
    else
163 164 165 166
    {
        errno = ENODEV;
        return -1;
    }
167

168
    return 0;
169 170 171 172
}

#elif ((defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
    defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_OPENBSD ||\
173
    defined ZMQ_HAVE_QNXNTO || defined ZMQ_HAVE_NETBSD ||\
174
    defined ZMQ_HAVE_DRAGONFLY || defined ZMQ_HAVE_GNU)\
175 176 177 178 179 180
    && defined ZMQ_HAVE_IFADDRS)

#include <ifaddrs.h>

//  On these platforms, network interface name can be queried
//  using getifaddrs function.
181
int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_)
182 183
{
    //  Get the addresses.
Pieter Hintjens's avatar
Pieter Hintjens committed
184
    ifaddrs *ifa = NULL;
185
    int rc = 0;
186 187 188 189 190 191 192 193 194
    const int max_attempts = 10;
    const int backoff_msec = 1;
    for (int i = 0; i < max_attempts; i++) {
        rc = getifaddrs (&ifa);
        if (rc == 0 || (rc < 0 && errno != ECONNREFUSED))
            break;
        usleep ((backoff_msec << i) * 1000);
    }

yasirs's avatar
yasirs committed
195
    if (rc != 0 && ((errno == EINVAL) || (errno==EOPNOTSUPP))) {
196 197 198 199 200 201 202
        // Windows Subsystem for Linux compatibility
        LIBZMQ_UNUSED (nic_);
        LIBZMQ_UNUSED (ipv6_);

        errno = ENODEV;
        return -1;
    }
203
    errno_assert (rc == 0);
204 205 206 207
    zmq_assert (ifa != NULL);

    //  Find the corresponding network interface.
    bool found = false;
Martin Hurton's avatar
Martin Hurton committed
208
    for (ifaddrs *ifp = ifa; ifp != NULL; ifp = ifp->ifa_next) {
209 210 211
        if (ifp->ifa_addr == NULL)
            continue;

Martin Hurton's avatar
Martin Hurton committed
212
        const int family = ifp->ifa_addr->sa_family;
213
        if (family == (ipv6_ ? AF_INET6 : AF_INET)
Pieter Hintjens's avatar
Pieter Hintjens committed
214
        && !strcmp (nic_, ifp->ifa_name)) {
Martin Hurton's avatar
Martin Hurton committed
215
            if (is_src_)
216 217 218
                memcpy (&source_address, ifp->ifa_addr,
                        (family == AF_INET) ? sizeof (struct sockaddr_in)
                                            : sizeof (struct sockaddr_in6));
Martin Hurton's avatar
Martin Hurton committed
219
            else
220 221 222
                memcpy (&address, ifp->ifa_addr,
                        (family == AF_INET) ? sizeof (struct sockaddr_in)
                                            : sizeof (struct sockaddr_in6));
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
            found = true;
            break;
        }
    }

    //  Clean-up;
    freeifaddrs (ifa);

    if (!found) {
        errno = ENODEV;
        return -1;
    }
    return 0;
}

238 239
#elif (defined ZMQ_HAVE_WINDOWS)

240 241
#include <netioapi.h>

242
int zmq::tcp_address_t::get_interface_name(unsigned long index, char ** dest) const {
243 244 245 246 247
#ifdef ZMQ_HAVE_WINDOWS_UWP
	char * buffer = (char*)malloc(1024);
#else
	char * buffer = (char*)malloc(IF_MAX_STRING_SIZE);
#endif
Caleb Epstein's avatar
Caleb Epstein committed
248 249 250
    alloc_assert(buffer);

    char * if_name_result = NULL;
251

252
#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP 
Caleb Epstein's avatar
Caleb Epstein committed
253
    if_name_result = if_indextoname(index, buffer);
Dmitriy-GH's avatar
Dmitriy-GH committed
254
#endif
Caleb Epstein's avatar
Caleb Epstein committed
255 256 257 258 259 260 261 262

    if (if_name_result == NULL) {
        free(buffer);
        return -1;
    }

    *dest = buffer;
    return 0;
263 264 265
}

int zmq::tcp_address_t::wchar_to_utf8(const WCHAR * src, char ** dest) const {
Caleb Epstein's avatar
Caleb Epstein committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    int rc;
    int buffer_len = WideCharToMultiByte(CP_UTF8, 0,
                                         src, -1,
                                         NULL, 0,
                                         NULL, 0);

    char * buffer = (char*) malloc(buffer_len);
    alloc_assert(buffer);

    rc = WideCharToMultiByte(CP_UTF8, 0,
                             src, -1,
                             buffer, buffer_len,
                             NULL, 0);

    if (rc == 0) {
        free(buffer);
        return -1;
    }

    *dest = buffer;
    return 0;
287 288 289 290
}

int zmq::tcp_address_t::resolve_nic_name(const char *nic_, bool ipv6_, bool is_src_)
{
Caleb Epstein's avatar
Caleb Epstein committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    int rc;
    bool found = false;
    const int max_attempts = 10;

    int iterations = 0;
    IP_ADAPTER_ADDRESSES * addresses = NULL;
    IP_ADAPTER_ADDRESSES * current_addresses = NULL;
    unsigned long out_buf_len = sizeof(IP_ADAPTER_ADDRESSES);

    do {
        addresses = (IP_ADAPTER_ADDRESSES *) malloc(out_buf_len);
        alloc_assert(addresses);

        rc = GetAdaptersAddresses(AF_UNSPEC,
                                  GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
                                  NULL,
                                  addresses, &out_buf_len);
        if (rc == ERROR_BUFFER_OVERFLOW) {
            free(addresses);
            addresses = NULL;
        }
        else {
            break;
        }
        iterations++;
    } while ((rc == ERROR_BUFFER_OVERFLOW) && (iterations < max_attempts));

    if (rc == 0) {
        current_addresses = addresses;
        while (current_addresses) {
            char * if_name = NULL;
            char * if_friendly_name = NULL;
            int str_rc1, str_rc2;

            str_rc1 = get_interface_name(current_addresses->IfIndex, &if_name);
            str_rc2 = wchar_to_utf8(current_addresses->FriendlyName, &if_friendly_name);

            //  Find a network adapter by its "name" or "friendly name"
            if (
                ((str_rc1 == 0) && (!strcmp(nic_, if_name)))
                || ((str_rc2 == 0) && (!strcmp(nic_, if_friendly_name)))
                ) {

                //  Iterate over all unicast addresses bound to the current network interface
                IP_ADAPTER_UNICAST_ADDRESS * unicast_address = current_addresses->FirstUnicastAddress;
                IP_ADAPTER_UNICAST_ADDRESS * current_unicast_address = unicast_address;

                while (current_unicast_address) {
                    ADDRESS_FAMILY family = current_unicast_address->Address.lpSockaddr->sa_family;

341
                    if (family == (ipv6_ ? AF_INET6 : AF_INET)) {
Caleb Epstein's avatar
Caleb Epstein committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
                        if (is_src_)
                            memcpy(&source_address, current_unicast_address->Address.lpSockaddr,
                                   (family == AF_INET) ? sizeof(struct sockaddr_in)
                                   : sizeof(struct sockaddr_in6));
                        else
                            memcpy(&address, current_unicast_address->Address.lpSockaddr,
                                   (family == AF_INET) ? sizeof(struct sockaddr_in)
                                   : sizeof(struct sockaddr_in6));
                        found = true;
                        break;
                    }

                    current_unicast_address = current_unicast_address->Next;
                }

                if (found) break;
            }

            if (str_rc1 == 0) free(if_name);
            if (str_rc2 == 0) free(if_friendly_name);

            current_addresses = current_addresses->Next;
        }

        free(addresses);
    }

    if (!found) {
        errno = ENODEV;
        return -1;
    }
    return 0;
374 375
}

376 377 378
#else

//  On other platforms we assume there are no sane interface names.
379
int zmq::tcp_address_t::resolve_nic_name (const char *nic_, bool ipv6_, bool is_src_)
380
{
381 382
    LIBZMQ_UNUSED (nic_);
    LIBZMQ_UNUSED (ipv6_);
383 384 385 386 387 388 389

    errno = ENODEV;
    return -1;
}

#endif

390
int zmq::tcp_address_t::resolve_interface (const char *interface_, bool ipv6_, bool is_src_)
391 392 393
{
    //  Initialize temporary output pointers with storage address.
    sockaddr_storage ss;
394 395
    sockaddr *out_addr = (sockaddr*) &ss;
    size_t out_addrlen;
396 397 398

    //  Initialise IP-format family/port and populate temporary output pointers
    //  with the address.
Pieter Hintjens's avatar
Pieter Hintjens committed
399
    if (ipv6_) {
400
        sockaddr_in6 ip6_addr;
401
        memset (&ip6_addr, 0, sizeof (ip6_addr) );
402
        ip6_addr.sin6_family = AF_INET6;
403 404
        memcpy (&ip6_addr.sin6_addr, &in6addr_any, sizeof (in6addr_any) );
        out_addrlen = sizeof (ip6_addr);
405 406
        memcpy (out_addr, &ip6_addr, out_addrlen);
    }
Pieter Hintjens's avatar
Pieter Hintjens committed
407 408
    else {
        sockaddr_in ip4_addr;
409
        memset (&ip4_addr, 0, sizeof (ip4_addr) );
Pieter Hintjens's avatar
Pieter Hintjens committed
410 411
        ip4_addr.sin_family = AF_INET;
        ip4_addr.sin_addr.s_addr = htonl (INADDR_ANY);
412
        out_addrlen = sizeof (ip4_addr);
Pieter Hintjens's avatar
Pieter Hintjens committed
413 414 415
        memcpy (out_addr, &ip4_addr, out_addrlen);
    }
    //  "*" resolves to INADDR_ANY or in6addr_any.
416
    if (strcmp (interface_, "*") == 0) {
417
        zmq_assert (out_addrlen <= sizeof (address) );
Martin Hurton's avatar
Martin Hurton committed
418
        if (is_src_)
419
            memcpy (&source_address, out_addr, out_addrlen);
Martin Hurton's avatar
Martin Hurton committed
420
        else
421
            memcpy (&address, out_addr, out_addrlen);
422 423 424 425
        return 0;
    }

    //  Try to resolve the string as a NIC name.
426
    int rc = resolve_nic_name (interface_, ipv6_, is_src_);
Martin Hurton's avatar
Martin Hurton committed
427
    if (rc == 0 || errno != ENODEV)
428 429 430 431 432 433 434 435 436 437
        return rc;

    //  There's no such interface name. Assume literal address.
#if defined ZMQ_HAVE_OPENVMS && defined __ia64
    __addrinfo64 *res = NULL;
    __addrinfo64 req;
#else
    addrinfo *res = NULL;
    addrinfo req;
#endif
438
    memset (&req, 0, sizeof (req) );
439 440 441

    //  Choose IPv4 or IPv6 protocol family. Note that IPv6 allows for
    //  IPv4-in-IPv6 addresses.
Pieter Hintjens's avatar
Pieter Hintjens committed
442
    req.ai_family = ipv6_? AF_INET6: AF_INET;
443 444 445 446 447 448 449 450

    //  Arbitrary, not used in the output, but avoids duplicate results.
    req.ai_socktype = SOCK_STREAM;

    //  Restrict hostname/service to literals to avoid any DNS lookups or
    //  service-name irregularity due to indeterminate socktype.
    req.ai_flags = AI_PASSIVE | AI_NUMERICHOST;

451
#if defined AI_V4MAPPED
452 453 454
    //  In this API we only require IPv4-mapped addresses when
    //  no native IPv6 interfaces are available (~AI_ALL).
    //  This saves an additional DNS roundtrip for IPv4 addresses.
455 456 457 458 459 460
    if (req.ai_family == AF_INET6)
        req.ai_flags |= AI_V4MAPPED;
#endif

    //  Resolve the literal address. Some of the error info is lost in case
    //  of error, however, there's no way to report EAI errors via errno.
461

Caleb Epstein's avatar
Caleb Epstein committed
462
    rc = getaddrinfo(interface_, NULL, &req, &res);
463

464 465 466 467 468 469 470 471 472
#if defined AI_V4MAPPED
    // Some OS do have AI_V4MAPPED defined but it is not supported in getaddrinfo()
    // returning EAI_BADFLAGS. Detect this and retry
    if (rc == EAI_BADFLAGS && (req.ai_flags & AI_V4MAPPED)) {
        req.ai_flags &= ~AI_V4MAPPED;
        rc = getaddrinfo(interface_, NULL, &req, &res);
    }
#endif

473
#if defined ZMQ_HAVE_WINDOWS
Caleb Epstein's avatar
Caleb Epstein committed
474 475
    //  Resolve specific case on Windows platform when using IPv4 address
    //  with ZMQ_IPv6 socket option.
476
    if ((req.ai_family == AF_INET6) && (rc == WSAHOST_NOT_FOUND)) {
Caleb Epstein's avatar
Caleb Epstein committed
477 478 479
        req.ai_family = AF_INET;
        rc = getaddrinfo(interface_, NULL, &req, &res);
    }
480 481
#endif

Caleb Epstein's avatar
Caleb Epstein committed
482 483 484 485
    if (rc) {
        errno = ENODEV;
        return -1;
    }
486 487

    //  Use the first result.
488
    zmq_assert (res != NULL);
489
    zmq_assert ((size_t) res->ai_addrlen <= sizeof (address) );
Martin Hurton's avatar
Martin Hurton committed
490
    if (is_src_)
491
        memcpy (&source_address, res->ai_addr, res->ai_addrlen);
Martin Hurton's avatar
Martin Hurton committed
492
    else
493
        memcpy (&address, res->ai_addr, res->ai_addrlen);
494 495

    //  Cleanup getaddrinfo after copying the possibly referenced result.
496
    freeaddrinfo (res);
497 498 499 500

    return 0;
}

501
int zmq::tcp_address_t::resolve_hostname (const char *hostname_, bool ipv6_, bool is_src_)
502 503
{
    //  Set up the query.
504 505 506
#if defined ZMQ_HAVE_OPENVMS && defined __ia64 && __INITIAL_POINTER_SIZE == 64
    __addrinfo64 req;
#else
507
    addrinfo req;
508
#endif
509
    memset (&req, 0, sizeof (req) );
510 511 512

    //  Choose IPv4 or IPv6 protocol family. Note that IPv6 allows for
    //  IPv4-in-IPv6 addresses.
Pieter Hintjens's avatar
Pieter Hintjens committed
513
    req.ai_family = ipv6_? AF_INET6: AF_INET;
514 515 516 517

    //  Need to choose one to avoid duplicate results from getaddrinfo() - this
    //  doesn't really matter, since it's not included in the addr-output.
    req.ai_socktype = SOCK_STREAM;
518

519
#if defined AI_V4MAPPED
520 521 522
    //  In this API we only require IPv4-mapped addresses when
    //  no native IPv6 interfaces are available.
    //  This saves an additional DNS roundtrip for IPv4 addresses.
523 524 525 526 527 528
    if (req.ai_family == AF_INET6)
        req.ai_flags |= AI_V4MAPPED;
#endif

    //  Resolve host name. Some of the error info is lost in case of error,
    //  however, there's no way to report EAI errors via errno.
529 530 531
#if defined ZMQ_HAVE_OPENVMS && defined __ia64 && __INITIAL_POINTER_SIZE == 64
    __addrinfo64 *res;
#else
532
    addrinfo *res;
533
#endif
534 535 536 537 538 539 540 541 542 543 544
    int rc = getaddrinfo (hostname_, NULL, &req, &res);

#if defined AI_V4MAPPED
    // Some OS do have AI_V4MAPPED defined but it is not supported in getaddrinfo()
    // returning EAI_BADFLAGS. Detect this and retry
    if (rc == EAI_BADFLAGS && (req.ai_flags & AI_V4MAPPED)) {
        req.ai_flags &= ~AI_V4MAPPED;
        rc = getaddrinfo(hostname_, NULL, &req, &res);
    }
#endif

545 546 547 548 549 550 551 552 553 554 555 556 557
    if (rc) {
        switch (rc) {
        case EAI_MEMORY:
            errno = ENOMEM;
            break;
        default:
            errno = EINVAL;
            break;
        }
        return -1;
    }

    //  Copy first result to output addr with hostname and service.
558
    zmq_assert ((size_t) res->ai_addrlen <= sizeof (address) );
Martin Hurton's avatar
Martin Hurton committed
559
    if (is_src_)
560
        memcpy (&source_address, res->ai_addr, res->ai_addrlen);
Martin Hurton's avatar
Martin Hurton committed
561
    else
562
        memcpy (&address, res->ai_addr, res->ai_addrlen);
563

564
    freeaddrinfo (res);
565

566 567 568
    return 0;
}

569 570
zmq::tcp_address_t::tcp_address_t () :
    _has_src_addr (false)
571
{
572 573
    memset (&address, 0, sizeof (address) );
    memset (&source_address, 0, sizeof (source_address) );
574 575
}

576 577
zmq::tcp_address_t::tcp_address_t (const sockaddr *sa, socklen_t sa_len) :
    _has_src_addr (false)
578
{
Martin Hurton's avatar
Martin Hurton committed
579 580
    zmq_assert (sa && sa_len > 0);

581 582 583 584
    memset (&address, 0, sizeof (address) );
    memset (&source_address, 0, sizeof (source_address) );
    if (sa->sa_family == AF_INET && sa_len >= (socklen_t) sizeof (address.ipv4) )
        memcpy (&address.ipv4, sa, sizeof (address.ipv4) );
Martin Hurton's avatar
Martin Hurton committed
585
    else
586 587
    if (sa->sa_family == AF_INET6 && sa_len >= (socklen_t) sizeof (address.ipv6) )
        memcpy (&address.ipv6, sa, sizeof (address.ipv6) );
588 589
}

590 591 592 593
zmq::tcp_address_t::~tcp_address_t ()
{
}

594
int zmq::tcp_address_t::resolve (const char *name_, bool local_, bool ipv6_, bool is_src_)
595
{
596 597 598 599 600
    if (!is_src_) {
        // Test the ';' to know if we have a source address in name_
        const char *src_delimiter = strrchr (name_, ';');
        if (src_delimiter) {
            std::string src_name (name_, src_delimiter - name_);
Martin Hurton's avatar
Martin Hurton committed
601
            const int rc = resolve (src_name.c_str (), local_, ipv6_, true);
602 603 604 605 606 607 608
            if (rc != 0)
                return -1;
            name_ = src_delimiter + 1;
            _has_src_addr = true;
        }
    }

609 610 611 612 613 614
    //  Find the ':' at end that separates address from the port number.
    const char *delimiter = strrchr (name_, ':');
    if (!delimiter) {
        errno = EINVAL;
        return -1;
    }
615

616 617 618 619
    //  Separate the address/port.
    std::string addr_str (name_, delimiter - name_);
    std::string port_str (delimiter + 1);

620
    //  Remove square brackets around the address, if any, as used in IPv6
621 622 623 624
    if (addr_str.size () >= 2 && addr_str [0] == '[' &&
          addr_str [addr_str.size () - 1] == ']')
        addr_str = addr_str.substr (1, addr_str.size () - 2);

625 626
    // Test the '%' to know if we have an interface name / zone_id in the address
    // Reference: https://tools.ietf.org/html/rfc4007
pavel.pimenov's avatar
pavel.pimenov committed
627
    std::size_t pos = addr_str.rfind('%');
628 629 630 631 632
    uint32_t zone_id = 0;
    if (pos != std::string::npos) {
        std::string if_str = addr_str.substr(pos + 1);
        addr_str = addr_str.substr(0, pos);
        if (isalpha (if_str.at (0)))
633
#if !defined ZMQ_HAVE_WINDOWS_TARGET_XP && !defined ZMQ_HAVE_WINDOWS_UWP 
634
            zone_id = if_nametoindex(if_str.c_str());
635 636 637 638 639 640 641 642
#else
            // The function 'if_nametoindex' is not supported on Windows XP.
            // If we are targeting XP using a vxxx_xp toolset then fail.
            // This is brutal as this code could be run on later windows clients
            // meaning the IPv6 zone_id cannot have an interface name.
            // This could be fixed with a runtime check.
            zone_id = 0;
#endif
643 644 645 646 647 648
        else
            zone_id = (uint32_t) atoi (if_str.c_str ());
        if (zone_id == 0) {
            errno = EINVAL;
            return -1;
        }
649

650 651
    }

652
    //  Allow 0 specifically, to detect invalid port error in atoi if not
Pieter Hintjens's avatar
Pieter Hintjens committed
653
    uint16_t port;
654
    if (port_str == "*" || port_str == "0")
655
        //  Resolve wildcard to 0 to allow autoselection of port
656
        port = 0;
657
    else {
658
        //  Parse the port number (0 is not a valid port).
659
        port = (uint16_t) atoi (port_str.c_str ());
660 661 662 663
        if (port == 0) {
            errno = EINVAL;
            return -1;
        }
664 665 666 667
    }

    //  Resolve the IP address.
    int rc;
668
    if (local_ || is_src_)
669
        rc = resolve_interface (addr_str.c_str (), ipv6_, is_src_);
670
    else
671
        rc = resolve_hostname (addr_str.c_str (), ipv6_, is_src_);
672 673 674 675
    if (rc != 0)
        return -1;

    //  Set the port into the address structure.
676
    if (is_src_) {
677
        if (source_address.generic.sa_family == AF_INET6) {
678
            source_address.ipv6.sin6_port = htons (port);
679 680
            source_address.ipv6.sin6_scope_id = zone_id;
        }
681 682
        else
            source_address.ipv4.sin_port = htons (port);
Martin Hurton's avatar
Martin Hurton committed
683 684
    }
    else {
685
        if (address.generic.sa_family == AF_INET6) {
686
            address.ipv6.sin6_port = htons (port);
687 688
            address.ipv6.sin6_scope_id = zone_id;
        }
689 690 691 692
        else
            address.ipv4.sin_port = htons (port);
    }

693 694 695
    return 0;
}

696 697
int zmq::tcp_address_t::to_string (std::string &addr_)
{
Pieter Hintjens's avatar
Pieter Hintjens committed
698 699
    if (address.generic.sa_family != AF_INET
    &&  address.generic.sa_family != AF_INET6) {
700 701 702 703
        addr_.clear ();
        return -1;
    }

704
    //  Not using service resolving because of
705
    //  https://github.com/zeromq/libzmq/commit/1824574f9b5a8ce786853320e3ea09fe1f822bc4
Martin Hurton's avatar
Martin Hurton committed
706
    char hbuf [NI_MAXHOST];
707
    int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, NI_NUMERICHOST);
708 709 710 711 712 713 714 715 716 717 718 719 720 721
    if (rc != 0) {
        addr_.clear ();
        return rc;
    }

    if (address.generic.sa_family == AF_INET6) {
        std::stringstream s;
        s << "tcp://[" << hbuf << "]:" << ntohs (address.ipv6.sin6_port);
        addr_ = s.str ();
    }
    else {
        std::stringstream s;
        s << "tcp://" << hbuf << ":" << ntohs (address.ipv4.sin_port);
        addr_ = s.str ();
Martin Hurton's avatar
Martin Hurton committed
722
    }
723 724 725
    return 0;
}

726
const sockaddr *zmq::tcp_address_t::addr () const
727 728 729 730
{
    return &address.generic;
}

731
socklen_t zmq::tcp_address_t::addrlen () const
732 733
{
    if (address.generic.sa_family == AF_INET6)
734
        return (socklen_t) sizeof (address.ipv6);
735
    else
736
        return (socklen_t) sizeof (address.ipv4);
737 738
}

739 740 741 742 743 744 745 746
const sockaddr *zmq::tcp_address_t::src_addr () const
{
    return &source_address.generic;
}

socklen_t zmq::tcp_address_t::src_addrlen () const
{
    if (address.generic.sa_family == AF_INET6)
747
        return (socklen_t) sizeof (source_address.ipv6);
748
    else
749
        return (socklen_t) sizeof (source_address.ipv4);
750 751
}

Martin Hurton's avatar
Martin Hurton committed
752
bool zmq::tcp_address_t::has_src_addr () const
753 754 755 756
{
    return _has_src_addr;
}

Martin Sustrik's avatar
Martin Sustrik committed
757
#if defined ZMQ_HAVE_WINDOWS
758
unsigned short zmq::tcp_address_t::family () const
Martin Sustrik's avatar
Martin Sustrik committed
759
#else
760
sa_family_t zmq::tcp_address_t::family () const
Martin Sustrik's avatar
Martin Sustrik committed
761
#endif
762 763 764 765
{
    return address.generic.sa_family;
}

766
zmq::tcp_address_mask_t::tcp_address_mask_t () :
Martin Hurton's avatar
Martin Hurton committed
767 768
    tcp_address_t (),
    address_mask (-1)
769 770 771
{
}

772
int zmq::tcp_address_mask_t::mask () const
773 774 775 776
{
    return address_mask;
}

Pieter Hintjens's avatar
Pieter Hintjens committed
777
int zmq::tcp_address_mask_t::resolve (const char *name_, bool ipv6_)
778 779
{
    // Find '/' at the end that separates address from the cidr mask number.
Martin Hurton's avatar
Martin Hurton committed
780
    // Allow empty mask clause and treat it like '/32' for ipv4 or '/128' for ipv6.
781
    std::string addr_str, mask_str;
782 783 784 785 786 787 788 789 790
    const char *delimiter = strrchr (name_, '/');
    if (delimiter != NULL) {
        addr_str.assign (name_, delimiter - name_);
        mask_str.assign (delimiter + 1);
        if (mask_str.empty ()) {
            errno = EINVAL;
            return -1;
        }
    }
Pieter Hintjens's avatar
Pieter Hintjens committed
791
    else
792 793 794
        addr_str.assign (name_);

    // Parse address part using standard routines.
Martin Hurton's avatar
Martin Hurton committed
795 796
    const int rc =
        tcp_address_t::resolve_hostname (addr_str.c_str (), ipv6_);
797 798 799 800 801 802 803 804 805 806 807
    if (rc != 0)
        return rc;

    // Parse the cidr mask number.
    if (mask_str.empty ()) {
        if (address.generic.sa_family == AF_INET6)
            address_mask = 128;
        else
            address_mask = 32;
    }
    else
Martin Hurton's avatar
Martin Hurton committed
808
    if (mask_str == "0")
809 810
        address_mask = 0;
    else {
Martin Hurton's avatar
Martin Hurton committed
811
        const int mask = atoi (mask_str.c_str ());
812 813 814 815 816 817 818 819 820 821 822 823 824 825
        if (
            (mask < 1) ||
            (address.generic.sa_family == AF_INET6 && mask > 128) ||
            (address.generic.sa_family != AF_INET6 && mask > 32)
        ) {
            errno = EINVAL;
            return -1;
        }
        address_mask = mask;
    }

    return 0;
}

826 827
int zmq::tcp_address_mask_t::to_string (std::string &addr_)
{
Martin Hurton's avatar
Martin Hurton committed
828 829
    if (address.generic.sa_family != AF_INET
    &&  address.generic.sa_family != AF_INET6) {
830 831 832 833 834 835 836 837
        addr_.clear ();
        return -1;
    }
    if (address_mask == -1) {
        addr_.clear ();
        return -1;
    }

Martin Hurton's avatar
Martin Hurton committed
838
    char hbuf [NI_MAXHOST];
839
    int rc = getnameinfo (addr (), addrlen (), hbuf, sizeof (hbuf), NULL, 0, NI_NUMERICHOST);
840 841 842 843 844 845 846 847 848 849 850 851 852 853
    if (rc != 0) {
        addr_.clear ();
        return rc;
    }

    if (address.generic.sa_family == AF_INET6) {
        std::stringstream s;
        s << "[" << hbuf << "]/" << address_mask;
        addr_ = s.str ();
    }
    else {
        std::stringstream s;
        s << hbuf << "/" << address_mask;
        addr_ = s.str ();
Martin Hurton's avatar
Martin Hurton committed
854
    }
855 856 857
    return 0;
}

858
bool zmq::tcp_address_mask_t::match_address (const struct sockaddr *ss, const socklen_t ss_len) const
859
{
Martin Hurton's avatar
Martin Hurton committed
860 861 862
    zmq_assert (address_mask != -1
             && ss != NULL
             && ss_len >= (socklen_t) sizeof (struct sockaddr));
863 864 865 866 867 868

    if (ss->sa_family != address.generic.sa_family)
        return false;

    if (address_mask > 0) {
        int mask;
869
        const uint8_t *our_bytes, *their_bytes;
870 871
        if (ss->sa_family == AF_INET6) {
            zmq_assert (ss_len == sizeof (struct sockaddr_in6));
872 873
            their_bytes = (const uint8_t *) &(((const struct sockaddr_in6 *) ss)->sin6_addr);
            our_bytes = (const uint8_t *) &address.ipv6.sin6_addr;
874 875 876 877
            mask = sizeof (struct in6_addr) * 8;
        }
        else {
            zmq_assert (ss_len == sizeof (struct sockaddr_in));
878 879
            their_bytes = (const uint8_t *) &(((const struct sockaddr_in *) ss)->sin_addr);
            our_bytes = (const uint8_t *) &address.ipv4.sin_addr;
880 881
            mask = sizeof (struct in_addr) * 8;
        }
Martin Hurton's avatar
Martin Hurton committed
882 883
        if (address_mask < mask)
            mask = address_mask;
884

Martin Hurton's avatar
Martin Hurton committed
885 886
        const size_t full_bytes = mask / 8;
        if (memcmp (our_bytes, their_bytes, full_bytes))
887
            return false;
888

Martin Hurton's avatar
Martin Hurton committed
889
        const uint8_t last_byte_bits = 0xffU << (8 - mask % 8);
890
        if (last_byte_bits) {
Martin Hurton's avatar
Martin Hurton committed
891
            if ((their_bytes [full_bytes] & last_byte_bits) != (our_bytes [full_bytes] & last_byte_bits))
892 893 894 895 896 897
                return false;
        }
    }

    return true;
}