PageRenderTime 166ms CodeModel.GetById 14ms app.highlight 130ms RepoModel.GetById 1ms app.codeStats 1ms

/components/ruby-2.1.0/ext/socket/raddrinfo.c

https://github.com/jhs/ruby-inabox
C | 2455 lines | 1763 code | 262 blank | 430 comment | 388 complexity | f0f5fe62fb844d32437620996fa37fdc MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/************************************************
   2
   3  ainfo.c -
   4
   5  created at: Thu Mar 31 12:21:29 JST 1994
   6
   7  Copyright (C) 1993-2007 Yukihiro Matsumoto
   8
   9************************************************/
  10
  11#include "rubysocket.h"
  12
  13#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6))
  14#define LOOKUP_ORDERS (sizeof(lookup_order_table) / sizeof(lookup_order_table[0]))
  15static const int lookup_order_table[] = {
  16#if defined(LOOKUP_ORDER_HACK_INET)
  17    PF_INET, PF_INET6, PF_UNSPEC,
  18#elif defined(LOOKUP_ORDER_HACK_INET6)
  19    PF_INET6, PF_INET, PF_UNSPEC,
  20#else
  21    /* should not happen */
  22#endif
  23};
  24
  25static int
  26ruby_getaddrinfo(const char *nodename, const char *servname,
  27		 const struct addrinfo *hints, struct addrinfo **res)
  28{
  29    struct addrinfo tmp_hints;
  30    int i, af, error;
  31
  32    if (hints->ai_family != PF_UNSPEC) {
  33	return getaddrinfo(nodename, servname, hints, res);
  34    }
  35
  36    for (i = 0; i < LOOKUP_ORDERS; i++) {
  37	af = lookup_order_table[i];
  38	MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
  39	tmp_hints.ai_family = af;
  40	error = getaddrinfo(nodename, servname, &tmp_hints, res);
  41	if (error) {
  42	    if (tmp_hints.ai_family == PF_UNSPEC) {
  43		break;
  44	    }
  45	}
  46	else {
  47	    break;
  48	}
  49    }
  50
  51    return error;
  52}
  53#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res))
  54#endif
  55
  56#if defined(_AIX)
  57static int
  58ruby_getaddrinfo__aix(const char *nodename, const char *servname,
  59		      const struct addrinfo *hints, struct addrinfo **res)
  60{
  61    int error = getaddrinfo(nodename, servname, hints, res);
  62    struct addrinfo *r;
  63    if (error)
  64	return error;
  65    for (r = *res; r != NULL; r = r->ai_next) {
  66	if (r->ai_addr->sa_family == 0)
  67	    r->ai_addr->sa_family = r->ai_family;
  68	if (r->ai_addr->sa_len == 0)
  69	    r->ai_addr->sa_len = r->ai_addrlen;
  70    }
  71    return 0;
  72}
  73#undef getaddrinfo
  74#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res))
  75static int
  76ruby_getnameinfo__aix(const struct sockaddr *sa, size_t salen,
  77		      char *host, size_t hostlen,
  78		      char *serv, size_t servlen, int flags)
  79{
  80    struct sockaddr_in6 *sa6;
  81    u_int32_t *a6;
  82
  83    if (sa->sa_family == AF_INET6) {
  84	sa6 = (struct sockaddr_in6 *)sa;
  85	a6 = sa6->sin6_addr.u6_addr.u6_addr32;
  86
  87	if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) {
  88	    strncpy(host, "::", hostlen);
  89	    snprintf(serv, servlen, "%d", sa6->sin6_port);
  90	    return 0;
  91	}
  92    }
  93    return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
  94}
  95#undef getnameinfo
  96#define getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) \
  97            ruby_getnameinfo__aix((sa), (salen), (host), (hostlen), (serv), (servlen), (flags))
  98#endif
  99
 100static int str_is_number(const char *);
 101
 102#if defined(__APPLE__)
 103static int
 104ruby_getaddrinfo__darwin(const char *nodename, const char *servname,
 105			 const struct addrinfo *hints, struct addrinfo **res)
 106{
 107    /* fix [ruby-core:29427] */
 108    const char *tmp_servname;
 109    struct addrinfo tmp_hints;
 110    int error;
 111
 112    tmp_servname = servname;
 113    MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
 114    if (nodename && servname) {
 115	if (str_is_number(tmp_servname) && atoi(servname) == 0) {
 116	    tmp_servname = NULL;
 117#ifdef AI_NUMERICSERV
 118	    if (tmp_hints.ai_flags) tmp_hints.ai_flags &= ~AI_NUMERICSERV;
 119#endif
 120	}
 121    }
 122
 123    error = getaddrinfo(nodename, tmp_servname, &tmp_hints, res);
 124    if (error == 0) {
 125        /* [ruby-dev:23164] */
 126        struct addrinfo *r;
 127        r = *res;
 128        while (r) {
 129            if (! r->ai_socktype) r->ai_socktype = hints->ai_socktype;
 130            if (! r->ai_protocol) {
 131                if (r->ai_socktype == SOCK_DGRAM) {
 132                    r->ai_protocol = IPPROTO_UDP;
 133                }
 134                else if (r->ai_socktype == SOCK_STREAM) {
 135                    r->ai_protocol = IPPROTO_TCP;
 136                }
 137            }
 138            r = r->ai_next;
 139        }
 140    }
 141
 142    return error;
 143}
 144#undef getaddrinfo
 145#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__darwin((node),(serv),(hints),(res))
 146#endif
 147
 148#ifndef GETADDRINFO_EMU
 149struct getaddrinfo_arg
 150{
 151    const char *node;
 152    const char *service;
 153    const struct addrinfo *hints;
 154    struct addrinfo **res;
 155};
 156
 157static void *
 158nogvl_getaddrinfo(void *arg)
 159{
 160    int ret;
 161    struct getaddrinfo_arg *ptr = arg;
 162    ret = getaddrinfo(ptr->node, ptr->service, ptr->hints, ptr->res);
 163#ifdef __linux__
 164    /* On Linux (mainly Ubuntu 13.04) /etc/nsswitch.conf has mdns4 and
 165     * it cause getaddrinfo to return EAI_SYSTEM/ENOENT. [ruby-list:49420]
 166     */
 167    if (ret == EAI_SYSTEM && errno == ENOENT)
 168	ret = EAI_NONAME;
 169#endif
 170    return (void *)(VALUE)ret;
 171}
 172#endif
 173
 174int
 175rb_getaddrinfo(const char *node, const char *service,
 176               const struct addrinfo *hints,
 177               struct addrinfo **res)
 178{
 179#ifdef GETADDRINFO_EMU
 180    return getaddrinfo(node, service, hints, res);
 181#else
 182    struct getaddrinfo_arg arg;
 183    int ret;
 184    MEMZERO(&arg, sizeof arg, 1);
 185    arg.node = node;
 186    arg.service = service;
 187    arg.hints = hints;
 188    arg.res = res;
 189    ret = (int)(VALUE)rb_thread_call_without_gvl(nogvl_getaddrinfo, &arg, RUBY_UBF_IO, 0);
 190    return ret;
 191#endif
 192}
 193
 194#ifndef GETADDRINFO_EMU
 195struct getnameinfo_arg
 196{
 197    const struct sockaddr *sa;
 198    socklen_t salen;
 199    char *host;
 200    size_t hostlen;
 201    char *serv;
 202    size_t servlen;
 203    int flags;
 204};
 205
 206static void *
 207nogvl_getnameinfo(void *arg)
 208{
 209    struct getnameinfo_arg *ptr = arg;
 210    return (void *)(VALUE)getnameinfo(ptr->sa, ptr->salen,
 211				      ptr->host, (socklen_t)ptr->hostlen,
 212				      ptr->serv, (socklen_t)ptr->servlen,
 213				      ptr->flags);
 214}
 215#endif
 216
 217int
 218rb_getnameinfo(const struct sockaddr *sa, socklen_t salen,
 219           char *host, size_t hostlen,
 220           char *serv, size_t servlen, int flags)
 221{
 222#ifdef GETADDRINFO_EMU
 223    return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
 224#else
 225    struct getnameinfo_arg arg;
 226    int ret;
 227    arg.sa = sa;
 228    arg.salen = salen;
 229    arg.host = host;
 230    arg.hostlen = hostlen;
 231    arg.serv = serv;
 232    arg.servlen = servlen;
 233    arg.flags = flags;
 234    ret = (int)(VALUE)rb_thread_call_without_gvl(nogvl_getnameinfo, &arg, RUBY_UBF_IO, 0);
 235    return ret;
 236#endif
 237}
 238
 239static void
 240make_ipaddr0(struct sockaddr *addr, socklen_t addrlen, char *buf, size_t buflen)
 241{
 242    int error;
 243
 244    error = rb_getnameinfo(addr, addrlen, buf, buflen, NULL, 0, NI_NUMERICHOST);
 245    if (error) {
 246        rsock_raise_socket_error("getnameinfo", error);
 247    }
 248}
 249
 250VALUE
 251rsock_make_ipaddr(struct sockaddr *addr, socklen_t addrlen)
 252{
 253    char hbuf[1024];
 254
 255    make_ipaddr0(addr, addrlen, hbuf, sizeof(hbuf));
 256    return rb_str_new2(hbuf);
 257}
 258
 259static void
 260make_inetaddr(unsigned int host, char *buf, size_t buflen)
 261{
 262    struct sockaddr_in sin;
 263
 264    INIT_SOCKADDR_IN(&sin, sizeof(sin));
 265    sin.sin_addr.s_addr = host;
 266    make_ipaddr0((struct sockaddr*)&sin, sizeof(sin), buf, buflen);
 267}
 268
 269static int
 270str_is_number(const char *p)
 271{
 272    char *ep;
 273
 274    if (!p || *p == '\0')
 275       return 0;
 276    ep = NULL;
 277    (void)STRTOUL(p, &ep, 10);
 278    if (ep && *ep == '\0')
 279       return 1;
 280    else
 281       return 0;
 282}
 283
 284static char*
 285host_str(VALUE host, char *hbuf, size_t hbuflen, int *flags_ptr)
 286{
 287    if (NIL_P(host)) {
 288        return NULL;
 289    }
 290    else if (rb_obj_is_kind_of(host, rb_cInteger)) {
 291        unsigned int i = NUM2UINT(host);
 292
 293        make_inetaddr(htonl(i), hbuf, hbuflen);
 294        if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
 295        return hbuf;
 296    }
 297    else {
 298        char *name;
 299
 300        SafeStringValue(host);
 301        name = RSTRING_PTR(host);
 302        if (!name || *name == 0 || (name[0] == '<' && strcmp(name, "<any>") == 0)) {
 303            make_inetaddr(INADDR_ANY, hbuf, hbuflen);
 304            if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
 305        }
 306        else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
 307            make_inetaddr(INADDR_BROADCAST, hbuf, hbuflen);
 308            if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
 309        }
 310        else if (strlen(name) >= hbuflen) {
 311            rb_raise(rb_eArgError, "hostname too long (%"PRIuSIZE")",
 312                strlen(name));
 313        }
 314        else {
 315            strcpy(hbuf, name);
 316        }
 317        return hbuf;
 318    }
 319}
 320
 321static char*
 322port_str(VALUE port, char *pbuf, size_t pbuflen, int *flags_ptr)
 323{
 324    if (NIL_P(port)) {
 325        return 0;
 326    }
 327    else if (FIXNUM_P(port)) {
 328        snprintf(pbuf, pbuflen, "%ld", FIX2LONG(port));
 329#ifdef AI_NUMERICSERV
 330        if (flags_ptr) *flags_ptr |= AI_NUMERICSERV;
 331#endif
 332        return pbuf;
 333    }
 334    else {
 335        char *serv;
 336
 337        SafeStringValue(port);
 338        serv = RSTRING_PTR(port);
 339        if (strlen(serv) >= pbuflen) {
 340            rb_raise(rb_eArgError, "service name too long (%"PRIuSIZE")",
 341                strlen(serv));
 342        }
 343        strcpy(pbuf, serv);
 344        return pbuf;
 345    }
 346}
 347
 348struct addrinfo*
 349rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack)
 350{
 351    struct addrinfo* res = NULL;
 352    char *hostp, *portp;
 353    int error;
 354    char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
 355    int additional_flags = 0;
 356
 357    hostp = host_str(host, hbuf, sizeof(hbuf), &additional_flags);
 358    portp = port_str(port, pbuf, sizeof(pbuf), &additional_flags);
 359
 360    if (socktype_hack && hints->ai_socktype == 0 && str_is_number(portp)) {
 361       hints->ai_socktype = SOCK_DGRAM;
 362    }
 363    hints->ai_flags |= additional_flags;
 364
 365    error = rb_getaddrinfo(hostp, portp, hints, &res);
 366    if (error) {
 367        if (hostp && hostp[strlen(hostp)-1] == '\n') {
 368            rb_raise(rb_eSocket, "newline at the end of hostname");
 369        }
 370        rsock_raise_socket_error("getaddrinfo", error);
 371    }
 372
 373    return res;
 374}
 375
 376struct addrinfo*
 377rsock_addrinfo(VALUE host, VALUE port, int socktype, int flags)
 378{
 379    struct addrinfo hints;
 380
 381    MEMZERO(&hints, struct addrinfo, 1);
 382    hints.ai_family = AF_UNSPEC;
 383    hints.ai_socktype = socktype;
 384    hints.ai_flags = flags;
 385    return rsock_getaddrinfo(host, port, &hints, 1);
 386}
 387
 388VALUE
 389rsock_ipaddr(struct sockaddr *sockaddr, socklen_t sockaddrlen, int norevlookup)
 390{
 391    VALUE family, port, addr1, addr2;
 392    VALUE ary;
 393    int error;
 394    char hbuf[1024], pbuf[1024];
 395    ID id;
 396
 397    id = rsock_intern_family(sockaddr->sa_family);
 398    if (id) {
 399        family = rb_str_dup(rb_id2str(id));
 400    }
 401    else {
 402        sprintf(pbuf, "unknown:%d", sockaddr->sa_family);
 403        family = rb_str_new2(pbuf);
 404    }
 405
 406    addr1 = Qnil;
 407    if (!norevlookup) {
 408        error = rb_getnameinfo(sockaddr, sockaddrlen, hbuf, sizeof(hbuf),
 409                               NULL, 0, 0);
 410        if (! error) {
 411            addr1 = rb_str_new2(hbuf);
 412        }
 413    }
 414    error = rb_getnameinfo(sockaddr, sockaddrlen, hbuf, sizeof(hbuf),
 415                           pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV);
 416    if (error) {
 417        rsock_raise_socket_error("getnameinfo", error);
 418    }
 419    addr2 = rb_str_new2(hbuf);
 420    if (addr1 == Qnil) {
 421        addr1 = addr2;
 422    }
 423    port = INT2FIX(atoi(pbuf));
 424    ary = rb_ary_new3(4, family, port, addr1, addr2);
 425
 426    return ary;
 427}
 428
 429#ifdef HAVE_SYS_UN_H
 430VALUE
 431rsock_unixpath_str(struct sockaddr_un *sockaddr, socklen_t len)
 432{
 433    char *s, *e;
 434    s = sockaddr->sun_path;
 435    e = (char *)sockaddr + len;
 436    while (s < e && *(e-1) == '\0')
 437        e--;
 438    if (s <= e)
 439        return rb_str_new(s, e-s);
 440    else
 441        return rb_str_new2("");
 442}
 443
 444VALUE
 445rsock_unixaddr(struct sockaddr_un *sockaddr, socklen_t len)
 446{
 447    return rb_assoc_new(rb_str_new2("AF_UNIX"),
 448                        rsock_unixpath_str(sockaddr, len));
 449}
 450
 451socklen_t
 452rsock_unix_sockaddr_len(VALUE path)
 453{
 454#ifdef __linux__
 455    if (RSTRING_LEN(path) == 0) {
 456	/* autobind; see unix(7) for details. */
 457	return (socklen_t) sizeof(sa_family_t);
 458    }
 459    else if (RSTRING_PTR(path)[0] == '\0') {
 460	/* abstract namespace; see unix(7) for details. */
 461        if (SOCKLEN_MAX - offsetof(struct sockaddr_un, sun_path) < (size_t)RSTRING_LEN(path))
 462            rb_raise(rb_eArgError, "Linux abstract socket too long");
 463	return (socklen_t) offsetof(struct sockaddr_un, sun_path) +
 464	    RSTRING_SOCKLEN(path);
 465    }
 466    else {
 467#endif
 468	return (socklen_t) sizeof(struct sockaddr_un);
 469#ifdef __linux__
 470    }
 471#endif
 472}
 473#endif
 474
 475struct hostent_arg {
 476    VALUE host;
 477    struct addrinfo* addr;
 478    VALUE (*ipaddr)(struct sockaddr*, socklen_t);
 479};
 480
 481static VALUE
 482make_hostent_internal(struct hostent_arg *arg)
 483{
 484    VALUE host = arg->host;
 485    struct addrinfo* addr = arg->addr;
 486    VALUE (*ipaddr)(struct sockaddr*, socklen_t) = arg->ipaddr;
 487
 488    struct addrinfo *ai;
 489    struct hostent *h;
 490    VALUE ary, names;
 491    char **pch;
 492    const char* hostp;
 493    char hbuf[NI_MAXHOST];
 494
 495    ary = rb_ary_new();
 496    if (addr->ai_canonname) {
 497        hostp = addr->ai_canonname;
 498    }
 499    else {
 500        hostp = host_str(host, hbuf, sizeof(hbuf), NULL);
 501    }
 502    rb_ary_push(ary, rb_str_new2(hostp));
 503
 504    if (addr->ai_canonname && (h = gethostbyname(addr->ai_canonname))) {
 505        names = rb_ary_new();
 506        if (h->h_aliases != NULL) {
 507            for (pch = h->h_aliases; *pch; pch++) {
 508                rb_ary_push(names, rb_str_new2(*pch));
 509            }
 510        }
 511    }
 512    else {
 513        names = rb_ary_new2(0);
 514    }
 515    rb_ary_push(ary, names);
 516    rb_ary_push(ary, INT2NUM(addr->ai_family));
 517    for (ai = addr; ai; ai = ai->ai_next) {
 518        rb_ary_push(ary, (*ipaddr)(ai->ai_addr, ai->ai_addrlen));
 519    }
 520
 521    return ary;
 522}
 523
 524VALUE
 525rsock_freeaddrinfo(struct addrinfo *addr)
 526{
 527    freeaddrinfo(addr);
 528    return Qnil;
 529}
 530
 531VALUE
 532rsock_make_hostent(VALUE host, struct addrinfo *addr, VALUE (*ipaddr)(struct sockaddr *, socklen_t))
 533{
 534    struct hostent_arg arg;
 535
 536    arg.host = host;
 537    arg.addr = addr;
 538    arg.ipaddr = ipaddr;
 539    return rb_ensure(make_hostent_internal, (VALUE)&arg,
 540                     rsock_freeaddrinfo, (VALUE)addr);
 541}
 542
 543typedef struct {
 544    VALUE inspectname;
 545    VALUE canonname;
 546    int pfamily;
 547    int socktype;
 548    int protocol;
 549    socklen_t sockaddr_len;
 550    union_sockaddr addr;
 551} rb_addrinfo_t;
 552
 553static void
 554addrinfo_mark(void *ptr)
 555{
 556    rb_addrinfo_t *rai = ptr;
 557    if (rai) {
 558        rb_gc_mark(rai->inspectname);
 559        rb_gc_mark(rai->canonname);
 560    }
 561}
 562
 563#define addrinfo_free RUBY_TYPED_DEFAULT_FREE
 564
 565static size_t
 566addrinfo_memsize(const void *ptr)
 567{
 568    return ptr ? sizeof(rb_addrinfo_t) : 0;
 569}
 570
 571static const rb_data_type_t addrinfo_type = {
 572    "socket/addrinfo",
 573    {addrinfo_mark, addrinfo_free, addrinfo_memsize,},
 574};
 575
 576static VALUE
 577addrinfo_s_allocate(VALUE klass)
 578{
 579    return TypedData_Wrap_Struct(klass, &addrinfo_type, 0);
 580}
 581
 582#define IS_ADDRINFO(obj) rb_typeddata_is_kind_of((obj), &addrinfo_type)
 583static inline rb_addrinfo_t *
 584check_addrinfo(VALUE self)
 585{
 586    return rb_check_typeddata(self, &addrinfo_type);
 587}
 588
 589static rb_addrinfo_t *
 590get_addrinfo(VALUE self)
 591{
 592    rb_addrinfo_t *rai = check_addrinfo(self);
 593
 594    if (!rai) {
 595        rb_raise(rb_eTypeError, "uninitialized socket address");
 596    }
 597    return rai;
 598}
 599
 600
 601static rb_addrinfo_t *
 602alloc_addrinfo()
 603{
 604    rb_addrinfo_t *rai = ALLOC(rb_addrinfo_t);
 605    memset(rai, 0, sizeof(rb_addrinfo_t));
 606    rai->inspectname = Qnil;
 607    rai->canonname = Qnil;
 608    return rai;
 609}
 610
 611static void
 612init_addrinfo(rb_addrinfo_t *rai, struct sockaddr *sa, socklen_t len,
 613              int pfamily, int socktype, int protocol,
 614              VALUE canonname, VALUE inspectname)
 615{
 616    if ((socklen_t)sizeof(rai->addr) < len)
 617        rb_raise(rb_eArgError, "sockaddr string too big");
 618    memcpy((void *)&rai->addr, (void *)sa, len);
 619    rai->sockaddr_len = len;
 620
 621    rai->pfamily = pfamily;
 622    rai->socktype = socktype;
 623    rai->protocol = protocol;
 624    rai->canonname = canonname;
 625    rai->inspectname = inspectname;
 626}
 627
 628VALUE
 629rsock_addrinfo_new(struct sockaddr *addr, socklen_t len,
 630                   int family, int socktype, int protocol,
 631                   VALUE canonname, VALUE inspectname)
 632{
 633    VALUE a;
 634    rb_addrinfo_t *rai;
 635
 636    a = addrinfo_s_allocate(rb_cAddrinfo);
 637    DATA_PTR(a) = rai = alloc_addrinfo();
 638    init_addrinfo(rai, addr, len, family, socktype, protocol, canonname, inspectname);
 639    return a;
 640}
 641
 642static struct addrinfo *
 643call_getaddrinfo(VALUE node, VALUE service,
 644                 VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
 645                 int socktype_hack)
 646{
 647    struct addrinfo hints, *res;
 648
 649    MEMZERO(&hints, struct addrinfo, 1);
 650    hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
 651
 652    if (!NIL_P(socktype)) {
 653	hints.ai_socktype = rsock_socktype_arg(socktype);
 654    }
 655    if (!NIL_P(protocol)) {
 656	hints.ai_protocol = NUM2INT(protocol);
 657    }
 658    if (!NIL_P(flags)) {
 659	hints.ai_flags = NUM2INT(flags);
 660    }
 661    res = rsock_getaddrinfo(node, service, &hints, socktype_hack);
 662
 663    if (res == NULL)
 664	rb_raise(rb_eSocket, "host not found");
 665    return res;
 666}
 667
 668static VALUE make_inspectname(VALUE node, VALUE service, struct addrinfo *res);
 669
 670static void
 671init_addrinfo_getaddrinfo(rb_addrinfo_t *rai, VALUE node, VALUE service,
 672                          VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
 673                          VALUE inspectnode, VALUE inspectservice)
 674{
 675    struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 1);
 676    VALUE canonname;
 677    VALUE inspectname = rb_str_equal(node, inspectnode) ? Qnil : make_inspectname(inspectnode, inspectservice, res);
 678
 679    canonname = Qnil;
 680    if (res->ai_canonname) {
 681        canonname = rb_tainted_str_new_cstr(res->ai_canonname);
 682        OBJ_FREEZE(canonname);
 683    }
 684
 685    init_addrinfo(rai, res->ai_addr, res->ai_addrlen,
 686                  NUM2INT(family), NUM2INT(socktype), NUM2INT(protocol),
 687                  canonname, inspectname);
 688
 689    freeaddrinfo(res);
 690}
 691
 692static VALUE
 693make_inspectname(VALUE node, VALUE service, struct addrinfo *res)
 694{
 695    VALUE inspectname = Qnil;
 696
 697    if (res) {
 698        /* drop redundant information which also shown in address:port part. */
 699        char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
 700        int ret;
 701        ret = rb_getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
 702                             sizeof(hbuf), pbuf, sizeof(pbuf),
 703                             NI_NUMERICHOST|NI_NUMERICSERV);
 704        if (ret == 0) {
 705            if (RB_TYPE_P(node, T_STRING) && strcmp(hbuf, RSTRING_PTR(node)) == 0)
 706                node = Qnil;
 707            if (RB_TYPE_P(service, T_STRING) && strcmp(pbuf, RSTRING_PTR(service)) == 0)
 708                service = Qnil;
 709            else if (RB_TYPE_P(service, T_FIXNUM) && atoi(pbuf) == FIX2INT(service))
 710                service = Qnil;
 711        }
 712    }
 713
 714    if (RB_TYPE_P(node, T_STRING)) {
 715        inspectname = rb_str_dup(node);
 716    }
 717    if (RB_TYPE_P(service, T_STRING)) {
 718        if (NIL_P(inspectname))
 719            inspectname = rb_sprintf(":%s", StringValueCStr(service));
 720        else
 721            rb_str_catf(inspectname, ":%s", StringValueCStr(service));
 722    }
 723    else if (RB_TYPE_P(service, T_FIXNUM) && FIX2INT(service) != 0)
 724    {
 725        if (NIL_P(inspectname))
 726            inspectname = rb_sprintf(":%d", FIX2INT(service));
 727        else
 728            rb_str_catf(inspectname, ":%d", FIX2INT(service));
 729    }
 730    if (!NIL_P(inspectname)) {
 731        OBJ_INFECT(inspectname, node);
 732        OBJ_INFECT(inspectname, service);
 733        OBJ_FREEZE(inspectname);
 734    }
 735    return inspectname;
 736}
 737
 738static VALUE
 739addrinfo_firstonly_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
 740{
 741    VALUE ret;
 742    VALUE canonname;
 743    VALUE inspectname;
 744
 745    struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
 746
 747    inspectname = make_inspectname(node, service, res);
 748
 749    canonname = Qnil;
 750    if (res->ai_canonname) {
 751        canonname = rb_tainted_str_new_cstr(res->ai_canonname);
 752        OBJ_FREEZE(canonname);
 753    }
 754
 755    ret = rsock_addrinfo_new(res->ai_addr, res->ai_addrlen,
 756                             res->ai_family, res->ai_socktype, res->ai_protocol,
 757                             canonname, inspectname);
 758
 759    freeaddrinfo(res);
 760    return ret;
 761}
 762
 763static VALUE
 764addrinfo_list_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
 765{
 766    VALUE ret;
 767    struct addrinfo *r;
 768    VALUE inspectname;
 769
 770    struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
 771
 772    inspectname = make_inspectname(node, service, res);
 773
 774    ret = rb_ary_new();
 775    for (r = res; r; r = r->ai_next) {
 776        VALUE addr;
 777        VALUE canonname = Qnil;
 778
 779        if (r->ai_canonname) {
 780            canonname = rb_tainted_str_new_cstr(r->ai_canonname);
 781            OBJ_FREEZE(canonname);
 782        }
 783
 784        addr = rsock_addrinfo_new(r->ai_addr, r->ai_addrlen,
 785                                  r->ai_family, r->ai_socktype, r->ai_protocol,
 786                                  canonname, inspectname);
 787
 788        rb_ary_push(ret, addr);
 789    }
 790
 791    freeaddrinfo(res);
 792    return ret;
 793}
 794
 795
 796#ifdef HAVE_SYS_UN_H
 797static void
 798init_unix_addrinfo(rb_addrinfo_t *rai, VALUE path, int socktype)
 799{
 800    struct sockaddr_un un;
 801    socklen_t len;
 802
 803    StringValue(path);
 804
 805    if (sizeof(un.sun_path) < (size_t)RSTRING_LEN(path))
 806        rb_raise(rb_eArgError,
 807            "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
 808            (size_t)RSTRING_LEN(path), sizeof(un.sun_path));
 809
 810    INIT_SOCKADDR_UN(&un, sizeof(struct sockaddr_un));
 811    memcpy((void*)&un.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
 812
 813    len = rsock_unix_sockaddr_len(path);
 814    init_addrinfo(rai, (struct sockaddr *)&un, len,
 815		  PF_UNIX, socktype, 0, Qnil, Qnil);
 816}
 817#endif
 818
 819/*
 820 * call-seq:
 821 *   Addrinfo.new(sockaddr)                             => addrinfo
 822 *   Addrinfo.new(sockaddr, family)                     => addrinfo
 823 *   Addrinfo.new(sockaddr, family, socktype)           => addrinfo
 824 *   Addrinfo.new(sockaddr, family, socktype, protocol) => addrinfo
 825 *
 826 * returns a new instance of Addrinfo.
 827 * The instance contains sockaddr, family, socktype, protocol.
 828 * sockaddr means struct sockaddr which can be used for connect(2), etc.
 829 * family, socktype and protocol are integers which is used for arguments of socket(2).
 830 *
 831 * sockaddr is specified as an array or a string.
 832 * The array should be compatible to the value of IPSocket#addr or UNIXSocket#addr.
 833 * The string should be struct sockaddr as generated by
 834 * Socket.sockaddr_in or Socket.unpack_sockaddr_un.
 835 *
 836 * sockaddr examples:
 837 * - ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"]
 838 * - ["AF_INET6", 42304, "ip6-localhost", "::1"]
 839 * - ["AF_UNIX", "/tmp/sock"]
 840 * - Socket.sockaddr_in("smtp", "2001:DB8::1")
 841 * - Socket.sockaddr_in(80, "172.18.22.42")
 842 * - Socket.sockaddr_in(80, "www.ruby-lang.org")
 843 * - Socket.sockaddr_un("/tmp/sock")
 844 *
 845 * In an AF_INET/AF_INET6 sockaddr array, the 4th element,
 846 * numeric IP address, is used to construct socket address in the Addrinfo instance.
 847 * If the 3rd element, textual host name, is non-nil, it is also recorded but used only for Addrinfo#inspect.
 848 *
 849 * family is specified as an integer to specify the protocol family such as Socket::PF_INET.
 850 * It can be a symbol or a string which is the constant name
 851 * with or without PF_ prefix such as :INET, :INET6, :UNIX, "PF_INET", etc.
 852 * If omitted, PF_UNSPEC is assumed.
 853 *
 854 * socktype is specified as an integer to specify the socket type such as Socket::SOCK_STREAM.
 855 * It can be a symbol or a string which is the constant name
 856 * with or without SOCK_ prefix such as :STREAM, :DGRAM, :RAW, "SOCK_STREAM", etc.
 857 * If omitted, 0 is assumed.
 858 *
 859 * protocol is specified as an integer to specify the protocol such as Socket::IPPROTO_TCP.
 860 * It must be an integer, unlike family and socktype.
 861 * If omitted, 0 is assumed.
 862 * Note that 0 is reasonable value for most protocols, except raw socket.
 863 *
 864 */
 865static VALUE
 866addrinfo_initialize(int argc, VALUE *argv, VALUE self)
 867{
 868    rb_addrinfo_t *rai;
 869    VALUE sockaddr_arg, sockaddr_ary, pfamily, socktype, protocol;
 870    int i_pfamily, i_socktype, i_protocol;
 871    struct sockaddr *sockaddr_ptr;
 872    socklen_t sockaddr_len;
 873    VALUE canonname = Qnil, inspectname = Qnil;
 874
 875    if (check_addrinfo(self))
 876        rb_raise(rb_eTypeError, "already initialized socket address");
 877    DATA_PTR(self) = rai = alloc_addrinfo();
 878
 879    rb_scan_args(argc, argv, "13", &sockaddr_arg, &pfamily, &socktype, &protocol);
 880
 881    i_pfamily = NIL_P(pfamily) ? PF_UNSPEC : rsock_family_arg(pfamily);
 882    i_socktype = NIL_P(socktype) ? 0 : rsock_socktype_arg(socktype);
 883    i_protocol = NIL_P(protocol) ? 0 : NUM2INT(protocol);
 884
 885    sockaddr_ary = rb_check_array_type(sockaddr_arg);
 886    if (!NIL_P(sockaddr_ary)) {
 887        VALUE afamily = rb_ary_entry(sockaddr_ary, 0);
 888        int af;
 889        StringValue(afamily);
 890        if (rsock_family_to_int(RSTRING_PTR(afamily), RSTRING_LEN(afamily), &af) == -1)
 891	    rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily));
 892        switch (af) {
 893          case AF_INET: /* ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] */
 894#ifdef INET6
 895          case AF_INET6: /* ["AF_INET6", 42304, "ip6-localhost", "::1"] */
 896#endif
 897          {
 898            VALUE service = rb_ary_entry(sockaddr_ary, 1);
 899            VALUE nodename = rb_ary_entry(sockaddr_ary, 2);
 900            VALUE numericnode = rb_ary_entry(sockaddr_ary, 3);
 901            int flags;
 902
 903            service = INT2NUM(NUM2INT(service));
 904            if (!NIL_P(nodename))
 905                StringValue(nodename);
 906            StringValue(numericnode);
 907            flags = AI_NUMERICHOST;
 908#ifdef AI_NUMERICSERV
 909            flags |= AI_NUMERICSERV;
 910#endif
 911
 912            init_addrinfo_getaddrinfo(rai, numericnode, service,
 913                    INT2NUM(i_pfamily ? i_pfamily : af), INT2NUM(i_socktype), INT2NUM(i_protocol),
 914                    INT2NUM(flags),
 915                    nodename, service);
 916            break;
 917          }
 918
 919#ifdef HAVE_SYS_UN_H
 920          case AF_UNIX: /* ["AF_UNIX", "/tmp/sock"] */
 921          {
 922            VALUE path = rb_ary_entry(sockaddr_ary, 1);
 923            StringValue(path);
 924            init_unix_addrinfo(rai, path, SOCK_STREAM);
 925            break;
 926          }
 927#endif
 928
 929          default:
 930            rb_raise(rb_eSocket, "unexpected address family");
 931        }
 932    }
 933    else {
 934        StringValue(sockaddr_arg);
 935        sockaddr_ptr = (struct sockaddr *)RSTRING_PTR(sockaddr_arg);
 936        sockaddr_len = RSTRING_SOCKLEN(sockaddr_arg);
 937        init_addrinfo(rai, sockaddr_ptr, sockaddr_len,
 938                      i_pfamily, i_socktype, i_protocol,
 939                      canonname, inspectname);
 940    }
 941
 942    return self;
 943}
 944
 945static int
 946get_afamily(struct sockaddr *addr, socklen_t len)
 947{
 948    if ((socklen_t)((char*)&addr->sa_family + sizeof(addr->sa_family) - (char*)addr) <= len)
 949        return addr->sa_family;
 950    else
 951        return AF_UNSPEC;
 952}
 953
 954static int
 955ai_get_afamily(rb_addrinfo_t *rai)
 956{
 957    return get_afamily(&rai->addr.addr, rai->sockaddr_len);
 958}
 959
 960static VALUE
 961inspect_sockaddr(VALUE addrinfo, VALUE ret)
 962{
 963    rb_addrinfo_t *rai = get_addrinfo(addrinfo);
 964    union_sockaddr *sockaddr = &rai->addr;
 965    socklen_t socklen = rai->sockaddr_len;
 966    return rsock_inspect_sockaddr((struct sockaddr *)sockaddr, socklen, ret);
 967}
 968
 969VALUE
 970rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE ret)
 971{
 972    union_sockaddr *sockaddr = (union_sockaddr *)sockaddr_arg;
 973    if (socklen == 0) {
 974        rb_str_cat2(ret, "empty-sockaddr");
 975    }
 976    else if ((long)socklen < ((char*)&sockaddr->addr.sa_family + sizeof(sockaddr->addr.sa_family)) - (char*)sockaddr)
 977        rb_str_cat2(ret, "too-short-sockaddr");
 978    else {
 979        switch (sockaddr->addr.sa_family) {
 980          case AF_UNSPEC:
 981	  {
 982	    rb_str_cat2(ret, "UNSPEC");
 983            break;
 984	  }
 985
 986          case AF_INET:
 987          {
 988            struct sockaddr_in *addr;
 989            int port;
 990	    addr = &sockaddr->in;
 991	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+0+1) <= socklen)
 992		rb_str_catf(ret, "%d", ((unsigned char*)&addr->sin_addr)[0]);
 993	    else
 994		rb_str_cat2(ret, "?");
 995	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+1+1) <= socklen)
 996		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[1]);
 997	    else
 998		rb_str_cat2(ret, ".?");
 999	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+2+1) <= socklen)
