1 /************************************************
2 
3   raddrinfo.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]))
15 static 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 
25 static int
ruby_getaddrinfo(const char * nodename,const char * servname,const struct addrinfo * hints,struct addrinfo ** res)26 ruby_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)
57 static int
ruby_getaddrinfo__aix(const char * nodename,const char * servname,const struct addrinfo * hints,struct addrinfo ** res)58 ruby_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))
75 static int
ruby_getnameinfo__aix(const struct sockaddr * sa,size_t salen,char * host,size_t hostlen,char * serv,size_t servlen,int flags)76 ruby_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 
100 static int str_is_number(const char *);
101 
102 #if defined(__APPLE__)
103 static int
ruby_getaddrinfo__darwin(const char * nodename,const char * servname,const struct addrinfo * hints,struct addrinfo ** res)104 ruby_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 #ifdef HAVE_INET_PTON
149 static int
parse_numeric_port(const char * service,int * portp)150 parse_numeric_port(const char *service, int *portp)
151 {
152     unsigned long u;
153 
154     if (!service) {
155         *portp = 0;
156         return 1;
157     }
158 
159     if (strspn(service, "0123456789") != strlen(service))
160         return 0;
161 
162     errno = 0;
163     u = STRTOUL(service, NULL, 10);
164     if (errno)
165         return 0;
166 
167     if (0x10000 <= u)
168         return 0;
169 
170     *portp = (int)u;
171 
172     return 1;
173 }
174 #endif
175 
176 #ifndef GETADDRINFO_EMU
177 struct getaddrinfo_arg
178 {
179     const char *node;
180     const char *service;
181     const struct addrinfo *hints;
182     struct addrinfo **res;
183 };
184 
185 static void *
nogvl_getaddrinfo(void * arg)186 nogvl_getaddrinfo(void *arg)
187 {
188     int ret;
189     struct getaddrinfo_arg *ptr = arg;
190     ret = getaddrinfo(ptr->node, ptr->service, ptr->hints, ptr->res);
191 #ifdef __linux__
192     /* On Linux (mainly Ubuntu 13.04) /etc/nsswitch.conf has mdns4 and
193      * it cause getaddrinfo to return EAI_SYSTEM/ENOENT. [ruby-list:49420]
194      */
195     if (ret == EAI_SYSTEM && errno == ENOENT)
196 	ret = EAI_NONAME;
197 #endif
198     return (void *)(VALUE)ret;
199 }
200 #endif
201 
202 static int
numeric_getaddrinfo(const char * node,const char * service,const struct addrinfo * hints,struct addrinfo ** res)203 numeric_getaddrinfo(const char *node, const char *service,
204         const struct addrinfo *hints,
205         struct addrinfo **res)
206 {
207 #ifdef HAVE_INET_PTON
208 # if defined __MINGW64__
209 #   define inet_pton(f,s,d)        rb_w32_inet_pton(f,s,d)
210 # endif
211 
212     int port;
213 
214     if (node && parse_numeric_port(service, &port)) {
215 	static const struct {
216 	    int socktype;
217 	    int protocol;
218 	} list[] = {
219 	    { SOCK_STREAM, IPPROTO_TCP },
220 	    { SOCK_DGRAM, IPPROTO_UDP },
221 	    { SOCK_RAW, 0 }
222 	};
223 	struct addrinfo *ai = NULL;
224         int hint_family = hints ? hints->ai_family : PF_UNSPEC;
225         int hint_socktype = hints ? hints->ai_socktype : 0;
226         int hint_protocol = hints ? hints->ai_protocol : 0;
227         char ipv4addr[4];
228 #ifdef AF_INET6
229         char ipv6addr[16];
230         if ((hint_family == PF_UNSPEC || hint_family == PF_INET6) &&
231             strspn(node, "0123456789abcdefABCDEF.:") == strlen(node) &&
232             inet_pton(AF_INET6, node, ipv6addr)) {
233             int i;
234             for (i = numberof(list)-1; 0 <= i; i--) {
235                 if ((hint_socktype == 0 || hint_socktype == list[i].socktype) &&
236                     (hint_protocol == 0 || list[i].protocol == 0 || hint_protocol == list[i].protocol)) {
237                     struct addrinfo *ai0 = xcalloc(1, sizeof(struct addrinfo));
238                     struct sockaddr_in6 *sa = xmalloc(sizeof(struct sockaddr_in6));
239                     INIT_SOCKADDR_IN6(sa, sizeof(struct sockaddr_in6));
240                     memcpy(&sa->sin6_addr, ipv6addr, sizeof(ipv6addr));
241                     sa->sin6_port = htons(port);
242                     ai0->ai_family = PF_INET6;
243                     ai0->ai_socktype = list[i].socktype;
244                     ai0->ai_protocol = hint_protocol ? hint_protocol : list[i].protocol;
245                     ai0->ai_addrlen = sizeof(struct sockaddr_in6);
246                     ai0->ai_addr = (struct sockaddr *)sa;
247                     ai0->ai_canonname = NULL;
248                     ai0->ai_next = ai;
249                     ai = ai0;
250                 }
251             }
252         }
253         else
254 #endif
255         if ((hint_family == PF_UNSPEC || hint_family == PF_INET) &&
256             strspn(node, "0123456789.") == strlen(node) &&
257             inet_pton(AF_INET, node, ipv4addr)) {
258             int i;
259             for (i = numberof(list)-1; 0 <= i; i--) {
260                 if ((hint_socktype == 0 || hint_socktype == list[i].socktype) &&
261                     (hint_protocol == 0 || list[i].protocol == 0 || hint_protocol == list[i].protocol)) {
262                     struct addrinfo *ai0 = xcalloc(1, sizeof(struct addrinfo));
263                     struct sockaddr_in *sa = xmalloc(sizeof(struct sockaddr_in));
264                     INIT_SOCKADDR_IN(sa, sizeof(struct sockaddr_in));
265                     memcpy(&sa->sin_addr, ipv4addr, sizeof(ipv4addr));
266                     sa->sin_port = htons(port);
267                     ai0->ai_family = PF_INET;
268                     ai0->ai_socktype = list[i].socktype;
269                     ai0->ai_protocol = hint_protocol ? hint_protocol : list[i].protocol;
270                     ai0->ai_addrlen = sizeof(struct sockaddr_in);
271                     ai0->ai_addr = (struct sockaddr *)sa;
272                     ai0->ai_canonname = NULL;
273                     ai0->ai_next = ai;
274                     ai = ai0;
275                 }
276             }
277         }
278         if (ai) {
279             *res = ai;
280             return 0;
281         }
282     }
283 #endif
284     return EAI_FAIL;
285 }
286 
287 int
rb_getaddrinfo(const char * node,const char * service,const struct addrinfo * hints,struct rb_addrinfo ** res)288 rb_getaddrinfo(const char *node, const char *service,
289                const struct addrinfo *hints,
290                struct rb_addrinfo **res)
291 {
292     struct addrinfo *ai;
293     int ret;
294     int allocated_by_malloc = 0;
295 
296     ret = numeric_getaddrinfo(node, service, hints, &ai);
297     if (ret == 0)
298         allocated_by_malloc = 1;
299     else {
300 #ifdef GETADDRINFO_EMU
301         ret = getaddrinfo(node, service, hints, &ai);
302 #else
303         struct getaddrinfo_arg arg;
304         MEMZERO(&arg, struct getaddrinfo_arg, 1);
305         arg.node = node;
306         arg.service = service;
307         arg.hints = hints;
308         arg.res = &ai;
309         ret = (int)(VALUE)rb_thread_call_without_gvl(nogvl_getaddrinfo, &arg, RUBY_UBF_IO, 0);
310 #endif
311     }
312 
313     if (ret == 0) {
314         *res = (struct rb_addrinfo *)xmalloc(sizeof(struct rb_addrinfo));
315         (*res)->allocated_by_malloc = allocated_by_malloc;
316         (*res)->ai = ai;
317     }
318     return ret;
319 }
320 
321 void
rb_freeaddrinfo(struct rb_addrinfo * ai)322 rb_freeaddrinfo(struct rb_addrinfo *ai)
323 {
324     if (!ai->allocated_by_malloc)
325         freeaddrinfo(ai->ai);
326     else {
327         struct addrinfo *ai1, *ai2;
328         ai1 = ai->ai;
329         while (ai1) {
330             ai2 = ai1->ai_next;
331             xfree(ai1->ai_addr);
332             xfree(ai1);
333             ai1 = ai2;
334         }
335     }
336     xfree(ai);
337 }
338 
339 #ifndef GETADDRINFO_EMU
340 struct getnameinfo_arg
341 {
342     const struct sockaddr *sa;
343     socklen_t salen;
344     int flags;
345     char *host;
346     size_t hostlen;
347     char *serv;
348     size_t servlen;
349 };
350 
351 static void *
nogvl_getnameinfo(void * arg)352 nogvl_getnameinfo(void *arg)
353 {
354     struct getnameinfo_arg *ptr = arg;
355     return (void *)(VALUE)getnameinfo(ptr->sa, ptr->salen,
356 				      ptr->host, (socklen_t)ptr->hostlen,
357 				      ptr->serv, (socklen_t)ptr->servlen,
358 				      ptr->flags);
359 }
360 #endif
361 
362 int
rb_getnameinfo(const struct sockaddr * sa,socklen_t salen,char * host,size_t hostlen,char * serv,size_t servlen,int flags)363 rb_getnameinfo(const struct sockaddr *sa, socklen_t salen,
364            char *host, size_t hostlen,
365            char *serv, size_t servlen, int flags)
366 {
367 #ifdef GETADDRINFO_EMU
368     return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
369 #else
370     struct getnameinfo_arg arg;
371     int ret;
372     arg.sa = sa;
373     arg.salen = salen;
374     arg.host = host;
375     arg.hostlen = hostlen;
376     arg.serv = serv;
377     arg.servlen = servlen;
378     arg.flags = flags;
379     ret = (int)(VALUE)rb_thread_call_without_gvl(nogvl_getnameinfo, &arg, RUBY_UBF_IO, 0);
380     return ret;
381 #endif
382 }
383 
384 static void
make_ipaddr0(struct sockaddr * addr,socklen_t addrlen,char * buf,size_t buflen)385 make_ipaddr0(struct sockaddr *addr, socklen_t addrlen, char *buf, size_t buflen)
386 {
387     int error;
388 
389     error = rb_getnameinfo(addr, addrlen, buf, buflen, NULL, 0, NI_NUMERICHOST);
390     if (error) {
391         rsock_raise_socket_error("getnameinfo", error);
392     }
393 }
394 
395 VALUE
rsock_make_ipaddr(struct sockaddr * addr,socklen_t addrlen)396 rsock_make_ipaddr(struct sockaddr *addr, socklen_t addrlen)
397 {
398     char hbuf[1024];
399 
400     make_ipaddr0(addr, addrlen, hbuf, sizeof(hbuf));
401     return rb_str_new2(hbuf);
402 }
403 
404 static void
make_inetaddr(unsigned int host,char * buf,size_t buflen)405 make_inetaddr(unsigned int host, char *buf, size_t buflen)
406 {
407     struct sockaddr_in sin;
408 
409     INIT_SOCKADDR_IN(&sin, sizeof(sin));
410     sin.sin_addr.s_addr = host;
411     make_ipaddr0((struct sockaddr*)&sin, sizeof(sin), buf, buflen);
412 }
413 
414 static int
str_is_number(const char * p)415 str_is_number(const char *p)
416 {
417     char *ep;
418 
419     if (!p || *p == '\0')
420        return 0;
421     ep = NULL;
422     (void)STRTOUL(p, &ep, 10);
423     if (ep && *ep == '\0')
424        return 1;
425     else
426        return 0;
427 }
428 
429 #define str_equal(ptr, len, name) \
430     ((ptr)[0] == name[0] && \
431      rb_strlen_lit(name) == (len) && memcmp(ptr, name, len) == 0)
432 #define SafeStringValueCStr(v) do {\
433     StringValueCStr(v);\
434     rb_check_safe_obj(v);\
435 } while(0)
436 
437 static char*
host_str(VALUE host,char * hbuf,size_t hbuflen,int * flags_ptr)438 host_str(VALUE host, char *hbuf, size_t hbuflen, int *flags_ptr)
439 {
440     if (NIL_P(host)) {
441         return NULL;
442     }
443     else if (rb_obj_is_kind_of(host, rb_cInteger)) {
444         unsigned int i = NUM2UINT(host);
445 
446         make_inetaddr(htonl(i), hbuf, hbuflen);
447         if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
448         return hbuf;
449     }
450     else {
451         const char *name;
452         size_t len;
453 
454         SafeStringValueCStr(host);
455         RSTRING_GETMEM(host, name, len);
456         if (!len || str_equal(name, len, "<any>")) {
457             make_inetaddr(INADDR_ANY, hbuf, hbuflen);
458             if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
459         }
460         else if (str_equal(name, len, "<broadcast>")) {
461             make_inetaddr(INADDR_BROADCAST, hbuf, hbuflen);
462             if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
463         }
464         else if (len >= hbuflen) {
465             rb_raise(rb_eArgError, "hostname too long (%"PRIuSIZE")",
466                      len);
467         }
468         else {
469             memcpy(hbuf, name, len);
470             hbuf[len] = '\0';
471         }
472         return hbuf;
473     }
474 }
475 
476 static char*
port_str(VALUE port,char * pbuf,size_t pbuflen,int * flags_ptr)477 port_str(VALUE port, char *pbuf, size_t pbuflen, int *flags_ptr)
478 {
479     if (NIL_P(port)) {
480         return 0;
481     }
482     else if (FIXNUM_P(port)) {
483         snprintf(pbuf, pbuflen, "%ld", FIX2LONG(port));
484 #ifdef AI_NUMERICSERV
485         if (flags_ptr) *flags_ptr |= AI_NUMERICSERV;
486 #endif
487         return pbuf;
488     }
489     else {
490         const char *serv;
491         size_t len;
492 
493         SafeStringValueCStr(port);
494         RSTRING_GETMEM(port, serv, len);
495         if (len >= pbuflen) {
496             rb_raise(rb_eArgError, "service name too long (%"PRIuSIZE")",
497                      len);
498         }
499         memcpy(pbuf, serv, len);
500         pbuf[len] = '\0';
501         return pbuf;
502     }
503 }
504 
505 struct rb_addrinfo*
rsock_getaddrinfo(VALUE host,VALUE port,struct addrinfo * hints,int socktype_hack)506 rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack)
507 {
508     struct rb_addrinfo* res = NULL;
509     char *hostp, *portp;
510     int error;
511     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
512     int additional_flags = 0;
513 
514     hostp = host_str(host, hbuf, sizeof(hbuf), &additional_flags);
515     portp = port_str(port, pbuf, sizeof(pbuf), &additional_flags);
516 
517     if (socktype_hack && hints->ai_socktype == 0 && str_is_number(portp)) {
518        hints->ai_socktype = SOCK_DGRAM;
519     }
520     hints->ai_flags |= additional_flags;
521 
522     error = rb_getaddrinfo(hostp, portp, hints, &res);
523     if (error) {
524         if (hostp && hostp[strlen(hostp)-1] == '\n') {
525             rb_raise(rb_eSocket, "newline at the end of hostname");
526         }
527         rsock_raise_socket_error("getaddrinfo", error);
528     }
529 
530     return res;
531 }
532 
533 int
rsock_fd_family(int fd)534 rsock_fd_family(int fd)
535 {
536     struct sockaddr sa = { 0 };
537     socklen_t sa_len = sizeof(sa);
538 
539     if (fd < 0 || getsockname(fd, &sa, &sa_len) != 0 ||
540         (size_t)sa_len < offsetof(struct sockaddr, sa_family) + sizeof(sa.sa_family)) {
541 	return AF_UNSPEC;
542     }
543     return sa.sa_family;
544 }
545 
546 struct rb_addrinfo*
rsock_addrinfo(VALUE host,VALUE port,int family,int socktype,int flags)547 rsock_addrinfo(VALUE host, VALUE port, int family, int socktype, int flags)
548 {
549     struct addrinfo hints;
550 
551     MEMZERO(&hints, struct addrinfo, 1);
552     hints.ai_family = family;
553     hints.ai_socktype = socktype;
554     hints.ai_flags = flags;
555     return rsock_getaddrinfo(host, port, &hints, 1);
556 }
557 
558 VALUE
rsock_ipaddr(struct sockaddr * sockaddr,socklen_t sockaddrlen,int norevlookup)559 rsock_ipaddr(struct sockaddr *sockaddr, socklen_t sockaddrlen, int norevlookup)
560 {
561     VALUE family, port, addr1, addr2;
562     VALUE ary;
563     int error;
564     char hbuf[1024], pbuf[1024];
565     ID id;
566 
567     id = rsock_intern_family(sockaddr->sa_family);
568     if (id) {
569         family = rb_str_dup(rb_id2str(id));
570     }
571     else {
572         sprintf(pbuf, "unknown:%d", sockaddr->sa_family);
573         family = rb_str_new2(pbuf);
574     }
575 
576     addr1 = Qnil;
577     if (!norevlookup) {
578         error = rb_getnameinfo(sockaddr, sockaddrlen, hbuf, sizeof(hbuf),
579                                NULL, 0, 0);
580         if (! error) {
581             addr1 = rb_str_new2(hbuf);
582         }
583     }
584     error = rb_getnameinfo(sockaddr, sockaddrlen, hbuf, sizeof(hbuf),
585                            pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV);
586     if (error) {
587         rsock_raise_socket_error("getnameinfo", error);
588     }
589     addr2 = rb_str_new2(hbuf);
590     if (addr1 == Qnil) {
591         addr1 = addr2;
592     }
593     port = INT2FIX(atoi(pbuf));
594     ary = rb_ary_new3(4, family, port, addr1, addr2);
595 
596     return ary;
597 }
598 
599 #ifdef HAVE_SYS_UN_H
600 VALUE
rsock_unixpath_str(struct sockaddr_un * sockaddr,socklen_t len)601 rsock_unixpath_str(struct sockaddr_un *sockaddr, socklen_t len)
602 {
603     char *s, *e;
604     s = sockaddr->sun_path;
605     e = (char *)sockaddr + len;
606     while (s < e && *(e-1) == '\0')
607         e--;
608     if (s <= e)
609         return rb_str_new(s, e-s);
610     else
611         return rb_str_new2("");
612 }
613 
614 VALUE
rsock_unixaddr(struct sockaddr_un * sockaddr,socklen_t len)615 rsock_unixaddr(struct sockaddr_un *sockaddr, socklen_t len)
616 {
617     return rb_assoc_new(rb_str_new2("AF_UNIX"),
618                         rsock_unixpath_str(sockaddr, len));
619 }
620 
621 socklen_t
rsock_unix_sockaddr_len(VALUE path)622 rsock_unix_sockaddr_len(VALUE path)
623 {
624 #ifdef __linux__
625     if (RSTRING_LEN(path) == 0) {
626 	/* autobind; see unix(7) for details. */
627 	return (socklen_t) sizeof(sa_family_t);
628     }
629     else if (RSTRING_PTR(path)[0] == '\0') {
630 	/* abstract namespace; see unix(7) for details. */
631         if (SOCKLEN_MAX - offsetof(struct sockaddr_un, sun_path) < (size_t)RSTRING_LEN(path))
632             rb_raise(rb_eArgError, "Linux abstract socket too long");
633 	return (socklen_t) offsetof(struct sockaddr_un, sun_path) +
634 	    RSTRING_SOCKLEN(path);
635     }
636     else {
637 #endif
638 	return (socklen_t) sizeof(struct sockaddr_un);
639 #ifdef __linux__
640     }
641 #endif
642 }
643 #endif
644 
645 struct hostent_arg {
646     VALUE host;
647     struct rb_addrinfo* addr;
648     VALUE (*ipaddr)(struct sockaddr*, socklen_t);
649 };
650 
651 static VALUE
make_hostent_internal(struct hostent_arg * arg)652 make_hostent_internal(struct hostent_arg *arg)
653 {
654     VALUE host = arg->host;
655     struct addrinfo* addr = arg->addr->ai;
656     VALUE (*ipaddr)(struct sockaddr*, socklen_t) = arg->ipaddr;
657 
658     struct addrinfo *ai;
659     struct hostent *h;
660     VALUE ary, names;
661     char **pch;
662     const char* hostp;
663     char hbuf[NI_MAXHOST];
664 
665     ary = rb_ary_new();
666     if (addr->ai_canonname) {
667         hostp = addr->ai_canonname;
668     }
669     else {
670         hostp = host_str(host, hbuf, sizeof(hbuf), NULL);
671     }
672     rb_ary_push(ary, rb_str_new2(hostp));
673 
674     if (addr->ai_canonname && strlen(addr->ai_canonname) < NI_MAXHOST &&
675 	(h = gethostbyname(addr->ai_canonname))) {
676         names = rb_ary_new();
677         if (h->h_aliases != NULL) {
678             for (pch = h->h_aliases; *pch; pch++) {
679                 rb_ary_push(names, rb_str_new2(*pch));
680             }
681         }
682     }
683     else {
684         names = rb_ary_new2(0);
685     }
686     rb_ary_push(ary, names);
687     rb_ary_push(ary, INT2NUM(addr->ai_family));
688     for (ai = addr; ai; ai = ai->ai_next) {
689         rb_ary_push(ary, (*ipaddr)(ai->ai_addr, ai->ai_addrlen));
690     }
691 
692     return ary;
693 }
694 
695 VALUE
rsock_freeaddrinfo(VALUE arg)696 rsock_freeaddrinfo(VALUE arg)
697 {
698     struct rb_addrinfo *addr = (struct rb_addrinfo *)arg;
699     rb_freeaddrinfo(addr);
700     return Qnil;
701 }
702 
703 VALUE
rsock_make_hostent(VALUE host,struct rb_addrinfo * addr,VALUE (* ipaddr)(struct sockaddr *,socklen_t))704 rsock_make_hostent(VALUE host, struct rb_addrinfo *addr, VALUE (*ipaddr)(struct sockaddr *, socklen_t))
705 {
706     struct hostent_arg arg;
707 
708     arg.host = host;
709     arg.addr = addr;
710     arg.ipaddr = ipaddr;
711     return rb_ensure(make_hostent_internal, (VALUE)&arg,
712                      rsock_freeaddrinfo, (VALUE)addr);
713 }
714 
715 typedef struct {
716     VALUE inspectname;
717     VALUE canonname;
718     int pfamily;
719     int socktype;
720     int protocol;
721     socklen_t sockaddr_len;
722     union_sockaddr addr;
723 } rb_addrinfo_t;
724 
725 static void
addrinfo_mark(void * ptr)726 addrinfo_mark(void *ptr)
727 {
728     rb_addrinfo_t *rai = ptr;
729     rb_gc_mark(rai->inspectname);
730     rb_gc_mark(rai->canonname);
731 }
732 
733 #define addrinfo_free RUBY_TYPED_DEFAULT_FREE
734 
735 static size_t
addrinfo_memsize(const void * ptr)736 addrinfo_memsize(const void *ptr)
737 {
738     return sizeof(rb_addrinfo_t);
739 }
740 
741 static const rb_data_type_t addrinfo_type = {
742     "socket/addrinfo",
743     {addrinfo_mark, addrinfo_free, addrinfo_memsize,},
744 };
745 
746 static VALUE
addrinfo_s_allocate(VALUE klass)747 addrinfo_s_allocate(VALUE klass)
748 {
749     return TypedData_Wrap_Struct(klass, &addrinfo_type, 0);
750 }
751 
752 #define IS_ADDRINFO(obj) rb_typeddata_is_kind_of((obj), &addrinfo_type)
753 static inline rb_addrinfo_t *
check_addrinfo(VALUE self)754 check_addrinfo(VALUE self)
755 {
756     return rb_check_typeddata(self, &addrinfo_type);
757 }
758 
759 static rb_addrinfo_t *
get_addrinfo(VALUE self)760 get_addrinfo(VALUE self)
761 {
762     rb_addrinfo_t *rai = check_addrinfo(self);
763 
764     if (!rai) {
765         rb_raise(rb_eTypeError, "uninitialized socket address");
766     }
767     return rai;
768 }
769 
770 
771 static rb_addrinfo_t *
alloc_addrinfo(void)772 alloc_addrinfo(void)
773 {
774     rb_addrinfo_t *rai = ZALLOC(rb_addrinfo_t);
775     rai->inspectname = Qnil;
776     rai->canonname = Qnil;
777     return rai;
778 }
779 
780 static void
init_addrinfo(rb_addrinfo_t * rai,struct sockaddr * sa,socklen_t len,int pfamily,int socktype,int protocol,VALUE canonname,VALUE inspectname)781 init_addrinfo(rb_addrinfo_t *rai, struct sockaddr *sa, socklen_t len,
782               int pfamily, int socktype, int protocol,
783               VALUE canonname, VALUE inspectname)
784 {
785     if ((socklen_t)sizeof(rai->addr) < len)
786         rb_raise(rb_eArgError, "sockaddr string too big");
787     memcpy((void *)&rai->addr, (void *)sa, len);
788     rai->sockaddr_len = len;
789 
790     rai->pfamily = pfamily;
791     rai->socktype = socktype;
792     rai->protocol = protocol;
793     rai->canonname = canonname;
794     rai->inspectname = inspectname;
795 }
796 
797 VALUE
rsock_addrinfo_new(struct sockaddr * addr,socklen_t len,int family,int socktype,int protocol,VALUE canonname,VALUE inspectname)798 rsock_addrinfo_new(struct sockaddr *addr, socklen_t len,
799                    int family, int socktype, int protocol,
800                    VALUE canonname, VALUE inspectname)
801 {
802     VALUE a;
803     rb_addrinfo_t *rai;
804 
805     a = addrinfo_s_allocate(rb_cAddrinfo);
806     DATA_PTR(a) = rai = alloc_addrinfo();
807     init_addrinfo(rai, addr, len, family, socktype, protocol, canonname, inspectname);
808     return a;
809 }
810 
811 static struct rb_addrinfo *
call_getaddrinfo(VALUE node,VALUE service,VALUE family,VALUE socktype,VALUE protocol,VALUE flags,int socktype_hack)812 call_getaddrinfo(VALUE node, VALUE service,
813                  VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
814                  int socktype_hack)
815 {
816     struct addrinfo hints;
817     struct rb_addrinfo *res;
818 
819     MEMZERO(&hints, struct addrinfo, 1);
820     hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
821 
822     if (!NIL_P(socktype)) {
823 	hints.ai_socktype = rsock_socktype_arg(socktype);
824     }
825     if (!NIL_P(protocol)) {
826 	hints.ai_protocol = NUM2INT(protocol);
827     }
828     if (!NIL_P(flags)) {
829 	hints.ai_flags = NUM2INT(flags);
830     }
831     res = rsock_getaddrinfo(node, service, &hints, socktype_hack);
832 
833     if (res == NULL)
834 	rb_raise(rb_eSocket, "host not found");
835     return res;
836 }
837 
838 static VALUE make_inspectname(VALUE node, VALUE service, struct addrinfo *res);
839 
840 static void
init_addrinfo_getaddrinfo(rb_addrinfo_t * rai,VALUE node,VALUE service,VALUE family,VALUE socktype,VALUE protocol,VALUE flags,VALUE inspectnode,VALUE inspectservice)841 init_addrinfo_getaddrinfo(rb_addrinfo_t *rai, VALUE node, VALUE service,
842                           VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
843                           VALUE inspectnode, VALUE inspectservice)
844 {
845     struct rb_addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 1);
846     VALUE canonname;
847     VALUE inspectname = rb_str_equal(node, inspectnode) ? Qnil : make_inspectname(inspectnode, inspectservice, res->ai);
848 
849     canonname = Qnil;
850     if (res->ai->ai_canonname) {
851         canonname = rb_tainted_str_new_cstr(res->ai->ai_canonname);
852         OBJ_FREEZE(canonname);
853     }
854 
855     init_addrinfo(rai, res->ai->ai_addr, res->ai->ai_addrlen,
856                   NUM2INT(family), NUM2INT(socktype), NUM2INT(protocol),
857                   canonname, inspectname);
858 
859     rb_freeaddrinfo(res);
860 }
861 
862 static VALUE
make_inspectname(VALUE node,VALUE service,struct addrinfo * res)863 make_inspectname(VALUE node, VALUE service, struct addrinfo *res)
864 {
865     VALUE inspectname = Qnil;
866 
867     if (res) {
868         /* drop redundant information which also shown in address:port part. */
869         char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
870         int ret;
871         ret = rb_getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
872                              sizeof(hbuf), pbuf, sizeof(pbuf),
873                              NI_NUMERICHOST|NI_NUMERICSERV);
874         if (ret == 0) {
875             if (RB_TYPE_P(node, T_STRING) && strcmp(hbuf, RSTRING_PTR(node)) == 0)
876                 node = Qnil;
877             if (RB_TYPE_P(service, T_STRING) && strcmp(pbuf, RSTRING_PTR(service)) == 0)
878                 service = Qnil;
879             else if (RB_TYPE_P(service, T_FIXNUM) && atoi(pbuf) == FIX2INT(service))
880                 service = Qnil;
881         }
882     }
883 
884     if (RB_TYPE_P(node, T_STRING)) {
885         inspectname = rb_str_dup(node);
886     }
887     if (RB_TYPE_P(service, T_STRING)) {
888         if (NIL_P(inspectname))
889             inspectname = rb_sprintf(":%s", StringValueCStr(service));
890         else
891             rb_str_catf(inspectname, ":%s", StringValueCStr(service));
892     }
893     else if (RB_TYPE_P(service, T_FIXNUM) && FIX2INT(service) != 0)
894     {
895         if (NIL_P(inspectname))
896             inspectname = rb_sprintf(":%d", FIX2INT(service));
897         else
898             rb_str_catf(inspectname, ":%d", FIX2INT(service));
899     }
900     if (!NIL_P(inspectname)) {
901         OBJ_INFECT(inspectname, node);
902         OBJ_INFECT(inspectname, service);
903         OBJ_FREEZE(inspectname);
904     }
905     return inspectname;
906 }
907 
908 static VALUE
addrinfo_firstonly_new(VALUE node,VALUE service,VALUE family,VALUE socktype,VALUE protocol,VALUE flags)909 addrinfo_firstonly_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
910 {
911     VALUE ret;
912     VALUE canonname;
913     VALUE inspectname;
914 
915     struct rb_addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
916 
917     inspectname = make_inspectname(node, service, res->ai);
918 
919     canonname = Qnil;
920     if (res->ai->ai_canonname) {
921         canonname = rb_tainted_str_new_cstr(res->ai->ai_canonname);
922         OBJ_FREEZE(canonname);
923     }
924 
925     ret = rsock_addrinfo_new(res->ai->ai_addr, res->ai->ai_addrlen,
926                              res->ai->ai_family, res->ai->ai_socktype,
927                              res->ai->ai_protocol,
928                              canonname, inspectname);
929 
930     rb_freeaddrinfo(res);
931     return ret;
932 }
933 
934 static VALUE
addrinfo_list_new(VALUE node,VALUE service,VALUE family,VALUE socktype,VALUE protocol,VALUE flags)935 addrinfo_list_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
936 {
937     VALUE ret;
938     struct addrinfo *r;
939     VALUE inspectname;
940 
941     struct rb_addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
942 
943     inspectname = make_inspectname(node, service, res->ai);
944 
945     ret = rb_ary_new();
946     for (r = res->ai; r; r = r->ai_next) {
947         VALUE addr;
948         VALUE canonname = Qnil;
949 
950         if (r->ai_canonname) {
951             canonname = rb_tainted_str_new_cstr(r->ai_canonname);
952             OBJ_FREEZE(canonname);
953         }
954 
955         addr = rsock_addrinfo_new(r->ai_addr, r->ai_addrlen,
956                                   r->ai_family, r->ai_socktype, r->ai_protocol,
957                                   canonname, inspectname);
958 
959         rb_ary_push(ret, addr);
960     }
961 
962     rb_freeaddrinfo(res);
963     return ret;
964 }
965 
966 
967 #ifdef HAVE_SYS_UN_H
968 static void
init_unix_addrinfo(rb_addrinfo_t * rai,VALUE path,int socktype)969 init_unix_addrinfo(rb_addrinfo_t *rai, VALUE path, int socktype)
970 {
971     struct sockaddr_un un;
972     socklen_t len;
973 
974     StringValue(path);
975 
976     if (sizeof(un.sun_path) < (size_t)RSTRING_LEN(path))
977         rb_raise(rb_eArgError,
978             "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
979             (size_t)RSTRING_LEN(path), sizeof(un.sun_path));
980 
981     INIT_SOCKADDR_UN(&un, sizeof(struct sockaddr_un));
982     memcpy((void*)&un.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
983 
984     len = rsock_unix_sockaddr_len(path);
985     init_addrinfo(rai, (struct sockaddr *)&un, len,
986 		  PF_UNIX, socktype, 0, Qnil, Qnil);
987 }
988 #endif
989 
990 /*
991  * call-seq:
992  *   Addrinfo.new(sockaddr)                             => addrinfo
993  *   Addrinfo.new(sockaddr, family)                     => addrinfo
994  *   Addrinfo.new(sockaddr, family, socktype)           => addrinfo
995  *   Addrinfo.new(sockaddr, family, socktype, protocol) => addrinfo
996  *
997  * returns a new instance of Addrinfo.
998  * The instance contains sockaddr, family, socktype, protocol.
999  * sockaddr means struct sockaddr which can be used for connect(2), etc.
1000  * family, socktype and protocol are integers which is used for arguments of socket(2).
1001  *
1002  * sockaddr is specified as an array or a string.
1003  * The array should be compatible to the value of IPSocket#addr or UNIXSocket#addr.
1004  * The string should be struct sockaddr as generated by
1005  * Socket.sockaddr_in or Socket.unpack_sockaddr_un.
1006  *
1007  * sockaddr examples:
1008  * - ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"]
1009  * - ["AF_INET6", 42304, "ip6-localhost", "::1"]
1010  * - ["AF_UNIX", "/tmp/sock"]
1011  * - Socket.sockaddr_in("smtp", "2001:DB8::1")
1012  * - Socket.sockaddr_in(80, "172.18.22.42")
1013  * - Socket.sockaddr_in(80, "www.ruby-lang.org")
1014  * - Socket.sockaddr_un("/tmp/sock")
1015  *
1016  * In an AF_INET/AF_INET6 sockaddr array, the 4th element,
1017  * numeric IP address, is used to construct socket address in the Addrinfo instance.
1018  * If the 3rd element, textual host name, is non-nil, it is also recorded but used only for Addrinfo#inspect.
1019  *
1020  * family is specified as an integer to specify the protocol family such as Socket::PF_INET.
1021  * It can be a symbol or a string which is the constant name
1022  * with or without PF_ prefix such as :INET, :INET6, :UNIX, "PF_INET", etc.
1023  * If omitted, PF_UNSPEC is assumed.
1024  *
1025  * socktype is specified as an integer to specify the socket type such as Socket::SOCK_STREAM.
1026  * It can be a symbol or a string which is the constant name
1027  * with or without SOCK_ prefix such as :STREAM, :DGRAM, :RAW, "SOCK_STREAM", etc.
1028  * If omitted, 0 is assumed.
1029  *
1030  * protocol is specified as an integer to specify the protocol such as Socket::IPPROTO_TCP.
1031  * It must be an integer, unlike family and socktype.
1032  * If omitted, 0 is assumed.
1033  * Note that 0 is reasonable value for most protocols, except raw socket.
1034  *
1035  */
1036 static VALUE
addrinfo_initialize(int argc,VALUE * argv,VALUE self)1037 addrinfo_initialize(int argc, VALUE *argv, VALUE self)
1038 {
1039     rb_addrinfo_t *rai;
1040     VALUE sockaddr_arg, sockaddr_ary, pfamily, socktype, protocol;
1041     int i_pfamily, i_socktype, i_protocol;
1042     struct sockaddr *sockaddr_ptr;
1043     socklen_t sockaddr_len;
1044     VALUE canonname = Qnil, inspectname = Qnil;
1045 
1046     if (check_addrinfo(self))
1047         rb_raise(rb_eTypeError, "already initialized socket address");
1048     DATA_PTR(self) = rai = alloc_addrinfo();
1049 
1050     rb_scan_args(argc, argv, "13", &sockaddr_arg, &pfamily, &socktype, &protocol);
1051 
1052     i_pfamily = NIL_P(pfamily) ? PF_UNSPEC : rsock_family_arg(pfamily);
1053     i_socktype = NIL_P(socktype) ? 0 : rsock_socktype_arg(socktype);
1054     i_protocol = NIL_P(protocol) ? 0 : NUM2INT(protocol);
1055 
1056     sockaddr_ary = rb_check_array_type(sockaddr_arg);
1057     if (!NIL_P(sockaddr_ary)) {
1058         VALUE afamily = rb_ary_entry(sockaddr_ary, 0);
1059         int af;
1060         StringValue(afamily);
1061         if (rsock_family_to_int(RSTRING_PTR(afamily), RSTRING_LEN(afamily), &af) == -1)
1062 	    rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily));
1063         switch (af) {
1064           case AF_INET: /* ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] */
1065 #ifdef INET6
1066           case AF_INET6: /* ["AF_INET6", 42304, "ip6-localhost", "::1"] */
1067 #endif
1068           {
1069             VALUE service = rb_ary_entry(sockaddr_ary, 1);
1070             VALUE nodename = rb_ary_entry(sockaddr_ary, 2);
1071             VALUE numericnode = rb_ary_entry(sockaddr_ary, 3);
1072             int flags;
1073 
1074             service = INT2NUM(NUM2INT(service));
1075             if (!NIL_P(nodename))
1076                 StringValue(nodename);
1077             StringValue(numericnode);
1078             flags = AI_NUMERICHOST;
1079 #ifdef AI_NUMERICSERV
1080             flags |= AI_NUMERICSERV;
1081 #endif
1082 
1083             init_addrinfo_getaddrinfo(rai, numericnode, service,
1084                     INT2NUM(i_pfamily ? i_pfamily : af), INT2NUM(i_socktype), INT2NUM(i_protocol),
1085                     INT2NUM(flags),
1086                     nodename, service);
1087             break;
1088           }
1089 
1090 #ifdef HAVE_SYS_UN_H
1091           case AF_UNIX: /* ["AF_UNIX", "/tmp/sock"] */
1092           {
1093             VALUE path = rb_ary_entry(sockaddr_ary, 1);
1094             StringValue(path);
1095             init_unix_addrinfo(rai, path, SOCK_STREAM);
1096             break;
1097           }
1098 #endif
1099 
1100           default:
1101             rb_raise(rb_eSocket, "unexpected address family");
1102         }
1103     }
1104     else {
1105         StringValue(sockaddr_arg);
1106         sockaddr_ptr = (struct sockaddr *)RSTRING_PTR(sockaddr_arg);
1107         sockaddr_len = RSTRING_SOCKLEN(sockaddr_arg);
1108         init_addrinfo(rai, sockaddr_ptr, sockaddr_len,
1109                       i_pfamily, i_socktype, i_protocol,
1110                       canonname, inspectname);
1111     }
1112 
1113     return self;
1114 }
1115 
1116 static int
get_afamily(struct sockaddr * addr,socklen_t len)1117 get_afamily(struct sockaddr *addr, socklen_t len)
1118 {
1119     if ((socklen_t)((char*)&addr->sa_family + sizeof(addr->sa_family) - (char*)addr) <= len)
1120         return addr->sa_family;
1121     else
1122         return AF_UNSPEC;
1123 }
1124 
1125 static int
ai_get_afamily(rb_addrinfo_t * rai)1126 ai_get_afamily(rb_addrinfo_t *rai)
1127 {
1128     return get_afamily(&rai->addr.addr, rai->sockaddr_len);
1129 }
1130 
1131 static VALUE
inspect_sockaddr(VALUE addrinfo,VALUE ret)1132 inspect_sockaddr(VALUE addrinfo, VALUE ret)
1133 {
1134     rb_addrinfo_t *rai = get_addrinfo(addrinfo);
1135     union_sockaddr *sockaddr = &rai->addr;
1136     socklen_t socklen = rai->sockaddr_len;
1137     return rsock_inspect_sockaddr((struct sockaddr *)sockaddr, socklen, ret);
1138 }
1139 
1140 VALUE
rsock_inspect_sockaddr(struct sockaddr * sockaddr_arg,socklen_t socklen,VALUE ret)1141 rsock_inspect_sockaddr(struct sockaddr *sockaddr_arg, socklen_t socklen, VALUE ret)
1142 {
1143     union_sockaddr *sockaddr = (union_sockaddr *)sockaddr_arg;
1144     if (socklen == 0) {
1145         rb_str_cat2(ret, "empty-sockaddr");
1146     }
1147     else if ((long)socklen < ((char*)&sockaddr->addr.sa_family + sizeof(sockaddr->addr.sa_family)) - (char*)sockaddr)
1148         rb_str_cat2(ret, "too-short-sockaddr");
1149     else {
1150         switch (sockaddr->addr.sa_family) {
1151           case AF_UNSPEC:
1152 	  {
1153 	    rb_str_cat2(ret, "UNSPEC");
1154             break;
1155 	  }
1156 
1157           case AF_INET:
1158           {
1159             struct sockaddr_in *addr;
1160             int port;
1161 	    addr = &sockaddr->in;
1162 	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+0+1) <= socklen)
1163 		rb_str_catf(ret, "%d", ((unsigned char*)&addr->sin_addr)[0]);
1164 	    else
1165 		rb_str_cat2(ret, "?");
1166 	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+1+1) <= socklen)
1167 		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[1]);
1168 	    else
1169 		rb_str_cat2(ret, ".?");
1170 	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+2+1) <= socklen)
1171 		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[2]);
1172 	    else
1173 		rb_str_cat2(ret, ".?");
1174 	    if ((socklen_t)(((char*)&addr->sin_addr)-(char*)addr+3+1) <= socklen)
1175 		rb_str_catf(ret, ".%d", ((unsigned char*)&addr->sin_addr)[3]);
1176 	    else
1177 		rb_str_cat2(ret, ".?");
1178 
1179 	    if ((socklen_t)(((char*)&addr->sin_port)-(char*)addr+(int)sizeof(addr->sin_port)) < socklen) {
1180 		port = ntohs(addr->sin_port);
1181 		if (port)
1182 		    rb_str_catf(ret, ":%d", port);
1183 	    }
1184 	    else {
1185 		rb_str_cat2(ret, ":?");
1186 	    }
1187 	    if ((socklen_t)sizeof(struct sockaddr_in) != socklen)
1188 		rb_str_catf(ret, " (%d bytes for %d bytes sockaddr_in)",
1189 		  (int)socklen,
1190 		  (int)sizeof(struct sockaddr_in));
1191             break;
1192           }
1193 
1194 #ifdef AF_INET6
1195           case AF_INET6:
1196           {
1197             struct sockaddr_in6 *addr;
1198             char hbuf[1024];
1199             int port;
1200             int error;
1201             if (socklen < (socklen_t)sizeof(struct sockaddr_in6)) {
1202                 rb_str_catf(ret, "too-short-AF_INET6-sockaddr %d bytes", (int)socklen);
1203             }
1204             else {
1205                 addr = &sockaddr->in6;
1206                 /* use getnameinfo for scope_id.
1207                  * RFC 4007: IPv6 Scoped Address Architecture
1208                  * draft-ietf-ipv6-scope-api-00.txt: Scoped Address Extensions to the IPv6 Basic Socket API
1209                  */
1210                 error = getnameinfo(&sockaddr->addr, socklen,
1211                                     hbuf, (socklen_t)sizeof(hbuf), NULL, 0,
1212                                     NI_NUMERICHOST|NI_NUMERICSERV);
1213                 if (error) {
1214                     rsock_raise_socket_error("getnameinfo", error);
1215                 }
1216                 if (addr->sin6_port == 0) {
1217                     rb_str_cat2(ret, hbuf);
1218                 }
1219                 else {
1220                     port = ntohs(addr->sin6_port);
1221                     rb_str_catf(ret, "[%s]:%d", hbuf, port);
1222                 }
1223                 if ((socklen_t)sizeof(struct sockaddr_in6) < socklen)
1224                     rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(socklen - sizeof(struct sockaddr_in6)));
1225             }
1226             break;
1227           }
1228 #endif
1229 
1230 #ifdef HAVE_SYS_UN_H
1231           case AF_UNIX:
1232           {
1233             struct sockaddr_un *addr = &sockaddr->un;
1234             char *p, *s, *e;
1235             s = addr->sun_path;
1236             e = (char*)addr + socklen;
1237             while (s < e && *(e-1) == '\0')
1238                 e--;
1239             if (e < s)
1240                 rb_str_cat2(ret, "too-short-AF_UNIX-sockaddr");
1241             else if (s == e)
1242                 rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr");
1243             else {
1244                 int printable_only = 1;
1245                 p = s;
1246                 while (p < e) {
1247                     printable_only = printable_only && ISPRINT(*p) && !ISSPACE(*p);
1248                     p++;
1249                 }
1250                 if (printable_only) { /* only printable, no space */
1251                     if (s[0] != '/') /* relative path */
1252                         rb_str_cat2(ret, "UNIX ");
1253                     rb_str_cat(ret, s, p - s);
1254                 }
1255                 else {
1256                     rb_str_cat2(ret, "UNIX");
1257                     while (s < e)
1258                         rb_str_catf(ret, ":%02x", (unsigned char)*s++);
1259                 }
1260             }
1261             break;
1262           }
1263 #endif
1264 
1265 #if defined(AF_PACKET) && defined(__linux__)
1266           /* GNU/Linux */
1267           case AF_PACKET:
1268           {
1269             struct sockaddr_ll *addr;
1270             const char *sep = "[";
1271 #define CATSEP do { rb_str_cat2(ret, sep); sep = " "; } while (0);
1272 
1273             addr = (struct sockaddr_ll *)sockaddr;
1274 
1275             rb_str_cat2(ret, "PACKET");
1276 
1277             if (offsetof(struct sockaddr_ll, sll_protocol) + sizeof(addr->sll_protocol) <= (size_t)socklen) {
1278                 CATSEP;
1279                 rb_str_catf(ret, "protocol=%d", ntohs(addr->sll_protocol));
1280             }
1281             if (offsetof(struct sockaddr_ll, sll_ifindex) + sizeof(addr->sll_ifindex) <= (size_t)socklen) {
1282                 char buf[IFNAMSIZ];
1283                 CATSEP;
1284                 if (if_indextoname(addr->sll_ifindex, buf) == NULL)
1285                     rb_str_catf(ret, "ifindex=%d", addr->sll_ifindex);
1286                 else
1287                     rb_str_catf(ret, "%s", buf);
1288             }
1289             if (offsetof(struct sockaddr_ll, sll_hatype) + sizeof(addr->sll_hatype) <= (size_t)socklen) {
1290                 CATSEP;
1291                 rb_str_catf(ret, "hatype=%d", addr->sll_hatype);
1292             }
1293             if (offsetof(struct sockaddr_ll, sll_pkttype) + sizeof(addr->sll_pkttype) <= (size_t)socklen) {
1294                 CATSEP;
1295                 if (addr->sll_pkttype == PACKET_HOST)
1296                     rb_str_cat2(ret, "HOST");
1297                 else if (addr->sll_pkttype == PACKET_BROADCAST)
1298                     rb_str_cat2(ret, "BROADCAST");
1299                 else if (addr->sll_pkttype == PACKET_MULTICAST)
1300                     rb_str_cat2(ret, "MULTICAST");
1301                 else if (addr->sll_pkttype == PACKET_OTHERHOST)
1302                     rb_str_cat2(ret, "OTHERHOST");
1303                 else if (addr->sll_pkttype == PACKET_OUTGOING)
1304                     rb_str_cat2(ret, "OUTGOING");
1305                 else
1306                     rb_str_catf(ret, "pkttype=%d", addr->sll_pkttype);
1307             }
1308             if (socklen != (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + addr->sll_halen)) {
1309                 CATSEP;
1310                 if (offsetof(struct sockaddr_ll, sll_halen) + sizeof(addr->sll_halen) <= (size_t)socklen) {
1311                     rb_str_catf(ret, "halen=%d", addr->sll_halen);
1312                 }
1313             }
1314             if (offsetof(struct sockaddr_ll, sll_addr) < (size_t)socklen) {
1315                 socklen_t len, i;
1316                 CATSEP;
1317                 rb_str_cat2(ret, "hwaddr");
1318                 len = addr->sll_halen;
1319                 if ((size_t)socklen < offsetof(struct sockaddr_ll, sll_addr) + len)
1320                     len = socklen - offsetof(struct sockaddr_ll, sll_addr);
1321                 for (i = 0; i < len; i++) {
1322                     rb_str_cat2(ret, i == 0 ? "=" : ":");
1323                     rb_str_catf(ret, "%02x", addr->sll_addr[i]);
1324                 }
1325             }
1326 
1327             if (socklen < (socklen_t)(offsetof(struct sockaddr_ll, sll_halen) + sizeof(addr->sll_halen)) ||
1328                 (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + addr->sll_halen) != socklen) {
1329                 CATSEP;
1330                 rb_str_catf(ret, "(%d bytes for %d bytes sockaddr_ll)",
1331                     (int)socklen, (int)sizeof(struct sockaddr_ll));
1332             }
1333 
1334             rb_str_cat2(ret, "]");
1335 #undef CATSEP
1336 
1337             break;
1338           }
1339 #endif
1340 
1341 #if defined(AF_LINK) && defined(HAVE_TYPE_STRUCT_SOCKADDR_DL)
1342 	  /* AF_LINK is defined in 4.4BSD derivations since Net2.
1343 	     link_ntoa is also defined at Net2.
1344              However Debian GNU/kFreeBSD defines AF_LINK but
1345              don't have link_ntoa.  */
1346           case AF_LINK:
1347 	  {
1348 	    /*
1349 	     * Simple implementation using link_ntoa():
1350 	     * This doesn't work on Debian GNU/kFreeBSD 6.0.7 (squeeze).
1351              * Also, the format is bit different.
1352 	     *
1353 	     * rb_str_catf(ret, "LINK %s", link_ntoa(&sockaddr->dl));
1354 	     * break;
1355 	     */
1356             struct sockaddr_dl *addr = &sockaddr->dl;
1357             char *np = NULL, *ap = NULL, *endp;
1358             int nlen = 0, alen = 0;
1359             int i, off;
1360             const char *sep = "[";
1361 #define CATSEP do { rb_str_cat2(ret, sep); sep = " "; } while (0);
1362 
1363             rb_str_cat2(ret, "LINK");
1364 
1365             endp = ((char *)addr) + socklen;
1366 
1367             if (offsetof(struct sockaddr_dl, sdl_data) < socklen) {
1368                 np = addr->sdl_data;
1369                 nlen = addr->sdl_nlen;
1370                 if (endp - np < nlen)
1371                     nlen = (int)(endp - np);
1372             }
1373             off = addr->sdl_nlen;
1374 
1375             if (offsetof(struct sockaddr_dl, sdl_data) + off < socklen) {
1376                 ap = addr->sdl_data + off;
1377                 alen = addr->sdl_alen;
1378                 if (endp - ap < alen)
1379                     alen = (int)(endp - ap);
1380             }
1381 
1382 	    CATSEP;
1383             if (np)
1384                 rb_str_catf(ret, "%.*s", nlen, np);
1385             else
1386                 rb_str_cat2(ret, "?");
1387 
1388             if (ap && 0 < alen) {
1389 		CATSEP;
1390                 for (i = 0; i < alen; i++)
1391                     rb_str_catf(ret, "%s%02x", i == 0 ? "" : ":", (unsigned char)ap[i]);
1392             }
1393 
1394             if (socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_nlen) + sizeof(addr->sdl_nlen)) ||
1395                 socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_alen) + sizeof(addr->sdl_alen)) ||
1396                 socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_slen) + sizeof(addr->sdl_slen)) ||
1397                 /* longer length is possible behavior because struct sockaddr_dl has "minimum work area, can be larger" as the last field.
1398                  * cf. Net2:/usr/src/sys/net/if_dl.h. */
1399                 socklen < (socklen_t)(offsetof(struct sockaddr_dl, sdl_data) + addr->sdl_nlen + addr->sdl_alen + addr->sdl_slen)) {
1400 		CATSEP;
1401                 rb_str_catf(ret, "(%d bytes for %d bytes sockaddr_dl)",
1402                     (int)socklen, (int)sizeof(struct sockaddr_dl));
1403 	    }
1404 
1405             rb_str_cat2(ret, "]");
1406 #undef CATSEP
1407             break;
1408           }
1409 #endif
1410 
1411           default:
1412           {
1413             ID id = rsock_intern_family(sockaddr->addr.sa_family);
1414             if (id == 0)
1415                 rb_str_catf(ret, "unknown address family %d", sockaddr->addr.sa_family);
1416             else
1417                 rb_str_catf(ret, "%s address format unknown", rb_id2name(id));
1418             break;
1419           }
1420         }
1421     }
1422 
1423     return ret;
1424 }
1425 
1426 /*
1427  * call-seq:
1428  *   addrinfo.inspect => string
1429  *
1430  * returns a string which shows addrinfo in human-readable form.
1431  *
1432  *   Addrinfo.tcp("localhost", 80).inspect #=> "#<Addrinfo: 127.0.0.1:80 TCP (localhost)>"
1433  *   Addrinfo.unix("/tmp/sock").inspect    #=> "#<Addrinfo: /tmp/sock SOCK_STREAM>"
1434  *
1435  */
1436 static VALUE
addrinfo_inspect(VALUE self)1437 addrinfo_inspect(VALUE self)
1438 {
1439     rb_addrinfo_t *rai = get_addrinfo(self);
1440     int internet_p;
1441     VALUE ret;
1442 
1443     ret = rb_sprintf("#<%s: ", rb_obj_classname(self));
1444 
1445     inspect_sockaddr(self, ret);
1446 
1447     if (rai->pfamily && ai_get_afamily(rai) != rai->pfamily) {
1448         ID id = rsock_intern_protocol_family(rai->pfamily);
1449         if (id)
1450             rb_str_catf(ret, " %s", rb_id2name(id));
1451         else
1452             rb_str_catf(ret, " PF_\?\?\?(%d)", rai->pfamily);
1453     }
1454 
1455     internet_p = rai->pfamily == PF_INET;
1456 #ifdef INET6
1457     internet_p = internet_p || rai->pfamily == PF_INET6;
1458 #endif
1459     if (internet_p && rai->socktype == SOCK_STREAM &&
1460         (rai->protocol == 0 || rai->protocol == IPPROTO_TCP)) {
1461         rb_str_cat2(ret, " TCP");
1462     }
1463     else if (internet_p && rai->socktype == SOCK_DGRAM &&
1464         (rai->protocol == 0 || rai->protocol == IPPROTO_UDP)) {
1465         rb_str_cat2(ret, " UDP");
1466     }
1467     else {
1468         if (rai->socktype) {
1469             ID id = rsock_intern_socktype(rai->socktype);
1470             if (id)
1471                 rb_str_catf(ret, " %s", rb_id2name(id));
1472             else
1473                 rb_str_catf(ret, " SOCK_\?\?\?(%d)", rai->socktype);
1474         }
1475 
1476         if (rai->protocol) {
1477             if (internet_p) {
1478                 ID id = rsock_intern_ipproto(rai->protocol);
1479                 if (id)
1480                     rb_str_catf(ret, " %s", rb_id2name(id));
1481                 else
1482                     goto unknown_protocol;
1483             }
1484             else {
1485               unknown_protocol:
1486                 rb_str_catf(ret, " UNKNOWN_PROTOCOL(%d)", rai->protocol);
1487             }
1488         }
1489     }
1490 
1491     if (!NIL_P(rai->canonname)) {
1492         VALUE name = rai->canonname;
1493         rb_str_catf(ret, " %s", StringValueCStr(name));
1494     }
1495 
1496     if (!NIL_P(rai->inspectname)) {
1497         VALUE name = rai->inspectname;
1498         rb_str_catf(ret, " (%s)", StringValueCStr(name));
1499     }
1500 
1501     rb_str_buf_cat2(ret, ">");
1502     return ret;
1503 }
1504 
1505 /*
1506  * call-seq:
1507  *   addrinfo.inspect_sockaddr => string
1508  *
1509  * returns a string which shows the sockaddr in _addrinfo_ with human-readable form.
1510  *
1511  *   Addrinfo.tcp("localhost", 80).inspect_sockaddr     #=> "127.0.0.1:80"
1512  *   Addrinfo.tcp("ip6-localhost", 80).inspect_sockaddr #=> "[::1]:80"
1513  *   Addrinfo.unix("/tmp/sock").inspect_sockaddr        #=> "/tmp/sock"
1514  *
1515  */
1516 VALUE
rsock_addrinfo_inspect_sockaddr(VALUE self)1517 rsock_addrinfo_inspect_sockaddr(VALUE self)
1518 {
1519     return inspect_sockaddr(self, rb_str_new("", 0));
1520 }
1521 
1522 /* :nodoc: */
1523 static VALUE
addrinfo_mdump(VALUE self)1524 addrinfo_mdump(VALUE self)
1525 {
1526     rb_addrinfo_t *rai = get_addrinfo(self);
1527     VALUE sockaddr, afamily, pfamily, socktype, protocol, canonname, inspectname;
1528     int afamily_int = ai_get_afamily(rai);
1529     ID id;
1530 
1531     id = rsock_intern_protocol_family(rai->pfamily);
1532     if (id == 0)
1533         rb_raise(rb_eSocket, "unknown protocol family: %d", rai->pfamily);
1534     pfamily = rb_id2str(id);
1535 
1536     if (rai->socktype == 0)
1537         socktype = INT2FIX(0);
1538     else {
1539         id = rsock_intern_socktype(rai->socktype);
1540         if (id == 0)
1541             rb_raise(rb_eSocket, "unknown socktype: %d", rai->socktype);
1542         socktype = rb_id2str(id);
1543     }
1544 
1545     if (rai->protocol == 0)
1546         protocol = INT2FIX(0);
1547     else if (IS_IP_FAMILY(afamily_int)) {
1548         id = rsock_intern_ipproto(rai->protocol);
1549         if (id == 0)
1550             rb_raise(rb_eSocket, "unknown IP protocol: %d", rai->protocol);
1551         protocol = rb_id2str(id);
1552     }
1553     else {
1554         rb_raise(rb_eSocket, "unknown protocol: %d", rai->protocol);
1555     }
1556 
1557     canonname = rai->canonname;
1558 
1559     inspectname = rai->inspectname;
1560 
1561     id = rsock_intern_family(afamily_int);
1562     if (id == 0)
1563         rb_raise(rb_eSocket, "unknown address family: %d", afamily_int);
1564     afamily = rb_id2str(id);
1565 
1566     switch(afamily_int) {
1567 #ifdef HAVE_SYS_UN_H
1568       case AF_UNIX:
1569       {
1570         struct sockaddr_un *su = &rai->addr.un;
1571         char *s, *e;
1572         s = su->sun_path;
1573         e = (char*)su + rai->sockaddr_len;
1574         while (s < e && *(e-1) == '\0')
1575             e--;
1576         sockaddr = rb_str_new(s, e-s);
1577         break;
1578       }
1579 #endif
1580 
1581       default:
1582       {
1583         char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
1584         int error;
1585         error = getnameinfo(&rai->addr.addr, rai->sockaddr_len,
1586                             hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf),
1587                             NI_NUMERICHOST|NI_NUMERICSERV);
1588         if (error) {
1589             rsock_raise_socket_error("getnameinfo", error);
1590         }
1591         sockaddr = rb_assoc_new(rb_str_new_cstr(hbuf), rb_str_new_cstr(pbuf));
1592         break;
1593       }
1594     }
1595 
1596     return rb_ary_new3(7, afamily, sockaddr, pfamily, socktype, protocol, canonname, inspectname);
1597 }
1598 
1599 /* :nodoc: */
1600 static VALUE
addrinfo_mload(VALUE self,VALUE ary)1601 addrinfo_mload(VALUE self, VALUE ary)
1602 {
1603     VALUE v;
1604     VALUE canonname, inspectname;
1605     int afamily, pfamily, socktype, protocol;
1606     union_sockaddr ss;
1607     socklen_t len;
1608     rb_addrinfo_t *rai;
1609 
1610     if (check_addrinfo(self))
1611         rb_raise(rb_eTypeError, "already initialized socket address");
1612 
1613     ary = rb_convert_type(ary, T_ARRAY, "Array", "to_ary");
1614 
1615     v = rb_ary_entry(ary, 0);
1616     StringValue(v);
1617     if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &afamily) == -1)
1618         rb_raise(rb_eTypeError, "unexpected address family");
1619 
1620     v = rb_ary_entry(ary, 2);
1621     StringValue(v);
1622     if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &pfamily) == -1)
1623         rb_raise(rb_eTypeError, "unexpected protocol family");
1624 
1625     v = rb_ary_entry(ary, 3);
1626     if (v == INT2FIX(0))
1627         socktype = 0;
1628     else {
1629         StringValue(v);
1630         if (rsock_socktype_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &socktype) == -1)
1631             rb_raise(rb_eTypeError, "unexpected socktype");
1632     }
1633 
1634     v = rb_ary_entry(ary, 4);
1635     if (v == INT2FIX(0))
1636         protocol = 0;
1637     else {
1638         StringValue(v);
1639         if (IS_IP_FAMILY(afamily)) {
1640             if (rsock_ipproto_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &protocol) == -1)
1641                 rb_raise(rb_eTypeError, "unexpected protocol");
1642         }
1643         else {
1644             rb_raise(rb_eTypeError, "unexpected protocol");
1645         }
1646     }
1647 
1648     v = rb_ary_entry(ary, 5);
1649     if (NIL_P(v))
1650         canonname = Qnil;
1651     else {
1652         StringValue(v);
1653         canonname = v;
1654     }
1655 
1656     v = rb_ary_entry(ary, 6);
1657     if (NIL_P(v))
1658         inspectname = Qnil;
1659     else {
1660         StringValue(v);
1661         inspectname = v;
1662     }
1663 
1664     v = rb_ary_entry(ary, 1);
1665     switch(afamily) {
1666 #ifdef HAVE_SYS_UN_H
1667       case AF_UNIX:
1668       {
1669         struct sockaddr_un uaddr;
1670         INIT_SOCKADDR_UN(&uaddr, sizeof(struct sockaddr_un));
1671 
1672         StringValue(v);
1673         if (sizeof(uaddr.sun_path) < (size_t)RSTRING_LEN(v))
1674             rb_raise(rb_eSocket,
1675                 "too long AF_UNIX path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
1676                 (size_t)RSTRING_LEN(v), sizeof(uaddr.sun_path));
1677         memcpy(uaddr.sun_path, RSTRING_PTR(v), RSTRING_LEN(v));
1678         len = (socklen_t)sizeof(uaddr);
1679         memcpy(&ss, &uaddr, len);
1680         break;
1681       }
1682 #endif
1683 
1684       default:
1685       {
1686         VALUE pair = rb_convert_type(v, T_ARRAY, "Array", "to_ary");
1687         struct rb_addrinfo *res;
1688         int flags = AI_NUMERICHOST;
1689 #ifdef AI_NUMERICSERV
1690         flags |= AI_NUMERICSERV;
1691 #endif
1692         res = call_getaddrinfo(rb_ary_entry(pair, 0), rb_ary_entry(pair, 1),
1693                                INT2NUM(pfamily), INT2NUM(socktype), INT2NUM(protocol),
1694                                INT2NUM(flags), 1);
1695 
1696         len = res->ai->ai_addrlen;
1697         memcpy(&ss, res->ai->ai_addr, res->ai->ai_addrlen);
1698         rb_freeaddrinfo(res);
1699         break;
1700       }
1701     }
1702 
1703     DATA_PTR(self) = rai = alloc_addrinfo();
1704     init_addrinfo(rai, &ss.addr, len,
1705                   pfamily, socktype, protocol,
1706                   canonname, inspectname);
1707     return self;
1708 }
1709 
1710 /*
1711  * call-seq:
1712  *   addrinfo.afamily => integer
1713  *
1714  * returns the address family as an integer.
1715  *
1716  *   Addrinfo.tcp("localhost", 80).afamily == Socket::AF_INET #=> true
1717  *
1718  */
1719 static VALUE
addrinfo_afamily(VALUE self)1720 addrinfo_afamily(VALUE self)
1721 {
1722     rb_addrinfo_t *rai = get_addrinfo(self);
1723     return INT2NUM(ai_get_afamily(rai));
1724 }
1725 
1726 /*
1727  * call-seq:
1728  *   addrinfo.pfamily => integer
1729  *
1730  * returns the protocol family as an integer.
1731  *
1732  *   Addrinfo.tcp("localhost", 80).pfamily == Socket::PF_INET #=> true
1733  *
1734  */
1735 static VALUE
addrinfo_pfamily(VALUE self)1736 addrinfo_pfamily(VALUE self)
1737 {
1738     rb_addrinfo_t *rai = get_addrinfo(self);
1739     return INT2NUM(rai->pfamily);
1740 }
1741 
1742 /*
1743  * call-seq:
1744  *   addrinfo.socktype => integer
1745  *
1746  * returns the socket type as an integer.
1747  *
1748  *   Addrinfo.tcp("localhost", 80).socktype == Socket::SOCK_STREAM #=> true
1749  *
1750  */
1751 static VALUE
addrinfo_socktype(VALUE self)1752 addrinfo_socktype(VALUE self)
1753 {
1754     rb_addrinfo_t *rai = get_addrinfo(self);
1755     return INT2NUM(rai->socktype);
1756 }
1757 
1758 /*
1759  * call-seq:
1760  *   addrinfo.protocol => integer
1761  *
1762  * returns the socket type as an integer.
1763  *
1764  *   Addrinfo.tcp("localhost", 80).protocol == Socket::IPPROTO_TCP #=> true
1765  *
1766  */
1767 static VALUE
addrinfo_protocol(VALUE self)1768 addrinfo_protocol(VALUE self)
1769 {
1770     rb_addrinfo_t *rai = get_addrinfo(self);
1771     return INT2NUM(rai->protocol);
1772 }
1773 
1774 /*
1775  * call-seq:
1776  *   addrinfo.to_sockaddr => string
1777  *   addrinfo.to_s => string
1778  *
1779  * returns the socket address as packed struct sockaddr string.
1780  *
1781  *   Addrinfo.tcp("localhost", 80).to_sockaddr
1782  *   #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1783  *
1784  */
1785 static VALUE
addrinfo_to_sockaddr(VALUE self)1786 addrinfo_to_sockaddr(VALUE self)
1787 {
1788     rb_addrinfo_t *rai = get_addrinfo(self);
1789     VALUE ret;
1790     ret = rb_str_new((char*)&rai->addr, rai->sockaddr_len);
1791     OBJ_INFECT(ret, self);
1792     return ret;
1793 }
1794 
1795 /*
1796  * call-seq:
1797  *   addrinfo.canonname => string or nil
1798  *
1799  * returns the canonical name as an string.
1800  *
1801  * nil is returned if no canonical name.
1802  *
1803  * The canonical name is set by Addrinfo.getaddrinfo when AI_CANONNAME is specified.
1804  *
1805  *   list = Addrinfo.getaddrinfo("www.ruby-lang.org", 80, :INET, :STREAM, nil, Socket::AI_CANONNAME)
1806  *   p list[0] #=> #<Addrinfo: 221.186.184.68:80 TCP carbon.ruby-lang.org (www.ruby-lang.org)>
1807  *   p list[0].canonname #=> "carbon.ruby-lang.org"
1808  *
1809  */
1810 static VALUE
addrinfo_canonname(VALUE self)1811 addrinfo_canonname(VALUE self)
1812 {
1813     rb_addrinfo_t *rai = get_addrinfo(self);
1814     return rai->canonname;
1815 }
1816 
1817 /*
1818  * call-seq:
1819  *   addrinfo.ip? => true or false
1820  *
1821  * returns true if addrinfo is internet (IPv4/IPv6) address.
1822  * returns false otherwise.
1823  *
1824  *   Addrinfo.tcp("127.0.0.1", 80).ip? #=> true
1825  *   Addrinfo.tcp("::1", 80).ip?       #=> true
1826  *   Addrinfo.unix("/tmp/sock").ip?    #=> false
1827  *
1828  */
1829 static VALUE
addrinfo_ip_p(VALUE self)1830 addrinfo_ip_p(VALUE self)
1831 {
1832     rb_addrinfo_t *rai = get_addrinfo(self);
1833     int family = ai_get_afamily(rai);
1834     return IS_IP_FAMILY(family) ? Qtrue : Qfalse;
1835 }
1836 
1837 /*
1838  * call-seq:
1839  *   addrinfo.ipv4? => true or false
1840  *
1841  * returns true if addrinfo is IPv4 address.
1842  * returns false otherwise.
1843  *
1844  *   Addrinfo.tcp("127.0.0.1", 80).ipv4? #=> true
1845  *   Addrinfo.tcp("::1", 80).ipv4?       #=> false
1846  *   Addrinfo.unix("/tmp/sock").ipv4?    #=> false
1847  *
1848  */
1849 static VALUE
addrinfo_ipv4_p(VALUE self)1850 addrinfo_ipv4_p(VALUE self)
1851 {
1852     rb_addrinfo_t *rai = get_addrinfo(self);
1853     return ai_get_afamily(rai) == AF_INET ? Qtrue : Qfalse;
1854 }
1855 
1856 /*
1857  * call-seq:
1858  *   addrinfo.ipv6? => true or false
1859  *
1860  * returns true if addrinfo is IPv6 address.
1861  * returns false otherwise.
1862  *
1863  *   Addrinfo.tcp("127.0.0.1", 80).ipv6? #=> false
1864  *   Addrinfo.tcp("::1", 80).ipv6?       #=> true
1865  *   Addrinfo.unix("/tmp/sock").ipv6?    #=> false
1866  *
1867  */
1868 static VALUE
addrinfo_ipv6_p(VALUE self)1869 addrinfo_ipv6_p(VALUE self)
1870 {
1871 #ifdef AF_INET6
1872     rb_addrinfo_t *rai = get_addrinfo(self);
1873     return ai_get_afamily(rai) == AF_INET6 ? Qtrue : Qfalse;
1874 #else
1875     return Qfalse;
1876 #endif
1877 }
1878 
1879 /*
1880  * call-seq:
1881  *   addrinfo.unix? => true or false
1882  *
1883  * returns true if addrinfo is UNIX address.
1884  * returns false otherwise.
1885  *
1886  *   Addrinfo.tcp("127.0.0.1", 80).unix? #=> false
1887  *   Addrinfo.tcp("::1", 80).unix?       #=> false
1888  *   Addrinfo.unix("/tmp/sock").unix?    #=> true
1889  *
1890  */
1891 static VALUE
addrinfo_unix_p(VALUE self)1892 addrinfo_unix_p(VALUE self)
1893 {
1894     rb_addrinfo_t *rai = get_addrinfo(self);
1895 #ifdef AF_UNIX
1896     return ai_get_afamily(rai) == AF_UNIX ? Qtrue : Qfalse;
1897 #else
1898     return Qfalse;
1899 #endif
1900 }
1901 
1902 /*
1903  * call-seq:
1904  *   addrinfo.getnameinfo        => [nodename, service]
1905  *   addrinfo.getnameinfo(flags) => [nodename, service]
1906  *
1907  * returns nodename and service as a pair of strings.
1908  * This converts struct sockaddr in addrinfo to textual representation.
1909  *
1910  * flags should be bitwise OR of Socket::NI_??? constants.
1911  *
1912  *   Addrinfo.tcp("127.0.0.1", 80).getnameinfo #=> ["localhost", "www"]
1913  *
1914  *   Addrinfo.tcp("127.0.0.1", 80).getnameinfo(Socket::NI_NUMERICSERV)
1915  *   #=> ["localhost", "80"]
1916  */
1917 static VALUE
addrinfo_getnameinfo(int argc,VALUE * argv,VALUE self)1918 addrinfo_getnameinfo(int argc, VALUE *argv, VALUE self)
1919 {
1920     rb_addrinfo_t *rai = get_addrinfo(self);
1921     VALUE vflags;
1922     char hbuf[1024], pbuf[1024];
1923     int flags, error;
1924 
1925     rb_scan_args(argc, argv, "01", &vflags);
1926 
1927     flags = NIL_P(vflags) ? 0 : NUM2INT(vflags);
1928 
1929     if (rai->socktype == SOCK_DGRAM)
1930         flags |= NI_DGRAM;
1931 
1932     error = getnameinfo(&rai->addr.addr, rai->sockaddr_len,
1933                         hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf),
1934                         flags);
1935     if (error) {
1936         rsock_raise_socket_error("getnameinfo", error);
1937     }
1938 
1939     return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
1940 }
1941 
1942 /*
1943  * call-seq:
1944  *   addrinfo.ip_unpack => [addr, port]
1945  *
1946  * Returns the IP address and port number as 2-element array.
1947  *
1948  *   Addrinfo.tcp("127.0.0.1", 80).ip_unpack    #=> ["127.0.0.1", 80]
1949  *   Addrinfo.tcp("::1", 80).ip_unpack          #=> ["::1", 80]
1950  */
1951 static VALUE
addrinfo_ip_unpack(VALUE self)1952 addrinfo_ip_unpack(VALUE self)
1953 {
1954     rb_addrinfo_t *rai = get_addrinfo(self);
1955     int family = ai_get_afamily(rai);
1956     VALUE vflags;
1957     VALUE ret, portstr;
1958 
1959     if (!IS_IP_FAMILY(family))
1960 	rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
1961 
1962     vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV);
1963     ret = addrinfo_getnameinfo(1, &vflags, self);
1964     portstr = rb_ary_entry(ret, 1);
1965     rb_ary_store(ret, 1, INT2NUM(atoi(StringValueCStr(portstr))));
1966     return ret;
1967 }
1968 
1969 /*
1970  * call-seq:
1971  *   addrinfo.ip_address => string
1972  *
1973  * Returns the IP address as a string.
1974  *
1975  *   Addrinfo.tcp("127.0.0.1", 80).ip_address    #=> "127.0.0.1"
1976  *   Addrinfo.tcp("::1", 80).ip_address          #=> "::1"
1977  */
1978 static VALUE
addrinfo_ip_address(VALUE self)1979 addrinfo_ip_address(VALUE self)
1980 {
1981     rb_addrinfo_t *rai = get_addrinfo(self);
1982     int family = ai_get_afamily(rai);
1983     VALUE vflags;
1984     VALUE ret;
1985 
1986     if (!IS_IP_FAMILY(family))
1987 	rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
1988 
1989     vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV);
1990     ret = addrinfo_getnameinfo(1, &vflags, self);
1991     return rb_ary_entry(ret, 0);
1992 }
1993 
1994 /*
1995  * call-seq:
1996  *   addrinfo.ip_port => port
1997  *
1998  * Returns the port number as an integer.
1999  *
2000  *   Addrinfo.tcp("127.0.0.1", 80).ip_port    #=> 80
2001  *   Addrinfo.tcp("::1", 80).ip_port          #=> 80
2002  */
2003 static VALUE
addrinfo_ip_port(VALUE self)2004 addrinfo_ip_port(VALUE self)
2005 {
2006     rb_addrinfo_t *rai = get_addrinfo(self);
2007     int family = ai_get_afamily(rai);
2008     int port;
2009 
2010     if (!IS_IP_FAMILY(family)) {
2011       bad_family:
2012 #ifdef AF_INET6
2013 	rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
2014 #else
2015 	rb_raise(rb_eSocket, "need IPv4 address");
2016 #endif
2017     }
2018 
2019     switch (family) {
2020       case AF_INET:
2021         if (rai->sockaddr_len != sizeof(struct sockaddr_in))
2022             rb_raise(rb_eSocket, "unexpected sockaddr size for IPv4");
2023         port = ntohs(rai->addr.in.sin_port);
2024         break;
2025 
2026 #ifdef AF_INET6
2027       case AF_INET6:
2028         if (rai->sockaddr_len != sizeof(struct sockaddr_in6))
2029             rb_raise(rb_eSocket, "unexpected sockaddr size for IPv6");
2030         port = ntohs(rai->addr.in6.sin6_port);
2031         break;
2032 #endif
2033 
2034       default:
2035 	goto bad_family;
2036     }
2037 
2038     return INT2NUM(port);
2039 }
2040 
2041 static int
extract_in_addr(VALUE self,uint32_t * addrp)2042 extract_in_addr(VALUE self, uint32_t *addrp)
2043 {
2044     rb_addrinfo_t *rai = get_addrinfo(self);
2045     int family = ai_get_afamily(rai);
2046     if (family != AF_INET) return 0;
2047     *addrp = ntohl(rai->addr.in.sin_addr.s_addr);
2048     return 1;
2049 }
2050 
2051 /*
2052  * Returns true for IPv4 private address (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).
2053  * It returns false otherwise.
2054  */
2055 static VALUE
addrinfo_ipv4_private_p(VALUE self)2056 addrinfo_ipv4_private_p(VALUE self)
2057 {
2058     uint32_t a;
2059     if (!extract_in_addr(self, &a)) return Qfalse;
2060     if ((a & 0xff000000) == 0x0a000000 || /* 10.0.0.0/8 */
2061         (a & 0xfff00000) == 0xac100000 || /* 172.16.0.0/12 */
2062         (a & 0xffff0000) == 0xc0a80000)   /* 192.168.0.0/16 */
2063         return Qtrue;
2064     return Qfalse;
2065 }
2066 
2067 /*
2068  * Returns true for IPv4 loopback address (127.0.0.0/8).
2069  * It returns false otherwise.
2070  */
2071 static VALUE
addrinfo_ipv4_loopback_p(VALUE self)2072 addrinfo_ipv4_loopback_p(VALUE self)
2073 {
2074     uint32_t a;
2075     if (!extract_in_addr(self, &a)) return Qfalse;
2076     if ((a & 0xff000000) == 0x7f000000) /* 127.0.0.0/8 */
2077         return Qtrue;
2078     return Qfalse;
2079 }
2080 
2081 /*
2082  * Returns true for IPv4 multicast address (224.0.0.0/4).
2083  * It returns false otherwise.
2084  */
2085 static VALUE
addrinfo_ipv4_multicast_p(VALUE self)2086 addrinfo_ipv4_multicast_p(VALUE self)
2087 {
2088     uint32_t a;
2089     if (!extract_in_addr(self, &a)) return Qfalse;
2090     if ((a & 0xf0000000) == 0xe0000000) /* 224.0.0.0/4 */
2091         return Qtrue;
2092     return Qfalse;
2093 }
2094 
2095 #ifdef INET6
2096 
2097 static struct in6_addr *
extract_in6_addr(VALUE self)2098 extract_in6_addr(VALUE self)
2099 {
2100     rb_addrinfo_t *rai = get_addrinfo(self);
2101     int family = ai_get_afamily(rai);
2102     if (family != AF_INET6) return NULL;
2103     return &rai->addr.in6.sin6_addr;
2104 }
2105 
2106 /*
2107  * Returns true for IPv6 unspecified address (::).
2108  * It returns false otherwise.
2109  */
2110 static VALUE
addrinfo_ipv6_unspecified_p(VALUE self)2111 addrinfo_ipv6_unspecified_p(VALUE self)
2112 {
2113     struct in6_addr *addr = extract_in6_addr(self);
2114     if (addr && IN6_IS_ADDR_UNSPECIFIED(addr)) return Qtrue;
2115     return Qfalse;
2116 }
2117 
2118 /*
2119  * Returns true for IPv6 loopback address (::1).
2120  * It returns false otherwise.
2121  */
2122 static VALUE
addrinfo_ipv6_loopback_p(VALUE self)2123 addrinfo_ipv6_loopback_p(VALUE self)
2124 {
2125     struct in6_addr *addr = extract_in6_addr(self);
2126     if (addr && IN6_IS_ADDR_LOOPBACK(addr)) return Qtrue;
2127     return Qfalse;
2128 }
2129 
2130 /*
2131  * Returns true for IPv6 multicast address (ff00::/8).
2132  * It returns false otherwise.
2133  */
2134 static VALUE
addrinfo_ipv6_multicast_p(VALUE self)2135 addrinfo_ipv6_multicast_p(VALUE self)
2136 {
2137     struct in6_addr *addr = extract_in6_addr(self);
2138     if (addr && IN6_IS_ADDR_MULTICAST(addr)) return Qtrue;
2139     return Qfalse;
2140 }
2141 
2142 /*
2143  * Returns true for IPv6 link local address (ff80::/10).
2144  * It returns false otherwise.
2145  */
2146 static VALUE
addrinfo_ipv6_linklocal_p(VALUE self)2147 addrinfo_ipv6_linklocal_p(VALUE self)
2148 {
2149     struct in6_addr *addr = extract_in6_addr(self);
2150     if (addr && IN6_IS_ADDR_LINKLOCAL(addr)) return Qtrue;
2151     return Qfalse;
2152 }
2153 
2154 /*
2155  * Returns true for IPv6 site local address (ffc0::/10).
2156  * It returns false otherwise.
2157  */
2158 static VALUE
addrinfo_ipv6_sitelocal_p(VALUE self)2159 addrinfo_ipv6_sitelocal_p(VALUE self)
2160 {
2161     struct in6_addr *addr = extract_in6_addr(self);
2162     if (addr && IN6_IS_ADDR_SITELOCAL(addr)) return Qtrue;
2163     return Qfalse;
2164 }
2165 
2166 /*
2167  * Returns true for IPv6 unique local address (fc00::/7, RFC4193).
2168  * It returns false otherwise.
2169  */
2170 static VALUE
addrinfo_ipv6_unique_local_p(VALUE self)2171 addrinfo_ipv6_unique_local_p(VALUE self)
2172 {
2173     struct in6_addr *addr = extract_in6_addr(self);
2174     if (addr && IN6_IS_ADDR_UNIQUE_LOCAL(addr)) return Qtrue;
2175     return Qfalse;
2176 }
2177 
2178 /*
2179  * Returns true for IPv4-mapped IPv6 address (::ffff:0:0/80).
2180  * It returns false otherwise.
2181  */
2182 static VALUE
addrinfo_ipv6_v4mapped_p(VALUE self)2183 addrinfo_ipv6_v4mapped_p(VALUE self)
2184 {
2185     struct in6_addr *addr = extract_in6_addr(self);
2186     if (addr && IN6_IS_ADDR_V4MAPPED(addr)) return Qtrue;
2187     return Qfalse;
2188 }
2189 
2190 /*
2191  * Returns true for IPv4-compatible IPv6 address (::/80).
2192  * It returns false otherwise.
2193  */
2194 static VALUE
addrinfo_ipv6_v4compat_p(VALUE self)2195 addrinfo_ipv6_v4compat_p(VALUE self)
2196 {
2197     struct in6_addr *addr = extract_in6_addr(self);
2198     if (addr && IN6_IS_ADDR_V4COMPAT(addr)) return Qtrue;
2199     return Qfalse;
2200 }
2201 
2202 /*
2203  * Returns true for IPv6 multicast node-local scope address.
2204  * It returns false otherwise.
2205  */
2206 static VALUE
addrinfo_ipv6_mc_nodelocal_p(VALUE self)2207 addrinfo_ipv6_mc_nodelocal_p(VALUE self)
2208 {
2209     struct in6_addr *addr = extract_in6_addr(self);
2210     if (addr && IN6_IS_ADDR_MC_NODELOCAL(addr)) return Qtrue;
2211     return Qfalse;
2212 }
2213 
2214 /*
2215  * Returns true for IPv6 multicast link-local scope address.
2216  * It returns false otherwise.
2217  */
2218 static VALUE
addrinfo_ipv6_mc_linklocal_p(VALUE self)2219 addrinfo_ipv6_mc_linklocal_p(VALUE self)
2220 {
2221     struct in6_addr *addr = extract_in6_addr(self);
2222     if (addr && IN6_IS_ADDR_MC_LINKLOCAL(addr)) return Qtrue;
2223     return Qfalse;
2224 }
2225 
2226 /*
2227  * Returns true for IPv6 multicast site-local scope address.
2228  * It returns false otherwise.
2229  */
2230 static VALUE
addrinfo_ipv6_mc_sitelocal_p(VALUE self)2231 addrinfo_ipv6_mc_sitelocal_p(VALUE self)
2232 {
2233     struct in6_addr *addr = extract_in6_addr(self);
2234     if (addr && IN6_IS_ADDR_MC_SITELOCAL(addr)) return Qtrue;
2235     return Qfalse;
2236 }
2237 
2238 /*
2239  * Returns true for IPv6 multicast organization-local scope address.
2240  * It returns false otherwise.
2241  */
2242 static VALUE
addrinfo_ipv6_mc_orglocal_p(VALUE self)2243 addrinfo_ipv6_mc_orglocal_p(VALUE self)
2244 {
2245     struct in6_addr *addr = extract_in6_addr(self);
2246     if (addr && IN6_IS_ADDR_MC_ORGLOCAL(addr)) return Qtrue;
2247     return Qfalse;
2248 }
2249 
2250 /*
2251  * Returns true for IPv6 multicast global scope address.
2252  * It returns false otherwise.
2253  */
2254 static VALUE
addrinfo_ipv6_mc_global_p(VALUE self)2255 addrinfo_ipv6_mc_global_p(VALUE self)
2256 {
2257     struct in6_addr *addr = extract_in6_addr(self);
2258     if (addr && IN6_IS_ADDR_MC_GLOBAL(addr)) return Qtrue;
2259     return Qfalse;
2260 }
2261 
2262 /*
2263  * Returns IPv4 address of IPv4 mapped/compatible IPv6 address.
2264  * It returns nil if +self+ is not IPv4 mapped/compatible IPv6 address.
2265  *
2266  *   Addrinfo.ip("::192.0.2.3").ipv6_to_ipv4      #=> #<Addrinfo: 192.0.2.3>
2267  *   Addrinfo.ip("::ffff:192.0.2.3").ipv6_to_ipv4 #=> #<Addrinfo: 192.0.2.3>
2268  *   Addrinfo.ip("::1").ipv6_to_ipv4              #=> nil
2269  *   Addrinfo.ip("192.0.2.3").ipv6_to_ipv4        #=> nil
2270  *   Addrinfo.unix("/tmp/sock").ipv6_to_ipv4      #=> nil
2271  */
2272 static VALUE
addrinfo_ipv6_to_ipv4(VALUE self)2273 addrinfo_ipv6_to_ipv4(VALUE self)
2274 {
2275     rb_addrinfo_t *rai = get_addrinfo(self);
2276     struct in6_addr *addr;
2277     int family = ai_get_afamily(rai);
2278     if (family != AF_INET6) return Qnil;
2279     addr = &rai->addr.in6.sin6_addr;
2280     if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) {
2281         struct sockaddr_in sin4;
2282         INIT_SOCKADDR_IN(&sin4, sizeof(sin4));
2283         memcpy(&sin4.sin_addr, (char*)addr + sizeof(*addr) - sizeof(sin4.sin_addr), sizeof(sin4.sin_addr));
2284         return rsock_addrinfo_new((struct sockaddr *)&sin4, (socklen_t)sizeof(sin4),
2285                                   PF_INET, rai->socktype, rai->protocol,
2286                                   rai->canonname, rai->inspectname);
2287     }
2288     else {
2289         return Qnil;
2290     }
2291 }
2292 
2293 #endif
2294 
2295 #ifdef HAVE_SYS_UN_H
2296 /*
2297  * call-seq:
2298  *   addrinfo.unix_path => path
2299  *
2300  * Returns the socket path as a string.
2301  *
2302  *   Addrinfo.unix("/tmp/sock").unix_path       #=> "/tmp/sock"
2303  */
2304 static VALUE
addrinfo_unix_path(VALUE self)2305 addrinfo_unix_path(VALUE self)
2306 {
2307     rb_addrinfo_t *rai = get_addrinfo(self);
2308     int family = ai_get_afamily(rai);
2309     struct sockaddr_un *addr;
2310     char *s, *e;
2311 
2312     if (family != AF_UNIX)
2313 	rb_raise(rb_eSocket, "need AF_UNIX address");
2314 
2315     addr = &rai->addr.un;
2316 
2317     s = addr->sun_path;
2318     e = (char*)addr + rai->sockaddr_len;
2319     if (e < s)
2320         rb_raise(rb_eSocket, "too short AF_UNIX address: %"PRIuSIZE" bytes given for minimum %"PRIuSIZE" bytes.",
2321             (size_t)rai->sockaddr_len, (size_t)(s - (char *)addr));
2322     if (addr->sun_path + sizeof(addr->sun_path) < e)
2323         rb_raise(rb_eSocket,
2324             "too long AF_UNIX path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
2325             (size_t)(e - addr->sun_path), sizeof(addr->sun_path));
2326     while (s < e && *(e-1) == '\0')
2327         e--;
2328     return rb_str_new(s, e-s);
2329 }
2330 #endif
2331 
2332 /*
2333  * call-seq:
2334  *   Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags) => [addrinfo, ...]
2335  *   Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol)        => [addrinfo, ...]
2336  *   Addrinfo.getaddrinfo(nodename, service, family, socktype)                  => [addrinfo, ...]
2337  *   Addrinfo.getaddrinfo(nodename, service, family)                            => [addrinfo, ...]
2338  *   Addrinfo.getaddrinfo(nodename, service)                                    => [addrinfo, ...]
2339  *
2340  * returns a list of addrinfo objects as an array.
2341  *
2342  * This method converts nodename (hostname) and service (port) to addrinfo.
2343  * Since the conversion is not unique, the result is a list of addrinfo objects.
2344  *
2345  * nodename or service can be nil if no conversion intended.
2346  *
2347  * family, socktype and protocol are hint for preferred protocol.
2348  * If the result will be used for a socket with SOCK_STREAM,
2349  * SOCK_STREAM should be specified as socktype.
2350  * If so, Addrinfo.getaddrinfo returns addrinfo list appropriate for SOCK_STREAM.
2351  * If they are omitted or nil is given, the result is not restricted.
2352  *
2353  * Similarly, PF_INET6 as family restricts for IPv6.
2354  *
2355  * flags should be bitwise OR of Socket::AI_??? constants such as follows.
2356  * Note that the exact list of the constants depends on OS.
2357  *
2358  *   AI_PASSIVE      Get address to use with bind()
2359  *   AI_CANONNAME    Fill in the canonical name
2360  *   AI_NUMERICHOST  Prevent host name resolution
2361  *   AI_NUMERICSERV  Prevent service name resolution
2362  *   AI_V4MAPPED     Accept IPv4-mapped IPv6 addresses
2363  *   AI_ALL          Allow all addresses
2364  *   AI_ADDRCONFIG   Accept only if any address is assigned
2365  *
2366  * Note that socktype should be specified whenever application knows the usage of the address.
2367  * Some platform causes an error when socktype is omitted and servname is specified as an integer
2368  * because some port numbers, 512 for example, are ambiguous without socktype.
2369  *
2370  *   Addrinfo.getaddrinfo("www.kame.net", 80, nil, :STREAM)
2371  *   #=> [#<Addrinfo: 203.178.141.194:80 TCP (www.kame.net)>,
2372  *   #    #<Addrinfo: [2001:200:dff:fff1:216:3eff:feb1:44d7]:80 TCP (www.kame.net)>]
2373  *
2374  */
2375 static VALUE
addrinfo_s_getaddrinfo(int argc,VALUE * argv,VALUE self)2376 addrinfo_s_getaddrinfo(int argc, VALUE *argv, VALUE self)
2377 {
2378     VALUE node, service, family, socktype, protocol, flags;
2379 
2380     rb_scan_args(argc, argv, "24", &node, &service, &family, &socktype, &protocol, &flags);
2381     return addrinfo_list_new(node, service, family, socktype, protocol, flags);
2382 }
2383 
2384 /*
2385  * call-seq:
2386  *   Addrinfo.ip(host) => addrinfo
2387  *
2388  * returns an addrinfo object for IP address.
2389  *
2390  * The port, socktype, protocol of the result is filled by zero.
2391  * So, it is not appropriate to create a socket.
2392  *
2393  *   Addrinfo.ip("localhost") #=> #<Addrinfo: 127.0.0.1 (localhost)>
2394  */
2395 static VALUE
addrinfo_s_ip(VALUE self,VALUE host)2396 addrinfo_s_ip(VALUE self, VALUE host)
2397 {
2398     VALUE ret;
2399     rb_addrinfo_t *rai;
2400     ret = addrinfo_firstonly_new(host, Qnil,
2401             INT2NUM(PF_UNSPEC), INT2FIX(0), INT2FIX(0), INT2FIX(0));
2402     rai = get_addrinfo(ret);
2403     rai->socktype = 0;
2404     rai->protocol = 0;
2405     return ret;
2406 }
2407 
2408 /*
2409  * call-seq:
2410  *   Addrinfo.tcp(host, port) => addrinfo
2411  *
2412  * returns an addrinfo object for TCP address.
2413  *
2414  *   Addrinfo.tcp("localhost", "smtp") #=> #<Addrinfo: 127.0.0.1:25 TCP (localhost:smtp)>
2415  */
2416 static VALUE
addrinfo_s_tcp(VALUE self,VALUE host,VALUE port)2417 addrinfo_s_tcp(VALUE self, VALUE host, VALUE port)
2418 {
2419     return addrinfo_firstonly_new(host, port,
2420             INT2NUM(PF_UNSPEC), INT2NUM(SOCK_STREAM), INT2NUM(IPPROTO_TCP), INT2FIX(0));
2421 }
2422 
2423 /*
2424  * call-seq:
2425  *   Addrinfo.udp(host, port) => addrinfo
2426  *
2427  * returns an addrinfo object for UDP address.
2428  *
2429  *   Addrinfo.udp("localhost", "daytime") #=> #<Addrinfo: 127.0.0.1:13 UDP (localhost:daytime)>
2430  */
2431 static VALUE
addrinfo_s_udp(VALUE self,VALUE host,VALUE port)2432 addrinfo_s_udp(VALUE self, VALUE host, VALUE port)
2433 {
2434     return addrinfo_firstonly_new(host, port,
2435             INT2NUM(PF_UNSPEC), INT2NUM(SOCK_DGRAM), INT2NUM(IPPROTO_UDP), INT2FIX(0));
2436 }
2437 
2438 #ifdef HAVE_SYS_UN_H
2439 
2440 /*
2441  * call-seq:
2442  *   Addrinfo.unix(path [, socktype]) => addrinfo
2443  *
2444  * returns an addrinfo object for UNIX socket address.
2445  *
2446  * _socktype_ specifies the socket type.
2447  * If it is omitted, :STREAM is used.
2448  *
2449  *   Addrinfo.unix("/tmp/sock")         #=> #<Addrinfo: /tmp/sock SOCK_STREAM>
2450  *   Addrinfo.unix("/tmp/sock", :DGRAM) #=> #<Addrinfo: /tmp/sock SOCK_DGRAM>
2451  */
2452 static VALUE
addrinfo_s_unix(int argc,VALUE * argv,VALUE self)2453 addrinfo_s_unix(int argc, VALUE *argv, VALUE self)
2454 {
2455     VALUE path, vsocktype, addr;
2456     int socktype;
2457     rb_addrinfo_t *rai;
2458 
2459     rb_scan_args(argc, argv, "11", &path, &vsocktype);
2460 
2461     if (NIL_P(vsocktype))
2462         socktype = SOCK_STREAM;
2463     else
2464         socktype = rsock_socktype_arg(vsocktype);
2465 
2466     addr = addrinfo_s_allocate(rb_cAddrinfo);
2467     DATA_PTR(addr) = rai = alloc_addrinfo();
2468     init_unix_addrinfo(rai, path, socktype);
2469     OBJ_INFECT(addr, path);
2470     return addr;
2471 }
2472 
2473 #endif
2474 
2475 VALUE
rsock_sockaddr_string_value(volatile VALUE * v)2476 rsock_sockaddr_string_value(volatile VALUE *v)
2477 {
2478     VALUE val = *v;
2479     if (IS_ADDRINFO(val)) {
2480         *v = addrinfo_to_sockaddr(val);
2481     }
2482     StringValue(*v);
2483     return *v;
2484 }
2485 
2486 VALUE
rsock_sockaddr_string_value_with_addrinfo(volatile VALUE * v,VALUE * rai_ret)2487 rsock_sockaddr_string_value_with_addrinfo(volatile VALUE *v, VALUE *rai_ret)
2488 {
2489     VALUE val = *v;
2490     *rai_ret = Qnil;
2491     if (IS_ADDRINFO(val)) {
2492         *v = addrinfo_to_sockaddr(val);
2493         *rai_ret = val;
2494     }
2495     StringValue(*v);
2496     return *v;
2497 }
2498 
2499 char *
rsock_sockaddr_string_value_ptr(volatile VALUE * v)2500 rsock_sockaddr_string_value_ptr(volatile VALUE *v)
2501 {
2502     rsock_sockaddr_string_value(v);
2503     return RSTRING_PTR(*v);
2504 }
2505 
2506 VALUE
rb_check_sockaddr_string_type(VALUE val)2507 rb_check_sockaddr_string_type(VALUE val)
2508 {
2509     if (IS_ADDRINFO(val))
2510         return addrinfo_to_sockaddr(val);
2511     return rb_check_string_type(val);
2512 }
2513 
2514 VALUE
rsock_fd_socket_addrinfo(int fd,struct sockaddr * addr,socklen_t len)2515 rsock_fd_socket_addrinfo(int fd, struct sockaddr *addr, socklen_t len)
2516 {
2517     int family;
2518     int socktype;
2519     int ret;
2520     socklen_t optlen = (socklen_t)sizeof(socktype);
2521 
2522     /* assumes protocol family and address family are identical */
2523     family = get_afamily(addr, len);
2524 
2525     ret = getsockopt(fd, SOL_SOCKET, SO_TYPE, (void*)&socktype, &optlen);
2526     if (ret == -1) {
2527         rb_sys_fail("getsockopt(SO_TYPE)");
2528     }
2529 
2530     return rsock_addrinfo_new(addr, len, family, socktype, 0, Qnil, Qnil);
2531 }
2532 
2533 VALUE
rsock_io_socket_addrinfo(VALUE io,struct sockaddr * addr,socklen_t len)2534 rsock_io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len)
2535 {
2536     rb_io_t *fptr;
2537 
2538     switch (TYPE(io)) {
2539       case T_FIXNUM:
2540         return rsock_fd_socket_addrinfo(FIX2INT(io), addr, len);
2541 
2542       case T_BIGNUM:
2543         return rsock_fd_socket_addrinfo(NUM2INT(io), addr, len);
2544 
2545       case T_FILE:
2546         GetOpenFile(io, fptr);
2547         return rsock_fd_socket_addrinfo(fptr->fd, addr, len);
2548 
2549       default:
2550         rb_raise(rb_eTypeError, "neither IO nor file descriptor");
2551     }
2552 
2553     UNREACHABLE_RETURN(Qnil);
2554 }
2555 
2556 /*
2557  * Addrinfo class
2558  */
2559 void
rsock_init_addrinfo(void)2560 rsock_init_addrinfo(void)
2561 {
2562     /*
2563      * The Addrinfo class maps <tt>struct addrinfo</tt> to ruby.  This
2564      * structure identifies an Internet host and a service.
2565      */
2566     rb_cAddrinfo = rb_define_class("Addrinfo", rb_cData);
2567     rb_define_alloc_func(rb_cAddrinfo, addrinfo_s_allocate);
2568     rb_define_method(rb_cAddrinfo, "initialize", addrinfo_initialize, -1);
2569     rb_define_method(rb_cAddrinfo, "inspect", addrinfo_inspect, 0);
2570     rb_define_method(rb_cAddrinfo, "inspect_sockaddr", rsock_addrinfo_inspect_sockaddr, 0);
2571     rb_define_singleton_method(rb_cAddrinfo, "getaddrinfo", addrinfo_s_getaddrinfo, -1);
2572     rb_define_singleton_method(rb_cAddrinfo, "ip", addrinfo_s_ip, 1);
2573     rb_define_singleton_method(rb_cAddrinfo, "tcp", addrinfo_s_tcp, 2);
2574     rb_define_singleton_method(rb_cAddrinfo, "udp", addrinfo_s_udp, 2);
2575 #ifdef HAVE_SYS_UN_H
2576     rb_define_singleton_method(rb_cAddrinfo, "unix", addrinfo_s_unix, -1);
2577 #endif
2578 
2579     rb_define_method(rb_cAddrinfo, "afamily", addrinfo_afamily, 0);
2580     rb_define_method(rb_cAddrinfo, "pfamily", addrinfo_pfamily, 0);
2581     rb_define_method(rb_cAddrinfo, "socktype", addrinfo_socktype, 0);
2582     rb_define_method(rb_cAddrinfo, "protocol", addrinfo_protocol, 0);
2583     rb_define_method(rb_cAddrinfo, "canonname", addrinfo_canonname, 0);
2584 
2585     rb_define_method(rb_cAddrinfo, "ipv4?", addrinfo_ipv4_p, 0);
2586     rb_define_method(rb_cAddrinfo, "ipv6?", addrinfo_ipv6_p, 0);
2587     rb_define_method(rb_cAddrinfo, "unix?", addrinfo_unix_p, 0);
2588 
2589     rb_define_method(rb_cAddrinfo, "ip?", addrinfo_ip_p, 0);
2590     rb_define_method(rb_cAddrinfo, "ip_unpack", addrinfo_ip_unpack, 0);
2591     rb_define_method(rb_cAddrinfo, "ip_address", addrinfo_ip_address, 0);
2592     rb_define_method(rb_cAddrinfo, "ip_port", addrinfo_ip_port, 0);
2593 
2594     rb_define_method(rb_cAddrinfo, "ipv4_private?", addrinfo_ipv4_private_p, 0);
2595     rb_define_method(rb_cAddrinfo, "ipv4_loopback?", addrinfo_ipv4_loopback_p, 0);
2596     rb_define_method(rb_cAddrinfo, "ipv4_multicast?", addrinfo_ipv4_multicast_p, 0);
2597 
2598 #ifdef INET6
2599     rb_define_method(rb_cAddrinfo, "ipv6_unspecified?", addrinfo_ipv6_unspecified_p, 0);
2600     rb_define_method(rb_cAddrinfo, "ipv6_loopback?", addrinfo_ipv6_loopback_p, 0);
2601     rb_define_method(rb_cAddrinfo, "ipv6_multicast?", addrinfo_ipv6_multicast_p, 0);
2602     rb_define_method(rb_cAddrinfo, "ipv6_linklocal?", addrinfo_ipv6_linklocal_p, 0);
2603     rb_define_method(rb_cAddrinfo, "ipv6_sitelocal?", addrinfo_ipv6_sitelocal_p, 0);
2604     rb_define_method(rb_cAddrinfo, "ipv6_unique_local?", addrinfo_ipv6_unique_local_p, 0);
2605     rb_define_method(rb_cAddrinfo, "ipv6_v4mapped?", addrinfo_ipv6_v4mapped_p, 0);
2606     rb_define_method(rb_cAddrinfo, "ipv6_v4compat?", addrinfo_ipv6_v4compat_p, 0);
2607     rb_define_method(rb_cAddrinfo, "ipv6_mc_nodelocal?", addrinfo_ipv6_mc_nodelocal_p, 0);
2608     rb_define_method(rb_cAddrinfo, "ipv6_mc_linklocal?", addrinfo_ipv6_mc_linklocal_p, 0);
2609     rb_define_method(rb_cAddrinfo, "ipv6_mc_sitelocal?", addrinfo_ipv6_mc_sitelocal_p, 0);
2610     rb_define_method(rb_cAddrinfo, "ipv6_mc_orglocal?", addrinfo_ipv6_mc_orglocal_p, 0);
2611     rb_define_method(rb_cAddrinfo, "ipv6_mc_global?", addrinfo_ipv6_mc_global_p, 0);
2612 
2613     rb_define_method(rb_cAddrinfo, "ipv6_to_ipv4", addrinfo_ipv6_to_ipv4, 0);
2614 #endif
2615 
2616 #ifdef HAVE_SYS_UN_H
2617     rb_define_method(rb_cAddrinfo, "unix_path", addrinfo_unix_path, 0);
2618 #endif
2619 
2620     rb_define_method(rb_cAddrinfo, "to_sockaddr", addrinfo_to_sockaddr, 0);
2621     rb_define_method(rb_cAddrinfo, "to_s", addrinfo_to_sockaddr, 0); /* compatibility for ruby before 1.9.2 */
2622 
2623     rb_define_method(rb_cAddrinfo, "getnameinfo", addrinfo_getnameinfo, -1);
2624 
2625     rb_define_method(rb_cAddrinfo, "marshal_dump", addrinfo_mdump, 0);
2626     rb_define_method(rb_cAddrinfo, "marshal_load", addrinfo_mload, 1);
2627 }
2628