1000		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[2]);
1001	    else
1002		rb_str_cat2(ret, ".?");
1003	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+3+1) <= socklen)
1004		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[3]);
1005	    else
1006		rb_str_cat2(ret, ".?");
1007
1008	    if ((socklen_t)(((char*)&addr->sin_port)-(char*)addr+(int)sizeof(addr->sin_port)) < socklen) {
1009		port = ntohs(addr->sin_port);
1010		if (port)
1011		    rb_str_catf(ret, ":%d", port);
1012	    }
1013	    else {
1014		rb_str_cat2(ret, ":?");
1015	    }
1016	    if ((socklen_t)sizeof(struct sockaddr_in) != socklen)
1017		rb_str_catf(ret, " (%d bytes for %d bytes sockaddr_in)",
1018		  (int)socklen,
1019		  (int)sizeof(struct sockaddr_in));
1020            break;
1021          }
1022
1023#ifdef AF_INET6
1024          case AF_INET6:
1025          {
1026            struct sockaddr_in6 *addr;
1027            char hbuf[1024];
1028            int port;
1029            int error;
1030            if (socklen < (socklen_t)sizeof(struct sockaddr_in6)) {
1031                rb_str_catf(ret, "too-short-AF_INET6-sockaddr %d bytes", (int)socklen);
1032            }
1033            else {
1034                addr = &sockaddr->in6;
1035                /* use getnameinfo for scope_id.
1036                 * RFC 4007: IPv6 Scoped Address Architecture
1037                 * draft-ietf-ipv6-scope-api-00.txt: Scoped Address Extensions to the IPv6 Basic Socket API
1038                 */
1039                error = getnameinfo(&sockaddr->addr, socklen,
1040                                    hbuf, (socklen_t)sizeof(hbuf), NULL, 0,
1041                                    NI_NUMERICHOST|NI_NUMERICSERV);
1042                if (error) {
1043                    rsock_raise_socket_error("getnameinfo", error);
1044                }
1045                if (addr->sin6_port == 0) {
1046                    rb_str_cat2(ret, hbuf);
1047                }
1048                else {
1049                    port = ntohs(addr->sin6_port);
1050                    rb_str_catf(ret, "[%s]:%d", hbuf, port);
1051                }
1052                if ((socklen_t)sizeof(struct sockaddr_in6) < socklen)
1053                    rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(socklen - sizeof(struct sockaddr_in6)));
1054            }
1055            break;
1056          }
1057#endif
1058
1059#ifdef HAVE_SYS_UN_H
1060          case AF_UNIX:
1061          {
1062            struct sockaddr_un *addr = &sockaddr->un;
1063            char *p, *s, *e;
1064            s = addr->sun_path;
1065            e = (char*)addr + socklen;
1066            while (s < e && *(e-1) == '\0')
1067                e--;
1068            if (e < s)
1069                rb_str_cat2(ret, "too-short-AF_UNIX-sockaddr");
1070            else if (s == e)
1071                rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr");
1072            else {
1073                int printable_only = 1;
1074                p = s;
1075                while (p < e) {
1076                    printable_only = printable_only && ISPRINT(*p) && !ISSPACE(*p);
1077                    p++;
1078                }
1079                if (printable_only) { /* only printable, no space */
1080                    if (s[0] != '/') /* relative path */
1081                        rb_str_cat2(ret, "UNIX ");
1082                    rb_str_cat(ret, s, p - s);
1083                }
1084                else {
1085                    rb_str_cat2(ret, "UNIX");
1086                    while (s < e)
1087                        rb_str_catf(ret, ":%02x", (unsigned char)*s++);
1088                }
1089            }
1090            break;
1091          }
1092#endif
1093
1094#ifdef AF_PACKET
1095          /* GNU/Linux */
1096          case AF_PACKET:
1097          {
1098            struct sockaddr_ll *addr;
1099            const char *sep = "[";
1100#define CATSEP do { rb_str_cat2(ret, sep); sep = " "; } while (0);
1101
1102            addr = (struct sockaddr_ll *)sockaddr;
1103
1104            rb_str_cat2(ret, "PACKET");
1105
1106            if (offsetof(struct sockaddr_ll, sll_protocol) + sizeof(addr->sll_protocol) <= (size_t)socklen) {
1107                CATSEP;
1108                rb_str_catf(ret, "protocol=%d", ntohs(addr->sll_protocol));
1109            }
1110            if (offsetof(struct sockaddr_ll, sll_ifindex) + sizeof(addr->sll_ifindex) <= (size_t)socklen) {
1111                char buf[IFNAMSIZ];
1112                CATSEP;
1113                if (if_indextoname(addr->sll_ifindex, buf) == NULL)
1114                    rb_str_catf(ret, "ifindex=%d", addr->sll_ifindex);
1115                else
1116                    rb_str_catf(ret, "%s", buf);
1117            }
1118            if (offsetof(struct sockaddr_ll, sll_hatype) + sizeof(addr->sll_hatype) <= (size_t)socklen) {
1119                CATSEP;
1120                rb_str_catf(ret, "hatype=%d", addr->sll_hatype);
1121            }
1122            if (offsetof(struct sockaddr_ll, sll_pkttype) + sizeof(addr->sll_pkttype) <= (size_t)socklen) {
1123                CATSEP;
1124                if (addr->sll_pkttype == PACKET_HOST)
1125                    rb_str_cat2(ret, "HOST");
1126                else if (addr->sll_pkttype == PACKET_BROADCAST)
1127                    rb_str_cat2(ret, "BROADCAST");
1128                else if (addr->sll_pkttype == PACKET_MULTICAST)
1129                    rb_str_cat2(ret, "MULTICAST");
1130                else if (addr->sll_pkttype == PACKET_OTHERHOST)
1131                    rb_str_cat2(ret, "OTHERHOST");
1132                else if (addr->sll_pkttype == PACKET_OUTGOING)
1133                    rb_str_cat2(ret, "OUTGOING");
1134                else
1135                    rb_str_catf(ret, "pkttype=%d", addr->sll_pkttype);
1136            }
1137            if (socklen != (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + addr->sll_halen)) {
1138                CATSEP;
1139                if (offsetof(struct sockaddr_ll, sll_halen) + sizeof(addr->sll_halen) <= (size_t)socklen) {
1140                    rb_str_catf(ret, "halen=%d", addr->sll_halen);
1141                }
1142            }
1143            if (offsetof(struct sockaddr_ll, sll_addr) < (size_t)socklen) {
1144                socklen_t len, i;
1145                CATSEP;
1146                rb_str_cat2(ret, "hwaddr");
1147                len = addr->sll_halen;
1148                if ((size_t)socklen < offsetof(struct sockaddr_ll, sll_addr) + len)
1149                    len = socklen - offsetof(struct sockaddr_ll, sll_addr);
1150                for (i = 0; i < len; i++) {
1151                    rb_str_cat2(ret, i == 0 ? "=" : ":");
1152                    rb_str_catf(ret, "%02x", addr->sll_addr[i]);
1153                }
1154            }
1155
1156            if (socklen < (socklen_t)(offsetof(struct sockaddr_ll, sll_halen) + sizeof(addr->sll_halen)) ||
1157                (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + addr->sll_halen) != socklen) {
1158                CATSEP;
1159                rb_str_catf(ret, "(%d bytes for %d bytes sockaddr_ll)",
1160                    (int)socklen, (int)sizeof(struct sockaddr_ll));
1161            }
1162
1163            rb_str_cat2(ret, "]");
1164#undef CATSEP
1165
1166            break;
1167          }
1168#endif
1169
1170#if defined(AF_LINK) && defined(HAVE_TYPE_STRUCT_SOCKADDR_DL)
1171	  /* AF_LINK is defined in 4.4BSD derivations since Net2.
1172	     link_ntoa is also defined at Net2.
1173             However Debian GNU/kFreeBSD defines AF_LINK but
1174             don't have link_ntoa.  */
1175          case AF_LINK:
1176	  {
1177	    /*
1178	     * Simple implementation using link_ntoa():
1179	     * This doesn't work on Debian GNU/kFreeBSD 6.0.7 (squeeze).
1180             * Also, the format is bit different.
1181	     *
1182	     * rb_str_catf(ret, "LINK %s", link_ntoa(&sockaddr->dl));
1183	     * break;
1184	     */
1185            struct sockaddr_dl *addr = &sockaddr->dl;
1186            char *np = NULL, *ap = NULL, *endp;
1187            int nlen = 0, alen = 0;
1188            int i, off;
1189            const char *sep = "[";
1190#define CATSEP do { rb_str_cat2(ret, sep); sep = " "; } while (0);
1191
1192            rb_str_cat2(ret, "LINK");
1193
1194            endp = ((char *)addr) + socklen;
1195
1196            if (offsetof(struct sockaddr_dl, sdl_data) < socklen) {
1197                np = addr->sdl_data;
1198                nlen = addr->sdl_nlen;
1199                if (endp - np < nlen)
1200                    nlen = (int)(endp - np);
1201            }
1202            off = addr->sdl_nlen;
1203
1204            if (offsetof(struct sockaddr_dl, sdl_data) + off < socklen) {
1205                ap = addr->sdl_data + off;
1206                alen = addr->sdl_alen;
1207                if (endp - ap < alen)
1208                    alen = (int)(endp - ap);
1209            }
1210
1211	    CATSEP;
1212            if (np)
1213                rb_str_catf(ret, "%.*s", nlen, np);
1214            else
1215                rb_str_cat2(ret, "?");
1216
1217            if (ap && 0 < alen) {
1218		CATSEP;
1219                for (i = 0; i < alen; i++)
1220                    rb_str_catf(ret, "%s%02x", i == 0 ? "" : ":", (unsigned char)ap[i]);
1221            }
1222
1223            if (socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_nlen) + sizeof(addr->sdl_nlen)) ||
1224                socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_alen) + sizeof(addr->sdl_alen)) ||
1225                socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_slen) + sizeof(addr->sdl_slen)) ||
1226                /* longer length is possible behavior because struct sockaddr_dl has "minimum work area, can be larger" as the last field.
1227                 * cf. Net2:/usr/src/sys/net/if_dl.h. */
1228                socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_data) + addr->sdl_nlen + addr->sdl_alen + addr->sdl_slen)) {
1229		CATSEP;
1230                rb_str_catf(ret, "(%d bytes for %d bytes sockaddr_dl)",
1231                    (int)socklen, (int)sizeof(struct sockaddr_dl));
1232	    }
1233
1234            rb_str_cat2(ret, "]");
1235#undef CATSEP
1236            break;
1237          }
1238#endif
1239
1240          default:
1241          {
1242            ID id = rsock_intern_family(sockaddr->addr.sa_family);
1243            if (id == 0)
1244                rb_str_catf(ret, "unknown address family %d", sockaddr->addr.sa_family);
1245            else
1246                rb_str_catf(ret, "%s address format unknown", rb_id2name(id));
1247            break;
1248          }
1249        }
1250    }
1251
1252    return ret;
1253}
1254
1255/*
1256 * call-seq:
1257 *   addrinfo.inspect => string
1258 *
1259 * returns a string which shows addrinfo in human-readable form.
1260 *
1261 *   Addrinfo.tcp("localhost", 80).inspect #=> "#<Addrinfo: 127.0.0.1:80 TCP (localhost)>"
1262 *   Addrinfo.unix("/tmp/sock").inspect    #=> "#<Addrinfo: /tmp/sock SOCK_STREAM>"
1263 *
1264 */
1265static VALUE
1266addrinfo_inspect(VALUE self)
1267{
1268    rb_addrinfo_t *rai = get_addrinfo(self);
1269    int internet_p;
1270    VALUE ret;
1271
1272    ret = rb_sprintf("#<%s: ", rb_obj_classname(self));
1273
1274    inspect_sockaddr(self, ret);
1275
1276    if (rai->pfamily && ai_get_afamily(rai) != rai->pfamily) {
1277        ID id = rsock_intern_protocol_family(rai->pfamily);
1278        if (id)
1279            rb_str_catf(ret, " %s", rb_id2name(id));
1280        else
1281            rb_str_catf(ret, " PF_\?\?\?(%d)", rai->pfamily);
1282    }
1283
1284    internet_p = rai->pfamily == PF_INET;
1285#ifdef INET6
1286    internet_p = internet_p || rai->pfamily == PF_INET6;
1287#endif
1288    if (internet_p && rai->socktype == SOCK_STREAM &&
1289        (rai->protocol == 0 || rai->protocol == IPPROTO_TCP)) {
1290        rb_str_cat2(ret, " TCP");
1291    }
1292    else if (internet_p && rai->socktype == SOCK_DGRAM &&
1293        (rai->protocol == 0 || rai->protocol == IPPROTO_UDP)) {
1294        rb_str_cat2(ret, " UDP");
1295    }
1296    else {
1297        if (rai->socktype) {
1298            ID id = rsock_intern_socktype(rai->socktype);
1299            if (id)
1300                rb_str_catf(ret, " %s", rb_id2name(id));
1301            else
1302                rb_str_catf(ret, " SOCK_\?\?\?(%d)", rai->socktype);
1303        }
1304
1305        if (rai->protocol) {
1306            if (internet_p) {
1307                ID id = rsock_intern_ipproto(rai->protocol);
1308                if (id)
1309                    rb_str_catf(ret, " %s", rb_id2name(id));
1310                else
1311                    goto unknown_protocol;
1312            }
1313            else {
1314              unknown_protocol:
1315                rb_str_catf(ret, " UNKNOWN_PROTOCOL(%d)", rai->protocol);
1316            }
1317        }
1318    }
1319
1320    if (!NIL_P(rai->canonname)) {
1321        VALUE name = rai->canonname;
1322        rb_str_catf(ret, " %s", StringValueCStr(name));
1323    }
1324
1325    if (!NIL_P(rai->inspectname)) {
1326        VALUE name = rai->inspectname;
1327        rb_str_catf(ret, " (%s)", StringValueCStr(name));
1328    }
1329
1330    rb_str_buf_cat2(ret, ">");
1331    return ret;
1332}
1333
1334/*
1335 * call-seq:
1336 *   addrinfo.inspect_sockaddr => string
1337 *
1338 * returns a string which shows the sockaddr in _addrinfo_ with human-readable form.
1339 *
1340 *   Addrinfo.tcp("localhost", 80).inspect_sockaddr     #=> "127.0.0.1:80"
1341 *   Addrinfo.tcp("ip6-localhost", 80).inspect_sockaddr #=> "[::1]:80"
1342 *   Addrinfo.unix("/tmp/sock").inspect_sockaddr        #=> "/tmp/sock"
1343 *
1344 */
1345VALUE
1346rsock_addrinfo_inspect_sockaddr(VALUE self)
1347{
1348    return inspect_sockaddr(self, rb_str_new("", 0));
1349}
1350
1351/* :nodoc: */
1352static VALUE
1353addrinfo_mdump(VALUE self)
1354{
1355    rb_addrinfo_t *rai = get_addrinfo(self);
1356    VALUE sockaddr, afamily, pfamily, socktype, protocol, canonname, inspectname;
1357    int afamily_int = ai_get_afamily(rai);
1358    ID id;
1359
1360    id = rsock_intern_protocol_family(rai->pfamily);
1361    if (id == 0)
1362        rb_raise(rb_eSocket, "unknown protocol family: %d", rai->pfamily);
1363    pfamily = rb_id2str(id);
1364
1365    if (rai->socktype == 0)
1366        socktype = INT2FIX(0);
1367    else {
1368        id = rsock_intern_socktype(rai->socktype);
1369        if (id == 0)
1370            rb_raise(rb_eSocket, "unknown socktype: %d", rai->socktype);
1371        socktype = rb_id2str(id);
1372    }
1373
1374    if (rai->protocol == 0)
1375        protocol = INT2FIX(0);
1376    else if (IS_IP_FAMILY(afamily_int)) {
1377        id = rsock_intern_ipproto(rai->protocol);
1378        if (id == 0)
1379            rb_raise(rb_eSocket, "unknown IP protocol: %d", rai->protocol);
1380        protocol = rb_id2str(id);
1381    }
1382    else {
1383        rb_raise(rb_eSocket, "unknown protocol: %d", rai->protocol);
1384    }
1385
1386    canonname = rai->canonname;
1387
1388    inspectname = rai->inspectname;
1389
1390    id = rsock_intern_family(afamily_int);
1391    if (id == 0)
1392        rb_raise(rb_eSocket, "unknown address family: %d", afamily_int);
1393    afamily = rb_id2str(id);
1394
1395    switch(afamily_int) {
1396#ifdef HAVE_SYS_UN_H
1397      case AF_UNIX:
1398      {
1399        struct sockaddr_un *su = &rai->addr.un;
1400        char *s, *e;
1401        s = su->sun_path;
1402        e = (char*)su + rai->sockaddr_len;
1403        while (s < e && *(e-1) == '\0')
1404            e--;
1405        sockaddr = rb_str_new(s, e-s);
1406        break;
1407      }
1408#endif
1409
1410      default:
1411      {
1412        char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
1413        int error;
1414        error = getnameinfo(&rai->addr.addr, rai->sockaddr_len,
1415                            hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf),
1416                            NI_NUMERICHOST|NI_NUMERICSERV);
1417        if (error) {
1418            rsock_raise_socket_error("getnameinfo", error);
1419        }
1420        sockaddr = rb_assoc_new(rb_str_new_cstr(hbuf), rb_str_new_cstr(pbuf));
1421        break;
1422      }
1423    }
1424
1425    return rb_ary_new3(7, afamily, sockaddr, pfamily, socktype, protocol, canonname, inspectname);
1426}
1427
1428/* :nodoc: */
1429static VALUE
1430addrinfo_mload(VALUE self, VALUE ary)
1431{
1432    VALUE v;
1433    VALUE canonname, inspectname;
1434    int afamily, pfamily, socktype, protocol;
1435    union_sockaddr ss;
1436    socklen_t len;
1437    rb_addrinfo_t *rai;
1438
1439    if (check_addrinfo(self))
1440        rb_raise(rb_eTypeError, "already initialized socket address");
1441
1442    ary = rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
1443
1444    v = rb_ary_entry(ary, 0);
1445    StringValue(v);
1446    if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &afamily) == -1)
1447        rb_raise(rb_eTypeError, "unexpected address family");
1448
1449    v = rb_ary_entry(ary, 2);
1450    StringValue(v);
1451    if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &pfamily) == -1)
1452        rb_raise(rb_eTypeError, "unexpected protocol family");
1453
1454    v = rb_ary_entry(ary, 3);
1455    if (v == INT2FIX(0))
1456        socktype = 0;
1457    else {
1458        StringValue(v);
1459        if (rsock_socktype_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &socktype) == -1)
1460            rb_raise(rb_eTypeError, "unexpected socktype");
1461    }
1462
1463    v = rb_ary_entry(ary, 4);
1464    if (v == INT2FIX(0))
1465        protocol = 0;
1466    else {
1467        StringValue(v);
1468        if (IS_IP_FAMILY(afamily)) {
1469            if (rsock_ipproto_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &protocol) == -1)
1470                rb_raise(rb_eTypeError, "unexpected protocol");
1471        }
1472        else {
1473            rb_raise(rb_eTypeError, "unexpected protocol");
1474        }
1475    }
1476
1477    v = rb_ary_entry(ary, 5);
1478    if (NIL_P(v))
1479        canonname = Qnil;
1480    else {
1481        StringValue(v);
1482        canonname = v;
1483    }
1484
1485    v = rb_ary_entry(ary, 6);
1486    if (NIL_P(v))
1487        inspectname = Qnil;
1488    else {
1489        StringValue(v);
1490        inspectname = v;
1491    }
1492
1493    v = rb_ary_entry(ary, 1);
1494    switch(afamily) {
1495#ifdef HAVE_SYS_UN_H
1496      case AF_UNIX:
1497      {
1498        struct sockaddr_un uaddr;
1499        INIT_SOCKADDR_UN(&uaddr, sizeof(struct sockaddr_un));
1500
1501        StringValue(v);
1502        if (sizeof(uaddr.sun_path) < (size_t)RSTRING_LEN(v))
1503            rb_raise(rb_eSocket,
1504                "too long AF_UNIX path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
1505                (size_t)RSTRING_LEN(v), sizeof(uaddr.sun_path));
1506        memcpy(uaddr.sun_path, RSTRING_PTR(v), RSTRING_LEN(v));
1507        len = (socklen_t)sizeof(uaddr);
1508        memcpy(&ss, &uaddr, len);
1509        break;
1510      }
1511#endif
1512
1513      default:
1514      {
1515        VALUE pair = rb_convert_type(v, T_ARRAY, "Array", "to_ary");
1516        struct addrinfo *res;
1517        int flags = AI_NUMERICHOST;
1518#ifdef AI_NUMERICSERV
1519        flags |= AI_NUMERICSERV;
1520#endif
1521        res = call_getaddrinfo(rb_ary_entry(pair, 0), rb_ary_entry(pair, 1),
1522                               INT2NUM(pfamily), INT2NUM(socktype), INT2NUM(protocol),
1523                               INT2NUM(flags), 1);
1524
1525        len = res->ai_addrlen;
1526        memcpy(&ss, res->ai_addr, res->ai_addrlen);
1527        break;
1528      }
1529    }
1530
1531    DATA_PTR(self) = rai = alloc_addrinfo();
1532    init_addrinfo(rai, &ss.addr, len,
1533                  pfamily, socktype, protocol,
1534                  canonname, inspectname);
1535    return self;
1536}
1537
1538/*
1539 * call-seq:
1540 *   addrinfo.afamily => integer
1541 *
1542 * returns the address family as an integer.
1543 *
1544 *   Addrinfo.tcp("localhost", 80).afamily == Socket::AF_INET #=> true
1545 *
1546 */
1547static VALUE
1548addrinfo_afamily(VALUE self)
1549{
1550    rb_addrinfo_t *rai = get_addrinfo(self);
1551    return INT2NUM(ai_get_afamily(rai));
1552}
1553
1554/*
1555 * call-seq:
1556 *   addrinfo.pfamily => integer
1557 *
1558 * returns the protocol family as an integer.
1559 *
1560 *   Addrinfo.tcp("localhost", 80).pfamily == Socket::PF_INET #=> true
1561 *
1562 */
1563static VALUE
1564addrinfo_pfamily(VALUE self)
1565{
1566    rb_addrinfo_t *rai = get_addrinfo(self);
1567    return INT2NUM(rai->pfamily);
1568}
1569
1570/*
1571 * call-seq:
1572 *   addrinfo.socktype => integer
1573 *
1574 * returns the socket type as an integer.
1575 *
1576 *   Addrinfo.tcp("localhost", 80).socktype == Socket::SOCK_STREAM #=> true
1577 *
1578 */
1579static VALUE
1580addrinfo_socktype(VALUE self)
1581{
1582    rb_addrinfo_t *rai = get_addrinfo(self);
1583    return INT2NUM(rai->socktype);
1584}
1585
1586/*
1587 * call-seq:
1588 *   addrinfo.protocol => integer
1589 *
1590 * returns the socket type as an integer.
1591 *
1592 *   Addrinfo.tcp("localhost", 80).protocol == Socket::IPPROTO_TCP #=> true
1593 *
1594 */
1595static VALUE
1596addrinfo_protocol(VALUE self)
1597{
1598    rb_addrinfo_t *rai = get_addrinfo(self);
1599    return INT2NUM(rai->protocol);
1600}
1601
1602/*
1603 * call-seq:
1604 *   addrinfo.to_sockaddr => string
1605 *   addrinfo.to_s => string
1606 *
1607 * returns the socket address as packed struct sockaddr string.
1608 *
1609 *   Addrinfo.tcp("localhost", 80).to_sockaddr
1610 *   #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1611 *
1612 */
1613static VALUE
1614addrinfo_to_sockaddr(VALUE self)
1615{
1616    rb_addrinfo_t *rai = get_addrinfo(self);
1617    VALUE ret;
1618    ret = rb_str_new((char*)&rai->addr, rai->sockaddr_len);
1619    OBJ_INFECT(ret, self);
1620    return ret;
1621}
1622
1623/*
1624 * call-seq:
1625 *   addrinfo.canonname => string or nil
1626 *
1627 * returns the canonical name as an string.
1628 *
1629 * nil is returned if no canonical name.
1630 *
1631 * The canonical name is set by Addrinfo.getaddrinfo when AI_CANONNAME is specified.
1632 *
1633 *   list = Addrinfo.getaddrinfo("www.ruby-lang.org", 80, :INET, :STREAM, nil, Socket::AI_CANONNAME)
1634 *   p list[0] #=> #<Addrinfo: 221.186.184.68:80 TCP carbon.ruby-lang.org (www.ruby-lang.org)>
1635 *   p list[0].canonname #=> "carbon.ruby-lang.org"
1636 *
1637 */
1638static VALUE
1639addrinfo_canonname(VALUE self)
1640{
1641    rb_addrinfo_t *rai = get_addrinfo(self);
1642    return rai->canonname;
1643}
1644
1645/*
1646 * call-seq:
1647 *   addrinfo.ip? => true or false
1648 *
1649 * returns true if addrinfo is internet (IPv4/IPv6) address.
1650 * returns false otherwise.
1651 *
1652 *   Addrinfo.tcp("127.0.0.1", 80).ip? #=> true
1653 *   Addrinfo.tcp("::1", 80).ip?       #=> true
1654 *   Addrinfo.unix("/tmp/sock").ip?    #=> false
1655 *
1656 */
1657static VALUE
1658addrinfo_ip_p(VALUE self)
1659{
1660    rb_addrinfo_t *rai = get_addrinfo(self);
1661    int family = ai_get_afamily(rai);
1662    return IS_IP_FAMILY(family) ? Qtrue : Qfalse;
1663}
1664
1665/*
1666 * call-seq:
1667 *   addrinfo.ipv4? => true or false
1668 *
1669 * returns true if addrinfo is IPv4 address.
1670 * returns false otherwise.
1671 *
1672 *   Addrinfo.tcp("127.0.0.1", 80).ipv4? #=> true
1673 *   Addrinfo.tcp("::1", 80).ipv4?       #=> false
1674 *   Addrinfo.unix("/tmp/sock").ipv4?    #=> false
1675 *
1676 */
1677static VALUE
1678addrinfo_ipv4_p(VALUE self)
1679{
1680    rb_addrinfo_t *rai = get_addrinfo(self);
1681    return ai_get_afamily(rai) == AF_INET ? Qtrue : Qfalse;
1682}
1683
1684/*
1685 * call-seq:
1686 *   addrinfo.ipv6? => true or false
1687 *
1688 * returns true if addrinfo is IPv6 address.
1689 * returns false otherwise.
1690 *
1691 *   Addrinfo.tcp("127.0.0.1", 80).ipv6? #=> false
1692 *   Addrinfo.tcp("::1", 80).ipv6?       #=> true
1693 *   Addrinfo.unix("/tmp/sock").ipv6?    #=> false
1694 *
1695 */
1696static VALUE
1697addrinfo_ipv6_p(VALUE self)
1698{
1699#ifdef AF_INET6
1700    rb_addrinfo_t *rai = get_addrinfo(self);
1701    return ai_get_afamily(rai) == AF_INET6 ? Qtrue : Qfalse;
1702#else
1703    return Qfalse;
1704#endif
1705}
1706
1707/*
1708 * call-seq:
1709 *   addrinfo.unix? => true or false
1710 *
1711 * returns true if addrinfo is UNIX address.
1712 * returns false otherwise.
1713 *
1714 *   Addrinfo.tcp("1…

Large files files are truncated, but you can click here to view the full file