diff options
Diffstat (limited to 'ext/socket')
| -rw-r--r-- | ext/socket/.cvsignore | 2 | ||||
| -rw-r--r-- | ext/socket/.document | 16 | ||||
| -rw-r--r-- | ext/socket/addrinfo.h | 51 | ||||
| -rw-r--r-- | ext/socket/ancdata.c | 1800 | ||||
| -rw-r--r-- | ext/socket/basicsocket.c | 771 | ||||
| -rw-r--r-- | ext/socket/constants.c | 145 | ||||
| -rw-r--r-- | ext/socket/depend | 28 | ||||
| -rw-r--r-- | ext/socket/extconf.rb | 143 | ||||
| -rw-r--r-- | ext/socket/getaddrinfo.c | 98 | ||||
| -rw-r--r-- | ext/socket/getnameinfo.c | 41 | ||||
| -rw-r--r-- | ext/socket/init.c | 575 | ||||
| -rw-r--r-- | ext/socket/ipsocket.c | 308 | ||||
| -rw-r--r-- | ext/socket/lib/socket.rb | 755 | ||||
| -rw-r--r-- | ext/socket/mkconstants.rb | 696 | ||||
| -rw-r--r-- | ext/socket/option.c | 692 | ||||
| -rw-r--r-- | ext/socket/raddrinfo.c | 2211 | ||||
| -rw-r--r-- | ext/socket/rubysocket.h | 306 | ||||
| -rw-r--r-- | ext/socket/socket.c | 4669 | ||||
| -rw-r--r-- | ext/socket/sockport.h | 20 | ||||
| -rw-r--r-- | ext/socket/sockssocket.c | 58 | ||||
| -rw-r--r-- | ext/socket/tcpserver.c | 145 | ||||
| -rw-r--r-- | ext/socket/tcpsocket.c | 69 | ||||
| -rw-r--r-- | ext/socket/udpsocket.c | 264 | ||||
| -rw-r--r-- | ext/socket/unixserver.c | 154 | ||||
| -rw-r--r-- | ext/socket/unixsocket.c | 514 |
25 files changed, 10662 insertions, 3869 deletions
diff --git a/ext/socket/.cvsignore b/ext/socket/.cvsignore index 4088712231..ce98586d91 100644 --- a/ext/socket/.cvsignore +++ b/ext/socket/.cvsignore @@ -1,3 +1,5 @@ Makefile mkmf.log *.def +constants.h +extconf.h diff --git a/ext/socket/.document b/ext/socket/.document new file mode 100644 index 0000000000..636418d086 --- /dev/null +++ b/ext/socket/.document @@ -0,0 +1,16 @@ +init.c +raddrinfo.c +basicsocket.c +ipsocket.c +tcpsocket.c +tcpserver.c +sockssocket.c +udpsocket.c +unixsocket.c +unixserver.c +socket.c +option.c +ancdata.c +constants.c +constdefs.c +lib/socket.rb diff --git a/ext/socket/addrinfo.h b/ext/socket/addrinfo.h index a22615ee00..3a478cf36c 100644 --- a/ext/socket/addrinfo.h +++ b/ext/socket/addrinfo.h @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -29,7 +29,6 @@ #ifndef ADDR_INFO_H #define ADDR_INFO_H -#ifndef HAVE_GETADDRINFO /* special compatibility hack */ #undef EAI_ADDRFAMILY @@ -50,6 +49,7 @@ #undef AI_PASSIVE #undef AI_CANONNAME #undef AI_NUMERICHOST +#undef AI_NUMERICSERV #undef AI_ALL #undef AI_ADDRCONFIG #undef AI_V4MAPPED @@ -61,12 +61,6 @@ #undef NI_NUMERICSERV #undef NI_DGRAM -#define addrinfo addrinfo__compat -#define getaddrinfo getaddrinfo__compat -#define getnameinfo getnameinfo__compat -#define freehostent freehostent__compat -#define freeaddrinfo freeaddrinfo__compat - #ifndef __P # ifdef HAVE_PROTOTYPES # define __P(args) args @@ -102,8 +96,12 @@ #define AI_PASSIVE 0x00000001 /* get address to use bind() */ #define AI_CANONNAME 0x00000002 /* fill ai_canonname */ #define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ +#define AI_NUMERICSERV 0x00000008 /* prevent service name resolution */ /* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) +#ifndef __HAIKU__ +#undef AI_MASK +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST | AI_NUMERICSERV) +#endif #define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ #define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ @@ -129,6 +127,7 @@ #define NI_NUMERICSERV 0x00000008 #define NI_DGRAM 0x00000010 +#ifndef HAVE_TYPE_STRUCT_ADDRINFO struct addrinfo { int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ int ai_family; /* PF_xxx */ @@ -139,6 +138,24 @@ struct addrinfo { struct sockaddr *ai_addr; /* binary address */ struct addrinfo *ai_next; /* next structure in linked list */ }; +#endif + +#ifndef HAVE_GETADDRINFO +#undef getaddrinfo +#define getaddrinfo getaddrinfo__compat +#endif +#ifndef HAVE_GETNAMEINFO +#undef getnameinfo +#define getnameinfo getnameinfo__compat +#endif +#ifndef HAVE_FREEHOSTENT +#undef freehostent +#define freehostent freehostent__compat +#endif +#ifndef HAVE_FREEADDRINFO +#undef freeaddrinfo +#define freeaddrinfo freeaddrinfo__compat +#endif extern int getaddrinfo __P(( const char *hostname, const char *servname, @@ -147,19 +164,22 @@ extern int getaddrinfo __P(( extern int getnameinfo __P(( const struct sockaddr *sa, - size_t salen, + socklen_t salen, char *host, - size_t hostlen, + socklen_t hostlen, char *serv, - size_t servlen, + socklen_t servlen, int flags)); extern void freehostent __P((struct hostent *)); +#ifndef HAVE_PADDRINFO extern void freeaddrinfo __P((struct addrinfo *)); -#if defined __UCLIBC__ +#endif +extern +#ifdef GAI_STRERROR_CONST const #endif -extern char *gai_strerror __P((int)); +char *gai_strerror __P((int)); /* In case there is no definition of offsetof() provided - though any proper Standard C system should have one. */ @@ -169,4 +189,3 @@ Standard C system should have one. */ #endif #endif -#endif diff --git a/ext/socket/ancdata.c b/ext/socket/ancdata.c new file mode 100644 index 0000000000..307e21ecaa --- /dev/null +++ b/ext/socket/ancdata.c @@ -0,0 +1,1800 @@ +#include "rubysocket.h" + +#include <time.h> + +#if defined(HAVE_ST_MSG_CONTROL) +static VALUE rb_cAncillaryData; + +static VALUE +constant_to_sym(int constant, ID (*intern_const)(int)) +{ + ID name = intern_const(constant); + if (name) { + return ID2SYM(name); + } + + return INT2NUM(constant); +} + +static VALUE +ip_cmsg_type_to_sym(int level, int cmsg_type) +{ + switch (level) { + case SOL_SOCKET: + return constant_to_sym(cmsg_type, rsock_intern_scm_optname); + case IPPROTO_IP: + return constant_to_sym(cmsg_type, rsock_intern_ip_optname); +#ifdef IPPROTO_IPV6 + case IPPROTO_IPV6: + return constant_to_sym(cmsg_type, rsock_intern_ipv6_optname); +#endif + case IPPROTO_TCP: + return constant_to_sym(cmsg_type, rsock_intern_tcp_optname); + case IPPROTO_UDP: + return constant_to_sym(cmsg_type, rsock_intern_udp_optname); + default: + return INT2NUM(cmsg_type); + } +} + +/* + * call-seq: + * Socket::AncillaryData.new(family, cmsg_level, cmsg_type, cmsg_data) -> ancillarydata + * + * _family_ should be an integer, a string or a symbol. + * - Socket::AF_INET, "AF_INET", "INET", :AF_INET, :INET + * - Socket::AF_UNIX, "AF_UNIX", "UNIX", :AF_UNIX, :UNIX + * - etc. + * + * _cmsg_level_ should be an integer, a string or a symbol. + * - Socket::SOL_SOCKET, "SOL_SOCKET", "SOCKET", :SOL_SOCKET and :SOCKET + * - Socket::IPPROTO_IP, "IP" and :IP + * - Socket::IPPROTO_IPV6, "IPV6" and :IPV6 + * - Socket::IPPROTO_TCP, "TCP" and :TCP + * - etc. + * + * _cmsg_type_ should be an integer, a string or a symbol. + * If a string/symbol is specified, it is interpreted depend on _cmsg_level_. + * - Socket::SCM_RIGHTS, "SCM_RIGHTS", "RIGHTS", :SCM_RIGHTS, :RIGHTS for SOL_SOCKET + * - Socket::IP_RECVTTL, "RECVTTL" and :RECVTTL for IPPROTO_IP + * - Socket::IPV6_PKTINFO, "PKTINFO" and :PKTINFO for IPPROTO_IPV6 + * - etc. + * + * _cmsg_data_ should be a string. + * + * p Socket::AncillaryData.new(:INET, :TCP, :NODELAY, "") + * #=> #<Socket::AncillaryData: INET TCP NODELAY ""> + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "") + * #=> #<Socket::AncillaryData: INET6 IPV6 PKTINFO ""> + * + */ +static VALUE +ancillary_initialize(VALUE self, VALUE vfamily, VALUE vlevel, VALUE vtype, VALUE data) +{ + int family = rsock_family_arg(vfamily); + int level = rsock_level_arg(family, vlevel); + int type = rsock_cmsg_type_arg(family, level, vtype); + StringValue(data); + rb_ivar_set(self, rb_intern("family"), INT2NUM(family)); + rb_ivar_set(self, rb_intern("level"), INT2NUM(level)); + rb_ivar_set(self, rb_intern("type"), INT2NUM(type)); + rb_ivar_set(self, rb_intern("data"), data); + return self; +} + +static VALUE +ancdata_new(int family, int level, int type, VALUE data) +{ + NEWOBJ(obj, struct RObject); + OBJSETUP(obj, rb_cAncillaryData, T_OBJECT); + StringValue(data); + ancillary_initialize((VALUE)obj, INT2NUM(family), INT2NUM(level), INT2NUM(type), data); + return (VALUE)obj; +} + +static int +ancillary_family(VALUE self) +{ + VALUE v = rb_attr_get(self, rb_intern("family")); + return NUM2INT(v); +} + +/* + * call-seq: + * ancillarydata.family => integer + * + * returns the socket family as an integer. + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").family + * #=> 10 + */ +static VALUE +ancillary_family_m(VALUE self) +{ + return INT2NUM(ancillary_family(self)); +} + +static int +ancillary_level(VALUE self) +{ + VALUE v = rb_attr_get(self, rb_intern("level")); + return NUM2INT(v); +} + +/* + * call-seq: + * ancillarydata.level => integer + * + * returns the cmsg level as an integer. + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").level + * #=> 41 + */ +static VALUE +ancillary_level_m(VALUE self) +{ + return INT2NUM(ancillary_level(self)); +} + +static int +ancillary_type(VALUE self) +{ + VALUE v = rb_attr_get(self, rb_intern("type")); + return NUM2INT(v); +} + +/* + * call-seq: + * ancillarydata.type => integer + * + * returns the cmsg type as an integer. + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").type + * #=> 2 + */ +static VALUE +ancillary_type_m(VALUE self) +{ + return INT2NUM(ancillary_type(self)); +} + +/* + * call-seq: + * ancillarydata.data => string + * + * returns the cmsg data as a string. + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").data + * #=> "" + */ +static VALUE +ancillary_data(VALUE self) +{ + VALUE v = rb_attr_get(self, rb_intern("data")); + StringValue(v); + return v; +} + +#ifdef SCM_RIGHTS +/* + * call-seq: + * Socket::AncillaryData.unix_rights(io1, io2, ...) => ancillarydata + * + * Creates a new Socket::AncillaryData object which contains file descriptors as data. + * + * p Socket::AncillaryData.unix_rights(STDERR) + * #=> #<Socket::AncillaryData: UNIX SOCKET RIGHTS 2> + */ +static VALUE +ancillary_s_unix_rights(int argc, VALUE *argv, VALUE klass) +{ + VALUE result, str, ary; + int i; + + ary = rb_ary_new(); + + for (i = 0 ; i < argc; i++) { + VALUE obj = argv[i]; + if (TYPE(obj) != T_FILE) { + rb_raise(rb_eTypeError, "IO expected"); + } + rb_ary_push(ary, obj); + } + + str = rb_str_buf_new(sizeof(int) * argc); + + for (i = 0 ; i < argc; i++) { + VALUE obj = RARRAY_PTR(ary)[i]; + rb_io_t *fptr; + int fd; + GetOpenFile(obj, fptr); + fd = fptr->fd; + rb_str_buf_cat(str, (char *)&fd, sizeof(int)); + } + + result = ancdata_new(AF_UNIX, SOL_SOCKET, SCM_RIGHTS, str); + rb_ivar_set(result, rb_intern("unix_rights"), ary); + return result; +} +#else +#define ancillary_s_unix_rights rb_f_notimplement +#endif + +#ifdef SCM_RIGHTS +/* + * call-seq: + * ancillarydata.unix_rights => array-of-IOs or nil + * + * returns the array of IO objects for SCM_RIGHTS control message in UNIX domain socket. + * + * The class of the IO objects in the array is IO or Socket. + * + * The array is attached to _ancillarydata_ when it is instantiated. + * For example, BasicSocket#recvmsg attach the array when + * receives a SCM_RIGHTS control message and :scm_rights=>true option is given. + * + * # recvmsg needs :scm_rights=>true for unix_rights + * s1, s2 = UNIXSocket.pair + * p s1 #=> #<UNIXSocket:fd 3> + * s1.sendmsg "stdin and a socket", 0, nil, Socket::AncillaryData.unix_rights(STDIN, s1) + * _, _, _, ctl = s2.recvmsg(:scm_rights=>true) + * p ctl #=> #<Socket::AncillaryData: UNIX SOCKET RIGHTS 6 7> + * p ctl.unix_rights #=> [#<IO:fd 6>, #<Socket:fd 7>] + * p File.identical?(STDIN, ctl.unix_rights[0]) #=> true + * p File.identical?(s1, ctl.unix_rights[1]) #=> true + * + * # If :scm_rights=>true is not given, unix_rights returns nil + * s1, s2 = UNIXSocket.pair + * s1.sendmsg "stdin and a socket", 0, nil, Socket::AncillaryData.unix_rights(STDIN, s1) + * _, _, _, ctl = s2.recvmsg + * p ctl #=> #<Socket::AncillaryData: UNIX SOCKET RIGHTS 6 7> + * p ctl.unix_rights #=> nil + * + */ +static VALUE +ancillary_unix_rights(VALUE self) +{ + int level, type; + + level = ancillary_level(self); + type = ancillary_type(self); + + if (level != SOL_SOCKET || type != SCM_RIGHTS) + rb_raise(rb_eTypeError, "SCM_RIGHTS ancillary data expected"); + + return rb_attr_get(self, rb_intern("unix_rights")); +} +#else +#define ancillary_unix_rights rb_f_notimplement +#endif + +#if defined(SCM_TIMESTAMP) || defined(SCM_TIMESTAMPNS) || defined(SCM_BINTIME) +/* + * call-seq: + * ancillarydata.timestamp => time + * + * returns the timestamp as a time object. + * + * _ancillarydata_ should be one of following type: + * - SOL_SOCKET/SCM_TIMESTAMP (micro second) GNU/Linux, FreeBSD, NetBSD, OpenBSD, Solaris, MacOS X + * - SOL_SOCKET/SCM_TIMESTAMPNS (nano second) GNU/Linux + * - SOL_SOCKET/SCM_BINTIME (2**(-64) second) FreeBSD + * + * Addrinfo.udp("127.0.0.1", 0).bind {|s1| + * Addrinfo.udp("127.0.0.1", 0).bind {|s2| + * s1.setsockopt(:SOCKET, :TIMESTAMP, true) + * s2.send "a", 0, s1.local_address + * ctl = s1.recvmsg.last + * p ctl #=> #<Socket::AncillaryData: INET SOCKET TIMESTAMP 2009-02-24 17:35:46.775581> + * t = ctl.timestamp + * p t #=> 2009-02-24 17:35:46 +0900 + * p t.usec #=> 775581 + * p t.nsec #=> 775581000 + * } + * } + * + */ +static VALUE +ancillary_timestamp(VALUE self) +{ + int level, type; + VALUE data; + VALUE result = Qnil; + + level = ancillary_level(self); + type = ancillary_type(self); + data = ancillary_data(self); + +# ifdef SCM_TIMESTAMP + if (level == SOL_SOCKET && type == SCM_TIMESTAMP && + RSTRING_LEN(data) == sizeof(struct timeval)) { + struct timeval tv; + memcpy((char*)&tv, RSTRING_PTR(data), sizeof(tv)); + result = rb_time_new(tv.tv_sec, tv.tv_usec); + } +# endif + +# ifdef SCM_TIMESTAMPNS + if (level == SOL_SOCKET && type == SCM_TIMESTAMPNS && + RSTRING_LEN(data) == sizeof(struct timespec)) { + struct timespec ts; + memcpy((char*)&ts, RSTRING_PTR(data), sizeof(ts)); + result = rb_time_nano_new(ts.tv_sec, ts.tv_nsec); + } +# endif + +#define add(x,y) (rb_funcall((x), '+', 1, (y))) +#define mul(x,y) (rb_funcall((x), '*', 1, (y))) +#define quo(x,y) (rb_funcall((x), rb_intern("quo"), 1, (y))) + +# ifdef SCM_BINTIME + if (level == SOL_SOCKET && type == SCM_BINTIME && + RSTRING_LEN(data) == sizeof(struct bintime)) { + struct bintime bt; + VALUE d, timev; + memcpy((char*)&bt, RSTRING_PTR(data), sizeof(bt)); + d = ULL2NUM(0x100000000UL); + d = mul(d,d); + timev = add(TIMET2NUM(bt.sec), quo(ULL2NUM(bt.frac), d)); + result = rb_time_num_new(timev, Qnil); + } +# endif + + if (result == Qnil) + rb_raise(rb_eTypeError, "timestamp ancillary data expected"); + + return result; +} +#else +#define ancillary_timestamp rb_f_notimplement +#endif + +/* + * call-seq: + * Socket::AncillaryData.int(family, cmsg_level, cmsg_type, integer) => ancillarydata + * + * Creates a new Socket::AncillaryData object which contains a int as data. + * + * The size and endian is dependent on the host. + * + * p Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, STDERR.fileno) + * #=> #<Socket::AncillaryData: UNIX SOCKET RIGHTS 2> + */ +static VALUE +ancillary_s_int(VALUE klass, VALUE vfamily, VALUE vlevel, VALUE vtype, VALUE integer) +{ + int family = rsock_family_arg(vfamily); + int level = rsock_level_arg(family, vlevel); + int type = rsock_cmsg_type_arg(family, level, vtype); + int i = NUM2INT(integer); + return ancdata_new(family, level, type, rb_str_new((char*)&i, sizeof(i))); +} + +/* + * call-seq: + * ancillarydata.int => integer + * + * Returns the data in _ancillarydata_ as an int. + * + * The size and endian is dependent on the host. + * + * ancdata = Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, STDERR.fileno) + * p ancdata.int #=> 2 + */ +static VALUE +ancillary_int(VALUE self) +{ + VALUE data; + int i; + data = ancillary_data(self); + if (RSTRING_LEN(data) != sizeof(int)) + rb_raise(rb_eTypeError, "size differ. expected as sizeof(int)=%d but %ld", (int)sizeof(int), (long)RSTRING_LEN(data)); + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + return INT2NUM(i); +} + +#if defined(IPPROTO_IP) && defined(IP_PKTINFO) && defined(HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST) /* GNU/Linux */ +/* + * call-seq: + * Socket::AncillaryData.ip_pktinfo(addr, ifindex) => ancdata + * Socket::AncillaryData.ip_pktinfo(addr, ifindex, spec_dst) => ancdata + * + * Returns new ancillary data for IP_PKTINFO. + * + * If spec_dst is not given, addr is used. + * + * IP_PKTINFO is not standard. + * + * Supported platform: GNU/Linux + * + * addr = Addrinfo.ip("127.0.0.1") + * ifindex = 0 + * spec_dst = Addrinfo.ip("127.0.0.1") + * p Socket::AncillaryData.ip_pktinfo(addr, ifindex, spec_dst) + * #=> #<Socket::AncillaryData: INET IP PKTINFO 127.0.0.1 ifindex:0 spec_dst:127.0.0.1> + * + */ +static VALUE +ancillary_s_ip_pktinfo(int argc, VALUE *argv, VALUE self) +{ + VALUE v_addr, v_ifindex, v_spec_dst; + unsigned int ifindex; + struct sockaddr_in sa; + struct in_pktinfo pktinfo; + + rb_scan_args(argc, argv, "21", &v_addr, &v_ifindex, &v_spec_dst); + + SockAddrStringValue(v_addr); + ifindex = NUM2UINT(v_ifindex); + if (NIL_P(v_spec_dst)) + v_spec_dst = v_addr; + else + SockAddrStringValue(v_spec_dst); + + memset(&pktinfo, 0, sizeof(pktinfo)); + + memset(&sa, 0, sizeof(sa)); + if (RSTRING_LEN(v_addr) != sizeof(sa)) + rb_raise(rb_eArgError, "addr size different to AF_INET sockaddr"); + memcpy(&sa, RSTRING_PTR(v_addr), sizeof(sa)); + if (sa.sin_family != AF_INET) + rb_raise(rb_eArgError, "addr is not AF_INET sockaddr"); + memcpy(&pktinfo.ipi_addr, &sa.sin_addr, sizeof(pktinfo.ipi_addr)); + + pktinfo.ipi_ifindex = ifindex; + + memset(&sa, 0, sizeof(sa)); + if (RSTRING_LEN(v_spec_dst) != sizeof(sa)) + rb_raise(rb_eArgError, "spec_dat size different to AF_INET sockaddr"); + memcpy(&sa, RSTRING_PTR(v_spec_dst), sizeof(sa)); + if (sa.sin_family != AF_INET) + rb_raise(rb_eArgError, "spec_dst is not AF_INET sockaddr"); + memcpy(&pktinfo.ipi_spec_dst, &sa.sin_addr, sizeof(pktinfo.ipi_spec_dst)); + + return ancdata_new(AF_INET, IPPROTO_IP, IP_PKTINFO, rb_str_new((char *)&pktinfo, sizeof(pktinfo))); +} +#else +#define ancillary_s_ip_pktinfo rb_f_notimplement +#endif + +#if defined(IPPROTO_IP) && defined(IP_PKTINFO) && defined(HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST) /* GNU/Linux */ +/* + * call-seq: + * ancdata.ip_pktinfo => [addr, ifindex, spec_dst] + * + * Extracts addr, ifindex and spec_dst from IP_PKTINFO ancillary data. + * + * IP_PKTINFO is not standard. + * + * Supported platform: GNU/Linux + * + * addr = Addrinfo.ip("127.0.0.1") + * ifindex = 0 + * spec_dest = Addrinfo.ip("127.0.0.1") + * ancdata = Socket::AncillaryData.ip_pktinfo(addr, ifindex, spec_dest) + * p ancdata.ip_pktinfo + * #=> [#<Addrinfo: 127.0.0.1>, 0, #<Addrinfo: 127.0.0.1>] + * + * + */ +static VALUE +ancillary_ip_pktinfo(VALUE self) +{ + int level, type; + VALUE data; + struct in_pktinfo pktinfo; + struct sockaddr_in sa; + VALUE v_spec_dst, v_addr; + + level = ancillary_level(self); + type = ancillary_type(self); + data = ancillary_data(self); + + if (level != IPPROTO_IP || type != IP_PKTINFO || + RSTRING_LEN(data) != sizeof(struct in_pktinfo)) { + rb_raise(rb_eTypeError, "IP_PKTINFO ancillary data expected"); + } + + memcpy(&pktinfo, RSTRING_PTR(data), sizeof(struct in_pktinfo)); + memset(&sa, 0, sizeof(sa)); + + sa.sin_family = AF_INET; + memcpy(&sa.sin_addr, &pktinfo.ipi_addr, sizeof(sa.sin_addr)); + v_addr = rsock_addrinfo_new((struct sockaddr *)&sa, sizeof(sa), PF_INET, 0, 0, Qnil, Qnil); + + sa.sin_family = AF_INET; + memcpy(&sa.sin_addr, &pktinfo.ipi_spec_dst, sizeof(sa.sin_addr)); + v_spec_dst = rsock_addrinfo_new((struct sockaddr *)&sa, sizeof(sa), PF_INET, 0, 0, Qnil, Qnil); + + return rb_ary_new3(3, v_addr, UINT2NUM(pktinfo.ipi_ifindex), v_spec_dst); +} +#else +#define ancillary_ip_pktinfo rb_f_notimplement +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) /* IPv6 RFC3542 */ +/* + * call-seq: + * Socket::AncillaryData.ipv6_pktinfo(addr, ifindex) => ancdata + * + * Returns new ancillary data for IPV6_PKTINFO. + * + * IPV6_PKTINFO is defined by RFC 3542. + * + * addr = Addrinfo.ip("::1") + * ifindex = 0 + * p Socket::AncillaryData.ipv6_pktinfo(addr, ifindex) + * #=> #<Socket::AncillaryData: INET6 IPV6 PKTINFO ::1 ifindex:0> + * + */ +static VALUE +ancillary_s_ipv6_pktinfo(VALUE self, VALUE v_addr, VALUE v_ifindex) +{ + unsigned int ifindex; + struct sockaddr_in6 sa; + struct in6_pktinfo pktinfo; + + SockAddrStringValue(v_addr); + ifindex = NUM2UINT(v_ifindex); + + memset(&pktinfo, 0, sizeof(pktinfo)); + + memset(&sa, 0, sizeof(sa)); + if (RSTRING_LEN(v_addr) != sizeof(sa)) + rb_raise(rb_eArgError, "addr size different to AF_INET6 sockaddr"); + memcpy(&sa, RSTRING_PTR(v_addr), sizeof(sa)); + if (sa.sin6_family != AF_INET6) + rb_raise(rb_eArgError, "addr is not AF_INET6 sockaddr"); + memcpy(&pktinfo.ipi6_addr, &sa.sin6_addr, sizeof(pktinfo.ipi6_addr)); + + pktinfo.ipi6_ifindex = ifindex; + + return ancdata_new(AF_INET6, IPPROTO_IPV6, IPV6_PKTINFO, rb_str_new((char *)&pktinfo, sizeof(pktinfo))); +} +#else +#define ancillary_s_ipv6_pktinfo rb_f_notimplement +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) /* IPv6 RFC3542 */ +static void +extract_ipv6_pktinfo(VALUE self, struct in6_pktinfo *pktinfo_ptr, struct sockaddr_in6 *sa_ptr) +{ + int level, type; + VALUE data; + + level = ancillary_level(self); + type = ancillary_type(self); + data = ancillary_data(self); + + if (level != IPPROTO_IPV6 || type != IPV6_PKTINFO || + RSTRING_LEN(data) != sizeof(struct in6_pktinfo)) { + rb_raise(rb_eTypeError, "IPV6_PKTINFO ancillary data expected"); + } + + memcpy(pktinfo_ptr, RSTRING_PTR(data), sizeof(*pktinfo_ptr)); + + memset(sa_ptr, 0, sizeof(*sa_ptr)); + SET_SA_LEN((struct sockaddr *)sa_ptr, sizeof(struct sockaddr_in6)); + sa_ptr->sin6_family = AF_INET6; + memcpy(&sa_ptr->sin6_addr, &pktinfo_ptr->ipi6_addr, sizeof(sa_ptr->sin6_addr)); + if (IN6_IS_ADDR_LINKLOCAL(&sa_ptr->sin6_addr)) + sa_ptr->sin6_scope_id = pktinfo_ptr->ipi6_ifindex; +} +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) /* IPv6 RFC3542 */ +/* + * call-seq: + * ancdata.ipv6_pktinfo => [addr, ifindex] + * + * Extracts addr and ifindex from IPV6_PKTINFO ancillary data. + * + * IPV6_PKTINFO is defined by RFC 3542. + * + * addr = Addrinfo.ip("::1") + * ifindex = 0 + * ancdata = Socket::AncillaryData.ipv6_pktinfo(addr, ifindex) + * p ancdata.ipv6_pktinfo #=> [#<Addrinfo: ::1>, 0] + * + */ +static VALUE +ancillary_ipv6_pktinfo(VALUE self) +{ + struct in6_pktinfo pktinfo; + struct sockaddr_in6 sa; + VALUE v_addr; + + extract_ipv6_pktinfo(self, &pktinfo, &sa); + v_addr = rsock_addrinfo_new((struct sockaddr *)&sa, (socklen_t)sizeof(sa), PF_INET6, 0, 0, Qnil, Qnil); + return rb_ary_new3(2, v_addr, UINT2NUM(pktinfo.ipi6_ifindex)); +} +#else +#define ancillary_ipv6_pktinfo rb_f_notimplement +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) /* IPv6 RFC3542 */ +/* + * call-seq: + * ancdata.ipv6_pktinfo_addr => addr + * + * Extracts addr from IPV6_PKTINFO ancillary data. + * + * IPV6_PKTINFO is defined by RFC 3542. + * + * addr = Addrinfo.ip("::1") + * ifindex = 0 + * ancdata = Socket::AncillaryData.ipv6_pktinfo(addr, ifindex) + * p ancdata.ipv6_pktinfo_addr #=> #<Addrinfo: ::1> + * + */ +static VALUE +ancillary_ipv6_pktinfo_addr(VALUE self) +{ + struct in6_pktinfo pktinfo; + struct sockaddr_in6 sa; + extract_ipv6_pktinfo(self, &pktinfo, &sa); + return rsock_addrinfo_new((struct sockaddr *)&sa, (socklen_t)sizeof(sa), PF_INET6, 0, 0, Qnil, Qnil); +} +#else +#define ancillary_ipv6_pktinfo_addr rb_f_notimplement +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) /* IPv6 RFC3542 */ +/* + * call-seq: + * ancdata.ipv6_pktinfo_ifindex => addr + * + * Extracts ifindex from IPV6_PKTINFO ancillary data. + * + * IPV6_PKTINFO is defined by RFC 3542. + * + * addr = Addrinfo.ip("::1") + * ifindex = 0 + * ancdata = Socket::AncillaryData.ipv6_pktinfo(addr, ifindex) + * p ancdata.ipv6_pktinfo_ifindex #=> 0 + * + */ +static VALUE +ancillary_ipv6_pktinfo_ifindex(VALUE self) +{ + struct in6_pktinfo pktinfo; + struct sockaddr_in6 sa; + extract_ipv6_pktinfo(self, &pktinfo, &sa); + return UINT2NUM(pktinfo.ipi6_ifindex); +} +#else +#define ancillary_ipv6_pktinfo_ifindex rb_f_notimplement +#endif + +#if defined(SOL_SOCKET) && defined(SCM_RIGHTS) /* 4.4BSD */ +static int +anc_inspect_socket_rights(int level, int type, VALUE data, VALUE ret) +{ + if (level == SOL_SOCKET && type == SCM_RIGHTS && + 0 < RSTRING_LEN(data) && (RSTRING_LEN(data) % sizeof(int) == 0)) { + long off; + for (off = 0; off < RSTRING_LEN(data); off += sizeof(int)) { + int fd; + memcpy((char*)&fd, RSTRING_PTR(data)+off, sizeof(int)); + rb_str_catf(ret, " %d", fd); + } + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SCM_CREDENTIALS) /* GNU/Linux */ +static int +anc_inspect_passcred_credentials(int level, int type, VALUE data, VALUE ret) +{ + if (level == SOL_SOCKET && type == SCM_CREDENTIALS && + RSTRING_LEN(data) == sizeof(struct ucred)) { + struct ucred cred; + memcpy(&cred, RSTRING_PTR(data), sizeof(struct ucred)); + rb_str_catf(ret, " pid=%u uid=%u gid=%u", cred.pid, cred.uid, cred.gid); + rb_str_cat2(ret, " (ucred)"); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SCM_CREDS) +#define INSPECT_SCM_CREDS +static int +anc_inspect_socket_creds(int level, int type, VALUE data, VALUE ret) +{ + if (level != SOL_SOCKET && type != SCM_CREDS) + return 0; + + /* + * FreeBSD has struct cmsgcred and struct sockcred. + * They use both SOL_SOCKET/SCM_CREDS in the ancillary message. + * They are not ambiguous from the view of the caller + * because struct sockcred is sent if and only if the caller sets LOCAL_CREDS socket option. + * But inspect method doesn't know it. + * So they are ambiguous from the view of inspect. + * This function distinguish them by the size of the ancillary message. + * This heuristics works well except when sc_ngroups == CMGROUP_MAX. + */ + +#if defined(HAVE_TYPE_STRUCT_CMSGCRED) /* FreeBSD */ + if (RSTRING_LEN(data) == sizeof(struct cmsgcred)) { + struct cmsgcred cred; + memcpy(&cred, RSTRING_PTR(data), sizeof(struct cmsgcred)); + rb_str_catf(ret, " pid=%u", cred.cmcred_pid); + rb_str_catf(ret, " uid=%u", cred.cmcred_uid); + rb_str_catf(ret, " euid=%u", cred.cmcred_euid); + rb_str_catf(ret, " gid=%u", cred.cmcred_gid); + if (cred.cmcred_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred.cmcred_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred.cmcred_groups[i]); + sep = ","; + } + } + rb_str_cat2(ret, " (cmsgcred)"); + return 1; + } +#endif +#if defined(HAVE_TYPE_STRUCT_SOCKCRED) /* FreeBSD, NetBSD */ + if ((size_t)RSTRING_LEN(data) >= SOCKCREDSIZE(0)) { + struct sockcred cred0, *cred; + memcpy(&cred0, RSTRING_PTR(data), SOCKCREDSIZE(0)); + if ((size_t)RSTRING_LEN(data) == SOCKCREDSIZE(cred0.sc_ngroups)) { + cred = (struct sockcred *)ALLOCA_N(char, SOCKCREDSIZE(cred0.sc_ngroups)); + memcpy(cred, RSTRING_PTR(data), SOCKCREDSIZE(cred0.sc_ngroups)); + rb_str_catf(ret, " uid=%u", cred->sc_uid); + rb_str_catf(ret, " euid=%u", cred->sc_euid); + rb_str_catf(ret, " gid=%u", cred->sc_gid); + rb_str_catf(ret, " egid=%u", cred->sc_egid); + if (cred0.sc_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred0.sc_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred->sc_groups[i]); + sep = ","; + } + } + rb_str_cat2(ret, " (sockcred)"); + return 1; + } + } +#endif + return 0; +} +#endif + +#if defined(IPPROTO_IP) && defined(IP_RECVDSTADDR) /* 4.4BSD */ +static int +anc_inspect_ip_recvdstaddr(int level, int type, VALUE data, VALUE ret) +{ + if (level == IPPROTO_IP && type == IP_RECVDSTADDR && + RSTRING_LEN(data) == sizeof(struct in_addr)) { + struct in_addr addr; + char addrbuf[INET_ADDRSTRLEN]; + memcpy(&addr, RSTRING_PTR(data), sizeof(addr)); + if (inet_ntop(AF_INET, &addr, addrbuf, (socklen_t)sizeof(addrbuf)) == NULL) + rb_str_cat2(ret, " invalid-address"); + else + rb_str_catf(ret, " %s", addrbuf); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(IPPROTO_IP) && defined(IP_PKTINFO) && defined(HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST) /* GNU/Linux */ +static int +anc_inspect_ip_pktinfo(int level, int type, VALUE data, VALUE ret) +{ + if (level == IPPROTO_IP && type == IP_PKTINFO && + RSTRING_LEN(data) == sizeof(struct in_pktinfo)) { + struct in_pktinfo pktinfo; + char buf[INET_ADDRSTRLEN > IFNAMSIZ ? INET_ADDRSTRLEN : IFNAMSIZ]; + memcpy(&pktinfo, RSTRING_PTR(data), sizeof(pktinfo)); + if (inet_ntop(AF_INET, &pktinfo.ipi_addr, buf, sizeof(buf)) == NULL) + rb_str_cat2(ret, " invalid-address"); + else + rb_str_catf(ret, " %s", buf); + if (if_indextoname(pktinfo.ipi_ifindex, buf) == NULL) + rb_str_catf(ret, " ifindex:%d", pktinfo.ipi_ifindex); + else + rb_str_catf(ret, " %s", buf); + if (inet_ntop(AF_INET, &pktinfo.ipi_spec_dst, buf, sizeof(buf)) == NULL) + rb_str_cat2(ret, " spec_dst:invalid-address"); + else + rb_str_catf(ret, " spec_dst:%s", buf); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO) && defined(HAVE_TYPE_STRUCT_IN6_PKTINFO) /* IPv6 RFC3542 */ +static int +anc_inspect_ipv6_pktinfo(int level, int type, VALUE data, VALUE ret) +{ + if (level == IPPROTO_IPV6 && type == IPV6_PKTINFO && + RSTRING_LEN(data) == sizeof(struct in6_pktinfo)) { + struct in6_pktinfo *pktinfo = (struct in6_pktinfo *)RSTRING_PTR(data); + struct in6_addr addr; + unsigned int ifindex; + char addrbuf[INET6_ADDRSTRLEN], ifbuf[IFNAMSIZ]; + memcpy(&addr, &pktinfo->ipi6_addr, sizeof(addr)); + memcpy(&ifindex, &pktinfo->ipi6_ifindex, sizeof(ifindex)); + if (inet_ntop(AF_INET6, &addr, addrbuf, (socklen_t)sizeof(addrbuf)) == NULL) + rb_str_cat2(ret, " invalid-address"); + else + rb_str_catf(ret, " %s", addrbuf); + if (if_indextoname(ifindex, ifbuf) == NULL) + rb_str_catf(ret, " ifindex:%d", ifindex); + else + rb_str_catf(ret, " %s", ifbuf); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SCM_TIMESTAMP) /* GNU/Linux, FreeBSD, NetBSD, OpenBSD, MacOS X, Solaris */ +static int +inspect_timeval_as_abstime(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct timeval)) { + struct timeval tv; + time_t time; + struct tm tm; + char buf[32]; + memcpy((char*)&tv, RSTRING_PTR(data), sizeof(tv)); + time = tv.tv_sec; + tm = *localtime(&time); + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + rb_str_catf(ret, " %s.%06ld", buf, (long)tv.tv_usec); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SCM_TIMESTAMPNS) /* GNU/Linux */ +static int +inspect_timespec_as_abstime(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct timespec)) { + struct timespec ts; + struct tm tm; + char buf[32]; + memcpy((char*)&ts, RSTRING_PTR(data), sizeof(ts)); + tm = *localtime(&ts.tv_sec); + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + rb_str_catf(ret, " %s.%09ld", buf, (long)ts.tv_nsec); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SCM_BINTIME) /* FreeBSD */ +static int +inspect_bintime_as_abstime(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct bintime)) { + struct bintime bt; + struct tm tm; + uint64_t frac_h, frac_l; + uint64_t scale_h, scale_l; + uint64_t tmp1, tmp2; + uint64_t res_h, res_l; + char buf[32]; + memcpy((char*)&bt, RSTRING_PTR(data), sizeof(bt)); + tm = *localtime(&bt.sec); + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + + /* res_h = frac * 10**19 / 2**64 */ + + frac_h = bt.frac >> 32; + frac_l = bt.frac & 0xffffffff; + + scale_h = 0x8ac72304; /* 0x8ac7230489e80000 == 10**19 */ + scale_l = 0x89e80000; + + res_h = frac_h * scale_h; + res_l = frac_l * scale_l; + + tmp1 = frac_h * scale_l; + res_h += tmp1 >> 32; + tmp2 = res_l; + res_l += tmp1 & 0xffffffff; + if (res_l < tmp2) res_h++; + + tmp1 = frac_l * scale_h; + res_h += tmp1 >> 32; + tmp2 = res_l; + res_l += tmp1 & 0xffffffff; + if (res_l < tmp2) res_h++; + + rb_str_catf(ret, " %s.%019"PRIu64, buf, res_h); + return 1; + } + else { + return 0; + } +} +#endif + +/* + * call-seq: + * ancillarydata.inspect => string + * + * returns a string which shows ancillarydata in human-readable form. + * + * p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").inspect + * #=> "#<Socket::AncillaryData: INET6 IPV6 PKTINFO \"\">" + */ +static VALUE +ancillary_inspect(VALUE self) +{ + VALUE ret; + int family, level, type; + VALUE data; + ID family_id, level_id, type_id; + VALUE vtype; + int inspected; + + family = ancillary_family(self); + level = ancillary_level(self); + type = ancillary_type(self); + data = ancillary_data(self); + + ret = rb_sprintf("#<%s:", rb_obj_classname(self)); + + family_id = rsock_intern_family_noprefix(family); + if (family_id) + rb_str_catf(ret, " %s", rb_id2name(family_id)); + else + rb_str_catf(ret, " family:%d", family); + + if (level == SOL_SOCKET) { + rb_str_cat2(ret, " SOCKET"); + + type_id = rsock_intern_scm_optname(type); + if (type_id) + rb_str_catf(ret, " %s", rb_id2name(type_id)); + else + rb_str_catf(ret, " cmsg_type:%d", type); + } + else if (IS_IP_FAMILY(family)) { + level_id = rsock_intern_iplevel(level); + if (level_id) + rb_str_catf(ret, " %s", rb_id2name(level_id)); + else + rb_str_catf(ret, " cmsg_level:%d", level); + + vtype = ip_cmsg_type_to_sym(level, type); + if (SYMBOL_P(vtype)) + rb_str_catf(ret, " %s", rb_id2name(SYM2ID(vtype))); + else + rb_str_catf(ret, " cmsg_type:%d", type); + } + else { + rb_str_catf(ret, " cmsg_level:%d", level); + rb_str_catf(ret, " cmsg_type:%d", type); + } + + inspected = 0; + + if (level == SOL_SOCKET) + family = AF_UNSPEC; + + switch (family) { + case AF_UNSPEC: + switch (level) { +# if defined(SOL_SOCKET) + case SOL_SOCKET: + switch (type) { +# if defined(SCM_TIMESTAMP) /* GNU/Linux, FreeBSD, NetBSD, OpenBSD, MacOS X, Solaris */ + case SCM_TIMESTAMP: inspected = inspect_timeval_as_abstime(level, type, data, ret); break; +# endif +# if defined(SCM_TIMESTAMPNS) /* GNU/Linux */ + case SCM_TIMESTAMPNS: inspected = inspect_timespec_as_abstime(level, type, data, ret); break; +# endif +# if defined(SCM_BINTIME) /* FreeBSD */ + case SCM_BINTIME: inspected = inspect_bintime_as_abstime(level, type, data, ret); break; +# endif +# if defined(SCM_RIGHTS) /* 4.4BSD */ + case SCM_RIGHTS: inspected = anc_inspect_socket_rights(level, type, data, ret); break; +# endif +# if defined(SCM_CREDENTIALS) /* GNU/Linux */ + case SCM_CREDENTIALS: inspected = anc_inspect_passcred_credentials(level, type, data, ret); break; +# endif +# if defined(INSPECT_SCM_CREDS) /* NetBSD */ + case SCM_CREDS: inspected = anc_inspect_socket_creds(level, type, data, ret); break; +# endif + } + break; +# endif + } + break; + + case AF_INET: +#ifdef INET6 + case AF_INET6: +#endif + switch (level) { +# if defined(IPPROTO_IP) + case IPPROTO_IP: + switch (type) { +# if defined(IP_RECVDSTADDR) /* 4.4BSD */ + case IP_RECVDSTADDR: inspected = anc_inspect_ip_recvdstaddr(level, type, data, ret); break; +# endif +# if defined(IP_PKTINFO) && defined(HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST) /* GNU/Linux */ + case IP_PKTINFO: inspected = anc_inspect_ip_pktinfo(level, type, data, ret); break; +# endif + } + break; +# endif + +# if defined(IPPROTO_IPV6) + case IPPROTO_IPV6: + switch (type) { +# if defined(IPV6_PKTINFO) /* RFC 3542 */ + case IPV6_PKTINFO: inspected = anc_inspect_ipv6_pktinfo(level, type, data, ret); break; +# endif + } + break; +# endif + } + break; + } + + if (!inspected) { + rb_str_cat2(ret, " "); + rb_str_append(ret, rb_str_dump(data)); + } + + rb_str_cat2(ret, ">"); + + return ret; +} + +/* + * call-seq: + * ancillarydata.cmsg_is?(level, type) => true or false + * + * tests the level and type of _ancillarydata_. + * + * ancdata = Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "") + * ancdata.cmsg_is?(Socket::IPPROTO_IPV6, Socket::IPV6_PKTINFO) #=> true + * ancdata.cmsg_is?(:IPV6, :PKTINFO) #=> true + * ancdata.cmsg_is?(:IP, :PKTINFO) #=> false + * ancdata.cmsg_is?(:SOCKET, :RIGHTS) #=> false + */ +static VALUE +ancillary_cmsg_is_p(VALUE self, VALUE vlevel, VALUE vtype) +{ + int family = ancillary_family(self); + int level = rsock_level_arg(family, vlevel); + int type = rsock_cmsg_type_arg(family, level, vtype); + + if (ancillary_level(self) == level && + ancillary_type(self) == type) + return Qtrue; + else + return Qfalse; +} + +#endif + +#if defined(HAVE_SENDMSG) +struct sendmsg_args_struct { + int fd; + const struct msghdr *msg; + int flags; +}; + +static VALUE +nogvl_sendmsg_func(void *ptr) +{ + struct sendmsg_args_struct *args = ptr; + return sendmsg(args->fd, args->msg, args->flags); +} + +static ssize_t +rb_sendmsg(int fd, const struct msghdr *msg, int flags) +{ + struct sendmsg_args_struct args; + args.fd = fd; + args.msg = msg; + args.flags = flags; + return rb_thread_blocking_region(nogvl_sendmsg_func, &args, RUBY_UBF_IO, 0); +} + +static VALUE +bsock_sendmsg_internal(int argc, VALUE *argv, VALUE sock, int nonblock) +{ + rb_io_t *fptr; + VALUE data, vflags, dest_sockaddr; + VALUE *controls_ptr; + int controls_num; + struct msghdr mh; + struct iovec iov; +#if defined(HAVE_ST_MSG_CONTROL) + volatile VALUE controls_str = 0; +#endif + int flags; + ssize_t ss; + int family; + + rb_secure(4); + GetOpenFile(sock, fptr); + family = rsock_getfamily(fptr->fd); + + data = vflags = dest_sockaddr = Qnil; + controls_ptr = NULL; + controls_num = 0; + + if (argc == 0) + rb_raise(rb_eArgError, "mesg argument required"); + data = argv[0]; + if (1 < argc) vflags = argv[1]; + if (2 < argc) dest_sockaddr = argv[2]; + if (3 < argc) { controls_ptr = &argv[3]; controls_num = argc - 3; } + + StringValue(data); + + if (controls_num) { +#if defined(HAVE_ST_MSG_CONTROL) + int i; + size_t last_pad = 0; + int last_level = 0; + int last_type = 0; + controls_str = rb_str_tmp_new(0); + for (i = 0; i < controls_num; i++) { + VALUE elt = controls_ptr[i], v; + VALUE vlevel, vtype; + int level, type; + VALUE cdata; + long oldlen; + struct cmsghdr cmh; + char *cmsg; + size_t cspace; + v = rb_check_convert_type(elt, T_ARRAY, "Array", "to_ary"); + if (!NIL_P(v)) { + elt = v; + if (RARRAY_LEN(elt) != 3) + rb_raise(rb_eArgError, "an element of controls should be 3-elements array"); + vlevel = rb_ary_entry(elt, 0); + vtype = rb_ary_entry(elt, 1); + cdata = rb_ary_entry(elt, 2); + } + else { + vlevel = rb_funcall(elt, rb_intern("level"), 0); + vtype = rb_funcall(elt, rb_intern("type"), 0); + cdata = rb_funcall(elt, rb_intern("data"), 0); + } + level = rsock_level_arg(family, vlevel); + type = rsock_cmsg_type_arg(family, level, vtype); + StringValue(cdata); + oldlen = RSTRING_LEN(controls_str); + cspace = CMSG_SPACE(RSTRING_LEN(cdata)); + rb_str_resize(controls_str, oldlen + cspace); + cmsg = RSTRING_PTR(controls_str)+oldlen; + memset((char *)cmsg, 0, cspace); + memset((char *)&cmh, 0, sizeof(cmh)); + cmh.cmsg_level = level; + cmh.cmsg_type = type; + cmh.cmsg_len = (socklen_t)CMSG_LEN(RSTRING_LEN(cdata)); + MEMCPY(cmsg, &cmh, char, sizeof(cmh)); + MEMCPY(cmsg+((char*)CMSG_DATA(&cmh)-(char*)&cmh), RSTRING_PTR(cdata), char, RSTRING_LEN(cdata)); + last_level = cmh.cmsg_level; + last_type = cmh.cmsg_type; + last_pad = cspace - cmh.cmsg_len; + } + if (last_pad) { + /* + * This code removes the last padding from msg_controllen. + * + * 4.3BSD-Reno reject the padding for SCM_RIGHTS. (There was no 64bit environments in those days?) + * RFC 2292 require the padding. + * RFC 3542 relaxes the condition - implementation must accept both as valid. + * + * Actual problems: + * + * - NetBSD 4.0.1 + * SCM_RIGHTS with padding causes EINVAL + * IPV6_PKTINFO without padding causes "page fault trap" + * http://www.netbsd.org/cgi-bin/query-pr-single.pl?number=40661 + * + * - OpenBSD 4.4 + * IPV6_PKTINFO without padding causes EINVAL + * + * Basically, msg_controllen should contains the padding. + * So the padding is removed only if a problem really exists. + */ +#if defined(__NetBSD__) + if (last_level == SOL_SOCKET && last_type == SCM_RIGHTS) + rb_str_set_len(controls_str, RSTRING_LEN(controls_str)-last_pad); +#endif + } +#else + rb_raise(rb_eNotImpError, "control message for sendmsg is unimplemented"); +#endif + } + + flags = NIL_P(vflags) ? 0 : NUM2INT(vflags); +#ifdef MSG_DONTWAIT + if (nonblock) + flags |= MSG_DONTWAIT; +#endif + + if (!NIL_P(dest_sockaddr)) + SockAddrStringValue(dest_sockaddr); + + rb_io_check_closed(fptr); + + retry: + memset(&mh, 0, sizeof(mh)); + if (!NIL_P(dest_sockaddr)) { + mh.msg_name = RSTRING_PTR(dest_sockaddr); + mh.msg_namelen = RSTRING_LENINT(dest_sockaddr); + } + mh.msg_iovlen = 1; + mh.msg_iov = &iov; + iov.iov_base = RSTRING_PTR(data); + iov.iov_len = RSTRING_LEN(data); +#if defined(HAVE_ST_MSG_CONTROL) + if (controls_str) { + mh.msg_control = RSTRING_PTR(controls_str); + mh.msg_controllen = RSTRING_LENINT(controls_str); + } + else { + mh.msg_control = NULL; + mh.msg_controllen = 0; + } +#endif + + rb_io_check_closed(fptr); + if (nonblock) + rb_io_set_nonblock(fptr); + + ss = rb_sendmsg(fptr->fd, &mh, flags); + + if (!nonblock && rb_io_wait_writable(fptr->fd)) { + rb_io_check_closed(fptr); + goto retry; + } + + if (ss == -1) { + if (nonblock && (errno == EWOULDBLOCK || errno == EAGAIN)) + rb_mod_sys_fail(rb_mWaitWritable, "sendmsg(2) would block"); + rb_sys_fail("sendmsg(2)"); + } + + return SSIZET2NUM(ss); +} +#endif + +#if defined(HAVE_SENDMSG) +/* + * call-seq: + * basicsocket.sendmsg(mesg, flags=0, dest_sockaddr=nil, *controls) => numbytes_sent + * + * sendmsg sends a message using sendmsg(2) system call in blocking manner. + * + * _mesg_ is a string to send. + * + * _flags_ is bitwise OR of MSG_* constants such as Socket::MSG_OOB. + * + * _dest_sockaddr_ is a destination socket address for connection-less socket. + * It should be a sockaddr such as a result of Socket.sockaddr_in. + * An Addrinfo object can be used too. + * + * _controls_ is a list of ancillary data. + * The element of _controls_ should be Socket::AncillaryData or + * 3-elements array. + * The 3-element array should contains cmsg_level, cmsg_type and data. + * + * The return value, _numbytes_sent_ is an integer which is the number of bytes sent. + * + * sendmsg can be used to implement send_io as follows: + * + * # use Socket::AncillaryData. + * ancdata = Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, io.fileno) + * sock.sendmsg("a", 0, nil, ancdata) + * + * # use 3-element array. + * ancdata = [:SOCKET, :RIGHTS, [io.fileno].pack("i!")] + * sock.sendmsg("\0", 0, nil, ancdata) + * + */ +VALUE +rsock_bsock_sendmsg(int argc, VALUE *argv, VALUE sock) +{ + return bsock_sendmsg_internal(argc, argv, sock, 0); +} +#endif + +#if defined(HAVE_SENDMSG) +/* + * call-seq: + * basicsocket.sendmsg_nonblock(mesg, flags=0, dest_sockaddr=nil, *controls) => numbytes_sent + * + * sendmsg_nonblock sends a message using sendmsg(2) system call in non-blocking manner. + * + * It is similar to BasicSocket#sendmsg + * but the non-blocking flag is set before the system call + * and it doesn't retry the system call. + * + */ +VALUE +rsock_bsock_sendmsg_nonblock(int argc, VALUE *argv, VALUE sock) +{ + return bsock_sendmsg_internal(argc, argv, sock, 1); +} +#endif + +#if defined(HAVE_RECVMSG) +struct recvmsg_args_struct { + int fd; + struct msghdr *msg; + int flags; +}; + +static VALUE +nogvl_recvmsg_func(void *ptr) +{ + struct recvmsg_args_struct *args = ptr; + return recvmsg(args->fd, args->msg, args->flags); +} + +static ssize_t +rb_recvmsg(int fd, struct msghdr *msg, int flags) +{ + struct recvmsg_args_struct args; + args.fd = fd; + args.msg = msg; + args.flags = flags; + return rb_thread_blocking_region(nogvl_recvmsg_func, &args, RUBY_UBF_IO, 0); +} + +#if defined(HAVE_ST_MSG_CONTROL) +static void +discard_cmsg(struct cmsghdr *cmh, char *msg_end) +{ + if (cmh->cmsg_level == SOL_SOCKET && cmh->cmsg_type == SCM_RIGHTS) { + int *fdp = (int *)CMSG_DATA(cmh); + int *end = (int *)((char *)cmh + cmh->cmsg_len); + while ((char *)fdp + sizeof(int) <= (char *)end && + (char *)fdp + sizeof(int) <= msg_end) { + close(*fdp); + fdp++; + } + } +} +#endif + +void +rsock_discard_cmsg_resource(struct msghdr *mh) +{ +#if defined(HAVE_ST_MSG_CONTROL) + struct cmsghdr *cmh; + char *msg_end; + + if (mh->msg_controllen == 0) + return; + + msg_end = (char *)mh->msg_control + mh->msg_controllen; + + for (cmh = CMSG_FIRSTHDR(mh); cmh != NULL; cmh = CMSG_NXTHDR(mh, cmh)) { + discard_cmsg(cmh, msg_end); + } +#endif +} + +#if defined(HAVE_ST_MSG_CONTROL) +static void +make_io_for_unix_rights(VALUE ctl, struct cmsghdr *cmh, char *msg_end) +{ + if (cmh->cmsg_level == SOL_SOCKET && cmh->cmsg_type == SCM_RIGHTS) { + int *fdp, *end; + VALUE ary = rb_ary_new(); + rb_ivar_set(ctl, rb_intern("unix_rights"), ary); + fdp = (int *)CMSG_DATA(cmh); + end = (int *)((char *)cmh + cmh->cmsg_len); + while ((char *)fdp + sizeof(int) <= (char *)end && + (char *)fdp + sizeof(int) <= msg_end) { + int fd = *fdp; + struct stat stbuf; + VALUE io; + if (fstat(fd, &stbuf) == -1) + rb_raise(rb_eSocket, "invalid fd in SCM_RIGHTS"); + if (S_ISSOCK(stbuf.st_mode)) + io = rsock_init_sock(rb_obj_alloc(rb_cSocket), fd); + else + io = rb_io_fdopen(fd, O_RDWR, NULL); + ary = rb_attr_get(ctl, rb_intern("unix_rights")); + rb_ary_push(ary, io); + fdp++; + } + OBJ_FREEZE(ary); + } +} +#endif + +static VALUE +bsock_recvmsg_internal(int argc, VALUE *argv, VALUE sock, int nonblock) +{ + rb_io_t *fptr; + VALUE vmaxdatlen, vmaxctllen, vflags, vopts; + int grow_buffer; + size_t maxdatlen; + int flags, orig_flags; + int request_scm_rights; + struct msghdr mh; + struct iovec iov; + struct sockaddr_storage namebuf; + char datbuf0[4096], *datbuf; + VALUE dat_str = Qnil; + VALUE ret; + ssize_t ss; +#if defined(HAVE_ST_MSG_CONTROL) + struct cmsghdr *cmh; + size_t maxctllen; + union { + char bytes[4096]; + struct cmsghdr align; + } ctlbuf0; + char *ctlbuf; + VALUE ctl_str = Qnil; + int family; + int gc_done = 0; +#endif + + rb_secure(4); + + vopts = Qnil; + if (0 < argc && TYPE(argv[argc-1]) == T_HASH) + vopts = argv[--argc]; + + rb_scan_args(argc, argv, "03", &vmaxdatlen, &vflags, &vmaxctllen); + + maxdatlen = NIL_P(vmaxdatlen) ? sizeof(datbuf0) : NUM2SIZET(vmaxdatlen); +#if defined(HAVE_ST_MSG_CONTROL) + maxctllen = NIL_P(vmaxctllen) ? sizeof(ctlbuf0) : NUM2SIZET(vmaxctllen); +#else + if (!NIL_P(vmaxctllen)) + rb_raise(rb_eArgError, "control message not supported"); +#endif + flags = NIL_P(vflags) ? 0 : NUM2INT(vflags); +#ifdef MSG_DONTWAIT + if (nonblock) + flags |= MSG_DONTWAIT; +#endif + orig_flags = flags; + + grow_buffer = NIL_P(vmaxdatlen) || NIL_P(vmaxctllen); + + request_scm_rights = 0; + if (!NIL_P(vopts) && RTEST(rb_hash_aref(vopts, ID2SYM(rb_intern("scm_rights"))))) + request_scm_rights = 1; + + GetOpenFile(sock, fptr); + if (rb_io_read_pending(fptr)) { + rb_raise(rb_eIOError, "recvmsg for buffered IO"); + } + +#if !defined(HAVE_ST_MSG_CONTROL) + if (grow_buffer) { + int socktype; + socklen_t optlen = (socklen_t)sizeof(socktype); + if (getsockopt(fptr->fd, SOL_SOCKET, SO_TYPE, (void*)&socktype, &optlen) == -1) { + rb_sys_fail("getsockopt(SO_TYPE)"); + } + if (socktype == SOCK_STREAM) + grow_buffer = 0; + } +#endif + + retry: + if (maxdatlen <= sizeof(datbuf0)) + datbuf = datbuf0; + else { + if (NIL_P(dat_str)) + dat_str = rb_str_tmp_new(maxdatlen); + else + rb_str_resize(dat_str, maxdatlen); + datbuf = RSTRING_PTR(dat_str); + } + +#if defined(HAVE_ST_MSG_CONTROL) + if (maxctllen <= sizeof(ctlbuf0)) + ctlbuf = ctlbuf0.bytes; + else { + if (NIL_P(ctl_str)) + ctl_str = rb_str_tmp_new(maxctllen); + else + rb_str_resize(ctl_str, maxctllen); + ctlbuf = RSTRING_PTR(ctl_str); + } +#endif + + memset(&mh, 0, sizeof(mh)); + + memset(&namebuf, 0, sizeof(namebuf)); + mh.msg_name = (struct sockaddr *)&namebuf; + mh.msg_namelen = (socklen_t)sizeof(namebuf); + + mh.msg_iov = &iov; + mh.msg_iovlen = 1; + iov.iov_base = datbuf; + iov.iov_len = maxdatlen; + +#if defined(HAVE_ST_MSG_CONTROL) + mh.msg_control = ctlbuf; + mh.msg_controllen = (socklen_t)maxctllen; +#endif + + if (grow_buffer) + flags |= MSG_PEEK; + + rb_io_check_closed(fptr); + if (nonblock) + rb_io_set_nonblock(fptr); + + ss = rb_recvmsg(fptr->fd, &mh, flags); + + if (!nonblock && rb_io_wait_readable(fptr->fd)) { + rb_io_check_closed(fptr); + goto retry; + } + + if (ss == -1) { + if (nonblock && (errno == EWOULDBLOCK || errno == EAGAIN)) + rb_mod_sys_fail(rb_mWaitReadable, "recvmsg(2) would block"); +#if defined(HAVE_ST_MSG_CONTROL) + if (!gc_done && (errno == EMFILE || errno == EMSGSIZE)) { + /* + * When SCM_RIGHTS hit the file descriptors limit: + * - Linux 2.6.18 causes success with MSG_CTRUNC + * - MacOS X 10.4 causes EMSGSIZE (and lost file descriptors?) + * - Solaris 11 causes EMFILE + */ + gc_and_retry: + rb_gc(); + gc_done = 1; + goto retry; + } +#endif + rb_sys_fail("recvmsg(2)"); + } + + if (grow_buffer) { + int grown = 0; +#if defined(HAVE_ST_MSG_CONTROL) + if (NIL_P(vmaxdatlen) && (mh.msg_flags & MSG_TRUNC)) { + if (SIZE_MAX/2 < maxdatlen) + rb_raise(rb_eArgError, "max data length too big"); + maxdatlen *= 2; + grown = 1; + } + if (NIL_P(vmaxctllen) && (mh.msg_flags & MSG_CTRUNC)) { +#define BIG_ENOUGH_SPACE 65536 + if (BIG_ENOUGH_SPACE < maxctllen && + mh.msg_controllen < maxctllen - BIG_ENOUGH_SPACE) { + /* there are big space bug truncated. + * file descriptors limit? */ + if (!gc_done) { + rsock_discard_cmsg_resource(&mh); + goto gc_and_retry; + } + } + else { + if (SIZE_MAX/2 < maxctllen) + rb_raise(rb_eArgError, "max control message length too big"); + maxctllen *= 2; + grown = 1; + } +#undef BIG_ENOUGH_SPACE + } +#else + if (NIL_P(vmaxdatlen) && ss != -1 && ss == (ssize_t)iov.iov_len) { + if (SIZE_MAX/2 < maxdatlen) + rb_raise(rb_eArgError, "max data length too big"); + maxdatlen *= 2; + grown = 1; + } +#endif + if (grown) { + rsock_discard_cmsg_resource(&mh); + goto retry; + } + else { + grow_buffer = 0; + if (flags != orig_flags) { + flags = orig_flags; + rsock_discard_cmsg_resource(&mh); + goto retry; + } + } + } + + if (NIL_P(dat_str)) + dat_str = rb_tainted_str_new(datbuf, ss); + else { + rb_str_resize(dat_str, ss); + OBJ_TAINT(dat_str); + RBASIC(dat_str)->klass = rb_cString; + } + + ret = rb_ary_new3(3, dat_str, + rsock_io_socket_addrinfo(sock, mh.msg_name, mh.msg_namelen), +#if defined(HAVE_ST_MSG_CONTROL) + INT2NUM(mh.msg_flags) +#else + Qnil +#endif + ); + +#if defined(HAVE_ST_MSG_CONTROL) + family = rsock_getfamily(fptr->fd); + if (mh.msg_controllen) { + char *msg_end = (char *)mh.msg_control + mh.msg_controllen; + for (cmh = CMSG_FIRSTHDR(&mh); cmh != NULL; cmh = CMSG_NXTHDR(&mh, cmh)) { + VALUE ctl; + char *ctl_end; + size_t clen; + if (cmh->cmsg_len == 0) { + rb_raise(rb_eTypeError, "invalid control message (cmsg_len == 0)"); + } + ctl_end = (char*)cmh + cmh->cmsg_len; + clen = (ctl_end <= msg_end ? ctl_end : msg_end) - (char*)CMSG_DATA(cmh); + ctl = ancdata_new(family, cmh->cmsg_level, cmh->cmsg_type, rb_tainted_str_new((char*)CMSG_DATA(cmh), clen)); + if (request_scm_rights) + make_io_for_unix_rights(ctl, cmh, msg_end); + else + discard_cmsg(cmh, msg_end); + rb_ary_push(ret, ctl); + } + } +#endif + + return ret; +} +#endif + +#if defined(HAVE_RECVMSG) +/* + * call-seq: + * basicsocket.recvmsg(maxmesglen=nil, flags=0, maxcontrollen=nil, opts={}) => [mesg, sender_addrinfo, rflags, *controls] + * + * recvmsg receives a message using recvmsg(2) system call in blocking manner. + * + * _maxmesglen_ is the maximum length of mesg to receive. + * + * _flags_ is bitwise OR of MSG_* constants such as Socket::MSG_PEEK. + * + * _maxcontrollen_ is the maximum length of controls (ancillary data) to receive. + * + * _opts_ is option hash. + * Currently :scm_rights=>bool is the only option. + * + * :scm_rights option specifies that application expects SCM_RIGHTS control message. + * If the value is nil or false, application don't expects SCM_RIGHTS control message. + * In this case, recvmsg closes the passed file descriptors immediately. + * This is the default behavior. + * + * If :scm_rights value is neither nil nor false, application expects SCM_RIGHTS control message. + * In this case, recvmsg creates IO objects for each file descriptors for + * Socket::AncillaryData#unix_rights method. + * + * The return value is 4-elements array. + * + * _mesg_ is a string of the received message. + * + * _sender_addrinfo_ is a sender socket address for connection-less socket. + * It is an Addrinfo object. + * For connection-oriented socket such as TCP, sender_addrinfo is platform dependent. + * + * _rflags_ is a flags on the received message which is bitwise OR of MSG_* constants such as Socket::MSG_TRUNC. + * It will be nil if the system uses 4.3BSD style old recvmsg system call. + * + * _controls_ is ancillary data which is an array of Socket::AncillaryData objects such as: + * + * #<Socket::AncillaryData: AF_UNIX SOCKET RIGHTS 7> + * + * _maxmesglen_ and _maxcontrollen_ can be nil. + * In that case, the buffer will be grown until the message is not truncated. + * Internally, MSG_PEEK is used and MSG_TRUNC/MSG_CTRUNC are checked. + * + * recvmsg can be used to implement recv_io as follows: + * + * mesg, sender_sockaddr, rflags, *controls = sock.recvmsg(:scm_rights=>true) + * controls.each {|ancdata| + * if ancdata.cmsg_is?(:SOCKET, :RIGHTS) + * return ancdata.unix_rights[0] + * end + * } + * + */ +VALUE +rsock_bsock_recvmsg(int argc, VALUE *argv, VALUE sock) +{ + return bsock_recvmsg_internal(argc, argv, sock, 0); +} +#endif + +#if defined(HAVE_RECVMSG) +/* + * call-seq: + * basicsocket.recvmsg_nonblock(maxdatalen=nil, flags=0, maxcontrollen=nil, opts={}) => [data, sender_addrinfo, rflags, *controls] + * + * recvmsg receives a message using recvmsg(2) system call in non-blocking manner. + * + * It is similar to BasicSocket#recvmsg + * but non-blocking flag is set before the system call + * and it doesn't retry the system call. + * + */ +VALUE +rsock_bsock_recvmsg_nonblock(int argc, VALUE *argv, VALUE sock) +{ + return bsock_recvmsg_internal(argc, argv, sock, 1); +} +#endif + +/* + * Document-class: ::Socket::AncillaryData + * + * Socket::AncillaryData represents the ancillary data (control information) + * used by sendmsg and recvmsg system call. + * It contains socket family, cmsg level, cmsg type and cmsg data. + */ +void +rsock_init_ancdata(void) +{ +#if defined(HAVE_ST_MSG_CONTROL) + rb_cAncillaryData = rb_define_class_under(rb_cSocket, "AncillaryData", rb_cObject); + rb_define_method(rb_cAncillaryData, "initialize", ancillary_initialize, 4); + rb_define_method(rb_cAncillaryData, "inspect", ancillary_inspect, 0); + rb_define_method(rb_cAncillaryData, "family", ancillary_family_m, 0); + rb_define_method(rb_cAncillaryData, "level", ancillary_level_m, 0); + rb_define_method(rb_cAncillaryData, "type", ancillary_type_m, 0); + rb_define_method(rb_cAncillaryData, "data", ancillary_data, 0); + + rb_define_method(rb_cAncillaryData, "cmsg_is?", ancillary_cmsg_is_p, 2); + + rb_define_singleton_method(rb_cAncillaryData, "int", ancillary_s_int, 4); + rb_define_method(rb_cAncillaryData, "int", ancillary_int, 0); + + rb_define_singleton_method(rb_cAncillaryData, "unix_rights", ancillary_s_unix_rights, -1); + rb_define_method(rb_cAncillaryData, "unix_rights", ancillary_unix_rights, 0); + + rb_define_method(rb_cAncillaryData, "timestamp", ancillary_timestamp, 0); + + rb_define_singleton_method(rb_cAncillaryData, "ip_pktinfo", ancillary_s_ip_pktinfo, -1); + rb_define_method(rb_cAncillaryData, "ip_pktinfo", ancillary_ip_pktinfo, 0); + + rb_define_singleton_method(rb_cAncillaryData, "ipv6_pktinfo", ancillary_s_ipv6_pktinfo, 2); + rb_define_method(rb_cAncillaryData, "ipv6_pktinfo", ancillary_ipv6_pktinfo, 0); + rb_define_method(rb_cAncillaryData, "ipv6_pktinfo_addr", ancillary_ipv6_pktinfo_addr, 0); + rb_define_method(rb_cAncillaryData, "ipv6_pktinfo_ifindex", ancillary_ipv6_pktinfo_ifindex, 0); +#endif +} diff --git a/ext/socket/basicsocket.c b/ext/socket/basicsocket.c new file mode 100644 index 0000000000..e744ad27d3 --- /dev/null +++ b/ext/socket/basicsocket.c @@ -0,0 +1,771 @@ +/************************************************ + + basicsocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +/* + * call-seq: + * BasicSocket.for_fd(fd) => basicsocket + * + * Returns a socket object which contains the file descriptor, _fd_. + * + * # If invoked by inetd, STDIN/STDOUT/STDERR is a socket. + * STDIN_SOCK = Socket.for_fd(STDIN.fileno) + * p STDIN_SOCK.remote_address + * + */ +static VALUE +bsock_s_for_fd(VALUE klass, VALUE fd) +{ + rb_io_t *fptr; + VALUE sock = rsock_init_sock(rb_obj_alloc(klass), NUM2INT(fd)); + + GetOpenFile(sock, fptr); + + return sock; +} + +/* + * call-seq: + * basicsocket.shutdown([how]) => 0 + * + * Calls shutdown(2) system call. + * + * s.shutdown(Socket::SHUT_RD) disallows further read. + * + * s.shutdown(Socket::SHUT_WR) disallows further write. + * + * s.shutdown(Socket::SHUT_RDWR) disallows further read and write. + * + * _how_ can be symbol or string: + * - :RD, :SHUT_RD, "RD" and "SHUT_RD" are accepted as Socket::SHUT_RD. + * - :WR, :SHUT_WR, "WR" and "SHUT_WR" are accepted as Socket::SHUT_WR. + * - :RDWR, :SHUT_RDWR, "RDWR" and "SHUT_RDWR" are accepted as Socket::SHUT_RDWR. + * + * UNIXSocket.pair {|s1, s2| + * s1.puts "ping" + * s1.shutdown(:WR) + * p s2.read #=> "ping\n" + * s2.puts "pong" + * s2.close + * p s1.read #=> "pong\n" + * } + * + */ +static VALUE +bsock_shutdown(int argc, VALUE *argv, VALUE sock) +{ + VALUE howto; + int how; + rb_io_t *fptr; + + if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { + rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket"); + } + rb_scan_args(argc, argv, "01", &howto); + if (howto == Qnil) + how = SHUT_RDWR; + else { + how = rsock_shutdown_how_arg(howto); + if (how != SHUT_WR && how != SHUT_RD && how != SHUT_RDWR) { + rb_raise(rb_eArgError, "`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR"); + } + } + GetOpenFile(sock, fptr); + if (shutdown(fptr->fd, how) == -1) + rb_sys_fail(0); + + return INT2FIX(0); +} + +/* + * call-seq: + * basicsocket.close_read => nil + * + * Disallows further read using shutdown system call. + * + * s1, s2 = UNIXSocket.pair + * s1.close_read + * s2.puts #=> Broken pipe (Errno::EPIPE) + */ +static VALUE +bsock_close_read(VALUE sock) +{ + rb_io_t *fptr; + + if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { + rb_raise(rb_eSecurityError, "Insecure: can't close socket"); + } + GetOpenFile(sock, fptr); + shutdown(fptr->fd, 0); + if (!(fptr->mode & FMODE_WRITABLE)) { + return rb_io_close(sock); + } + fptr->mode &= ~FMODE_READABLE; + + return Qnil; +} + +/* + * call-seq: + * basicsocket.close_write => nil + * + * Disallows further write using shutdown system call. + * + * UNIXSocket.pair {|s1, s2| + * s1.print "ping" + * s1.close_write + * p s2.read #=> "ping" + * s2.print "pong" + * s2.close + * p s1.read #=> "pong" + * } + */ +static VALUE +bsock_close_write(VALUE sock) +{ + rb_io_t *fptr; + + if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { + rb_raise(rb_eSecurityError, "Insecure: can't close socket"); + } + GetOpenFile(sock, fptr); + if (!(fptr->mode & FMODE_READABLE)) { + return rb_io_close(sock); + } + shutdown(fptr->fd, 1); + fptr->mode &= ~FMODE_WRITABLE; + + return Qnil; +} + +/* + * Document-method: setsockopt + * call-seq: + * setsockopt(level, optname, optval) + * setsockopt(socketoption) + * + * Sets a socket option. These are protocol and system specific, see your + * local system documentation for details. + * + * === Parameters + * * +level+ is an integer, usually one of the SOL_ constants such as + * Socket::SOL_SOCKET, or a protocol level. + * A string or symbol of the name, possibly without prefix, is also + * accepted. + * * +optname+ is an integer, usually one of the SO_ constants, such + * as Socket::SO_REUSEADDR. + * A string or symbol of the name, possibly without prefix, is also + * accepted. + * * +optval+ is the value of the option, it is passed to the underlying + * setsockopt() as a pointer to a certain number of bytes. How this is + * done depends on the type: + * - Fixnum: value is assigned to an int, and a pointer to the int is + * passed, with length of sizeof(int). + * - true or false: 1 or 0 (respectively) is assigned to an int, and the + * int is passed as for a Fixnum. Note that +false+ must be passed, + * not +nil+. + * - String: the string's data and length is passed to the socket. + * * +socketoption+ is an instance of Socket::Option + * + * === Examples + * + * Some socket options are integers with boolean values, in this case + * #setsockopt could be called like this: + * sock.setsockopt(:SOCKET, :REUSEADDR, true) + * sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true) + * sock.setsockopt(Socket::Option.bool(:INET, :SOCKET, :REUSEADDR, true)) + * + * Some socket options are integers with numeric values, in this case + * #setsockopt could be called like this: + * sock.setsockopt(:IP, :TTL, 255) + * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255) + * sock.setsockopt(Socket::Option.int(:INET, :IP, :TTL, 255)) + * + * Option values may be structs. Passing them can be complex as it involves + * examining your system headers to determine the correct definition. An + * example is an +ip_mreq+, which may be defined in your system headers as: + * struct ip_mreq { + * struct in_addr imr_multiaddr; + * struct in_addr imr_interface; + * }; + * + * In this case #setsockopt could be called like this: + * optval = IPAddr.new("224.0.0.251").hton + + * IPAddr.new(Socket::INADDR_ANY, Socket::AF_INET).hton + * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval) + * +*/ +static VALUE +bsock_setsockopt(int argc, VALUE *argv, VALUE sock) +{ + VALUE lev, optname, val; + int family, level, option; + rb_io_t *fptr; + int i; + char *v; + int vlen; + + if (argc == 1) { + lev = rb_funcall(argv[0], rb_intern("level"), 0); + optname = rb_funcall(argv[0], rb_intern("optname"), 0); + val = rb_funcall(argv[0], rb_intern("data"), 0); + } + else { + rb_scan_args(argc, argv, "30", &lev, &optname, &val); + } + + rb_secure(2); + GetOpenFile(sock, fptr); + family = rsock_getfamily(fptr->fd); + level = rsock_level_arg(family, lev); + option = rsock_optname_arg(family, level, optname); + + switch (TYPE(val)) { + case T_FIXNUM: + i = FIX2INT(val); + goto numval; + case T_FALSE: + i = 0; + goto numval; + case T_TRUE: + i = 1; + numval: + v = (char*)&i; vlen = (int)sizeof(i); + break; + default: + StringValue(val); + v = RSTRING_PTR(val); + vlen = RSTRING_LENINT(val); + break; + } + +#define rb_sys_fail_path(path) rb_sys_fail(NIL_P(path) ? 0 : RSTRING_PTR(path)) + + rb_io_check_closed(fptr); + if (setsockopt(fptr->fd, level, option, v, vlen) < 0) + rb_sys_fail_path(fptr->pathv); + + return INT2FIX(0); +} + +#if !defined(__BEOS__) +/* + * Document-method: getsockopt + * call-seq: + * getsockopt(level, optname) => socketoption + * + * Gets a socket option. These are protocol and system specific, see your + * local system documentation for details. The option is returned as + * a Socket::Option object. + * + * === Parameters + * * +level+ is an integer, usually one of the SOL_ constants such as + * Socket::SOL_SOCKET, or a protocol level. + * A string or symbol of the name, possibly without prefix, is also + * accepted. + * * +optname+ is an integer, usually one of the SO_ constants, such + * as Socket::SO_REUSEADDR. + * A string or symbol of the name, possibly without prefix, is also + * accepted. + * + * === Examples + * + * Some socket options are integers with boolean values, in this case + * #getsockopt could be called like this: + * + * reuseaddr = sock.getsockopt(:SOCKET, :REUSEADDR).bool + * + * optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR) + * optval = optval.unpack "i" + * reuseaddr = optval[0] == 0 ? false : true + * + * Some socket options are integers with numeric values, in this case + * #getsockopt could be called like this: + * + * ipttl = sock.getsockopt(:IP, :TTL).int + * + * optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL) + * ipttl = optval.unpack("i")[0] + * + * Option values may be structs. Decoding them can be complex as it involves + * examining your system headers to determine the correct definition. An + * example is a +struct linger+, which may be defined in your system headers + * as: + * struct linger { + * int l_onoff; + * int l_linger; + * }; + * + * In this case #getsockopt could be called like this: + * + * # Socket::Option knows linger structure. + * onoff, linger = sock.getsockopt(:SOCKET, :LINGER).linger + * + * optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER) + * onoff, linger = optval.unpack "ii" + * onoff = onoff == 0 ? false : true +*/ +static VALUE +bsock_getsockopt(VALUE sock, VALUE lev, VALUE optname) +{ + int level, option; + socklen_t len; + char *buf; + rb_io_t *fptr; + int family; + + GetOpenFile(sock, fptr); + family = rsock_getfamily(fptr->fd); + level = rsock_level_arg(family, lev); + option = rsock_optname_arg(family, level, optname); + len = 256; + buf = ALLOCA_N(char,len); + + rb_io_check_closed(fptr); + + if (getsockopt(fptr->fd, level, option, buf, &len) < 0) + rb_sys_fail_path(fptr->pathv); + + return rsock_sockopt_new(family, level, option, rb_str_new(buf, len)); +} +#else +#define bsock_getsockopt rb_f_notimplement +#endif + +/* + * call-seq: + * basicsocket.getsockname => sockaddr + * + * Returns the local address of the socket as a sockaddr string. + * + * TCPServer.open("127.0.0.1", 15120) {|serv| + * p serv.getsockname #=> "\x02\x00;\x10\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" + * } + * + * If Addrinfo object is preferred over the binary string, + * use BasicSocket#local_address. + */ +static VALUE +bsock_getsockname(VALUE sock) +{ + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + if (getsockname(fptr->fd, (struct sockaddr*)&buf, &len) < 0) + rb_sys_fail("getsockname(2)"); + return rb_str_new((char*)&buf, len); +} + +/* + * call-seq: + * basicsocket.getpeername => sockaddr + * + * Returns the remote address of the socket as a sockaddr string. + * + * TCPServer.open("127.0.0.1", 1440) {|serv| + * c = TCPSocket.new("127.0.0.1", 1440) + * s = serv.accept + * p s.getpeername #=> "\x02\x00\x82u\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" + * } + * + * If Addrinfo object is preferred over the binary string, + * use BasicSocket#remote_address. + * + */ +static VALUE +bsock_getpeername(VALUE sock) +{ + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + if (getpeername(fptr->fd, (struct sockaddr*)&buf, &len) < 0) + rb_sys_fail("getpeername(2)"); + return rb_str_new((char*)&buf, len); +} + +#if defined(HAVE_GETPEEREID) || defined(SO_PEERCRED) || defined(HAVE_GETPEERUCRED) +/* + * call-seq: + * basicsocket.getpeereid => [euid, egid] + * + * Returns the user and group on the peer of the UNIX socket. + * The result is a two element array which contains the effective uid and the effective gid. + * + * Socket.unix_server_loop("/tmp/sock") {|s| + * begin + * euid, egid = s.getpeereid + * + * # Check the connected client is myself or not. + * next if euid != Process.uid + * + * # do something about my resource. + * + * ensure + * s.close + * end + * } + * + */ +static VALUE +bsock_getpeereid(VALUE self) +{ +#if defined(HAVE_GETPEEREID) + rb_io_t *fptr; + uid_t euid; + gid_t egid; + GetOpenFile(self, fptr); + if (getpeereid(fptr->fd, &euid, &egid) == -1) + rb_sys_fail("getpeereid"); + return rb_assoc_new(UIDT2NUM(euid), GIDT2NUM(egid)); +#elif defined(SO_PEERCRED) /* GNU/Linux */ + rb_io_t *fptr; + struct ucred cred; + socklen_t len = sizeof(cred); + GetOpenFile(self, fptr); + if (getsockopt(fptr->fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) == -1) + rb_sys_fail("getsockopt(SO_PEERCRED)"); + return rb_assoc_new(UIDT2NUM(cred.uid), GIDT2NUM(cred.gid)); +#elif defined(HAVE_GETPEERUCRED) /* Solaris */ + rb_io_t *fptr; + ucred_t *uc = NULL; + VALUE ret; + GetOpenFile(self, fptr); + if (getpeerucred(fptr->fd, &uc) == -1) + rb_sys_fail("getpeerucred"); + ret = rb_assoc_new(UIDT2NUM(ucred_geteuid(uc)), GIDT2NUM(ucred_getegid(uc))); + ucred_free(uc); + return ret; +#endif +} +#else +#define bsock_getpeereid rb_f_notimplement +#endif + +/* + * call-seq: + * bsock.local_address => addrinfo + * + * Returns an Addrinfo object for local address obtained by getsockname. + * + * Note that addrinfo.protocol is filled by 0. + * + * TCPSocket.open("www.ruby-lang.org", 80) {|s| + * p s.local_address #=> #<Addrinfo: 192.168.0.129:36873 TCP> + * } + * + * TCPServer.open("127.0.0.1", 1512) {|serv| + * p serv.local_address #=> #<Addrinfo: 127.0.0.1:1512 TCP> + * } + * + */ +static VALUE +bsock_local_address(VALUE sock) +{ + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + if (getsockname(fptr->fd, (struct sockaddr*)&buf, &len) < 0) + rb_sys_fail("getsockname(2)"); + return rsock_fd_socket_addrinfo(fptr->fd, (struct sockaddr *)&buf, len); +} + +/* + * call-seq: + * bsock.remote_address => addrinfo + * + * Returns an Addrinfo object for remote address obtained by getpeername. + * + * Note that addrinfo.protocol is filled by 0. + * + * TCPSocket.open("www.ruby-lang.org", 80) {|s| + * p s.remote_address #=> #<Addrinfo: 221.186.184.68:80 TCP> + * } + * + * TCPServer.open("127.0.0.1", 1728) {|serv| + * c = TCPSocket.new("127.0.0.1", 1728) + * s = serv.accept + * p s.remote_address #=> #<Addrinfo: 127.0.0.1:36504 TCP> + * } + * + */ +static VALUE +bsock_remote_address(VALUE sock) +{ + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + if (getpeername(fptr->fd, (struct sockaddr*)&buf, &len) < 0) + rb_sys_fail("getpeername(2)"); + return rsock_fd_socket_addrinfo(fptr->fd, (struct sockaddr *)&buf, len); +} + +/* + * call-seq: + * basicsocket.send(mesg, flags [, dest_sockaddr]) => numbytes_sent + * + * send _mesg_ via _basicsocket_. + * + * _mesg_ should be a string. + * + * _flags_ should be a bitwise OR of Socket::MSG_* constants. + * + * _dest_sockaddr_ should be a packed sockaddr string or an addrinfo. + * + * TCPSocket.open("localhost", 80) {|s| + * s.send "GET / HTTP/1.0\r\n\r\n", 0 + * p s.read + * } + */ +VALUE +rsock_bsock_send(int argc, VALUE *argv, VALUE sock) +{ + struct rsock_send_arg arg; + VALUE flags, to; + rb_io_t *fptr; + int n; + rb_blocking_function_t *func; + + rb_secure(4); + rb_scan_args(argc, argv, "21", &arg.mesg, &flags, &to); + + StringValue(arg.mesg); + if (!NIL_P(to)) { + SockAddrStringValue(to); + to = rb_str_new4(to); + arg.to = (struct sockaddr *)RSTRING_PTR(to); + arg.tolen = (socklen_t)RSTRING_LENINT(to); + func = rsock_sendto_blocking; + } + else { + func = rsock_send_blocking; + } + GetOpenFile(sock, fptr); + arg.fd = fptr->fd; + arg.flags = NUM2INT(flags); + while (rb_thread_fd_writable(arg.fd), + (n = (int)BLOCKING_REGION(func, &arg)) < 0) { + if (rb_io_wait_writable(arg.fd)) { + continue; + } + rb_sys_fail("send(2)"); + } + return INT2FIX(n); +} + +/* + * call-seq: + * basicsocket.do_not_reverse_lookup => true or false + * + * Gets the do_not_reverse_lookup flag of _basicsocket_. + * + * TCPSocket.open("www.ruby-lang.org", 80) {|sock| + * p sock.do_not_reverse_lookup #=> false + * p sock.peeraddr #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"] + * sock.do_not_reverse_lookup = true + * p sock.peeraddr #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"] + * } + */ +static VALUE +bsock_do_not_reverse_lookup(VALUE sock) +{ + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + return (fptr->mode & FMODE_NOREVLOOKUP) ? Qtrue : Qfalse; +} + +/* + * call-seq: + * basicsocket.do_not_reverse_lookup = bool + * + * Sets the do_not_reverse_lookup flag of _basicsocket_. + * + * BasicSocket.do_not_reverse_lookup = false + * p TCPSocket.new("127.0.0.1", 80).do_not_reverse_lookup #=> false + * BasicSocket.do_not_reverse_lookup = true + * p TCPSocket.new("127.0.0.1", 80).do_not_reverse_lookup #=> true + * + */ +static VALUE +bsock_do_not_reverse_lookup_set(VALUE sock, VALUE state) +{ + rb_io_t *fptr; + + rb_secure(4); + GetOpenFile(sock, fptr); + if (RTEST(state)) { + fptr->mode |= FMODE_NOREVLOOKUP; + } + else { + fptr->mode &= ~FMODE_NOREVLOOKUP; + } + return sock; +} + +/* + * call-seq: + * basicsocket.recv(maxlen) => mesg + * basicsocket.recv(maxlen, flags) => mesg + * + * Receives a message. + * + * _maxlen_ is the maximum number of bytes to receive. + * + * _flags_ should be a bitwise OR of Socket::MSG_* constants. + * + * UNIXSocket.pair {|s1, s2| + * s1.puts "Hello World" + * p s2.recv(4) #=> "Hell" + * p s2.recv(4, Socket::MSG_PEEK) #=> "o Wo" + * p s2.recv(4) #=> "o Wo" + * p s2.recv(10) #=> "rld\n" + * } + */ +static VALUE +bsock_recv(int argc, VALUE *argv, VALUE sock) +{ + return rsock_s_recvfrom(sock, argc, argv, RECV_RECV); +} + +/* + * call-seq: + * basicsocket.recv_nonblock(maxlen) => mesg + * basicsocket.recv_nonblock(maxlen, flags) => mesg + * + * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after + * O_NONBLOCK is set for the underlying file descriptor. + * _flags_ is zero or more of the +MSG_+ options. + * The result, _mesg_, is the data received. + * + * When recvfrom(2) returns 0, Socket#recv_nonblock returns + * an empty string as data. + * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc. + * + * === Parameters + * * +maxlen+ - the number of bytes to receive from the socket + * * +flags+ - zero or more of the +MSG_+ options + * + * === Example + * serv = TCPServer.new("127.0.0.1", 0) + * af, port, host, addr = serv.addr + * c = TCPSocket.new(addr, port) + * s = serv.accept + * c.send "aaa", 0 + * begin # emulate blocking recv. + * p s.recv_nonblock(10) #=> "aaa" + * rescue IO::WaitReadable + * IO.select([s]) + * retry + * end + * + * Refer to Socket#recvfrom for the exceptions that may be thrown if the call + * to _recv_nonblock_ fails. + * + * BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure, + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying recv_nonblock. + * + * === See + * * Socket#recvfrom + */ + +static VALUE +bsock_recv_nonblock(int argc, VALUE *argv, VALUE sock) +{ + return rsock_s_recvfrom_nonblock(sock, argc, argv, RECV_RECV); +} + +/* + * call-seq: + * BasicSocket.do_not_reverse_lookup => true or false + * + * Gets the global do_not_reverse_lookup flag. + * + * BasicSocket.do_not_reverse_lookup #=> false + */ +static VALUE +bsock_do_not_rev_lookup(void) +{ + return rsock_do_not_reverse_lookup?Qtrue:Qfalse; +} + +/* + * call-seq: + * BasicSocket.do_not_reverse_lookup = bool + * + * Sets the global do_not_reverse_lookup flag. + * + * The flag is used for initial value of do_not_reverse_lookup for each socket. + * + * s1 = TCPSocket.new("localhost", 80) + * p s1.do_not_reverse_lookup #=> true + * BasicSocket.do_not_reverse_lookup = false + * s2 = TCPSocket.new("localhost", 80) + * p s2.do_not_reverse_lookup #=> false + * p s1.do_not_reverse_lookup #=> true + * + */ +static VALUE +bsock_do_not_rev_lookup_set(VALUE self, VALUE val) +{ + rb_secure(4); + rsock_do_not_reverse_lookup = RTEST(val); + return val; +} + +/* + * BasicSocket is the super class for the all socket classes. + */ +void +rsock_init_basicsocket(void) +{ + rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO); + rb_undef_method(rb_cBasicSocket, "initialize"); + + rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup", + bsock_do_not_rev_lookup, 0); + rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup=", + bsock_do_not_rev_lookup_set, 1); + rb_define_singleton_method(rb_cBasicSocket, "for_fd", bsock_s_for_fd, 1); + + rb_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0); + rb_define_method(rb_cBasicSocket, "close_write", bsock_close_write, 0); + rb_define_method(rb_cBasicSocket, "shutdown", bsock_shutdown, -1); + rb_define_method(rb_cBasicSocket, "setsockopt", bsock_setsockopt, -1); + rb_define_method(rb_cBasicSocket, "getsockopt", bsock_getsockopt, 2); + rb_define_method(rb_cBasicSocket, "getsockname", bsock_getsockname, 0); + rb_define_method(rb_cBasicSocket, "getpeername", bsock_getpeername, 0); + rb_define_method(rb_cBasicSocket, "getpeereid", bsock_getpeereid, 0); + rb_define_method(rb_cBasicSocket, "local_address", bsock_local_address, 0); + rb_define_method(rb_cBasicSocket, "remote_address", bsock_remote_address, 0); + rb_define_method(rb_cBasicSocket, "send", rsock_bsock_send, -1); + rb_define_method(rb_cBasicSocket, "recv", bsock_recv, -1); + rb_define_method(rb_cBasicSocket, "recv_nonblock", bsock_recv_nonblock, -1); + rb_define_method(rb_cBasicSocket, "do_not_reverse_lookup", bsock_do_not_reverse_lookup, 0); + rb_define_method(rb_cBasicSocket, "do_not_reverse_lookup=", bsock_do_not_reverse_lookup_set, 1); + + rb_define_method(rb_cBasicSocket, "sendmsg", rsock_bsock_sendmsg, -1); /* in ancdata.c */ + rb_define_method(rb_cBasicSocket, "sendmsg_nonblock", rsock_bsock_sendmsg_nonblock, -1); /* in ancdata.c */ + rb_define_method(rb_cBasicSocket, "recvmsg", rsock_bsock_recvmsg, -1); /* in ancdata.c */ + rb_define_method(rb_cBasicSocket, "recvmsg_nonblock", rsock_bsock_recvmsg_nonblock, -1); /* in ancdata.c */ + +} diff --git a/ext/socket/constants.c b/ext/socket/constants.c new file mode 100644 index 0000000000..39f985b316 --- /dev/null +++ b/ext/socket/constants.c @@ -0,0 +1,145 @@ +/************************************************ + + constants.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +static VALUE rb_mSockConst; + +#include "constdefs.c" + +static int +constant_arg(VALUE arg, int (*str_to_int)(const char*, long, int*), const char *errmsg) +{ + VALUE tmp; + char *ptr; + int ret; + + if (SYMBOL_P(arg)) { + arg = rb_sym_to_s(arg); + goto str; + } + else if (!NIL_P(tmp = rb_check_string_type(arg))) { + arg = tmp; + str: + rb_check_safe_obj(arg); + ptr = RSTRING_PTR(arg); + if (str_to_int(ptr, RSTRING_LEN(arg), &ret) == -1) + rb_raise(rb_eSocket, "%s: %s", errmsg, ptr); + } + else { + ret = NUM2INT(arg); + } + return ret; +} + +int +rsock_family_arg(VALUE domain) +{ + /* convert AF_INET, etc. */ + return constant_arg(domain, rsock_family_to_int, "unknown socket domain"); +} + +int +rsock_socktype_arg(VALUE type) +{ + /* convert SOCK_STREAM, etc. */ + return constant_arg(type, rsock_socktype_to_int, "unknown socket type"); +} + +int +rsock_level_arg(int family, VALUE level) +{ + /* convert SOL_SOCKET, IPPROTO_TCP, etc. */ + if (IS_IP_FAMILY(family)) { + return constant_arg(level, rsock_ip_level_to_int, "unknown protocol level"); + } + else { + return constant_arg(level, rsock_unknown_level_to_int, "unknown protocol level"); + } +} + +int +rsock_optname_arg(int family, int level, VALUE optname) +{ + if (IS_IP_FAMILY(family)) { + switch (level) { + case SOL_SOCKET: + return constant_arg(optname, rsock_so_optname_to_int, "unknown socket level option name"); + case IPPROTO_IP: + return constant_arg(optname, rsock_ip_optname_to_int, "unknown IP level option name"); +#ifdef IPPROTO_IPV6 + case IPPROTO_IPV6: + return constant_arg(optname, rsock_ipv6_optname_to_int, "unknown IPv6 level option name"); +#endif + case IPPROTO_TCP: + return constant_arg(optname, rsock_tcp_optname_to_int, "unknown TCP level option name"); + case IPPROTO_UDP: + return constant_arg(optname, rsock_udp_optname_to_int, "unknown UDP level option name"); + default: + return NUM2INT(optname); + } + } + else { + switch (level) { + case SOL_SOCKET: + return constant_arg(optname, rsock_so_optname_to_int, "unknown socket level option name"); + default: + return NUM2INT(optname); + } + } +} + +int +rsock_cmsg_type_arg(int family, int level, VALUE type) +{ + if (IS_IP_FAMILY(family)) { + switch (level) { + case SOL_SOCKET: + return constant_arg(type, rsock_scm_optname_to_int, "unknown UNIX control message"); + case IPPROTO_IP: + return constant_arg(type, rsock_ip_optname_to_int, "unknown IP control message"); +#ifdef INET6 + case IPPROTO_IPV6: + return constant_arg(type, rsock_ipv6_optname_to_int, "unknown IPv6 control message"); +#endif + case IPPROTO_TCP: + return constant_arg(type, rsock_tcp_optname_to_int, "unknown TCP control message"); + case IPPROTO_UDP: + return constant_arg(type, rsock_udp_optname_to_int, "unknown UDP control message"); + default: + return NUM2INT(type); + } + } + else { + switch (level) { + case SOL_SOCKET: + return constant_arg(type, rsock_scm_optname_to_int, "unknown UNIX control message"); + default: + return NUM2INT(type); + } + } +} + +int +rsock_shutdown_how_arg(VALUE how) +{ + /* convert SHUT_RD, SHUT_WR, SHUT_RDWR. */ + return constant_arg(how, rsock_shutdown_how_to_int, "unknown shutdown argument"); +} + +/* + * Socket::Constants module + */ +void +rsock_init_socket_constants(void) +{ + /* constants */ + init_constants(); +} diff --git a/ext/socket/depend b/ext/socket/depend index cca6d4e62a..f870b9f834 100644 --- a/ext/socket/depend +++ b/ext/socket/depend @@ -1,3 +1,25 @@ -socket.o : socket.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h $(hdrdir)/rubyio.h $(hdrdir)/rubysig.h sockport.h -getnameinfo.o: getnameinfo.c $(topdir)/config.h addrinfo.h sockport.h -getaddrinfo.o: getaddrinfo.c $(topdir)/config.h addrinfo.h sockport.h +SOCK_HEADERS = $(srcdir)/rubysocket.h $(hdrdir)/ruby/ruby.h $(arch_hdrdir)/ruby/config.h \ + $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/io.h \ + $(srcdir)/addrinfo.h $(srcdir)/sockport.h constdefs.h + +init.o: init.c $(SOCK_HEADERS) +constants.o: constants.c constdefs.c $(SOCK_HEADERS) +basicsocket.o: basicsocket.c $(SOCK_HEADERS) +socket.o: socket.c $(SOCK_HEADERS) +ipsocket.o: ipsocket.c $(SOCK_HEADERS) +tcpsocket.o: tcpsocket.c $(SOCK_HEADERS) +tcpserver.o: tcpserver.c $(SOCK_HEADERS) +sockssocket.o: sockssocket.c $(SOCK_HEADERS) +udpsocket.o: udpsocket.c $(SOCK_HEADERS) +unixsocket.o: unixsocket.c $(SOCK_HEADERS) +unixserver.o: unixserver.c $(SOCK_HEADERS) +option.o: option.c $(SOCK_HEADERS) +ancdata.o: ancdata.c $(SOCK_HEADERS) +raddrinfo.o: raddrinfo.c $(SOCK_HEADERS) + +getnameinfo.o: getnameinfo.c $(arch_hdrdir)/ruby/config.h addrinfo.h sockport.h +getaddrinfo.o: getaddrinfo.c $(arch_hdrdir)/ruby/config.h addrinfo.h sockport.h + +constdefs.h constdefs.c : $(srcdir)/mkconstants.rb + @echo "generating constant definitions" + @$(RUBY) $(srcdir)/mkconstants.rb -H constdefs.h -o constdefs.c diff --git a/ext/socket/extconf.rb b/ext/socket/extconf.rb index 41b715e0af..92fa6bf7e1 100644 --- a/ext/socket/extconf.rb +++ b/ext/socket/extconf.rb @@ -1,22 +1,18 @@ require 'mkmf' case RUBY_PLATFORM -when /bccwin32/ +when /(ms|bcc)win32|mingw/ test_func = "WSACleanup" have_library("ws2_32", "WSACleanup") -when /mswin32|mingw/ - test_func = "WSACleanup" - if with_config("winsock2") - have_library("ws2_32", "WSACleanup") - else - have_library("wsock32", "WSACleanup") - end + $defs << "-DHAVE_SOCKETPAIR" when /cygwin/ test_func = "socket" when /beos/ test_func = "socket" have_library("net", "socket") - have_func("closesocket") +when /haiku/ + test_func = "socket" + have_library("network", "socket") when /i386-os2_emx/ test_func = "socket" have_library("socket", "socket") @@ -33,13 +29,19 @@ if /solaris/ =~ RUBY_PLATFORM and !try_compile("") # bug of gcc 3.0 on Solaris 8 ? headers << "sys/feature_tests.h" end +if have_header("arpa/inet.h") + headers << "arpa/inet.h" +end ipv6 = false -default_ipv6 = /cygwin/ !~ RUBY_PLATFORM +default_ipv6 = /mswin|cygwin|beos|haiku/ !~ RUBY_PLATFORM if enable_config("ipv6", default_ipv6) if checking_for("ipv6") {try_link(<<EOF)} #include <sys/types.h> +#ifndef _WIN32 #include <sys/socket.h> +#endif +int main() { socket(AF_INET6, SOCK_STREAM, 0); @@ -51,6 +53,9 @@ EOF end if ipv6 + if $mingw + $CPPFLAGS << " -D_WIN32_WINNT=0x501" + end ipv6lib = nil class << (fmt = "unknown") def %(s) s || self end @@ -91,33 +96,36 @@ if have_struct_member("struct sockaddr_in", "sin_len", headers) end # doug's fix, NOW add -Dss_family... only if required! -[nil, " -Dss_family=__ss_family -Dss_len=__ss_len"].each do |flags| - if flags - cppflags = $CPPFLAGS - $CPPFLAGS += flags - end - if have_struct_member("struct sockaddr_storage", "ss_family", headers) - $defs[-1] = "-DHAVE_SOCKADDR_STORAGE" - break - elsif flags - $CPPFLAGS = cppflags - end +doug = proc {have_struct_member("struct sockaddr_storage", "ss_family", headers)} +if (doug[] or + with_cppflags($CPPFLAGS + " -Dss_family=__ss_family", &doug)) + $defs[-1] = "-DHAVE_SOCKADDR_STORAGE" + doug = proc {have_struct_member("struct sockaddr_storage", "ss_len", headers)} + doug[] or with_cppflags($CPPFLAGS + " -Dss_len=__ss_len", &doug) end if have_struct_member("struct sockaddr", "sa_len", headers) $defs[-1] = "-DHAVE_SA_LEN " end -have_header("netinet/tcp.h") if not /cygwin/ =~ RUBY_PLATFORM # for cygwin 1.1.5 +have_header("netinet/tcp.h") if /cygwin/ !~ RUBY_PLATFORM # for cygwin 1.1.5 have_header("netinet/udp.h") +if !have_macro("IPPROTO_IPV6", headers) && have_const("IPPROTO_IPV6", headers) + IO.read(File.join(File.dirname(__FILE__), "mkconstants.rb")).sub(/\A.*^__END__$/m, '').split(/\r?\n/).grep(/\AIPPROTO_\w*/){$&}.each {|name| + have_const(name, headers) unless $defs.include?("-DHAVE_CONST_#{name.upcase}") + } +end + if have_func("sendmsg") | have_func("recvmsg") have_struct_member('struct msghdr', 'msg_control', ['sys/types.h', 'sys/socket.h']) have_struct_member('struct msghdr', 'msg_accrights', ['sys/types.h', 'sys/socket.h']) end -getaddr_info_ok = enable_config("wide-getaddrinfo") do - checking_for("wide getaddrinfo") {try_run(<<EOF)} +have_type("PADDRINFO", %w[ ws2tcpip.h wspiapi.h ]) + +getaddr_info_ok = (enable_config("wide-getaddrinfo") && :wide) || + (checking_for("wide getaddrinfo") {try_run(<<EOF)} && :os) #{cpp_include(headers)} #include <stdlib.h> @@ -132,11 +140,17 @@ getaddr_info_ok = enable_config("wide-getaddrinfo") do #define AF_LOCAL AF_UNIX #endif +int main() { int passive, gaierr, inet4 = 0, inet6 = 0; struct addrinfo hints, *ai, *aitop; char straddr[INET6_ADDRSTRLEN], strport[16]; +#ifdef _WIN32 + WSADATA retdata; + + WSAStartup(MAKEWORD(2, 0), &retdata); +#endif for (passive = 0; passive <= 1; passive++) { memset(&hints, 0, sizeof(hints)); @@ -153,6 +167,10 @@ main() if (ai->ai_addr == NULL) goto bad; #if defined(_AIX) + if (ai->ai_family == AF_INET6 && passive) { + inet6++; + continue; + } ai->ai_addr->sa_len = ai->ai_addrlen; ai->ai_addr->sa_family = ai->ai_family; #endif @@ -215,7 +233,6 @@ main() exit(EXIT_FAILURE); } EOF -end if ipv6 and not getaddr_info_ok abort <<EOS @@ -240,34 +257,100 @@ Fatal: invalid value for --with-lookup-order-hack (expected INET, INET6 or UNSPE EOS end -$objs = ["socket.#{$OBJEXT}"] +have_type("struct addrinfo", headers) +have_func("freehostent") +have_func("freeaddrinfo") +if /haiku/ !~ RUBY_PLATFORM and have_func("gai_strerror") + if checking_for("gai_strerror() returns const pointer") {!try_compile(<<EOF)} +#{cpp_include(headers)} +#include <stdlib.h> +void +conftest_gai_strerror_is_const() +{ + *gai_strerror(0) = 0; +} +EOF + $defs << "-DGAI_STRERROR_CONST" + end +end -unless getaddr_info_ok and have_func("getnameinfo", "netdb.h") and have_func("getaddrinfo", "netdb.h") +$objs = [ + "init.#{$OBJEXT}", + "constants.#{$OBJEXT}", + "basicsocket.#{$OBJEXT}", + "socket.#{$OBJEXT}", + "ipsocket.#{$OBJEXT}", + "tcpsocket.#{$OBJEXT}", + "tcpserver.#{$OBJEXT}", + "sockssocket.#{$OBJEXT}", + "udpsocket.#{$OBJEXT}", + "unixsocket.#{$OBJEXT}", + "unixserver.#{$OBJEXT}", + "option.#{$OBJEXT}", + "ancdata.#{$OBJEXT}", + "raddrinfo.#{$OBJEXT}" +] + +if getaddr_info_ok == :wide or + !have_func("getnameinfo", headers) or !have_func("getaddrinfo", headers) if have_struct_member("struct in6_addr", "s6_addr8", headers) - $defs[-1] = "-DHAVE_ADDR8" + $defs[-1] = "s6_addr=s6_addr8" + end + if ipv6 == "kame" && have_struct_member("struct in6_addr", "s6_addr32", headers) + $defs[-1] = "-DFAITH" end $CPPFLAGS="-I. "+$CPPFLAGS $objs += ["getaddrinfo.#{$OBJEXT}"] $objs += ["getnameinfo.#{$OBJEXT}"] + $defs << "-DGETADDRINFO_EMU" have_func("inet_ntop") or have_func("inet_ntoa") have_func("inet_pton") or have_func("inet_aton") have_func("getservbyport") - have_header("arpa/inet.h") have_header("arpa/nameser.h") have_header("resolv.h") end +have_header("ifaddrs.h") +have_func("getifaddrs") +have_header("sys/ioctl.h") +have_header("sys/sockio.h") +have_header("net/if.h", headers) + +have_header("sys/param.h", headers) +have_header("sys/ucred.h", headers) + unless have_type("socklen_t", headers) $defs << "-Dsocklen_t=int" end have_header("sys/un.h") have_header("sys/uio.h") +have_type("struct in_pktinfo", headers) {|src| + src.sub(%r'^/\*top\*/', '\1'"\n#if defined(IPPROTO_IP) && defined(IP_PKTINFO)") << + "#else\n" << "#error\n" << ">>>>>> no in_pktinfo <<<<<<\n" << "#endif\n" +} and have_struct_member("struct in_pktinfo", "ipi_spec_dst", headers) +have_type("struct in6_pktinfo", headers) {|src| + src.sub(%r'^/\*top\*/', '\1'"\n#if defined(IPPROTO_IPV6) && defined(IPV6_PKTINFO)") << + "#else\n" << "#error\n" << ">>>>>> no in6_pktinfo <<<<<<\n" << "#endif\n" +} + +have_type("struct sockcred", headers) +have_type("struct cmsgcred", headers) + +have_func("getpeereid") + +have_header("ucred.h", headers) +have_func("getpeerucred") + +# workaround for recent Windows SDK +$defs << "-DIPPROTO_IPV6=IPPROTO_IPV6" if $defs.include?("-DHAVE_CONST_IPPROTO_IPV6") && !have_macro("IPPROTO_IPV6") + +$distcleanfiles << "constants.h" << "constdefs.*" if have_func(test_func) have_func("hsterror") have_func("getipnodebyname") or have_func("gethostbyname2") - have_func("socketpair") + have_func("socketpair") unless $defs.include?("-DHAVE_SOCKETPAIR") unless have_func("gethostname") have_func("uname") end diff --git a/ext/socket/getaddrinfo.c b/ext/socket/getaddrinfo.c index 9fb4ebcb06..3382f00e52 100644 --- a/ext/socket/getaddrinfo.c +++ b/ext/socket/getaddrinfo.c @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -38,11 +38,14 @@ * - PF_UNSPEC case would be handled in getipnodebyname() with the AI_ALL flag. */ -#include "config.h" +#include "ruby/config.h" +#ifdef RUBY_EXTCONF_H +#include RUBY_EXTCONF_H +#endif #include <sys/types.h> -#if !defined(_WIN32) && !defined(__VMS) +#ifndef _WIN32 #include <sys/param.h> -#if defined(__BEOS__) +#if defined(__BEOS__) && !defined(__HAIKU__) && !defined(BONE) # include <net/socket.h> #else # include <sys/socket.h> @@ -62,13 +65,9 @@ #include <resolv.h> #endif #include <unistd.h> -#elif defined(__VMS ) -#include <socket.h> -#include <inet.h> -#include <in.h> -#include <netdb.h> #else #include <winsock2.h> +#include <ws2tcpip.h> #include <io.h> #endif #include <string.h> @@ -84,10 +83,6 @@ #include "addrinfo.h" #include "sockport.h" -#if defined(__KAME__) && defined(INET6) -# define FAITH -#endif - #define SUCCESS 0 #define ANY 0 #define YES 1 @@ -102,7 +97,7 @@ static const char in_addrany[] = { 0, 0, 0, 0 }; static const char in6_addrany[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -static const char in_loopback[] = { 127, 0, 0, 1 }; +static const char in_loopback[] = { 127, 0, 0, 1 }; static const char in6_loopback[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; @@ -119,7 +114,7 @@ static const struct afd { int a_socklen; int a_off; const char *a_addrany; - const char *a_loopback; + const char *a_loopback; } afdl [] = { #ifdef INET6 #define N_INET6 0 @@ -150,7 +145,7 @@ static int get_name __P((const char *, const struct afd *, static int get_addr __P((const char *, int, struct addrinfo **, struct addrinfo *, int)); static int str_isnumber __P((const char *)); - + static const char *const ai_errlist[] = { "success.", "address family for hostname not supported.", /* EAI_ADDRFAMILY */ @@ -199,21 +194,21 @@ if (pai->ai_flags & AI_CANONNAME) {\ #define ERR(err) { error = (err); goto bad; } -#if defined __UCLIBC__ +#ifndef HAVE_GAI_STRERROR +#ifdef GAI_STRERROR_CONST const #endif char * -gai_strerror(ecode) - int ecode; +gai_strerror(int ecode) { if (ecode < 0 || ecode > EAI_MAX) ecode = EAI_MAX; return (char *)ai_errlist[ecode]; } +#endif void -freeaddrinfo(ai) - struct addrinfo *ai; +freeaddrinfo(struct addrinfo *ai) { struct addrinfo *next; @@ -227,8 +222,7 @@ freeaddrinfo(ai) } static int -str_isnumber(p) - const char *p; +str_isnumber(const char *p) { char *q = (char *)p; while (*q) { @@ -242,10 +236,7 @@ str_isnumber(p) #ifndef HAVE_INET_PTON static int -inet_pton(af, hostname, pton) - int af; - const char *hostname; - void *pton; +inet_pton(int af, const char *hostname, void *pton) { struct in_addr in; @@ -273,10 +264,7 @@ inet_pton(af, hostname, pton) #endif int -getaddrinfo(hostname, servname, hints, res) - const char *hostname, *servname; - const struct addrinfo *hints; - struct addrinfo **res; +getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { struct addrinfo sentinel; struct addrinfo *top = NULL; @@ -314,7 +302,7 @@ getaddrinfo(hostname, servname, hints, res) pai->ai_addr = NULL; pai->ai_next = NULL; port = ANY; - + if (hostname == NULL && servname == NULL) return EAI_NONAME; if (hints) { @@ -386,9 +374,11 @@ getaddrinfo(hostname, servname, hints, res) pai->ai_protocol = IPPROTO_UDP; } port = htons((unsigned short)atoi(servname)); + } else if (pai->ai_flags & AI_NUMERICSERV) { + ERR(EAI_NONAME); } else { struct servent *sp; - char *proto; + const char *proto; proto = NULL; switch (pai->ai_socktype) { @@ -419,7 +409,7 @@ getaddrinfo(hostname, servname, hints, res) ERR(EAI_PROTOCOL); /*xxx*/ } } - + /* * hostname == NULL. * passive socket -> anyaddr (0.0.0.0 or ::) @@ -442,7 +432,7 @@ getaddrinfo(hostname, servname, hints, res) s = socket(afd->a_af, SOCK_DGRAM, 0); if (s < 0) continue; -#if defined(HAVE_CLOSESOCKET) +#if defined(__BEOS__) closesocket(s); #else close(s); @@ -468,7 +458,7 @@ getaddrinfo(hostname, servname, hints, res) else ERR(EAI_FAMILY); } - + /* hostname as numeric name */ for (i = 0; afdl[i].a_af; i++) { if (inet_pton(afdl[i].a_af, hostname, pton)) { @@ -488,17 +478,13 @@ getaddrinfo(hostname, servname, hints, res) break; #ifdef INET6 case AF_INET6: -#ifdef HAVE_ADDR8 - pfx = ((struct in6_addr *)pton)->s6_addr8[0]; -#else pfx = ((struct in6_addr *)pton)->s6_addr[0]; -#endif if (pfx == 0 || pfx == 0xfe || pfx == 0xff) pai->ai_flags &= ~AI_CANONNAME; break; #endif } - + if (pai->ai_family == afdl[i].a_af || pai->ai_family == PF_UNSPEC) { if (! (pai->ai_flags & AI_CANONNAME)) { @@ -516,7 +502,7 @@ getaddrinfo(hostname, servname, hints, res) */ get_name(pton, &afdl[i], &top, pton, pai, port); goto good; - } else + } else ERR(EAI_FAMILY); /*xxx*/ } } @@ -543,13 +529,7 @@ getaddrinfo(hostname, servname, hints, res) } static int -get_name(addr, afd, res, numaddr, pai, port0) - const char *addr; - const struct afd *afd; - struct addrinfo **res; - char *numaddr; - struct addrinfo *pai; - int port0; +get_name(const char *addr, const struct afd *afd, struct addrinfo **res, char *numaddr, struct addrinfo *pai, int port0) { u_short port = port0 & 0xffff; struct hostent *hp; @@ -569,7 +549,7 @@ get_name(addr, afd, res, numaddr, pai, port0) GET_CANONNAME(cur, hp->h_name); } else GET_AI(cur, afd, numaddr, port); - + #ifdef INET6 if (hp) freehostent(hp); @@ -589,12 +569,7 @@ get_name(addr, afd, res, numaddr, pai, port0) } static int -get_addr(hostname, af, res, pai, port0) - const char *hostname; - int af; - struct addrinfo **res; - struct addrinfo *pai; - int port0; +get_addr(const char *hostname, int af, struct addrinfo **res, struct addrinfo *pai, int port0) { u_short port = port0 & 0xffff; struct addrinfo sentinel; @@ -637,7 +612,7 @@ get_addr(hostname, af, res, pai, port0) if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || (hp->h_addr_list[0] == NULL)) ERR(EAI_FAIL); - + for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { switch (af) { #ifdef INET6 @@ -668,9 +643,10 @@ get_addr(hostname, af, res, pai, port0) GET_AI(cur->ai_next, &afdl[N_INET6], ap, port); in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr32[0], &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); + memcpy(&in6->s6_addr, &faith_prefix, + sizeof(struct in6_addr) - sizeof(struct in_addr)); + memcpy(&in6->s6_addr + sizeof(struct in_addr), ap, + sizeof(struct in_addr)); } else #endif /* FAITH */ GET_AI(cur->ai_next, afd, ap, port); diff --git a/ext/socket/getnameinfo.c b/ext/socket/getnameinfo.c index 66f7e8818a..3ee83eb2a0 100644 --- a/ext/socket/getnameinfo.c +++ b/ext/socket/getnameinfo.c @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -34,11 +34,14 @@ * but INRIA implementation returns EAI_xxx defined for getaddrinfo(). */ -#include "config.h" +#include "ruby/config.h" +#ifdef RUBY_EXTCONF_H +#include RUBY_EXTCONF_H +#endif #include <stdio.h> #include <sys/types.h> #ifndef _WIN32 -#if defined(__BEOS__) +#if defined(__BEOS__) && !defined(__HAIKU__) && !defined(BONE) # include <net/socket.h> #else # include <sys/socket.h> @@ -57,6 +60,7 @@ #endif #ifdef _WIN32 #include <winsock2.h> +#include <ws2tcpip.h> #define snprintf _snprintf #endif @@ -110,13 +114,12 @@ static struct afd { #define ENI_FAMILY 5 #define ENI_SALEN 6 +#ifdef __HAIKU__ +#define HAVE_INET_NTOP +#endif #ifndef HAVE_INET_NTOP static const char * -inet_ntop(af, addr, numaddr, numaddr_len) - int af; - const void *addr; - char *numaddr; - size_t numaddr_len; +inet_ntop(int af, const void *addr, char *numaddr, size_t numaddr_len) { #ifdef HAVE_INET_NTOA struct in_addr in; @@ -133,17 +136,9 @@ inet_ntop(af, addr, numaddr, numaddr_len) #endif int -getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - size_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; +getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags) { struct afd *afd; - struct servent *sp; struct hostent *hp; u_short port; int family, len, i; @@ -161,7 +156,7 @@ getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) len = SA_LEN(sa); if (len != salen) return ENI_SALEN; - + family = sa->sa_family; for (i = 0; afdl[i].a_af; i++) if (afdl[i].a_af == family) { @@ -169,10 +164,10 @@ getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) goto found; } return ENI_FAMILY; - + found: if (len != afd->a_socklen) return ENI_SALEN; - + port = ((struct sockinet *)sa)->si_port; /* network byte order */ addr = (char *)sa + afd->a_off; @@ -185,7 +180,7 @@ getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) strcpy(serv, numserv); } else { #if defined(HAVE_GETSERVBYPORT) - sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); + struct servent *sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); if (sp) { if (strlen(sp->s_name) + 1 > servlen) return ENI_MEMORY; @@ -204,7 +199,7 @@ getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) flags |= NI_NUMERICHOST; v4a >>= IN_CLASSA_NSHIFT; if (v4a == 0) - flags |= NI_NUMERICHOST; + flags |= NI_NUMERICHOST; break; #ifdef INET6 case AF_INET6: diff --git a/ext/socket/init.c b/ext/socket/init.c new file mode 100644 index 0000000000..48718313f0 --- /dev/null +++ b/ext/socket/init.c @@ -0,0 +1,575 @@ +/************************************************ + + init.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +VALUE rb_cBasicSocket; +VALUE rb_cIPSocket; +VALUE rb_cTCPSocket; +VALUE rb_cTCPServer; +VALUE rb_cUDPSocket; +#ifdef AF_UNIX +VALUE rb_cUNIXSocket; +VALUE rb_cUNIXServer; +#endif +VALUE rb_cSocket; +VALUE rb_cAddrinfo; + +VALUE rb_eSocket; + +#ifdef SOCKS +VALUE rb_cSOCKSSocket; +#endif + +int rsock_do_not_reverse_lookup = 1; + +void +rsock_raise_socket_error(const char *reason, int error) +{ +#ifdef EAI_SYSTEM + if (error == EAI_SYSTEM) rb_sys_fail(reason); +#endif + rb_raise(rb_eSocket, "%s: %s", reason, gai_strerror(error)); +} + +VALUE +rsock_init_sock(VALUE sock, int fd) +{ + rb_io_t *fp; + struct stat sbuf; + +#ifndef _WIN32 + if (fstat(fd, &sbuf) < 0) + rb_sys_fail(0); + if (!S_ISSOCK(sbuf.st_mode)) + rb_raise(rb_eArgError, "not a socket file descriptor"); +#else + if (!rb_w32_is_socket(fd)) + rb_raise(rb_eArgError, "not a socket file descriptor"); +#endif + + MakeOpenFile(sock, fp); + fp->fd = fd; + fp->mode = FMODE_READWRITE|FMODE_DUPLEX; + rb_io_ascii8bit_binmode(sock); + if (rsock_do_not_reverse_lookup) { + fp->mode |= FMODE_NOREVLOOKUP; + } + rb_io_synchronized(fp); + + return sock; +} + +VALUE +rsock_sendto_blocking(void *data) +{ + struct rsock_send_arg *arg = data; + VALUE mesg = arg->mesg; + return (VALUE)sendto(arg->fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), + arg->flags, arg->to, arg->tolen); +} + +VALUE +rsock_send_blocking(void *data) +{ + struct rsock_send_arg *arg = data; + VALUE mesg = arg->mesg; + return (VALUE)send(arg->fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), + arg->flags); +} + +struct recvfrom_arg { + int fd, flags; + VALUE str; + socklen_t alen; + struct sockaddr_storage buf; +}; + +static VALUE +recvfrom_blocking(void *data) +{ + struct recvfrom_arg *arg = data; + return (VALUE)recvfrom(arg->fd, RSTRING_PTR(arg->str), RSTRING_LEN(arg->str), + arg->flags, (struct sockaddr*)&arg->buf, &arg->alen); +} + +VALUE +rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from) +{ + rb_io_t *fptr; + VALUE str, klass; + struct recvfrom_arg arg; + VALUE len, flg; + long buflen; + long slen; + + rb_scan_args(argc, argv, "11", &len, &flg); + + if (flg == Qnil) arg.flags = 0; + else arg.flags = NUM2INT(flg); + buflen = NUM2INT(len); + + GetOpenFile(sock, fptr); + if (rb_io_read_pending(fptr)) { + rb_raise(rb_eIOError, "recv for buffered IO"); + } + arg.fd = fptr->fd; + arg.alen = (socklen_t)sizeof(arg.buf); + + arg.str = str = rb_tainted_str_new(0, buflen); + klass = RBASIC(str)->klass; + RBASIC(str)->klass = 0; + + while (rb_io_check_closed(fptr), + rb_thread_wait_fd(arg.fd), + (slen = BLOCKING_REGION(recvfrom_blocking, &arg)) < 0) { + if (!rb_io_wait_readable(fptr->fd)) { + rb_sys_fail("recvfrom(2)"); + } + if (RBASIC(str)->klass || RSTRING_LEN(str) != buflen) { + rb_raise(rb_eRuntimeError, "buffer string modified"); + } + } + + RBASIC(str)->klass = klass; + if (slen < RSTRING_LEN(str)) { + rb_str_set_len(str, slen); + } + rb_obj_taint(str); + switch (from) { + case RECV_RECV: + return str; + case RECV_IP: +#if 0 + if (arg.alen != sizeof(struct sockaddr_in)) { + rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); + } +#endif + if (arg.alen && arg.alen != sizeof(arg.buf)) /* OSX doesn't return a from result for connection-oriented sockets */ + return rb_assoc_new(str, rsock_ipaddr((struct sockaddr*)&arg.buf, fptr->mode & FMODE_NOREVLOOKUP)); + else + return rb_assoc_new(str, Qnil); + +#ifdef HAVE_SYS_UN_H + case RECV_UNIX: + return rb_assoc_new(str, rsock_unixaddr((struct sockaddr_un*)&arg.buf, arg.alen)); +#endif + case RECV_SOCKET: + return rb_assoc_new(str, rsock_io_socket_addrinfo(sock, (struct sockaddr*)&arg.buf, arg.alen)); + default: + rb_bug("rsock_s_recvfrom called with bad value"); + } +} + +VALUE +rsock_s_recvfrom_nonblock(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from) +{ + rb_io_t *fptr; + VALUE str; + struct sockaddr_storage buf; + socklen_t alen = (socklen_t)sizeof buf; + VALUE len, flg; + long buflen; + long slen; + int fd, flags; + VALUE addr = Qnil; + + rb_scan_args(argc, argv, "11", &len, &flg); + + if (flg == Qnil) flags = 0; + else flags = NUM2INT(flg); + buflen = NUM2INT(len); + +#ifdef MSG_DONTWAIT + /* MSG_DONTWAIT avoids the race condition between fcntl and recvfrom. + It is not portable, though. */ + flags |= MSG_DONTWAIT; +#endif + + GetOpenFile(sock, fptr); + if (rb_io_read_pending(fptr)) { + rb_raise(rb_eIOError, "recvfrom for buffered IO"); + } + fd = fptr->fd; + + str = rb_tainted_str_new(0, buflen); + + rb_io_check_closed(fptr); + rb_io_set_nonblock(fptr); + slen = recvfrom(fd, RSTRING_PTR(str), buflen, flags, (struct sockaddr*)&buf, &alen); + + if (slen < 0) { + switch (errno) { + case EAGAIN: +#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + rb_mod_sys_fail(rb_mWaitReadable, "recvfrom(2) would block"); + } + rb_sys_fail("recvfrom(2)"); + } + if (slen < RSTRING_LEN(str)) { + rb_str_set_len(str, slen); + } + rb_obj_taint(str); + switch (from) { + case RECV_RECV: + return str; + + case RECV_IP: + if (alen && alen != sizeof(buf)) /* connection-oriented socket may not return a from result */ + addr = rsock_ipaddr((struct sockaddr*)&buf, fptr->mode & FMODE_NOREVLOOKUP); + break; + + case RECV_SOCKET: + addr = rsock_io_socket_addrinfo(sock, (struct sockaddr*)&buf, alen); + break; + + default: + rb_bug("rsock_s_recvfrom_nonblock called with bad value"); + } + return rb_assoc_new(str, addr); +} + +int +rsock_socket(int domain, int type, int proto) +{ + int fd; + + fd = socket(domain, type, proto); + if (fd < 0) { + if (errno == EMFILE || errno == ENFILE) { + rb_gc(); + fd = socket(domain, type, proto); + } + } + return fd; +} + +static int +wait_connectable0(int fd, rb_fdset_t *fds_w, rb_fdset_t *fds_e) +{ + int sockerr; + socklen_t sockerrlen; + + for (;;) { + rb_fd_zero(fds_w); + rb_fd_zero(fds_e); + + rb_fd_set(fd, fds_w); + rb_fd_set(fd, fds_e); + + rb_thread_select(fd+1, 0, rb_fd_ptr(fds_w), rb_fd_ptr(fds_e), 0); + + if (rb_fd_isset(fd, fds_w)) { + return 0; + } + else if (rb_fd_isset(fd, fds_e)) { + sockerrlen = (socklen_t)sizeof(sockerr); + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, + &sockerrlen) == 0) { + if (sockerr == 0) + continue; /* workaround for winsock */ + errno = sockerr; + } + return -1; + } + } +} + +struct wait_connectable_arg { + int fd; + rb_fdset_t fds_w; + rb_fdset_t fds_e; +}; + +#ifdef HAVE_RB_FD_INIT +static VALUE +try_wait_connectable(VALUE arg) +{ + struct wait_connectable_arg *p = (struct wait_connectable_arg *)arg; + return (VALUE)wait_connectable0(p->fd, &p->fds_w, &p->fds_e); +} + +static VALUE +wait_connectable_ensure(VALUE arg) +{ + struct wait_connectable_arg *p = (struct wait_connectable_arg *)arg; + rb_fd_term(&p->fds_w); + rb_fd_term(&p->fds_e); + return Qnil; +} +#endif + +static int +wait_connectable(int fd) +{ + struct wait_connectable_arg arg; + + rb_fd_init(&arg.fds_w); + rb_fd_init(&arg.fds_e); +#ifdef HAVE_RB_FD_INIT + arg.fd = fd; + return (int)rb_ensure(try_wait_connectable, (VALUE)&arg, + wait_connectable_ensure,(VALUE)&arg); +#else + return wait_connectable0(fd, &arg.fds_w, &arg.fds_e); +#endif +} + +#ifdef __CYGWIN__ +#define WAIT_IN_PROGRESS 10 +#endif +#ifdef __APPLE__ +#define WAIT_IN_PROGRESS 10 +#endif +#ifdef __linux__ +/* returns correct error */ +#define WAIT_IN_PROGRESS 0 +#endif +#ifndef WAIT_IN_PROGRESS +/* BSD origin code apparently has a problem */ +#define WAIT_IN_PROGRESS 1 +#endif + +struct connect_arg { + int fd; + const struct sockaddr *sockaddr; + socklen_t len; +}; + +static VALUE +connect_blocking(void *data) +{ + struct connect_arg *arg = data; + return (VALUE)connect(arg->fd, arg->sockaddr, arg->len); +} + +#if defined(SOCKS) && !defined(SOCKS5) +static VALUE +socks_connect_blocking(void *data) +{ + struct connect_arg *arg = data; + return (VALUE)Rconnect(arg->fd, arg->sockaddr, arg->len); +} +#endif + +int +rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks) +{ + int status; + rb_blocking_function_t *func = connect_blocking; + struct connect_arg arg; +#if WAIT_IN_PROGRESS > 0 + int wait_in_progress = -1; + int sockerr; + socklen_t sockerrlen; +#endif + + arg.fd = fd; + arg.sockaddr = sockaddr; + arg.len = len; +#if defined(SOCKS) && !defined(SOCKS5) + if (socks) func = socks_connect_blocking; +#endif + for (;;) { + status = (int)BLOCKING_REGION(func, &arg); + if (status < 0) { + switch (errno) { + case EINTR: +#if defined(ERESTART) + case ERESTART: +#endif + continue; + + case EAGAIN: +#ifdef EINPROGRESS + case EINPROGRESS: +#endif +#if WAIT_IN_PROGRESS > 0 + sockerrlen = (socklen_t)sizeof(sockerr); + status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen); + if (status) break; + if (sockerr) { + status = -1; + errno = sockerr; + break; + } +#endif +#ifdef EALREADY + case EALREADY: +#endif +#if WAIT_IN_PROGRESS > 0 + wait_in_progress = WAIT_IN_PROGRESS; +#endif + status = wait_connectable(fd); + if (status) { + break; + } + errno = 0; + continue; + +#if WAIT_IN_PROGRESS > 0 + case EINVAL: + if (wait_in_progress-- > 0) { + /* + * connect() after EINPROGRESS returns EINVAL on + * some platforms, need to check true error + * status. + */ + sockerrlen = (socklen_t)sizeof(sockerr); + status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen); + if (!status && !sockerr) { + struct timeval tv = {0, 100000}; + rb_thread_wait_for(tv); + continue; + } + status = -1; + errno = sockerr; + } + break; +#endif + +#ifdef EISCONN + case EISCONN: + status = 0; + errno = 0; + break; +#endif + default: + break; + } + } + return status; + } +} + +static void +make_fd_nonblock(int fd) +{ + int flags; +#ifdef F_GETFL + flags = fcntl(fd, F_GETFL); + if (flags == -1) { + rb_sys_fail(0); + } +#else + flags = 0; +#endif + flags |= O_NONBLOCK; + if (fcntl(fd, F_SETFL, flags) == -1) { + rb_sys_fail(0); + } +} + +VALUE +rsock_s_accept_nonblock(VALUE klass, rb_io_t *fptr, struct sockaddr *sockaddr, socklen_t *len) +{ + int fd2; + + rb_secure(3); + rb_io_set_nonblock(fptr); + fd2 = accept(fptr->fd, (struct sockaddr*)sockaddr, len); + if (fd2 < 0) { + switch (errno) { + case EAGAIN: +#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + case ECONNABORTED: +#if defined EPROTO + case EPROTO: +#endif + rb_mod_sys_fail(rb_mWaitReadable, "accept(2) would block"); + } + rb_sys_fail("accept(2)"); + } + make_fd_nonblock(fd2); + return rsock_init_sock(rb_obj_alloc(klass), fd2); +} + +struct accept_arg { + int fd; + struct sockaddr *sockaddr; + socklen_t *len; +}; + +static VALUE +accept_blocking(void *data) +{ + struct accept_arg *arg = data; + return (VALUE)accept(arg->fd, arg->sockaddr, arg->len); +} + +VALUE +rsock_s_accept(VALUE klass, int fd, struct sockaddr *sockaddr, socklen_t *len) +{ + int fd2; + int retry = 0; + struct accept_arg arg; + + rb_secure(3); + arg.fd = fd; + arg.sockaddr = sockaddr; + arg.len = len; + retry: + rb_thread_wait_fd(fd); + fd2 = (int)BLOCKING_REGION(accept_blocking, &arg); + if (fd2 < 0) { + switch (errno) { + case EMFILE: + case ENFILE: + if (retry) break; + rb_gc(); + retry = 1; + goto retry; + default: + if (!rb_io_wait_readable(fd)) break; + retry = 0; + goto retry; + } + rb_sys_fail(0); + } + if (!klass) return INT2NUM(fd2); + return rsock_init_sock(rb_obj_alloc(klass), fd2); +} + +int +rsock_getfamily(int sockfd) +{ + struct sockaddr_storage ss; + socklen_t sslen = (socklen_t)sizeof(ss); + + ss.ss_family = AF_UNSPEC; + if (getsockname(sockfd, (struct sockaddr*)&ss, &sslen) < 0) + return AF_UNSPEC; + + return ss.ss_family; +} + +/* + * SocketError is the error class for socket. + */ +void +rsock_init_socket_init() +{ + rb_eSocket = rb_define_class("SocketError", rb_eStandardError); + rsock_init_ipsocket(); + rsock_init_tcpsocket(); + rsock_init_tcpserver(); + rsock_init_sockssocket(); + rsock_init_udpsocket(); + rsock_init_unixsocket(); + rsock_init_unixserver(); + rsock_init_sockopt(); + rsock_init_ancdata(); + rsock_init_addrinfo(); + rsock_init_socket_constants(); +} diff --git a/ext/socket/ipsocket.c b/ext/socket/ipsocket.c new file mode 100644 index 0000000000..dd7eb80b55 --- /dev/null +++ b/ext/socket/ipsocket.c @@ -0,0 +1,308 @@ +/************************************************ + + ipsocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +struct inetsock_arg +{ + VALUE sock; + struct { + VALUE host, serv; + struct addrinfo *res; + } remote, local; + int type; + int fd; +}; + +static VALUE +inetsock_cleanup(struct inetsock_arg *arg) +{ + if (arg->remote.res) { + freeaddrinfo(arg->remote.res); + arg->remote.res = 0; + } + if (arg->local.res) { + freeaddrinfo(arg->local.res); + arg->local.res = 0; + } + if (arg->fd >= 0) { + close(arg->fd); + } + return Qnil; +} + +static VALUE +init_inetsock_internal(struct inetsock_arg *arg) +{ + int type = arg->type; + struct addrinfo *res; + int fd, status = 0; + const char *syscall = 0; + + arg->remote.res = rsock_addrinfo(arg->remote.host, arg->remote.serv, SOCK_STREAM, + (type == INET_SERVER) ? AI_PASSIVE : 0); + /* + * Maybe also accept a local address + */ + + if (type != INET_SERVER && (!NIL_P(arg->local.host) || !NIL_P(arg->local.serv))) { + arg->local.res = rsock_addrinfo(arg->local.host, arg->local.serv, SOCK_STREAM, 0); + } + + arg->fd = fd = -1; + for (res = arg->remote.res; res; res = res->ai_next) { +#if !defined(INET6) && defined(AF_INET6) + if (res->ai_family == AF_INET6) + continue; +#endif + status = rsock_socket(res->ai_family,res->ai_socktype,res->ai_protocol); + syscall = "socket(2)"; + fd = status; + if (fd < 0) { + continue; + } + arg->fd = fd; + if (type == INET_SERVER) { +#if !defined(_WIN32) && !defined(__CYGWIN__) + status = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, + (char*)&status, (socklen_t)sizeof(status)); +#endif + status = bind(fd, res->ai_addr, res->ai_addrlen); + syscall = "bind(2)"; + } + else { + if (arg->local.res) { + status = bind(fd, arg->local.res->ai_addr, arg->local.res->ai_addrlen); + syscall = "bind(2)"; + } + + if (status >= 0) { + status = rsock_connect(fd, res->ai_addr, res->ai_addrlen, + (type == INET_SOCKS)); + syscall = "connect(2)"; + } + } + + if (status < 0) { + close(fd); + arg->fd = fd = -1; + continue; + } else + break; + } + if (status < 0) { + rb_sys_fail(syscall); + } + + arg->fd = -1; + + if (type == INET_SERVER) { + status = listen(fd, 5); + if (status < 0) { + close(fd); + syscall = "listen(2)"; + } + } + + /* create new instance */ + return rsock_init_sock(arg->sock, fd); +} + +VALUE +rsock_init_inetsock(VALUE sock, VALUE remote_host, VALUE remote_serv, + VALUE local_host, VALUE local_serv, int type) +{ + struct inetsock_arg arg; + arg.sock = sock; + arg.remote.host = remote_host; + arg.remote.serv = remote_serv; + arg.remote.res = 0; + arg.local.host = local_host; + arg.local.serv = local_serv; + arg.local.res = 0; + arg.type = type; + arg.fd = -1; + return rb_ensure(init_inetsock_internal, (VALUE)&arg, + inetsock_cleanup, (VALUE)&arg); +} + +static ID id_numeric, id_hostname; + +int +rsock_revlookup_flag(VALUE revlookup, int *norevlookup) +{ +#define return_norevlookup(x) {*norevlookup = x; return 1;} + ID id; + + switch (revlookup) { + case Qtrue: return_norevlookup(0); + case Qfalse: return_norevlookup(1); + case Qnil: break; + default: + Check_Type(revlookup, T_SYMBOL); + id = SYM2ID(revlookup); + if (id == id_numeric) return_norevlookup(1); + if (id == id_hostname) return_norevlookup(0); + rb_raise(rb_eArgError, "invalid reverse_lookup flag: :%s", rb_id2name(id)); + } + return 0; +#undef return_norevlookup +} + +/* + * call-seq: + * ipsocket.addr([reverse_lookup]) => [address_family, port, hostname, numeric_address] + * + * Returns the local address as an array which contains + * address_family, port, hostname and numeric_address. + * + * If +reverse_lookup+ is +true+ or +:hostname+, + * hostname is obtained from numeric_address using reverse lookup. + * Or if it is +false+, or +:numeric+, + * hostname is same as numeric_address. + * Or if it is +nil+ or ommitted, obeys to +ipsocket.do_not_reverse_lookup+. + * See +Socket.getaddrinfo+ also. + * + * TCPSocket.open("www.ruby-lang.org", 80) {|sock| + * p sock.addr #=> ["AF_INET", 49429, "hal", "192.168.0.128"] + * p sock.addr(true) #=> ["AF_INET", 49429, "hal", "192.168.0.128"] + * p sock.addr(false) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"] + * p sock.addr(:hostname) #=> ["AF_INET", 49429, "hal", "192.168.0.128"] + * p sock.addr(:numeric) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"] + * } + * + */ +static VALUE +ip_addr(int argc, VALUE *argv, VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_storage addr; + socklen_t len = (socklen_t)sizeof addr; + int norevlookup; + + GetOpenFile(sock, fptr); + + if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup)) + norevlookup = fptr->mode & FMODE_NOREVLOOKUP; + if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + rb_sys_fail("getsockname(2)"); + return rsock_ipaddr((struct sockaddr*)&addr, norevlookup); +} + +/* + * call-seq: + * ipsocket.peeraddr([reverse_lookup]) => [address_family, port, hostname, numeric_address] + * + * Returns the remote address as an array which contains + * address_family, port, hostname and numeric_address. + * It is defined for connection oriented socket such as TCPSocket. + * + * If +reverse_lookup+ is +true+ or +:hostname+, + * hostname is obtained from numeric_address using reverse lookup. + * Or if it is +false+, or +:numeric+, + * hostname is same as numeric_address. + * Or if it is +nil+ or ommitted, obeys to +ipsocket.do_not_reverse_lookup+. + * See +Socket.getaddrinfo+ also. + * + * TCPSocket.open("www.ruby-lang.org", 80) {|sock| + * p sock.peeraddr #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"] + * p sock.peeraddr(true) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"] + * p sock.peeraddr(false) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"] + * p sock.peeraddr(:hostname) #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"] + * p sock.peeraddr(:numeric) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"] + * } + * + */ +static VALUE +ip_peeraddr(int argc, VALUE *argv, VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_storage addr; + socklen_t len = (socklen_t)sizeof addr; + int norevlookup; + + GetOpenFile(sock, fptr); + + if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup)) + norevlookup = fptr->mode & FMODE_NOREVLOOKUP; + if (getpeername(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + rb_sys_fail("getpeername(2)"); + return rsock_ipaddr((struct sockaddr*)&addr, norevlookup); +} + +/* + * call-seq: + * ipsocket.recvfrom(maxlen) => [mesg, ipaddr] + * ipsocket.recvfrom(maxlen, flags) => [mesg, ipaddr] + * + * Receives a message and return the message as a string and + * an address which the message come from. + * + * _maxlen_ is the maximum number of bytes to receive. + * + * _flags_ should be a bitwise OR of Socket::MSG_* constants. + * + * ipaddr is same as IPSocket#{peeraddr,addr}. + * + * u1 = UDPSocket.new + * u1.bind("127.0.0.1", 4913) + * u2 = UDPSocket.new + * u2.send "uuuu", 0, "127.0.0.1", 4913 + * p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]] + * + */ +static VALUE +ip_recvfrom(int argc, VALUE *argv, VALUE sock) +{ + return rsock_s_recvfrom(sock, argc, argv, RECV_IP); +} + +/* + * call-seq: + * IPSocket.getaddress(host) => ipaddress + * + * Lookups the IP address of _host_. + * + * IPSocket.getaddress("localhost") #=> "127.0.0.1" + * IPSocket.getaddress("ip6-localhost") #=> "::1" + * + */ +static VALUE +ip_s_getaddress(VALUE obj, VALUE host) +{ + struct sockaddr_storage addr; + struct addrinfo *res = rsock_addrinfo(host, Qnil, SOCK_STREAM, 0); + + /* just take the first one */ + memcpy(&addr, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); + + return rsock_make_ipaddr((struct sockaddr*)&addr); +} + +/* + * Document-class: ::IPSocket < BasicSocket + * + * IPSocket is the super class of TCPSocket and UDPSocket. + */ +void +rsock_init_ipsocket(void) +{ + rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket); + rb_define_method(rb_cIPSocket, "addr", ip_addr, -1); + rb_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, -1); + rb_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1); + rb_define_singleton_method(rb_cIPSocket, "getaddress", ip_s_getaddress, 1); + rb_undef_method(rb_cIPSocket, "getpeereid"); + + id_numeric = rb_intern_const("numeric"); + id_hostname = rb_intern_const("hostname"); +} diff --git a/ext/socket/lib/socket.rb b/ext/socket/lib/socket.rb new file mode 100644 index 0000000000..b7dc446c94 --- /dev/null +++ b/ext/socket/lib/socket.rb @@ -0,0 +1,755 @@ +require 'socket.so' + +class Addrinfo + # creates an Addrinfo object from the arguments. + # + # The arguments are interpreted as similar to self. + # + # Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("www.ruby-lang.org", 80) + # #=> #<Addrinfo: 221.186.184.68:80 TCP (www.ruby-lang.org:80)> + # + # Addrinfo.unix("/tmp/sock").family_addrinfo("/tmp/sock2") + # #=> #<Addrinfo: /tmp/sock2 SOCK_STREAM> + # + def family_addrinfo(*args) + if args.empty? + raise ArgumentError, "no address specified" + elsif Addrinfo === args.first + raise ArgumentError, "too many arguments" if args.length != 1 + elsif self.ip? + raise ArgumentError, "IP address needs host and port but #{args.length} arguments given" if args.length != 2 + host, port = args + Addrinfo.getaddrinfo(host, port, self.pfamily, self.socktype, self.protocol)[0] + elsif self.unix? + raise ArgumentError, "UNIX socket needs single path argument but #{args.length} arguments given" if args.length != 1 + path, = args + Addrinfo.unix(path) + else + raise ArgumentError, "unexpected family" + end + end + + def connect_internal(local_addrinfo) + sock = Socket.new(self.pfamily, self.socktype, self.protocol) + begin + sock.ipv6only! if self.ipv6? + sock.bind local_addrinfo if local_addrinfo + sock.connect(self) + if block_given? + yield sock + else + sock + end + ensure + sock.close if !sock.closed? && (block_given? || $!) + end + end + private :connect_internal + + # creates a socket connected to the address of self. + # + # If one or more arguments given as _local_addr_args_, + # it is used as the local address of the socket. + # _local_addr_args_ is given for family_addrinfo to obtain actual address. + # + # If no arguments given, the local address of the socket is not bound. + # + # If a block is given, it is called with the socket and the value of the block is returned. + # The socket is returned otherwise. + # + # Addrinfo.tcp("www.ruby-lang.org", 80).connect_from("0.0.0.0", 4649) {|s| + # s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n" + # puts s.read + # } + # + # # Addrinfo object can be taken for the argument. + # Addrinfo.tcp("www.ruby-lang.org", 80).connect_from(Addrinfo.tcp("0.0.0.0", 4649)) {|s| + # s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n" + # puts s.read + # } + # + def connect_from(*local_addr_args, &block) + connect_internal(family_addrinfo(*local_addr_args), &block) + end + + # creates a socket connected to the address of self. + # + # If a block is given, it is called with the socket and the value of the block is returned. + # The socket is returned otherwise. + # + # Addrinfo.tcp("www.ruby-lang.org", 80).connect {|s| + # s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n" + # puts s.read + # } + # + def connect(&block) + connect_internal(nil, &block) + end + + # creates a socket connected to _remote_addr_args_ and bound to self. + # + # If a block is given, it is called with the socket and the value of the block is returned. + # The socket is returned otherwise. + # + # Addrinfo.tcp("0.0.0.0", 4649).connect_to("www.ruby-lang.org", 80) {|s| + # s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n" + # puts s.read + # } + # + def connect_to(*remote_addr_args, &block) + remote_addrinfo = family_addrinfo(*remote_addr_args) + remote_addrinfo.send(:connect_internal, self, &block) + end + + # creates a socket bound to self. + # + # If a block is given, it is called with the socket and the value of the block is returned. + # The socket is returned otherwise. + # + # Addrinfo.udp("0.0.0.0", 9981).bind {|s| + # s.local_address.connect {|s| s.send "hello", 0 } + # p s.recv(10) #=> "hello" + # } + # + def bind + sock = Socket.new(self.pfamily, self.socktype, self.protocol) + begin + sock.ipv6only! if self.ipv6? + sock.setsockopt(:SOCKET, :REUSEADDR, 1) + sock.bind(self) + if block_given? + yield sock + else + sock + end + ensure + sock.close if !sock.closed? && (block_given? || $!) + end + end + + # creates a listening socket bound to self. + def listen(backlog=5) + sock = Socket.new(self.pfamily, self.socktype, self.protocol) + begin + sock.ipv6only! if self.ipv6? + sock.setsockopt(:SOCKET, :REUSEADDR, 1) + sock.bind(self) + sock.listen(backlog) + if block_given? + yield sock + else + sock + end + ensure + sock.close if !sock.closed? && (block_given? || $!) + end + end + + # iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo. + # + # Addrinfo.foreach(nil, 80) {|x| p x } + # #=> #<Addrinfo: 127.0.0.1:80 TCP (:80)> + # # #<Addrinfo: 127.0.0.1:80 UDP (:80)> + # # #<Addrinfo: [::1]:80 TCP (:80)> + # # #<Addrinfo: [::1]:80 UDP (:80)> + # + def self.foreach(nodename, service, family=nil, socktype=nil, protocol=nil, flags=nil, &block) + Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags).each(&block) + end +end + +class BasicSocket < IO + # Returns an address of the socket suitable for connect in the local machine. + # + # This method returns _self_.local_address, except following condition. + # + # - IPv4 unspecified address (0.0.0.0) is replaced by IPv4 loopback address (127.0.0.1). + # - IPv6 unspecified address (::) is replaced by IPv6 loopback address (::1). + # + # If the local address is not suitable for connect, SocketError is raised. + # IPv4 and IPv6 address which port is 0 is not suitable for connect. + # Unix domain socket which has no path is not suitable for connect. + # + # Addrinfo.tcp("0.0.0.0", 0).listen {|serv| + # p serv.connect_address #=> #<Addrinfo: 127.0.0.1:53660 TCP> + # serv.connect_address.connect {|c| + # s, _ = serv.accept + # p [c, s] #=> [#<Socket:fd 4>, #<Socket:fd 6>] + # } + # } + # + def connect_address + addr = local_address + afamily = addr.afamily + if afamily == Socket::AF_INET + raise SocketError, "unbound IPv4 socket" if addr.ip_port == 0 + if addr.ip_address == "0.0.0.0" + addr = Addrinfo.new(["AF_INET", addr.ip_port, nil, "127.0.0.1"], addr.pfamily, addr.socktype, addr.protocol) + end + elsif defined?(Socket::AF_INET6) && afamily == Socket::AF_INET6 + raise SocketError, "unbound IPv6 socket" if addr.ip_port == 0 + if addr.ip_address == "::" + addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol) + elsif addr.ip_address == "0.0.0.0" # MacOS X 10.4 returns "a.b.c.d" for IPv4-mapped IPv6 address. + addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol) + elsif addr.ip_address == "::ffff:0.0.0.0" # MacOS X 10.6 returns "::ffff:a.b.c.d" for IPv4-mapped IPv6 address. + addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol) + end + elsif defined?(Socket::AF_UNIX) && afamily == Socket::AF_UNIX + raise SocketError, "unbound Unix socket" if addr.unix_path == "" + end + addr + end +end + +class Socket < BasicSocket + # enable the socket option IPV6_V6ONLY if IPV6_V6ONLY is available. + def ipv6only! + if defined? Socket::IPV6_V6ONLY + self.setsockopt(:IPV6, :V6ONLY, 1) + end + end + + # creates a new socket object connected to host:port using TCP/IP. + # + # If local_host:local_port is given, + # the socket is bound to it. + # + # If a block is given, the block is called with the socket. + # The value of the block is returned. + # The socket is closed when this method returns. + # + # If no block is given, the socket is returned. + # + # Socket.tcp("www.ruby-lang.org", 80) {|sock| + # sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n" + # sock.close_write + # puts sock.read + # } + # + def self.tcp(host, port, local_host=nil, local_port=nil) # :yield: socket + last_error = nil + ret = nil + + local_addr_list = nil + if local_host != nil || local_port != nil + local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil) + end + + Addrinfo.foreach(host, port, nil, :STREAM) {|ai| + if local_addr_list + local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily } + next if !local_addr + else + local_addr = nil + end + begin + sock = local_addr ? ai.connect_from(local_addr) : ai.connect + rescue SystemCallError + last_error = $! + next + end + ret = sock + break + } + if !ret + if last_error + raise last_error + else + raise SocketError, "no appropriate local address" + end + end + if block_given? + begin + yield ret + ensure + ret.close if !ret.closed? + end + else + ret + end + end + + # :stopdoc: + def self.ip_sockets_port0(ai_list, reuseaddr) + begin + sockets = [] + port = nil + ai_list.each {|ai| + begin + s = Socket.new(ai.pfamily, ai.socktype, ai.protocol) + rescue SystemCallError + next + end + sockets << s + s.ipv6only! if ai.ipv6? + if reuseaddr + s.setsockopt(:SOCKET, :REUSEADDR, 1) + end + if !port + s.bind(ai) + port = s.local_address.ip_port + else + s.bind(ai.family_addrinfo(ai.ip_address, port)) + end + } + rescue Errno::EADDRINUSE + sockets.each {|s| + s.close + } + retry + end + sockets + ensure + sockets.each {|s| s.close if !s.closed? } if $! + end + class << self + private :ip_sockets_port0 + end + + def self.tcp_server_sockets_port0(host) + ai_list = Addrinfo.getaddrinfo(host, 0, nil, :STREAM, nil, Socket::AI_PASSIVE) + sockets = ip_sockets_port0(ai_list, true) + sockets.each {|s| + s.listen(5) + } + sockets + ensure + sockets.each {|s| s.close if !s.closed? } if $! && sockets + end + class << self + private :tcp_server_sockets_port0 + end + # :startdoc: + + # creates TCP/IP server sockets for _host_ and _port_. + # _host_ is optional. + # + # If no block given, + # it returns an array of listening sockets. + # + # If a block is given, the block is called with the sockets. + # The value of the block is returned. + # The socket is closed when this method returns. + # + # If _port_ is 0, actual port number is choosen dynamically. + # However all sockets in the result has same port number. + # + # # tcp_server_sockets returns two sockets. + # sockets = Socket.tcp_server_sockets(1296) + # p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>] + # + # # The sockets contains IPv6 and IPv4 sockets. + # sockets.each {|s| p s.local_address } + # #=> #<Addrinfo: [::]:1296 TCP> + # # #<Addrinfo: 0.0.0.0:1296 TCP> + # + # # IPv6 and IPv4 socket has same port number, 53114, even if it is choosen dynamically. + # sockets = Socket.tcp_server_sockets(0) + # sockets.each {|s| p s.local_address } + # #=> #<Addrinfo: [::]:53114 TCP> + # # #<Addrinfo: 0.0.0.0:53114 TCP> + # + # # The block is called with the sockets. + # Socket.tcp_server_sockets(0) {|sockets| + # p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>] + # } + # + def self.tcp_server_sockets(host=nil, port) + if port == 0 + sockets = tcp_server_sockets_port0(host) + else + begin + last_error = nil + sockets = [] + Addrinfo.foreach(host, port, nil, :STREAM, nil, Socket::AI_PASSIVE) {|ai| + begin + s = ai.listen + rescue SystemCallError + last_error = $! + next + end + sockets << s + } + if sockets.empty? + raise last_error + end + ensure + sockets.each {|s| s.close if !s.closed? } if $! + end + end + if block_given? + begin + yield sockets + ensure + sockets.each {|s| s.close if !s.closed? } + end + else + sockets + end + end + + # yield socket and client address for each a connection accepted via given sockets. + # + # The arguments are a list of sockets. + # The individual argument should be a socket or an array of sockets. + # + # This method yields the block sequentially. + # It means that the next connection is not accepted until the block returns. + # So concurrent mechanism, thread for example, should be used to service multiple clients at a time. + # + def self.accept_loop(*sockets) # :yield: socket, client_addrinfo + sockets.flatten!(1) + if sockets.empty? + raise ArgumentError, "no sockets" + end + loop { + readable, _, _ = IO.select(sockets) + readable.each {|r| + begin + sock, addr = r.accept_nonblock + rescue IO::WaitReadable + next + end + yield sock, addr + } + } + end + + # creates a TCP/IP server on _port_ and calls the block for each connection accepted. + # The block is called with a socket and a client_address as an Addrinfo object. + # + # If _host_ is specified, it is used with _port_ to determine the server addresses. + # + # The socket is *not* closed when the block returns. + # So application should close it explicitly. + # + # This method calls the block sequentially. + # It means that the next connection is not accepted until the block returns. + # So concurrent mechanism, thread for example, should be used to service multiple clients at a time. + # + # Note that Addrinfo.getaddrinfo is used to determine the server socket addresses. + # When Addrinfo.getaddrinfo returns two or more addresses, + # IPv4 and IPv6 address for example, + # all of them are used. + # Socket.tcp_server_loop succeeds if one socket can be used at least. + # + # # Sequential echo server. + # # It services only one client at a time. + # Socket.tcp_server_loop(16807) {|sock, client_addrinfo| + # begin + # IO.copy_stream(sock, sock) + # ensure + # sock.close + # end + # } + # + # # Threaded echo server + # # It services multiple clients at a time. + # # Note that it may accept connections too much. + # Socket.tcp_server_loop(16807) {|sock, client_addrinfo| + # Thread.new { + # begin + # IO.copy_stream(sock, sock) + # ensure + # sock.close + # end + # } + # } + # + def self.tcp_server_loop(host=nil, port, &b) # :yield: socket, client_addrinfo + tcp_server_sockets(host, port) {|sockets| + accept_loop(sockets, &b) + } + end + + # :call-seq: + # Socket.udp_server_sockets([host, ] port) + # + # Creates UDP/IP sockets for a UDP server. + # + # If no block given, it returns an array of sockets. + # + # If a block is given, the block is called with the sockets. + # The value of the block is returned. + # The sockets are closed when this method returns. + # + # If _port_ is zero, some port is choosen. + # But the choosen port is used for the all sockets. + # + # # UDP/IP echo server + # Socket.udp_server_sockets(0) {|sockets| + # p sockets.first.local_address.ip_port #=> 32963 + # Socket.udp_server_loop_on(sockets) {|msg, msg_src| + # msg_src.reply msg + # } + # } + # + def self.udp_server_sockets(host=nil, port) + last_error = nil + sockets = [] + + ipv6_recvpktinfo = nil + if defined? Socket::AncillaryData + if defined? Socket::IPV6_RECVPKTINFO # RFC 3542 + ipv6_recvpktinfo = Socket::IPV6_RECVPKTINFO + elsif defined? Socket::IPV6_PKTINFO # RFC 2292 + ipv6_recvpktinfo = Socket::IPV6_PKTINFO + end + end + + local_addrs = Socket.ip_address_list + + ip_list = [] + Addrinfo.foreach(host, port, nil, :DGRAM, nil, Socket::AI_PASSIVE) {|ai| + if ai.ipv4? && ai.ip_address == "0.0.0.0" + local_addrs.each {|a| + next if !a.ipv4? + ip_list << Addrinfo.new(a.to_sockaddr, :INET, :DGRAM, 0); + } + elsif ai.ipv6? && ai.ip_address == "::" && !ipv6_recvpktinfo + local_addrs.each {|a| + next if !a.ipv6? + ip_list << Addrinfo.new(a.to_sockaddr, :INET6, :DGRAM, 0); + } + else + ip_list << ai + end + } + + if port == 0 + sockets = ip_sockets_port0(ip_list, false) + else + ip_list.each {|ip| + ai = Addrinfo.udp(ip.ip_address, port) + begin + s = ai.bind + rescue SystemCallError + last_error = $! + next + end + sockets << s + } + if sockets.empty? + raise last_error + end + end + + pktinfo_sockets = {} + sockets.each {|s| + ai = s.local_address + if ipv6_recvpktinfo && ai.ipv6? && ai.ip_address == "::" + s.setsockopt(:IPV6, ipv6_recvpktinfo, 1) + pktinfo_sockets[s] = true + end + } + + if block_given? + begin + yield sockets + ensure + sockets.each {|s| s.close if !s.closed? } if sockets + end + else + sockets + end + end + + # :call-seq: + # Socket.udp_server_recv(sockets) {|msg, msg_src| ... } + # + # Receive UDP/IP packets from the given _sockets_. + # For each packet received, the block is called. + # + # The block receives _msg_ and _msg_src_. + # _msg_ is a string which is the payload of the received packet. + # _msg_src_ is a Socket::UDPSource object which is used for reply. + # + # Socket.udp_server_loop can be implemented using this method as follows. + # + # udp_server_sockets(host, port) {|sockets| + # loop { + # readable, _, _ = IO.select(sockets) + # udp_server_recv(readable) {|msg, msg_src| ... } + # } + # } + # + def self.udp_server_recv(sockets) + sockets.each {|r| + begin + msg, sender_addrinfo, rflags, *controls = r.recvmsg_nonblock + rescue IO::WaitReadable + next + end + ai = r.local_address + if ai.ipv6? and pktinfo = controls.find {|c| c.cmsg_is?(:IPV6, :PKTINFO) } + ai = Addrinfo.udp(pktinfo.ipv6_pktinfo_addr.ip_address, ai.ip_port) + yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg| + r.sendmsg reply_msg, 0, sender_addrinfo, pktinfo + } + else + yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg| + r.send reply_msg, 0, sender_addrinfo + } + end + } + end + + # :call-seq: + # Socket.udp_server_loop_on(sockets) {|msg, msg_src| ... } + # + # Run UDP/IP server loop on the given sockets. + # + # The return value of Socket.udp_server_sockets is appropriate for the argument. + # + # It calls the block for each message received. + # + def self.udp_server_loop_on(sockets, &b) # :yield: msg, msg_src + loop { + readable, _, _ = IO.select(sockets) + udp_server_recv(readable, &b) + } + end + + # :call-seq: + # Socket.udp_server_loop(port) {|msg, msg_src| ... } + # Socket.udp_server_loop(host, port) {|msg, msg_src| ... } + # + # creates a UDP/IP server on _port_ and calls the block for each message arrived. + # The block is called with the message and its source information. + # + # This method allocates sockets internally using _port_. + # If _host_ is specified, it is used conjunction with _port_ to determine the server addresses. + # + # The _msg_ is a string. + # + # The _msg_src_ is a Socket::UDPSource object. + # It is used for reply. + # + # # UDP/IP echo server. + # Socket.udp_server_loop(9261) {|msg, msg_src| + # msg_src.reply msg + # } + # + def self.udp_server_loop(host=nil, port, &b) # :yield: message, message_source + udp_server_sockets(host, port) {|sockets| + udp_server_loop_on(sockets, &b) + } + end + + # UDP/IP address information used by Socket.udp_server_loop. + class UDPSource + def initialize(remote_address, local_address, &reply_proc) + @remote_address = remote_address + @local_address = local_address + @reply_proc = reply_proc + end + attr_reader :remote_address, :local_address + + def inspect + "\#<#{self.class}: #{@remote_address.inspect_sockaddr} to #{@local_address.inspect_sockaddr}>" + end + + def reply(msg) + @reply_proc.call msg + end + end + + # creates a new socket connected to path using UNIX socket socket. + # + # If a block is given, the block is called with the socket. + # The value of the block is returned. + # The socket is closed when this method returns. + # + # If no block is given, the socket is returned. + # + # # talk to /tmp/sock socket. + # Socket.unix("/tmp/sock") {|sock| + # t = Thread.new { IO.copy_stream(sock, STDOUT) } + # IO.copy_stream(STDIN, sock) + # t.join + # } + # + def self.unix(path) # :yield: socket + addr = Addrinfo.unix(path) + sock = addr.connect + if block_given? + begin + yield sock + ensure + sock.close if !sock.closed? + end + else + sock + end + end + + # creates a UNIX server socket on _path_ + # + # If no block given, it returns a listening socket. + # + # If a block is given, it is called with the socket and the block value is returned. + # When the block exits, the socket is closed and the socket file is removed. + # + # socket = Socket.unix_server_socket("/tmp/s") + # p socket #=> #<Socket:fd 3> + # p socket.local_address #=> #<Addrinfo: /tmp/s SOCK_STREAM> + # + # Socket.unix_server_socket("/tmp/sock") {|s| + # p s #=> #<Socket:fd 3> + # p s.local_address #=> # #<Addrinfo: /tmp/sock SOCK_STREAM> + # } + # + def self.unix_server_socket(path) + begin + st = File.lstat(path) + rescue Errno::ENOENT + end + if st && st.socket? && st.owned? + File.unlink path + end + s = Addrinfo.unix(path).listen + if block_given? + begin + yield s + ensure + s.close if !s.closed? + File.unlink path + end + else + s + end + end + + # creates a UNIX socket server on _path_. + # It calls the block for each socket accepted. + # + # If _host_ is specified, it is used with _port_ to determine the server ports. + # + # The socket is *not* closed when the block returns. + # So application should close it. + # + # This method deletes the socket file pointed by _path_ at first if + # the file is a socket file and it is owned by the user of the application. + # This is safe only if the directory of _path_ is not changed by a malicious user. + # So don't use /tmp/malicious-users-directory/socket. + # Note that /tmp/socket and /tmp/your-private-directory/socket is safe assuming that /tmp has sticky bit. + # + # # Sequential echo server. + # # It services only one client at a time. + # Socket.unix_server_loop("/tmp/sock") {|sock, client_addrinfo| + # begin + # IO.copy_stream(sock, sock) + # ensure + # sock.close + # end + # } + # + def self.unix_server_loop(path, &b) # :yield: socket, client_addrinfo + unix_server_socket(path) {|serv| + accept_loop(serv, &b) + } + end + +end + diff --git a/ext/socket/mkconstants.rb b/ext/socket/mkconstants.rb new file mode 100644 index 0000000000..fe00f30e3d --- /dev/null +++ b/ext/socket/mkconstants.rb @@ -0,0 +1,696 @@ +require 'optparse' +require 'erb' + +opt = OptionParser.new + +opt.def_option('-h', 'help') { + puts opt + exit 0 +} + +opt_o = nil +opt.def_option('-o FILE', 'specify output file') {|filename| + opt_o = filename +} + +opt_H = nil +opt.def_option('-H FILE', 'specify output header file') {|filename| + opt_H = filename +} + +C_ESC = { + "\\" => "\\\\", + '"' => '\"', + "\n" => '\n', +} + +0x00.upto(0x1f) {|ch| C_ESC[[ch].pack("C")] ||= "\\%03o" % ch } +0x7f.upto(0xff) {|ch| C_ESC[[ch].pack("C")] = "\\%03o" % ch } +C_ESC_PAT = Regexp.union(*C_ESC.keys) + +def c_str(str) + '"' + str.gsub(C_ESC_PAT) {|s| C_ESC[s]} + '"' +end + +opt.parse! + + + +h = {} +DATA.each_line {|s| + name, default_value = s.scan(/\S+/) + next unless name && name[0] != ?# + if h.has_key? name + warn "#{$.}: warning: duplicate name: #{name}" + next + end + h[name] = default_value +} +DEFS = h.to_a + +def each_const + DEFS.each {|name, default_value| + if name =~ /\AINADDR_/ + make_value = "UINT2NUM" + else + make_value = "INT2NUM" + end + guard = nil + if /\A(AF_INET6|PF_INET6|IPV6_.*)\z/ =~ name + # IPv6 is not supported although AF_INET6 is defined on bcc32/mingw + guard = "defined(INET6)" + end + yield guard, make_value, name, default_value + } +end + +def each_name(pat) + DEFS.each {|name, default_value| + next if pat !~ name + yield name + } +end + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_const_decls") +% each_const {|guard, make_value, name, default_value| +#if !defined(<%=name%>) +# if defined(HAVE_CONST_<%=name.upcase%>) +# define <%=name%> <%=name%> +%if default_value +# else +# define <%=name%> <%=default_value%> +%end +# endif +#endif +% } +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_const_defs_in_guard(make_value, name, default_value)") +#if defined(<%=name%>) + /* <%=name%>: */ + rb_define_const(rb_cSocket, <%=c_str name%>, <%=make_value%>(<%=name%>)); + /* <%=name%>: */ + rb_define_const(rb_mSockConst, <%=c_str name%>, <%=make_value%>(<%=name%>)); +#endif +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_const_defs") +% each_const {|guard, make_value, name, default_value| +% if guard +#if <%=guard%> +<%= gen_const_defs_in_guard(make_value, name, default_value).chomp %> +#endif +% else +<%= gen_const_defs_in_guard(make_value, name, default_value).chomp %> +% end +% } +EOS + +def reverse_each_name(pat) + DEFS.reverse_each {|name, default_value| + next if pat !~ name + yield name + } +end + +def each_names_with_len(pat, prefix_optional=nil) + h = {} + DEFS.each {|name, default_value| + next if pat !~ name + (h[name.length] ||= []) << [name, name] + } + if prefix_optional + if Regexp === prefix_optional + prefix_pat = prefix_optional + else + prefix_pat = /\A#{Regexp.escape prefix_optional}/ + end + DEFS.each {|const, default_value| + next if pat !~ const + next if prefix_pat !~ const + name = $' + (h[name.length] ||= []) << [name, const] + } + end + hh = {} + h.each {|len, pairs| + pairs.each {|name, const| + raise "name crash: #{name}" if hh[name] + hh[name] = true + } + } + h.keys.sort.each {|len| + yield h[len], len + } +end + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_name_to_int_decl(funcname, pat, prefix_optional, guard=nil)") +%if guard +#ifdef <%=guard%> +int <%=funcname%>(const char *str, long len, int *valp); +#endif +%else +int <%=funcname%>(const char *str, long len, int *valp); +%end +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_name_to_int_func_in_guard(funcname, pat, prefix_optional, guard=nil)") +int +<%=funcname%>(const char *str, long len, int *valp) +{ + switch (len) { +% each_names_with_len(pat, prefix_optional) {|pairs, len| + case <%=len%>: +% pairs.each {|name, const| +#ifdef <%=const%> + if (memcmp(str, <%=c_str name%>, <%=len%>) == 0) { *valp = <%=const%>; return 0; } +#endif +% } + return -1; + +% } + default: + return -1; + } +} +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_name_to_int_func(funcname, pat, prefix_optional, guard=nil)") +%if guard +#ifdef <%=guard%> +<%=gen_name_to_int_func_in_guard(funcname, pat, prefix_optional, guard)%> +#endif +%else +<%=gen_name_to_int_func_in_guard(funcname, pat, prefix_optional, guard)%> +%end +EOS + +NAME_TO_INT_DEFS = [] +def def_name_to_int(funcname, pat, prefix_optional, guard=nil) + decl = gen_name_to_int_decl(funcname, pat, prefix_optional, guard) + func = gen_name_to_int_func(funcname, pat, prefix_optional, guard) + NAME_TO_INT_DEFS << [decl, func] +end + +def reverse_each_name_with_prefix_optional(pat, prefix_pat) + reverse_each_name(pat) {|n| + yield n, n + } + if prefix_pat + reverse_each_name(pat) {|n| + next if prefix_pat !~ n + yield n, $' + } + end +end + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_int_to_name_hash(hash_var, pat, prefix_pat)") + <%=hash_var%> = st_init_numtable(); +% reverse_each_name_with_prefix_optional(pat, prefix_pat) {|n,s| +#ifdef <%=n%> + st_insert(<%=hash_var%>, (st_data_t)<%=n%>, (st_data_t)rb_intern2(<%=c_str s%>, <%=s.length%>)); +#endif +% } +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_int_to_name_func(func_name, hash_var)") +ID +<%=func_name%>(int val) +{ + st_data_t name; + if (st_lookup(<%=hash_var%>, (st_data_t)val, &name)) + return (ID)name; + return 0; +} +EOS + +ERB.new(<<'EOS', nil, '%').def_method(Object, "gen_int_to_name_decl(func_name, hash_var)") +ID <%=func_name%>(int val); +EOS + +INTERN_DEFS = [] +def def_intern(func_name, pat, prefix_optional=nil) + prefix_pat = nil + if prefix_optional + if Regexp === prefix_optional + prefix_pat = prefix_optional + else + prefix_pat = /\A#{Regexp.escape prefix_optional}/ + end + end + hash_var = "#{func_name}_hash" + vardef = "static st_table *#{hash_var};" + gen_hash = gen_int_to_name_hash(hash_var, pat, prefix_pat) + decl = gen_int_to_name_decl(func_name, hash_var) + func = gen_int_to_name_func(func_name, hash_var) + INTERN_DEFS << [vardef, gen_hash, decl, func] +end + +def_name_to_int("rsock_family_to_int", /\A(AF_|PF_)/, "AF_") +def_name_to_int("rsock_socktype_to_int", /\ASOCK_/, "SOCK_") +def_name_to_int("rsock_ipproto_to_int", /\AIPPROTO_/, "IPPROTO_") +def_name_to_int("rsock_unknown_level_to_int", /\ASOL_SOCKET\z/, "SOL_") +def_name_to_int("rsock_ip_level_to_int", /\A(SOL_SOCKET\z|IPPROTO_)/, /\A(SOL_|IPPROTO_)/) +def_name_to_int("rsock_so_optname_to_int", /\ASO_/, "SO_") +def_name_to_int("rsock_ip_optname_to_int", /\AIP_/, "IP_") +def_name_to_int("rsock_ipv6_optname_to_int", /\AIPV6_/, "IPV6_", "IPPROTO_IPV6") +def_name_to_int("rsock_tcp_optname_to_int", /\ATCP_/, "TCP_") +def_name_to_int("rsock_udp_optname_to_int", /\AUDP_/, "UDP_") +def_name_to_int("rsock_shutdown_how_to_int", /\ASHUT_/, "SHUT_") +def_name_to_int("rsock_scm_optname_to_int", /\ASCM_/, "SCM_") + +def_intern('rsock_intern_family', /\AAF_/) +def_intern('rsock_intern_family_noprefix', /\AAF_/, "AF_") +def_intern('rsock_intern_protocol_family', /\APF_/) +def_intern('rsock_intern_socktype', /\ASOCK_/) +def_intern('rsock_intern_ipproto', /\AIPPROTO_/) +def_intern('rsock_intern_iplevel', /\A(SOL_SOCKET\z|IPPROTO_)/, /\A(SOL_|IPPROTO_)/) +def_intern('rsock_intern_so_optname', /\ASO_/, "SO_") +def_intern('rsock_intern_ip_optname', /\AIP_/, "IP_") +def_intern('rsock_intern_ipv6_optname', /\AIPV6_/, "IPV6_") +def_intern('rsock_intern_tcp_optname', /\ATCP_/, "TCP_") +def_intern('rsock_intern_udp_optname', /\AUDP_/, "UDP_") +def_intern('rsock_intern_scm_optname', /\ASCM_/, "SCM_") +def_intern('rsock_intern_local_optname', /\ALOCAL_/, "LOCAL_") + +result = ERB.new(<<'EOS', nil, '%').result(binding) +/* autogenerated file */ + +<%= INTERN_DEFS.map {|vardef, gen_hash, decl, func| vardef }.join("\n") %> + +/* + * Document-module: ::Socket::Constants + * + * Socket::Constants provides socket related constants. + * Following lists possible constants. + * If underlying platform doesn't define a constant, + * the corresponding Ruby constant is not defined. + * + */ +static void +init_constants(void) +{ + rb_mSockConst = rb_define_module_under(rb_cSocket, "Constants"); + +<%= gen_const_defs %> +<%= INTERN_DEFS.map {|vardef, gen_hash, decl, func| gen_hash }.join("\n") %> +} + +<%= NAME_TO_INT_DEFS.map {|decl, func| func }.join("\n") %> + +<%= INTERN_DEFS.map {|vardef, gen_hash, decl, func| func }.join("\n") %> + +EOS + +header_result = ERB.new(<<'EOS', nil, '%').result(binding) +/* autogenerated file */ +<%= gen_const_decls %> +<%= NAME_TO_INT_DEFS.map {|decl, func| decl }.join("\n") %> +<%= INTERN_DEFS.map {|vardef, gen_hash, decl, func| decl }.join("\n") %> +EOS + +if opt_H + File.open(opt_H, 'w') {|f| + f << header_result + } +else + result = header_result + result +end + +if opt_o + File.open(opt_o, 'w') {|f| + f << result + } +else + $stdout << result +end + +__END__ + +SOCK_STREAM +SOCK_DGRAM +SOCK_RAW +SOCK_RDM +SOCK_SEQPACKET +SOCK_PACKET + +AF_UNSPEC +PF_UNSPEC +AF_INET +PF_INET +AF_INET6 +PF_INET6 +AF_UNIX +PF_UNIX +AF_AX25 +PF_AX25 +AF_IPX +PF_IPX +AF_APPLETALK +PF_APPLETALK +AF_LOCAL +PF_LOCAL +AF_IMPLINK +PF_IMPLINK +AF_PUP +PF_PUP +AF_CHAOS +PF_CHAOS +AF_NS +PF_NS +AF_ISO +PF_ISO +AF_OSI +PF_OSI +AF_ECMA +PF_ECMA +AF_DATAKIT +PF_DATAKIT +AF_CCITT +PF_CCITT +AF_SNA +PF_SNA +AF_DEC +PF_DEC +AF_DLI +PF_DLI +AF_LAT +PF_LAT +AF_HYLINK +PF_HYLINK +AF_ROUTE +PF_ROUTE +AF_LINK +PF_LINK +AF_COIP +PF_COIP +AF_CNT +PF_CNT +AF_SIP +PF_SIP +AF_NDRV +PF_NDRV +AF_ISDN +PF_ISDN +AF_NATM +PF_NATM +AF_SYSTEM +PF_SYSTEM +AF_NETBIOS +PF_NETBIOS +AF_PPP +PF_PPP +AF_ATM +PF_ATM +AF_NETGRAPH +PF_NETGRAPH +AF_MAX +PF_MAX +AF_PACKET +PF_PACKET + +AF_E164 +PF_XTP +PF_RTIP +PF_PIP +PF_KEY + +MSG_OOB +MSG_PEEK +MSG_DONTROUTE +MSG_EOR +MSG_TRUNC +MSG_CTRUNC +MSG_WAITALL +MSG_DONTWAIT +MSG_EOF +MSG_FLUSH +MSG_HOLD +MSG_SEND +MSG_HAVEMORE +MSG_RCVMORE +MSG_COMPAT +MSG_PROXY +MSG_FIN +MSG_SYN +MSG_CONFIRM +MSG_RST +MSG_ERRQUEUE +MSG_NOSIGNAL +MSG_MORE + +SOL_SOCKET +SOL_IP +SOL_IPX +SOL_AX25 +SOL_ATALK +SOL_TCP +SOL_UDP + +IPPROTO_IP 0 +IPPROTO_ICMP 1 +IPPROTO_IGMP +IPPROTO_GGP +IPPROTO_TCP 6 +IPPROTO_EGP +IPPROTO_PUP +IPPROTO_UDP 17 +IPPROTO_IDP +IPPROTO_HELLO +IPPROTO_ND +IPPROTO_TP +IPPROTO_XTP +IPPROTO_EON +IPPROTO_BIP +IPPROTO_AH +IPPROTO_DSTOPTS +IPPROTO_ESP +IPPROTO_FRAGMENT +IPPROTO_HOPOPTS +IPPROTO_ICMPV6 +IPPROTO_IPV6 +IPPROTO_NONE +IPPROTO_ROUTING + +IPPROTO_RAW 255 +IPPROTO_MAX + +# Some port configuration +IPPORT_RESERVED 1024 +IPPORT_USERRESERVED 5000 + +# Some reserved IP v.4 addresses +INADDR_ANY 0x00000000 +INADDR_BROADCAST 0xffffffff +INADDR_LOOPBACK 0x7F000001 +INADDR_UNSPEC_GROUP 0xe0000000 +INADDR_ALLHOSTS_GROUP 0xe0000001 +INADDR_MAX_LOCAL_GROUP 0xe00000ff +INADDR_NONE 0xffffffff + +# IP [gs]etsockopt options +IP_OPTIONS +IP_HDRINCL +IP_TOS +IP_TTL +IP_RECVOPTS +IP_RECVRETOPTS +IP_RECVDSTADDR +IP_RETOPTS +IP_MINTTL +IP_DONTFRAG +IP_SENDSRCADDR +IP_ONESBCAST +IP_RECVTTL +IP_RECVIF +IP_RECVSLLA +IP_PORTRANGE +IP_MULTICAST_IF +IP_MULTICAST_TTL +IP_MULTICAST_LOOP +IP_ADD_MEMBERSHIP +IP_DROP_MEMBERSHIP +IP_DEFAULT_MULTICAST_TTL +IP_DEFAULT_MULTICAST_LOOP +IP_MAX_MEMBERSHIPS +IP_ROUTER_ALERT +IP_PKTINFO +IP_PKTOPTIONS +IP_MTU_DISCOVER +IP_RECVERR +IP_RECVTOS +IP_MTU +IP_FREEBIND +IP_IPSEC_POLICY +IP_XFRM_POLICY +IP_PASSSEC +IP_PMTUDISC_DONT +IP_PMTUDISC_WANT +IP_PMTUDISC_DO +IP_UNBLOCK_SOURCE +IP_BLOCK_SOURCE +IP_ADD_SOURCE_MEMBERSHIP +IP_DROP_SOURCE_MEMBERSHIP +IP_MSFILTER + +MCAST_JOIN_GROUP +MCAST_BLOCK_SOURCE +MCAST_UNBLOCK_SOURCE +MCAST_LEAVE_GROUP +MCAST_JOIN_SOURCE_GROUP +MCAST_LEAVE_SOURCE_GROUP +MCAST_MSFILTER +MCAST_EXCLUDE +MCAST_INCLUDE + +SO_DEBUG +SO_REUSEADDR +SO_REUSEPORT +SO_TYPE +SO_ERROR +SO_DONTROUTE +SO_BROADCAST +SO_SNDBUF +SO_RCVBUF +SO_KEEPALIVE +SO_OOBINLINE +SO_NO_CHECK +SO_PRIORITY +SO_LINGER +SO_PASSCRED +SO_PEERCRED +SO_RCVLOWAT +SO_SNDLOWAT +SO_RCVTIMEO +SO_SNDTIMEO +SO_ACCEPTCONN +SO_USELOOPBACK +SO_ACCEPTFILTER +SO_DONTTRUNC +SO_WANTMORE +SO_WANTOOBFLAG +SO_NREAD +SO_NKE +SO_NOSIGPIPE +SO_SECURITY_AUTHENTICATION +SO_SECURITY_ENCRYPTION_TRANSPORT +SO_SECURITY_ENCRYPTION_NETWORK +SO_BINDTODEVICE +SO_ATTACH_FILTER +SO_DETACH_FILTER +SO_PEERNAME +SO_TIMESTAMP +SO_TIMESTAMPNS +SO_BINTIME +SO_RECVUCRED +SO_MAC_EXEMPT +SO_ALLZONES + +SOPRI_INTERACTIVE +SOPRI_NORMAL +SOPRI_BACKGROUND + +IPX_TYPE + +TCP_NODELAY +TCP_MAXSEG +TCP_CORK +TCP_DEFER_ACCEPT +TCP_INFO +TCP_KEEPCNT +TCP_KEEPIDLE +TCP_KEEPINTVL +TCP_LINGER2 +TCP_MD5SIG +TCP_NOOPT +TCP_NOPUSH +TCP_QUICKACK +TCP_SYNCNT +TCP_WINDOW_CLAMP + +UDP_CORK + +EAI_ADDRFAMILY +EAI_AGAIN +EAI_BADFLAGS +EAI_FAIL +EAI_FAMILY +EAI_MEMORY +EAI_NODATA +EAI_NONAME +EAI_OVERFLOW +EAI_SERVICE +EAI_SOCKTYPE +EAI_SYSTEM +EAI_BADHINTS +EAI_PROTOCOL +EAI_MAX + +AI_PASSIVE +AI_CANONNAME +AI_NUMERICHOST +AI_NUMERICSERV +AI_MASK +AI_ALL +AI_V4MAPPED_CFG +AI_ADDRCONFIG +AI_V4MAPPED +AI_DEFAULT + +NI_MAXHOST +NI_MAXSERV +NI_NOFQDN +NI_NUMERICHOST +NI_NAMEREQD +NI_NUMERICSERV +NI_DGRAM + +SHUT_RD 0 +SHUT_WR 1 +SHUT_RDWR 2 + +IPV6_JOIN_GROUP +IPV6_LEAVE_GROUP +IPV6_MULTICAST_HOPS +IPV6_MULTICAST_IF +IPV6_MULTICAST_LOOP +IPV6_UNICAST_HOPS +IPV6_V6ONLY +IPV6_CHECKSUM +IPV6_DONTFRAG +IPV6_DSTOPTS +IPV6_HOPLIMIT +IPV6_HOPOPTS +IPV6_NEXTHOP +IPV6_PATHMTU +IPV6_PKTINFO +IPV6_RECVDSTOPTS +IPV6_RECVHOPLIMIT +IPV6_RECVHOPOPTS +IPV6_RECVPKTINFO +IPV6_RECVRTHDR +IPV6_RECVTCLASS +IPV6_RTHDR +IPV6_RTHDRDSTOPTS +IPV6_RTHDR_TYPE_0 +IPV6_RECVPATHMTU +IPV6_TCLASS +IPV6_USE_MIN_MTU + +INET_ADDRSTRLEN +INET6_ADDRSTRLEN +IFNAMSIZ + +SOMAXCONN + +SCM_RIGHTS +SCM_TIMESTAMP +SCM_TIMESTAMPNS +SCM_BINTIME +SCM_CREDENTIALS +SCM_CREDS +SCM_UCRED + +LOCAL_PEERCRED +LOCAL_CREDS +LOCAL_CONNWAIT diff --git a/ext/socket/option.c b/ext/socket/option.c new file mode 100644 index 0000000000..63bffb9f68 --- /dev/null +++ b/ext/socket/option.c @@ -0,0 +1,692 @@ +#include "rubysocket.h" + +VALUE rb_cSockOpt; + +static VALUE +constant_to_sym(int constant, ID (*intern_const)(int)) +{ + ID name = intern_const(constant); + if (name) { + return ID2SYM(name); + } + + return INT2NUM(constant); +} + +static VALUE +optname_to_sym(int level, int optname) +{ + switch (level) { + case SOL_SOCKET: + return constant_to_sym(optname, rsock_intern_so_optname); + case IPPROTO_IP: + return constant_to_sym(optname, rsock_intern_ip_optname); +#ifdef INET6 + case IPPROTO_IPV6: + return constant_to_sym(optname, rsock_intern_ipv6_optname); +#endif + case IPPROTO_TCP: + return constant_to_sym(optname, rsock_intern_tcp_optname); + case IPPROTO_UDP: + return constant_to_sym(optname, rsock_intern_udp_optname); + default: + return INT2NUM(optname); + } +} + +/* + * call-seq: + * Socket::Option.new(family, level, optname, data) => sockopt + * + * Returns a new Socket::Option object. + * + * sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, [1].pack("i")) + * p sockopt #=> #<Socket::Option: INET SOCKET KEEPALIVE 1> + * + */ +static VALUE +sockopt_initialize(VALUE self, VALUE vfamily, VALUE vlevel, VALUE voptname, VALUE data) +{ + int family = rsock_family_arg(vfamily); + int level = rsock_level_arg(family, vlevel); + int optname = rsock_optname_arg(family, level, voptname); + StringValue(data); + rb_ivar_set(self, rb_intern("family"), INT2NUM(family)); + rb_ivar_set(self, rb_intern("level"), INT2NUM(level)); + rb_ivar_set(self, rb_intern("optname"), INT2NUM(optname)); + rb_ivar_set(self, rb_intern("data"), data); + return self; +} + +VALUE +rsock_sockopt_new(int family, int level, int optname, VALUE data) +{ + NEWOBJ(obj, struct RObject); + OBJSETUP(obj, rb_cSockOpt, T_OBJECT); + StringValue(data); + sockopt_initialize((VALUE)obj, INT2NUM(family), INT2NUM(level), INT2NUM(optname), data); + return (VALUE)obj; +} + +/* + * call-seq: + * sockopt.family => integer + * + * returns the socket family as an integer. + * + * p Socket::Option.new(:INET6, :IPV6, :RECVPKTINFO, [1].pack("i!")).family + * #=> 10 + */ +static VALUE +sockopt_family_m(VALUE self) +{ + return rb_attr_get(self, rb_intern("family")); +} + +static int +sockopt_level(VALUE self) +{ + return NUM2INT(rb_attr_get(self, rb_intern("level"))); +} + +/* + * call-seq: + * sockopt.level => integer + * + * returns the socket level as an integer. + * + * p Socket::Option.new(:INET6, :IPV6, :RECVPKTINFO, [1].pack("i!")).level + * #=> 41 + */ +static VALUE +sockopt_level_m(VALUE self) +{ + return INT2NUM(sockopt_level(self)); +} + +static int +sockopt_optname(VALUE self) +{ + return NUM2INT(rb_attr_get(self, rb_intern("optname"))); +} + +/* + * call-seq: + * sockopt.optname => integer + * + * returns the socket option name as an integer. + * + * p Socket::Option.new(:INET6, :IPV6, :RECVPKTINFO, [1].pack("i!")).optname + * #=> 2 + */ +static VALUE +sockopt_optname_m(VALUE self) +{ + return INT2NUM(sockopt_optname(self)); +} + +/* + * call-seq: + * sockopt.data => string + * + * returns the socket option data as a string. + * + * p Socket::Option.new(:INET6, :IPV6, :RECVPKTINFO, [1].pack("i!")).data + * #=> "\x01\x00\x00\x00" + */ +static VALUE +sockopt_data(VALUE self) +{ + VALUE v = rb_attr_get(self, rb_intern("data")); + StringValue(v); + return v; +} + +/* + * call-seq: + * Socket::Option.int(family, level, optname, integer) => sockopt + * + * Creates a new Socket::Option object which contains an int as data. + * + * The size and endian is dependent on the platform. + * + * p Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 1) + * #=> #<Socket::Option: INET SOCKET KEEPALIVE 1> + */ +static VALUE +sockopt_s_int(VALUE klass, VALUE vfamily, VALUE vlevel, VALUE voptname, VALUE vint) +{ + int family = rsock_family_arg(vfamily); + int level = rsock_level_arg(family, vlevel); + int optname = rsock_optname_arg(family, level, voptname); + int i = NUM2INT(vint); + return rsock_sockopt_new(family, level, optname, rb_str_new((char*)&i, sizeof(i))); +} + +/* + * call-seq: + * sockopt.int => integer + * + * Returns the data in _sockopt_ as an int. + * + * The size and endian is dependent on the platform. + * + * sockopt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 1) + * p sockopt.int => 1 + */ +static VALUE +sockopt_int(VALUE self) +{ + int i; + VALUE data = sockopt_data(self); + StringValue(data); + if (RSTRING_LEN(data) != sizeof(int)) + rb_raise(rb_eTypeError, "size differ. expected as sizeof(int)=%d but %ld", + (int)sizeof(int), (long)RSTRING_LEN(data)); + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + return INT2NUM(i); +} + +/* + * call-seq: + * Socket::Option.bool(family, level, optname, bool) => sockopt + * + * Creates a new Socket::Option object which contains boolean as data. + * Actually 0 or 1 as int is used. + * + * p Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true) + * #=> #<Socket::Option: INET SOCKET KEEPALIVE 1> + * + * p Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false) + * #=> #<Socket::Option: AF_INET SOCKET KEEPALIVE 0> + * + */ +static VALUE +sockopt_s_bool(VALUE klass, VALUE vfamily, VALUE vlevel, VALUE voptname, VALUE vbool) +{ + int family = rsock_family_arg(vfamily); + int level = rsock_level_arg(family, vlevel); + int optname = rsock_optname_arg(family, level, voptname); + int i = RTEST(vbool) ? 1 : 0; + return rsock_sockopt_new(family, level, optname, rb_str_new((char*)&i, sizeof(i))); +} + +/* + * call-seq: + * sockopt.bool => true or false + * + * Returns the data in _sockopt_ as an boolean value. + * + * sockopt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 1) + * p sockopt.bool => true + */ +static VALUE +sockopt_bool(VALUE self) +{ + int i; + VALUE data = sockopt_data(self); + StringValue(data); + if (RSTRING_LEN(data) != sizeof(int)) + rb_raise(rb_eTypeError, "size differ. expected as sizeof(int)=%d but %ld", + (int)sizeof(int), (long)RSTRING_LEN(data)); + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + return i == 0 ? Qfalse : Qtrue; +} + +/* + * call-seq: + * Socket::Option.linger(onoff, secs) => sockopt + * + * Creates a new Socket::Option object for SOL_SOCKET/SO_LINGER. + * + * _onoff_ should be an integer or a boolean. + * + * _secs_ should be the number of seconds. + * + * p Socket::Option.linger(true, 10) + * #=> #<Socket::Option: UNSPEC SOCKET LINGER on 10sec> + * + */ +static VALUE +sockopt_s_linger(VALUE klass, VALUE vonoff, VALUE vsecs) +{ + VALUE tmp; + struct linger l; + memset(&l, 0, sizeof(l)); + if (!NIL_P(tmp = rb_check_to_integer(vonoff, "to_int"))) + l.l_onoff = NUM2INT(tmp); + else + l.l_onoff = RTEST(vonoff) ? 1 : 0; + l.l_linger = NUM2INT(vsecs); + return rsock_sockopt_new(AF_UNSPEC, SOL_SOCKET, SO_LINGER, rb_str_new((char*)&l, sizeof(l))); +} + +/* + * call-seq: + * sockopt.linger => [bool, seconds] + * + * Returns the linger data in _sockopt_ as a pair of boolean and integer. + * + * sockopt = Socket::Option.linger(true, 10) + * p sockopt.linger => [true, 10] + */ +static VALUE +sockopt_linger(VALUE self) +{ + int level = sockopt_level(self); + int optname = sockopt_optname(self); + VALUE data = sockopt_data(self); + struct linger l; + VALUE vonoff, vsecs; + + if (level != SOL_SOCKET || optname != SO_LINGER) + rb_raise(rb_eTypeError, "linger socket option expected"); + if (RSTRING_LEN(data) != sizeof(l)) + rb_raise(rb_eTypeError, "size differ. expected as sizeof(struct linger)=%d but %ld", + (int)sizeof(struct linger), (long)RSTRING_LEN(data)); + memcpy((char*)&l, RSTRING_PTR(data), sizeof(struct linger)); + switch (l.l_onoff) { + case 0: vonoff = Qfalse; break; + case 1: vonoff = Qtrue; break; + default: vonoff = INT2NUM(l.l_onoff); break; + } + vsecs = INT2NUM(l.l_linger); + return rb_assoc_new(vonoff, vsecs); +} + +static int +inspect_int(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(int)) { + int i; + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + rb_str_catf(ret, " %d", i); + return 1; + } + else { + return 0; + } +} + +static int +inspect_errno(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(int)) { + int i; + char *err; + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + err = strerror(i); + rb_str_catf(ret, " %s (%d)", err, i); + return 1; + } + else { + return 0; + } +} + +#if defined(IPV6_MULTICAST_IF) || defined(IPV6_MULTICAST_LOOP) +static int +inspect_uint(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(int)) { + unsigned int i; + memcpy((char*)&i, RSTRING_PTR(data), sizeof(unsigned int)); + rb_str_catf(ret, " %u", i); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SOL_SOCKET) && defined(SO_LINGER) /* POSIX */ +static int +inspect_linger(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct linger)) { + struct linger s; + memcpy((char*)&s, RSTRING_PTR(data), sizeof(s)); + switch (s.l_onoff) { + case 0: rb_str_cat2(ret, " off"); break; + case 1: rb_str_cat2(ret, " on"); break; + default: rb_str_catf(ret, " on(%d)", s.l_onoff); break; + } + rb_str_catf(ret, " %dsec", s.l_linger); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(SOL_SOCKET) && defined(SO_TYPE) /* POSIX */ +static int +inspect_socktype(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(int)) { + int i; + ID id; + memcpy((char*)&i, RSTRING_PTR(data), sizeof(int)); + id = rsock_intern_socktype(i); + if (id) + rb_str_catf(ret, " %s", rb_id2name(id)); + else + rb_str_catf(ret, " %d", i); + return 1; + } + else { + return 0; + } +} +#endif + +static int +inspect_timeval_as_interval(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct timeval)) { + struct timeval s; + memcpy((char*)&s, RSTRING_PTR(data), sizeof(s)); + rb_str_catf(ret, " %ld.%06ldsec", (long)s.tv_sec, (long)s.tv_usec); + return 1; + } + else { + return 0; + } +} + +#if defined(SOL_SOCKET) && defined(SO_PEERCRED) /* GNU/Linux */ +static int +inspect_peercred(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct ucred)) { + struct ucred cred; + memcpy(&cred, RSTRING_PTR(data), sizeof(struct ucred)); + rb_str_catf(ret, " pid=%u euid=%u egid=%u", + (unsigned)cred.pid, (unsigned)cred.uid, (unsigned)cred.gid); + rb_str_cat2(ret, " (ucred)"); + return 1; + } + else { + return 0; + } +} +#endif + +#if defined(LOCAL_PEERCRED) /* FreeBSD, MacOS X */ +static int +inspect_local_peercred(int level, int optname, VALUE data, VALUE ret) +{ + if (RSTRING_LEN(data) == sizeof(struct xucred)) { + struct xucred cred; + memcpy(&cred, RSTRING_PTR(data), sizeof(struct xucred)); + if (cred.cr_version != XUCRED_VERSION) + return 0; + rb_str_catf(ret, " version=%u", cred.cr_version); + rb_str_catf(ret, " euid=%u", cred.cr_uid); + if (cred.cr_ngroups) { + int i; + const char *sep = " groups="; + for (i = 0; i < cred.cr_ngroups; i++) { + rb_str_catf(ret, "%s%u", sep, cred.cr_groups[i]); + sep = ","; + } + } + rb_str_cat2(ret, " (xucred)"); + return 1; + } + else { + return 0; + } +} +#endif + + +/* + * call-seq: + * sockopt.inspect => string + * + * Returns a string which shows sockopt in human-readable form. + * + * p Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, [1].pack("i")).inspect + * #=> "#<Socket::Option: INET SOCKET KEEPALIVE 1>" + * + */ +static VALUE +sockopt_inspect(VALUE self) +{ + int family = NUM2INT(sockopt_family_m(self)); + int level = NUM2INT(sockopt_level_m(self)); + int optname = NUM2INT(sockopt_optname_m(self)); + VALUE data = sockopt_data(self); + VALUE v, ret; + ID family_id, level_id, optname_id; + int inspected; + + StringValue(data); + + ret = rb_sprintf("#<%s:", rb_obj_classname(self)); + + family_id = rsock_intern_family_noprefix(family); + if (family_id) + rb_str_catf(ret, " %s", rb_id2name(family_id)); + else + rb_str_catf(ret, " family:%d", family); + + if (level == SOL_SOCKET) { + rb_str_cat2(ret, " SOCKET"); + + optname_id = rsock_intern_so_optname(optname); + if (optname_id) + rb_str_catf(ret, " %s", rb_id2name(optname_id)); + else + rb_str_catf(ret, " optname:%d", optname); + } +#ifdef HAVE_SYS_UN_H + else if (family == AF_UNIX) { + rb_str_catf(ret, " level:%d", level); + + optname_id = rsock_intern_local_optname(optname); + if (optname_id) + rb_str_catf(ret, " %s", rb_id2name(optname_id)); + else + rb_str_catf(ret, " optname:%d", optname); + } +#endif + else if (IS_IP_FAMILY(family)) { + level_id = rsock_intern_iplevel(level); + if (level_id) + rb_str_catf(ret, " %s", rb_id2name(level_id)); + else + rb_str_catf(ret, " level:%d", level); + + v = optname_to_sym(level, optname); + if (SYMBOL_P(v)) + rb_str_catf(ret, " %s", rb_id2name(SYM2ID(v))); + else + rb_str_catf(ret, " optname:%d", optname); + } + else { + rb_str_catf(ret, " level:%d", level); + rb_str_catf(ret, " optname:%d", optname); + } + + inspected = 0; + + if (level == SOL_SOCKET) + family = AF_UNSPEC; + switch (family) { + case AF_UNSPEC: + switch (level) { + case SOL_SOCKET: + switch (optname) { +# if defined(SO_DEBUG) /* POSIX */ + case SO_DEBUG: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_ERROR) /* POSIX */ + case SO_ERROR: inspected = inspect_errno(level, optname, data, ret); break; +# endif +# if defined(SO_TYPE) /* POSIX */ + case SO_TYPE: inspected = inspect_socktype(level, optname, data, ret); break; +# endif +# if defined(SO_ACCEPTCONN) /* POSIX */ + case SO_ACCEPTCONN: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_BROADCAST) /* POSIX */ + case SO_BROADCAST: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_REUSEADDR) /* POSIX */ + case SO_REUSEADDR: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_KEEPALIVE) /* POSIX */ + case SO_KEEPALIVE: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_OOBINLINE) /* POSIX */ + case SO_OOBINLINE: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_SNDBUF) /* POSIX */ + case SO_SNDBUF: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_RCVBUF) /* POSIX */ + case SO_RCVBUF: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_DONTROUTE) /* POSIX */ + case SO_DONTROUTE: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_RCVLOWAT) /* POSIX */ + case SO_RCVLOWAT: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_SNDLOWAT) /* POSIX */ + case SO_SNDLOWAT: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(SO_LINGER) /* POSIX */ + case SO_LINGER: inspected = inspect_linger(level, optname, data, ret); break; +# endif +# if defined(SO_RCVTIMEO) /* POSIX */ + case SO_RCVTIMEO: inspected = inspect_timeval_as_interval(level, optname, data, ret); break; +# endif +# if defined(SO_SNDTIMEO) /* POSIX */ + case SO_SNDTIMEO: inspected = inspect_timeval_as_interval(level, optname, data, ret); break; +# endif +# if defined(SO_PEERCRED) /* GNU/Linux */ + case SO_PEERCRED: inspected = inspect_peercred(level, optname, data, ret); break; +# endif + } + break; + } + break; + + case AF_INET: +#ifdef INET6 + case AF_INET6: +#endif + switch (level) { +# if defined(IPPROTO_IPV6) + case IPPROTO_IPV6: + switch (optname) { + /* IPV6_JOIN_GROUP ipv6_mreq, IPV6_LEAVE_GROUP ipv6_mreq */ +# if defined(IPV6_MULTICAST_HOPS) /* POSIX */ + case IPV6_MULTICAST_HOPS: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(IPV6_MULTICAST_IF) /* POSIX */ + case IPV6_MULTICAST_IF: inspected = inspect_uint(level, optname, data, ret); break; +# endif +# if defined(IPV6_MULTICAST_LOOP) /* POSIX */ + case IPV6_MULTICAST_LOOP: inspected = inspect_uint(level, optname, data, ret); break; +# endif +# if defined(IPV6_UNICAST_HOPS) /* POSIX */ + case IPV6_UNICAST_HOPS: inspected = inspect_int(level, optname, data, ret); break; +# endif +# if defined(IPV6_V6ONLY) /* POSIX */ + case IPV6_V6ONLY: inspected = inspect_int(level, optname, data, ret); break; +# endif + } + break; +# endif + +# if defined(IPPROTO_TCP) + case IPPROTO_TCP: + switch (optname) { +# if defined(TCP_NODELAY) /* POSIX */ + case TCP_NODELAY: inspected = inspect_int(level, optname, data, ret); break; +# endif + } + break; +# endif + } + break; + +#ifdef HAVE_SYS_UN_H + case AF_UNIX: + switch (level) { + case 0: + switch (optname) { +# if defined(LOCAL_PEERCRED) + case LOCAL_PEERCRED: inspected = inspect_local_peercred(level, optname, data, ret); break; +# endif + } + break; + } + break; +#endif + } + + if (!inspected) { + rb_str_cat2(ret, " "); + rb_str_append(ret, rb_str_dump(data)); + } + + rb_str_cat2(ret, ">"); + + return ret; +} + +/* + * call-seq: + * sockopt.unpack(template) => array + * + * Calls String#unpack on sockopt.data. + * + * sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, [1].pack("i")) + * p sockopt.unpack("i") #=> [1] + * p sockopt.data.unpack("i") #=> [1] + */ +static VALUE +sockopt_unpack(VALUE self, VALUE template) +{ + return rb_funcall(sockopt_data(self), rb_intern("unpack"), 1, template); +} + +/* + * Document-class: ::Socket::Option + * + * Socket::Option represents a socket option used by getsockopt and setsockopt + * system call. + * It contains socket family, protocol level, option name and option value. + */ +void +rsock_init_sockopt(void) +{ + rb_cSockOpt = rb_define_class_under(rb_cSocket, "Option", rb_cObject); + rb_define_method(rb_cSockOpt, "initialize", sockopt_initialize, 4); + rb_define_method(rb_cSockOpt, "family", sockopt_family_m, 0); + rb_define_method(rb_cSockOpt, "level", sockopt_level_m, 0); + rb_define_method(rb_cSockOpt, "optname", sockopt_optname_m, 0); + rb_define_method(rb_cSockOpt, "data", sockopt_data, 0); + rb_define_method(rb_cSockOpt, "inspect", sockopt_inspect, 0); + + rb_define_singleton_method(rb_cSockOpt, "int", sockopt_s_int, 4); + rb_define_method(rb_cSockOpt, "int", sockopt_int, 0); + + rb_define_singleton_method(rb_cSockOpt, "bool", sockopt_s_bool, 4); + rb_define_method(rb_cSockOpt, "bool", sockopt_bool, 0); + + rb_define_singleton_method(rb_cSockOpt, "linger", sockopt_s_linger, 2); + rb_define_method(rb_cSockOpt, "linger", sockopt_linger, 0); + + rb_define_method(rb_cSockOpt, "unpack", sockopt_unpack, 1); + + rb_define_method(rb_cSockOpt, "to_s", sockopt_data, 0); /* compatibility for ruby before 1.9.2 */ +} + diff --git a/ext/socket/raddrinfo.c b/ext/socket/raddrinfo.c new file mode 100644 index 0000000000..65b2b63927 --- /dev/null +++ b/ext/socket/raddrinfo.c @@ -0,0 +1,2211 @@ +/************************************************ + + ainfo.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6)) +#define LOOKUP_ORDERS (sizeof(lookup_order_table) / sizeof(lookup_order_table[0])) +static const int lookup_order_table[] = { +#if defined(LOOKUP_ORDER_HACK_INET) + PF_INET, PF_INET6, PF_UNSPEC, +#elif defined(LOOKUP_ORDER_HACK_INET6) + PF_INET6, PF_INET, PF_UNSPEC, +#else + /* should not happen */ +#endif +}; + +static int +ruby_getaddrinfo(const char *nodename, const char *servname, + const struct addrinfo *hints, struct addrinfo **res) +{ + struct addrinfo tmp_hints; + int i, af, error; + + if (hints->ai_family != PF_UNSPEC) { + return getaddrinfo(nodename, servname, hints, res); + } + + for (i = 0; i < LOOKUP_ORDERS; i++) { + af = lookup_order_table[i]; + MEMCPY(&tmp_hints, hints, struct addrinfo, 1); + tmp_hints.ai_family = af; + error = getaddrinfo(nodename, servname, &tmp_hints, res); + if (error) { + if (tmp_hints.ai_family == PF_UNSPEC) { + break; + } + } + else { + break; + } + } + + return error; +} +#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res)) +#endif + +#if defined(_AIX) +static int +ruby_getaddrinfo__aix(const char *nodename, const char *servname, + struct addrinfo *hints, struct addrinfo **res) +{ + int error = getaddrinfo(nodename, servname, hints, res); + struct addrinfo *r; + if (error) + return error; + for (r = *res; r != NULL; r = r->ai_next) { + if (r->ai_addr->sa_family == 0) + r->ai_addr->sa_family = r->ai_family; + if (r->ai_addr->sa_len == 0) + r->ai_addr->sa_len = r->ai_addrlen; + } + return 0; +} +#undef getaddrinfo +#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res)) +static int +ruby_getnameinfo__aix(const struct sockaddr *sa, size_t salen, + char *host, size_t hostlen, + char *serv, size_t servlen, int flags) +{ + struct sockaddr_in6 *sa6; + u_int32_t *a6; + + if (sa->sa_family == AF_INET6) { + sa6 = (struct sockaddr_in6 *)sa; + a6 = sa6->sin6_addr.u6_addr.u6_addr32; + + if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) { + strncpy(host, "::", hostlen); + snprintf(serv, servlen, "%d", sa6->sin6_port); + return 0; + } + } + return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags); +} +#undef getnameinfo +#define getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) \ + ruby_getnameinfo__aix((sa), (salen), (host), (hostlen), (serv), (servlen), (flags)) +#endif + +static int str_is_number(const char *); + +#if defined(__APPLE__) +/* fix [ruby-core:29427] */ +static int +ruby_getaddrinfo__darwin(const char *nodename, const char *servname, + struct addrinfo *hints, struct addrinfo **res) +{ + const char *tmp_servname; + struct addrinfo tmp_hints; + tmp_servname = servname; + MEMCPY(&tmp_hints, hints, struct addrinfo, 1); + if (nodename && servname) { + if (str_is_number(tmp_servname) && atoi(servname) == 0) { + tmp_servname = NULL; +#ifdef AI_NUMERICSERV + if (tmp_hints.ai_flags) tmp_hints.ai_flags &= ~AI_NUMERICSERV; +#endif + } + } + int error = getaddrinfo(nodename, tmp_servname, &tmp_hints, res); + return error; +} +#undef getaddrinfo +#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__darwin((node),(serv),(hints),(res)) +#endif + +#ifndef GETADDRINFO_EMU +struct getaddrinfo_arg +{ + const char *node; + const char *service; + const struct addrinfo *hints; + struct addrinfo **res; +}; + +static VALUE +nogvl_getaddrinfo(void *arg) +{ + struct getaddrinfo_arg *ptr = arg; + return getaddrinfo(ptr->node, ptr->service, + ptr->hints, ptr->res); +} +#endif + +int +rb_getaddrinfo(const char *node, const char *service, + const struct addrinfo *hints, + struct addrinfo **res) +{ +#ifdef GETADDRINFO_EMU + return getaddrinfo(node, service, hints, res); +#else + struct getaddrinfo_arg arg; + int ret; + MEMZERO(&arg, sizeof arg, 1); + arg.node = node; + arg.service = service; + arg.hints = hints; + arg.res = res; + ret = (int)BLOCKING_REGION(nogvl_getaddrinfo, &arg); + return ret; +#endif +} + +#ifndef GETADDRINFO_EMU +struct getnameinfo_arg +{ + const struct sockaddr *sa; + socklen_t salen; + char *host; + size_t hostlen; + char *serv; + size_t servlen; + int flags; +}; + +static VALUE +nogvl_getnameinfo(void *arg) +{ + struct getnameinfo_arg *ptr = arg; + return getnameinfo(ptr->sa, ptr->salen, + ptr->host, (socklen_t)ptr->hostlen, + ptr->serv, (socklen_t)ptr->servlen, + ptr->flags); +} +#endif + +int +rb_getnameinfo(const struct sockaddr *sa, socklen_t salen, + char *host, size_t hostlen, + char *serv, size_t servlen, int flags) +{ +#ifdef GETADDRINFO_EMU + return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags); +#else + struct getnameinfo_arg arg; + int ret; + arg.sa = sa; + arg.salen = salen; + arg.host = host; + arg.hostlen = hostlen; + arg.serv = serv; + arg.servlen = servlen; + arg.flags = flags; + ret = (int)BLOCKING_REGION(nogvl_getnameinfo, &arg); + return ret; +#endif +} + +static void +make_ipaddr0(struct sockaddr *addr, char *buf, size_t len) +{ + int error; + + error = rb_getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST); + if (error) { + rsock_raise_socket_error("getnameinfo", error); + } +} + +VALUE +rsock_make_ipaddr(struct sockaddr *addr) +{ + char hbuf[1024]; + + make_ipaddr0(addr, hbuf, sizeof(hbuf)); + return rb_str_new2(hbuf); +} + +static void +make_inetaddr(unsigned int host, char *buf, size_t len) +{ + struct sockaddr_in sin; + + MEMZERO(&sin, struct sockaddr_in, 1); + sin.sin_family = AF_INET; + SET_SIN_LEN(&sin, sizeof(sin)); + sin.sin_addr.s_addr = host; + make_ipaddr0((struct sockaddr*)&sin, buf, len); +} + +static int +str_is_number(const char *p) +{ + char *ep; + + if (!p || *p == '\0') + return 0; + ep = NULL; + (void)STRTOUL(p, &ep, 10); + if (ep && *ep == '\0') + return 1; + else + return 0; +} + +static char* +host_str(VALUE host, char *hbuf, size_t len, int *flags_ptr) +{ + if (NIL_P(host)) { + return NULL; + } + else if (rb_obj_is_kind_of(host, rb_cInteger)) { + unsigned int i = NUM2UINT(host); + + make_inetaddr(htonl(i), hbuf, len); + if (flags_ptr) *flags_ptr |= AI_NUMERICHOST; + return hbuf; + } + else { + char *name; + + SafeStringValue(host); + name = RSTRING_PTR(host); + if (!name || *name == 0 || (name[0] == '<' && strcmp(name, "<any>") == 0)) { + make_inetaddr(INADDR_ANY, hbuf, len); + if (flags_ptr) *flags_ptr |= AI_NUMERICHOST; + } + else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) { + make_inetaddr(INADDR_BROADCAST, hbuf, len); + if (flags_ptr) *flags_ptr |= AI_NUMERICHOST; + } + else if (strlen(name) >= len) { + rb_raise(rb_eArgError, "hostname too long (%"PRIuSIZE")", + strlen(name)); + } + else { + strcpy(hbuf, name); + } + return hbuf; + } +} + +static char* +port_str(VALUE port, char *pbuf, size_t len, int *flags_ptr) +{ + if (NIL_P(port)) { + return 0; + } + else if (FIXNUM_P(port)) { + snprintf(pbuf, len, "%ld", FIX2LONG(port)); +#ifdef AI_NUMERICSERV + if (flags_ptr) *flags_ptr |= AI_NUMERICSERV; +#endif + return pbuf; + } + else { + char *serv; + + SafeStringValue(port); + serv = RSTRING_PTR(port); + if (strlen(serv) >= len) { + rb_raise(rb_eArgError, "service name too long (%"PRIuSIZE")", + strlen(serv)); + } + strcpy(pbuf, serv); + return pbuf; + } +} + +struct addrinfo* +rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack) +{ + struct addrinfo* res = NULL; + char *hostp, *portp; + int error; + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + int additional_flags = 0; + + hostp = host_str(host, hbuf, sizeof(hbuf), &additional_flags); + portp = port_str(port, pbuf, sizeof(pbuf), &additional_flags); + + if (socktype_hack && hints->ai_socktype == 0 && str_is_number(portp)) { + hints->ai_socktype = SOCK_DGRAM; + } + hints->ai_flags |= additional_flags; + + error = rb_getaddrinfo(hostp, portp, hints, &res); + if (error) { + if (hostp && hostp[strlen(hostp)-1] == '\n') { + rb_raise(rb_eSocket, "newline at the end of hostname"); + } + rsock_raise_socket_error("getaddrinfo", error); + } + +#if defined(__APPLE__) && defined(__MACH__) + /* [ruby-dev:23164] */ + { + struct addrinfo *r; + r = res; + while (r) { + if (! r->ai_socktype) r->ai_socktype = hints->ai_socktype; + if (! r->ai_protocol) { + if (r->ai_socktype == SOCK_DGRAM) { + r->ai_protocol = IPPROTO_UDP; + } + else if (r->ai_socktype == SOCK_STREAM) { + r->ai_protocol = IPPROTO_TCP; + } + } + r = r->ai_next; + } + } +#endif + return res; +} + +struct addrinfo* +rsock_addrinfo(VALUE host, VALUE port, int socktype, int flags) +{ + struct addrinfo hints; + + MEMZERO(&hints, struct addrinfo, 1); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = socktype; + hints.ai_flags = flags; + return rsock_getaddrinfo(host, port, &hints, 1); +} + +VALUE +rsock_ipaddr(struct sockaddr *sockaddr, int norevlookup) +{ + VALUE family, port, addr1, addr2; + VALUE ary; + int error; + char hbuf[1024], pbuf[1024]; + ID id; + + id = rsock_intern_family(sockaddr->sa_family); + if (id) { + family = rb_str_dup(rb_id2str(id)); + } + else { + sprintf(pbuf, "unknown:%d", sockaddr->sa_family); + family = rb_str_new2(pbuf); + } + + addr1 = Qnil; + if (!norevlookup) { + error = rb_getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), + NULL, 0, 0); + if (! error) { + addr1 = rb_str_new2(hbuf); + } + } + error = rb_getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), + pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV); + if (error) { + rsock_raise_socket_error("getnameinfo", error); + } + addr2 = rb_str_new2(hbuf); + if (addr1 == Qnil) { + addr1 = addr2; + } + port = INT2FIX(atoi(pbuf)); + ary = rb_ary_new3(4, family, port, addr1, addr2); + + return ary; +} + +#ifdef HAVE_SYS_UN_H +const char* +rsock_unixpath(struct sockaddr_un *sockaddr, socklen_t len) +{ + if (sockaddr->sun_path < (char*)sockaddr + len) + return sockaddr->sun_path; + else + return ""; +} + +VALUE +rsock_unixaddr(struct sockaddr_un *sockaddr, socklen_t len) +{ + return rb_assoc_new(rb_str_new2("AF_UNIX"), + rb_str_new2(rsock_unixpath(sockaddr, len))); +} +#endif + +struct hostent_arg { + VALUE host; + struct addrinfo* addr; + VALUE (*ipaddr)(struct sockaddr*, size_t); +}; + +static VALUE +make_hostent_internal(struct hostent_arg *arg) +{ + VALUE host = arg->host; + struct addrinfo* addr = arg->addr; + VALUE (*ipaddr)(struct sockaddr*, size_t) = arg->ipaddr; + + struct addrinfo *ai; + struct hostent *h; + VALUE ary, names; + char **pch; + const char* hostp; + char hbuf[NI_MAXHOST]; + + ary = rb_ary_new(); + if (addr->ai_canonname) { + hostp = addr->ai_canonname; + } + else { + hostp = host_str(host, hbuf, sizeof(hbuf), NULL); + } + rb_ary_push(ary, rb_str_new2(hostp)); + + if (addr->ai_canonname && (h = gethostbyname(addr->ai_canonname))) { + names = rb_ary_new(); + if (h->h_aliases != NULL) { + for (pch = h->h_aliases; *pch; pch++) { + rb_ary_push(names, rb_str_new2(*pch)); + } + } + } + else { + names = rb_ary_new2(0); + } + rb_ary_push(ary, names); + rb_ary_push(ary, INT2NUM(addr->ai_family)); + for (ai = addr; ai; ai = ai->ai_next) { + rb_ary_push(ary, (*ipaddr)(ai->ai_addr, ai->ai_addrlen)); + } + + return ary; +} + +VALUE +rsock_freeaddrinfo(struct addrinfo *addr) +{ + freeaddrinfo(addr); + return Qnil; +} + +VALUE +rsock_make_hostent(VALUE host, struct addrinfo *addr, VALUE (*ipaddr)(struct sockaddr *, size_t)) +{ + struct hostent_arg arg; + + arg.host = host; + arg.addr = addr; + arg.ipaddr = ipaddr; + return rb_ensure(make_hostent_internal, (VALUE)&arg, + rsock_freeaddrinfo, (VALUE)addr); +} + +typedef struct { + VALUE inspectname; + VALUE canonname; + int pfamily; + int socktype; + int protocol; + socklen_t sockaddr_len; + struct sockaddr_storage addr; +} rb_addrinfo_t; + +static void +addrinfo_mark(void *ptr) +{ + rb_addrinfo_t *rai = ptr; + if (rai) { + rb_gc_mark(rai->inspectname); + rb_gc_mark(rai->canonname); + } +} + +#define addrinfo_free RUBY_TYPED_DEFAULT_FREE + +static size_t +addrinfo_memsize(const void *ptr) +{ + return ptr ? sizeof(rb_addrinfo_t) : 0; +} + +static const rb_data_type_t addrinfo_type = { + "socket/addrinfo", + addrinfo_mark, addrinfo_free, addrinfo_memsize, +}; + +static VALUE +addrinfo_s_allocate(VALUE klass) +{ + return TypedData_Wrap_Struct(klass, &addrinfo_type, 0); +} + +#define IS_ADDRINFO(obj) rb_typeddata_is_kind_of(obj, &addrinfo_type) +static inline rb_addrinfo_t * +check_addrinfo(VALUE self) +{ + return rb_check_typeddata(self, &addrinfo_type); +} + +static rb_addrinfo_t * +get_addrinfo(VALUE self) +{ + rb_addrinfo_t *rai = check_addrinfo(self); + + if (!rai) { + rb_raise(rb_eTypeError, "uninitialized socket address"); + } + return rai; +} + + +static rb_addrinfo_t * +alloc_addrinfo() +{ + rb_addrinfo_t *rai = ALLOC(rb_addrinfo_t); + memset(rai, 0, sizeof(rb_addrinfo_t)); + rai->inspectname = Qnil; + rai->canonname = Qnil; + return rai; +} + +static void +init_addrinfo(rb_addrinfo_t *rai, struct sockaddr *sa, socklen_t len, + int pfamily, int socktype, int protocol, + VALUE canonname, VALUE inspectname) +{ + if (sizeof(rai->addr) < len) + rb_raise(rb_eArgError, "sockaddr string too big"); + memcpy((void *)&rai->addr, (void *)sa, len); + rai->sockaddr_len = len; + + rai->pfamily = pfamily; + rai->socktype = socktype; + rai->protocol = protocol; + rai->canonname = canonname; + rai->inspectname = inspectname; +} + +VALUE +rsock_addrinfo_new(struct sockaddr *addr, socklen_t len, + int family, int socktype, int protocol, + VALUE canonname, VALUE inspectname) +{ + VALUE a; + rb_addrinfo_t *rai; + + a = addrinfo_s_allocate(rb_cAddrinfo); + DATA_PTR(a) = rai = alloc_addrinfo(); + init_addrinfo(rai, addr, len, family, socktype, protocol, canonname, inspectname); + return a; +} + +static struct addrinfo * +call_getaddrinfo(VALUE node, VALUE service, + VALUE family, VALUE socktype, VALUE protocol, VALUE flags, + int socktype_hack) +{ + struct addrinfo hints, *res; + + MEMZERO(&hints, struct addrinfo, 1); + hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family); + + if (!NIL_P(socktype)) { + hints.ai_socktype = rsock_socktype_arg(socktype); + } + if (!NIL_P(protocol)) { + hints.ai_protocol = NUM2INT(protocol); + } + if (!NIL_P(flags)) { + hints.ai_flags = NUM2INT(flags); + } + res = rsock_getaddrinfo(node, service, &hints, socktype_hack); + + if (res == NULL) + rb_raise(rb_eSocket, "host not found"); + return res; +} + +static VALUE make_inspectname(VALUE node, VALUE service, struct addrinfo *res); + +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) +{ + struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 1); + VALUE canonname; + VALUE inspectname = rb_str_equal(node, inspectnode) ? Qnil : make_inspectname(inspectnode, inspectservice, res); + + canonname = Qnil; + if (res->ai_canonname) { + canonname = rb_tainted_str_new_cstr(res->ai_canonname); + OBJ_FREEZE(canonname); + } + + init_addrinfo(rai, res->ai_addr, res->ai_addrlen, + NUM2INT(family), NUM2INT(socktype), NUM2INT(protocol), + canonname, inspectname); + + freeaddrinfo(res); +} + +static VALUE +make_inspectname(VALUE node, VALUE service, struct addrinfo *res) +{ + VALUE inspectname = Qnil; + + if (res) { + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + int ret; + ret = rb_getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, + sizeof(hbuf), pbuf, sizeof(pbuf), + NI_NUMERICHOST|NI_NUMERICSERV); + if (ret == 0) { + if (TYPE(node) == T_STRING && strcmp(hbuf, RSTRING_PTR(node)) == 0) + node = Qnil; + if (TYPE(service) == T_STRING && strcmp(pbuf, RSTRING_PTR(service)) == 0) + service = Qnil; + else if (TYPE(service) == T_FIXNUM && atoi(pbuf) == FIX2INT(service)) + service = Qnil; + } + } + + if (TYPE(node) == T_STRING) { + inspectname = rb_str_dup(node); + } + if (TYPE(service) == T_STRING) { + if (NIL_P(inspectname)) + inspectname = rb_sprintf(":%s", StringValueCStr(service)); + else + rb_str_catf(inspectname, ":%s", StringValueCStr(service)); + } + else if (TYPE(service) == T_FIXNUM && FIX2INT(service) != 0) + { + if (NIL_P(inspectname)) + inspectname = rb_sprintf(":%d", FIX2INT(service)); + else + rb_str_catf(inspectname, ":%d", FIX2INT(service)); + } + if (!NIL_P(inspectname)) { + OBJ_INFECT(inspectname, node); + OBJ_INFECT(inspectname, service); + OBJ_FREEZE(inspectname); + } + return inspectname; +} + +static VALUE +addrinfo_firstonly_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags) +{ + VALUE ret; + VALUE canonname; + VALUE inspectname; + + struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0); + + inspectname = make_inspectname(node, service, res); + + canonname = Qnil; + if (res->ai_canonname) { + canonname = rb_tainted_str_new_cstr(res->ai_canonname); + OBJ_FREEZE(canonname); + } + + ret = rsock_addrinfo_new(res->ai_addr, res->ai_addrlen, + res->ai_family, res->ai_socktype, res->ai_protocol, + canonname, inspectname); + + freeaddrinfo(res); + return ret; +} + +static VALUE +addrinfo_list_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags) +{ + VALUE ret; + struct addrinfo *r; + VALUE inspectname; + + struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0); + + inspectname = make_inspectname(node, service, res); + + ret = rb_ary_new(); + for (r = res; r; r = r->ai_next) { + VALUE addr; + VALUE canonname = Qnil; + + if (r->ai_canonname) { + canonname = rb_tainted_str_new_cstr(r->ai_canonname); + OBJ_FREEZE(canonname); + } + + addr = rsock_addrinfo_new(r->ai_addr, r->ai_addrlen, + r->ai_family, r->ai_socktype, r->ai_protocol, + canonname, inspectname); + + rb_ary_push(ret, addr); + } + + freeaddrinfo(res); + return ret; +} + + +#ifdef HAVE_SYS_UN_H +static void +init_unix_addrinfo(rb_addrinfo_t *rai, VALUE path, int socktype) +{ + struct sockaddr_un un; + + StringValue(path); + + if (sizeof(un.sun_path) <= (size_t)RSTRING_LEN(path)) + rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)", + (int)sizeof(un.sun_path)-1); + + MEMZERO(&un, struct sockaddr_un, 1); + + un.sun_family = AF_UNIX; + memcpy((void*)&un.sun_path, RSTRING_PTR(path), RSTRING_LEN(path)); + + init_addrinfo(rai, (struct sockaddr *)&un, (socklen_t)sizeof(un), + PF_UNIX, socktype, 0, Qnil, Qnil); +} +#endif + +/* + * call-seq: + * Addrinfo.new(sockaddr) => addrinfo + * Addrinfo.new(sockaddr, family) => addrinfo + * Addrinfo.new(sockaddr, family, socktype) => addrinfo + * Addrinfo.new(sockaddr, family, socktype, protocol) => addrinfo + * + * returns a new instance of Addrinfo. + * The instance contains sockaddr, family, socktype, protocol. + * sockaddr means struct sockaddr which can be used for connect(2), etc. + * family, socktype and protocol are integers which is used for arguments of socket(2). + * + * sockaddr is specified as an array or a string. + * The array should be compatible to the value of IPSocket#addr or UNIXSocket#addr. + * The string should be struct sockaddr as generated by + * Socket.sockaddr_in or Socket.unpack_sockaddr_un. + * + * sockaddr examples: + * - ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] + * - ["AF_INET6", 42304, "ip6-localhost", "::1"] + * - ["AF_UNIX", "/tmp/sock"] + * - Socket.sockaddr_in("smtp", "2001:DB8::1") + * - Socket.sockaddr_in(80, "172.18.22.42") + * - Socket.sockaddr_in(80, "www.ruby-lang.org") + * - Socket.sockaddr_un("/tmp/sock") + * + * In an AF_INET/AF_INET6 sockaddr array, the 4th element, + * numeric IP address, is used to construct socket address in the Addrinfo instance. + * If the 3rd element, textual host name, is non-nil, it is also recorded but used only for Addrinfo#inspect. + * + * family is specified as an integer to specify the protocol family such as Socket::PF_INET. + * It can be a symbol or a string which is the constant name + * with or without PF_ prefix such as :INET, :INET6, :UNIX, "PF_INET", etc. + * If omitted, PF_UNSPEC is assumed. + * + * socktype is specified as an integer to specify the socket type such as Socket::SOCK_STREAM. + * It can be a symbol or a string which is the constant name + * with or without SOCK_ prefix such as :STREAM, :DGRAM, :RAW, "SOCK_STREAM", etc. + * If omitted, 0 is assumed. + * + * protocol is specified as an integer to specify the protocol such as Socket::IPPROTO_TCP. + * It must be an integer, unlike family and socktype. + * If omitted, 0 is assumed. + * Note that 0 is reasonable value for most protocols, except raw socket. + * + */ +static VALUE +addrinfo_initialize(int argc, VALUE *argv, VALUE self) +{ + rb_addrinfo_t *rai; + VALUE sockaddr_arg, sockaddr_ary, pfamily, socktype, protocol; + int i_pfamily, i_socktype, i_protocol; + struct sockaddr *sockaddr_ptr; + socklen_t sockaddr_len; + VALUE canonname = Qnil, inspectname = Qnil; + + if (check_addrinfo(self)) + rb_raise(rb_eTypeError, "already initialized socket address"); + DATA_PTR(self) = rai = alloc_addrinfo(); + + rb_scan_args(argc, argv, "13", &sockaddr_arg, &pfamily, &socktype, &protocol); + + i_pfamily = NIL_P(pfamily) ? PF_UNSPEC : rsock_family_arg(pfamily); + i_socktype = NIL_P(socktype) ? 0 : rsock_socktype_arg(socktype); + i_protocol = NIL_P(protocol) ? 0 : NUM2INT(protocol); + + sockaddr_ary = rb_check_array_type(sockaddr_arg); + if (!NIL_P(sockaddr_ary)) { + VALUE afamily = rb_ary_entry(sockaddr_ary, 0); + int af; + StringValue(afamily); + if (rsock_family_to_int(RSTRING_PTR(afamily), RSTRING_LEN(afamily), &af) == -1) + rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily)); + switch (af) { + case AF_INET: /* ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] */ +#ifdef INET6 + case AF_INET6: /* ["AF_INET6", 42304, "ip6-localhost", "::1"] */ +#endif + { + VALUE service = rb_ary_entry(sockaddr_ary, 1); + VALUE nodename = rb_ary_entry(sockaddr_ary, 2); + VALUE numericnode = rb_ary_entry(sockaddr_ary, 3); + int flags; + + service = INT2NUM(NUM2INT(service)); + if (!NIL_P(nodename)) + StringValue(nodename); + StringValue(numericnode); + flags = AI_NUMERICHOST; +#ifdef AI_NUMERICSERV + flags |= AI_NUMERICSERV; +#endif + + init_addrinfo_getaddrinfo(rai, numericnode, service, + INT2NUM(i_pfamily ? i_pfamily : af), INT2NUM(i_socktype), INT2NUM(i_protocol), + INT2NUM(flags), + nodename, service); + break; + } + +#ifdef HAVE_SYS_UN_H + case AF_UNIX: /* ["AF_UNIX", "/tmp/sock"] */ + { + VALUE path = rb_ary_entry(sockaddr_ary, 1); + StringValue(path); + init_unix_addrinfo(rai, path, SOCK_STREAM); + break; + } +#endif + + default: + rb_raise(rb_eSocket, "unexpected address family"); + } + } + else { + StringValue(sockaddr_arg); + sockaddr_ptr = (struct sockaddr *)RSTRING_PTR(sockaddr_arg); + sockaddr_len = RSTRING_LENINT(sockaddr_arg); + init_addrinfo(rai, sockaddr_ptr, sockaddr_len, + i_pfamily, i_socktype, i_protocol, + canonname, inspectname); + } + + return self; +} + +static int +get_afamily(struct sockaddr *addr, socklen_t len) +{ + if ((char*)&addr->sa_family + sizeof(addr->sa_family) - (char*)addr <= len) + return addr->sa_family; + else + return AF_UNSPEC; +} + +static int +ai_get_afamily(rb_addrinfo_t *rai) +{ + return get_afamily((struct sockaddr *)&rai->addr, rai->sockaddr_len); +} + +static VALUE +inspect_sockaddr(VALUE addrinfo, VALUE ret) +{ + rb_addrinfo_t *rai = get_addrinfo(addrinfo); + + if (rai->sockaddr_len == 0) { + rb_str_cat2(ret, "empty-sockaddr"); + } + else if ((long)rai->sockaddr_len < ((char*)&rai->addr.ss_family + sizeof(rai->addr.ss_family)) - (char*)&rai->addr) + rb_str_cat2(ret, "too-short-sockaddr"); + else { + switch (rai->addr.ss_family) { + case AF_INET: + { + struct sockaddr_in *addr; + int port; + if (rai->sockaddr_len < sizeof(struct sockaddr_in)) { + rb_str_cat2(ret, "too-short-AF_INET-sockaddr"); + } + else { + addr = (struct sockaddr_in *)&rai->addr; + rb_str_catf(ret, "%d.%d.%d.%d", + ((unsigned char*)&addr->sin_addr)[0], + ((unsigned char*)&addr->sin_addr)[1], + ((unsigned char*)&addr->sin_addr)[2], + ((unsigned char*)&addr->sin_addr)[3]); + port = ntohs(addr->sin_port); + if (port) + rb_str_catf(ret, ":%d", port); + if (sizeof(struct sockaddr_in) < rai->sockaddr_len) + rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(rai->sockaddr_len - sizeof(struct sockaddr_in))); + } + break; + } + +#ifdef AF_INET6 + case AF_INET6: + { + struct sockaddr_in6 *addr; + char hbuf[1024]; + int port; + int error; + if (rai->sockaddr_len < sizeof(struct sockaddr_in6)) { + rb_str_cat2(ret, "too-short-AF_INET6-sockaddr"); + } + else { + addr = (struct sockaddr_in6 *)&rai->addr; + /* use getnameinfo for scope_id. + * RFC 4007: IPv6 Scoped Address Architecture + * draft-ietf-ipv6-scope-api-00.txt: Scoped Address Extensions to the IPv6 Basic Socket API + */ + error = getnameinfo((struct sockaddr *)&rai->addr, rai->sockaddr_len, + hbuf, (socklen_t)sizeof(hbuf), NULL, 0, + NI_NUMERICHOST|NI_NUMERICSERV); + if (error) { + rsock_raise_socket_error("getnameinfo", error); + } + if (addr->sin6_port == 0) { + rb_str_cat2(ret, hbuf); + } + else { + port = ntohs(addr->sin6_port); + rb_str_catf(ret, "[%s]:%d", hbuf, port); + } + if (sizeof(struct sockaddr_in6) < rai->sockaddr_len) + rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(rai->sockaddr_len - sizeof(struct sockaddr_in6))); + } + break; + } +#endif + +#ifdef HAVE_SYS_UN_H + case AF_UNIX: + { + struct sockaddr_un *addr = (struct sockaddr_un *)&rai->addr; + char *p, *s, *t, *e; + s = addr->sun_path; + e = (char*)addr + rai->sockaddr_len; + if (e < s) + rb_str_cat2(ret, "too-short-AF_UNIX-sockaddr"); + else if (s == e) + rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr"); + else { + int printable_only = 1; + p = s; + while (p < e && *p != '\0') { + printable_only = printable_only && ISPRINT(*p) && !ISSPACE(*p); + p++; + } + t = p; + while (p < e && *p == '\0') + p++; + if (printable_only && /* only printable, no space */ + t < e && /* NUL terminated */ + p == e) { /* no data after NUL */ + if (s == t) + rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr"); + else if (s[0] == '/') /* absolute path */ + rb_str_cat2(ret, s); + else + rb_str_catf(ret, "AF_UNIX %s", s); + } + else { + rb_str_cat2(ret, "AF_UNIX"); + e = (char *)addr->sun_path + sizeof(addr->sun_path); + while (s < e && *(e-1) == '\0') + e--; + while (s < e) + rb_str_catf(ret, ":%02x", (unsigned char)*s++); + } + if (addr->sun_path + sizeof(addr->sun_path) < (char*)&rai->addr + rai->sockaddr_len) + rb_str_catf(ret, "(sockaddr %d bytes too long)", + (int)(rai->sockaddr_len - (addr->sun_path + sizeof(addr->sun_path) - (char*)&rai->addr))); + } + break; + } +#endif + + default: + { + ID id = rsock_intern_family(rai->addr.ss_family); + if (id == 0) + rb_str_catf(ret, "unknown address family %d", rai->addr.ss_family); + else + rb_str_catf(ret, "%s address format unknown", rb_id2name(id)); + break; + } + } + } + + return ret; +} + +/* + * call-seq: + * addrinfo.inspect => string + * + * returns a string which shows addrinfo in human-readable form. + * + * Addrinfo.tcp("localhost", 80).inspect #=> "#<Addrinfo: 127.0.0.1:80 TCP (localhost:80)>" + * Addrinfo.unix("/tmp/sock").inspect #=> "#<Addrinfo: /tmp/sock SOCK_STREAM>" + * + */ +static VALUE +addrinfo_inspect(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int internet_p; + VALUE ret; + + ret = rb_sprintf("#<%s: ", rb_obj_classname(self)); + + inspect_sockaddr(self, ret); + + if (rai->pfamily && ai_get_afamily(rai) != rai->pfamily) { + ID id = rsock_intern_protocol_family(rai->pfamily); + if (id) + rb_str_catf(ret, " %s", rb_id2name(id)); + else + rb_str_catf(ret, " PF_\?\?\?(%d)", rai->pfamily); + } + + internet_p = rai->pfamily == PF_INET; +#ifdef INET6 + internet_p = internet_p || rai->pfamily == PF_INET6; +#endif + if (internet_p && rai->socktype == SOCK_STREAM && + (rai->protocol == 0 || rai->protocol == IPPROTO_TCP)) { + rb_str_cat2(ret, " TCP"); + } + else if (internet_p && rai->socktype == SOCK_DGRAM && + (rai->protocol == 0 || rai->protocol == IPPROTO_UDP)) { + rb_str_cat2(ret, " UDP"); + } + else { + if (rai->socktype) { + ID id = rsock_intern_socktype(rai->socktype); + if (id) + rb_str_catf(ret, " %s", rb_id2name(id)); + else + rb_str_catf(ret, " SOCK_\?\?\?(%d)", rai->socktype); + } + + if (rai->protocol) { + if (internet_p) { + ID id = rsock_intern_ipproto(rai->protocol); + if (id) + rb_str_catf(ret, " %s", rb_id2name(id)); + else + goto unknown_protocol; + } + else { + unknown_protocol: + rb_str_catf(ret, " UNKNOWN_PROTOCOL(%d)", rai->protocol); + } + } + } + + if (!NIL_P(rai->canonname)) { + VALUE name = rai->canonname; + rb_str_catf(ret, " %s", StringValueCStr(name)); + } + + if (!NIL_P(rai->inspectname)) { + VALUE name = rai->inspectname; + rb_str_catf(ret, " (%s)", StringValueCStr(name)); + } + + rb_str_buf_cat2(ret, ">"); + return ret; +} + +/* + * call-seq: + * addrinfo.inspect_sockaddr => string + * + * returns a string which shows the sockaddr in _addrinfo_ with human-readable form. + * + * Addrinfo.tcp("localhost", 80).inspect_sockaddr #=> "127.0.0.1:80" + * Addrinfo.tcp("ip6-localhost", 80).inspect_sockaddr #=> "[::1]:80" + * Addrinfo.unix("/tmp/sock").inspect_sockaddr #=> "/tmp/sock" + * + */ +static VALUE +addrinfo_inspect_sockaddr(VALUE self) +{ + return inspect_sockaddr(self, rb_str_new("", 0)); +} + +/* :nodoc: */ +static VALUE +addrinfo_mdump(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + VALUE sockaddr, afamily, pfamily, socktype, protocol, canonname, inspectname; + int afamily_int = ai_get_afamily(rai); + ID id; + + id = rsock_intern_protocol_family(rai->pfamily); + if (id == 0) + rb_raise(rb_eSocket, "unknown protocol family: %d", rai->pfamily); + pfamily = rb_id2str(id); + + if (rai->socktype == 0) + socktype = INT2FIX(0); + else { + id = rsock_intern_socktype(rai->socktype); + if (id == 0) + rb_raise(rb_eSocket, "unknown socktype: %d", rai->socktype); + socktype = rb_id2str(id); + } + + if (rai->protocol == 0) + protocol = INT2FIX(0); + else if (IS_IP_FAMILY(afamily_int)) { + id = rsock_intern_ipproto(rai->protocol); + if (id == 0) + rb_raise(rb_eSocket, "unknown IP protocol: %d", rai->protocol); + protocol = rb_id2str(id); + } + else { + rb_raise(rb_eSocket, "unknown protocol: %d", rai->protocol); + } + + canonname = rai->canonname; + + inspectname = rai->inspectname; + + id = rsock_intern_family(afamily_int); + if (id == 0) + rb_raise(rb_eSocket, "unknown address family: %d", afamily_int); + afamily = rb_id2str(id); + + switch(afamily_int) { +#ifdef HAVE_SYS_UN_H + case AF_UNIX: + { + struct sockaddr_un *su = (struct sockaddr_un *)&rai->addr; + char *s, *e; + s = su->sun_path; + e = (char*)s + sizeof(su->sun_path); + while (s < e && *(e-1) == '\0') + e--; + sockaddr = rb_str_new(s, e-s); + break; + } +#endif + + default: + { + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + int error; + error = getnameinfo((struct sockaddr *)&rai->addr, rai->sockaddr_len, + hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf), + NI_NUMERICHOST|NI_NUMERICSERV); + if (error) { + rsock_raise_socket_error("getnameinfo", error); + } + sockaddr = rb_assoc_new(rb_str_new_cstr(hbuf), rb_str_new_cstr(pbuf)); + break; + } + } + + return rb_ary_new3(7, afamily, sockaddr, pfamily, socktype, protocol, canonname, inspectname); +} + +/* :nodoc: */ +static VALUE +addrinfo_mload(VALUE self, VALUE ary) +{ + VALUE v; + VALUE canonname, inspectname; + int afamily, pfamily, socktype, protocol; + struct sockaddr_storage ss; + socklen_t len; + rb_addrinfo_t *rai; + + if (check_addrinfo(self)) + rb_raise(rb_eTypeError, "already initialized socket address"); + + ary = rb_convert_type(ary, T_ARRAY, "Array", "to_ary"); + + v = rb_ary_entry(ary, 0); + StringValue(v); + if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &afamily) == -1) + rb_raise(rb_eTypeError, "unexpected address family"); + + v = rb_ary_entry(ary, 2); + StringValue(v); + if (rsock_family_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &pfamily) == -1) + rb_raise(rb_eTypeError, "unexpected protocol family"); + + v = rb_ary_entry(ary, 3); + if (v == INT2FIX(0)) + socktype = 0; + else { + StringValue(v); + if (rsock_socktype_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &socktype) == -1) + rb_raise(rb_eTypeError, "unexpected socktype"); + } + + v = rb_ary_entry(ary, 4); + if (v == INT2FIX(0)) + protocol = 0; + else { + StringValue(v); + if (IS_IP_FAMILY(afamily)) { + if (rsock_ipproto_to_int(RSTRING_PTR(v), RSTRING_LEN(v), &protocol) == -1) + rb_raise(rb_eTypeError, "unexpected protocol"); + } + else { + rb_raise(rb_eTypeError, "unexpected protocol"); + } + } + + v = rb_ary_entry(ary, 5); + if (NIL_P(v)) + canonname = Qnil; + else { + StringValue(v); + canonname = v; + } + + v = rb_ary_entry(ary, 6); + if (NIL_P(v)) + inspectname = Qnil; + else { + StringValue(v); + inspectname = v; + } + + v = rb_ary_entry(ary, 1); + switch(afamily) { +#ifdef HAVE_SYS_UN_H + case AF_UNIX: + { + struct sockaddr_un uaddr; + memset(&uaddr, 0, sizeof(uaddr)); + uaddr.sun_family = AF_UNIX; + + StringValue(v); + if (sizeof(uaddr.sun_path) <= (size_t)RSTRING_LEN(v)) + rb_raise(rb_eSocket, "too long AF_UNIX path"); + memcpy(uaddr.sun_path, RSTRING_PTR(v), RSTRING_LEN(v)); + len = (socklen_t)sizeof(uaddr); + memcpy(&ss, &uaddr, len); + break; + } +#endif + + default: + { + VALUE pair = rb_convert_type(v, T_ARRAY, "Array", "to_ary"); + struct addrinfo *res; + int flags = AI_NUMERICHOST; +#ifdef AI_NUMERICSERV + flags |= AI_NUMERICSERV; +#endif + res = call_getaddrinfo(rb_ary_entry(pair, 0), rb_ary_entry(pair, 1), + INT2NUM(pfamily), INT2NUM(socktype), INT2NUM(protocol), + INT2NUM(flags), 1); + + len = res->ai_addrlen; + memcpy(&ss, res->ai_addr, res->ai_addrlen); + break; + } + } + + DATA_PTR(self) = rai = alloc_addrinfo(); + init_addrinfo(rai, (struct sockaddr *)&ss, len, + pfamily, socktype, protocol, + canonname, inspectname); + return self; +} + +/* + * call-seq: + * addrinfo.afamily => integer + * + * returns the address family as an integer. + * + * Addrinfo.tcp("localhost", 80).afamily == Socket::AF_INET #=> true + * + */ +static VALUE +addrinfo_afamily(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return INT2NUM(ai_get_afamily(rai)); +} + +/* + * call-seq: + * addrinfo.pfamily => integer + * + * returns the protocol family as an integer. + * + * Addrinfo.tcp("localhost", 80).pfamily == Socket::PF_INET #=> true + * + */ +static VALUE +addrinfo_pfamily(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return INT2NUM(rai->pfamily); +} + +/* + * call-seq: + * addrinfo.socktype => integer + * + * returns the socket type as an integer. + * + * Addrinfo.tcp("localhost", 80).socktype == Socket::SOCK_STREAM #=> true + * + */ +static VALUE +addrinfo_socktype(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return INT2NUM(rai->socktype); +} + +/* + * call-seq: + * addrinfo.protocol => integer + * + * returns the socket type as an integer. + * + * Addrinfo.tcp("localhost", 80).protocol == Socket::IPPROTO_TCP #=> true + * + */ +static VALUE +addrinfo_protocol(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return INT2NUM(rai->protocol); +} + +/* + * call-seq: + * addrinfo.to_sockaddr => string + * + * returns the socket address as packed struct sockaddr string. + * + * Addrinfo.tcp("localhost", 80).to_sockaddr + * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" + * + */ +static VALUE +addrinfo_to_sockaddr(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + VALUE ret; + ret = rb_str_new((char*)&rai->addr, rai->sockaddr_len); + OBJ_INFECT(ret, self); + return ret; +} + +/* + * call-seq: + * addrinfo.canonname => string or nil + * + * returns the canonical name as an string. + * + * nil is returned if no canonical name. + * + * The canonical name is set by Addrinfo.getaddrinfo when AI_CANONNAME is specified. + * + * list = Addrinfo.getaddrinfo("www.ruby-lang.org", 80, :INET, :STREAM, nil, Socket::AI_CANONNAME) + * p list[0] #=> #<Addrinfo: 221.186.184.68:80 TCP carbon.ruby-lang.org (www.ruby-lang.org:80)> + * p list[0].canonname #=> "carbon.ruby-lang.org" + * + */ +static VALUE +addrinfo_canonname(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return rai->canonname; +} + +/* + * call-seq: + * addrinfo.ip? => true or false + * + * returns true if addrinfo is internet (IPv4/IPv6) address. + * returns false otherwise. + * + * Addrinfo.tcp("127.0.0.1", 80).ip? #=> true + * Addrinfo.tcp("::1", 80).ip? #=> true + * Addrinfo.unix("/tmp/sock").ip? #=> false + * + */ +static VALUE +addrinfo_ip_p(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + return IS_IP_FAMILY(family) ? Qtrue : Qfalse; +} + +/* + * call-seq: + * addrinfo.ipv4? => true or false + * + * returns true if addrinfo is IPv4 address. + * returns false otherwise. + * + * Addrinfo.tcp("127.0.0.1", 80).ipv4? #=> true + * Addrinfo.tcp("::1", 80).ipv4? #=> false + * Addrinfo.unix("/tmp/sock").ipv4? #=> false + * + */ +static VALUE +addrinfo_ipv4_p(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + return ai_get_afamily(rai) == AF_INET ? Qtrue : Qfalse; +} + +/* + * call-seq: + * addrinfo.ipv6? => true or false + * + * returns true if addrinfo is IPv6 address. + * returns false otherwise. + * + * Addrinfo.tcp("127.0.0.1", 80).ipv6? #=> false + * Addrinfo.tcp("::1", 80).ipv6? #=> true + * Addrinfo.unix("/tmp/sock").ipv6? #=> false + * + */ +static VALUE +addrinfo_ipv6_p(VALUE self) +{ +#ifdef AF_INET6 + rb_addrinfo_t *rai = get_addrinfo(self); + return ai_get_afamily(rai) == AF_INET6 ? Qtrue : Qfalse; +#else + return Qfalse; +#endif +} + +/* + * call-seq: + * addrinfo.unix? => true or false + * + * returns true if addrinfo is UNIX address. + * returns false otherwise. + * + * Addrinfo.tcp("127.0.0.1", 80).unix? #=> false + * Addrinfo.tcp("::1", 80).unix? #=> false + * Addrinfo.unix("/tmp/sock").unix? #=> true + * + */ +static VALUE +addrinfo_unix_p(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); +#ifdef AF_UNIX + return ai_get_afamily(rai) == AF_UNIX ? Qtrue : Qfalse; +#else + return Qfalse; +#endif +} + +/* + * call-seq: + * addrinfo.getnameinfo => [nodename, service] + * addrinfo.getnameinfo(flags) => [nodename, service] + * + * returns nodename and service as a pair of strings. + * This converts struct sockaddr in addrinfo to textual representation. + * + * flags should be bitwise OR of Socket::NI_??? constants. + * + * Addrinfo.tcp("127.0.0.1", 80).getnameinfo #=> ["localhost", "www"] + * + * Addrinfo.tcp("127.0.0.1", 80).getnameinfo(Socket::NI_NUMERICSERV) + * #=> ["localhost", "80"] + */ +static VALUE +addrinfo_getnameinfo(int argc, VALUE *argv, VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + VALUE vflags; + char hbuf[1024], pbuf[1024]; + int flags, error; + + rb_scan_args(argc, argv, "01", &vflags); + + flags = NIL_P(vflags) ? 0 : NUM2INT(vflags); + + if (rai->socktype == SOCK_DGRAM) + flags |= NI_DGRAM; + + error = getnameinfo((struct sockaddr *)&rai->addr, rai->sockaddr_len, + hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf), + flags); + if (error) { + rsock_raise_socket_error("getnameinfo", error); + } + + return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf)); +} + +/* + * call-seq: + * addrinfo.ip_unpack => [addr, port] + * + * Returns the IP address and port number as 2-element array. + * + * Addrinfo.tcp("127.0.0.1", 80).ip_unpack #=> ["127.0.0.1", 80] + * Addrinfo.tcp("::1", 80).ip_unpack #=> ["::1", 80] + */ +static VALUE +addrinfo_ip_unpack(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + VALUE vflags; + VALUE ret, portstr; + + if (!IS_IP_FAMILY(family)) + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); + + vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV); + ret = addrinfo_getnameinfo(1, &vflags, self); + portstr = rb_ary_entry(ret, 1); + rb_ary_store(ret, 1, INT2NUM(atoi(StringValueCStr(portstr)))); + return ret; +} + +/* + * call-seq: + * addrinfo.ip_address => string + * + * Returns the IP address as a string. + * + * Addrinfo.tcp("127.0.0.1", 80).ip_address #=> "127.0.0.1" + * Addrinfo.tcp("::1", 80).ip_address #=> "::1" + */ +static VALUE +addrinfo_ip_address(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + VALUE vflags; + VALUE ret; + + if (!IS_IP_FAMILY(family)) + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); + + vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV); + ret = addrinfo_getnameinfo(1, &vflags, self); + return rb_ary_entry(ret, 0); +} + +/* + * call-seq: + * addrinfo.ip_port => port + * + * Returns the port number as an integer. + * + * Addrinfo.tcp("127.0.0.1", 80).ip_port #=> 80 + * Addrinfo.tcp("::1", 80).ip_port #=> 80 + */ +static VALUE +addrinfo_ip_port(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + int port; + + if (!IS_IP_FAMILY(family)) { + bad_family: +#ifdef AF_INET6 + rb_raise(rb_eSocket, "need IPv4 or IPv6 address"); +#else + rb_raise(rb_eSocket, "need IPv4 address"); +#endif + } + + switch (family) { + case AF_INET: + if (rai->sockaddr_len != sizeof(struct sockaddr_in)) + rb_raise(rb_eSocket, "unexpected sockaddr size for IPv4"); + port = ntohs(((struct sockaddr_in *)&rai->addr)->sin_port); + break; + +#ifdef AF_INET6 + case AF_INET6: + if (rai->sockaddr_len != sizeof(struct sockaddr_in6)) + rb_raise(rb_eSocket, "unexpected sockaddr size for IPv6"); + port = ntohs(((struct sockaddr_in6 *)&rai->addr)->sin6_port); + break; +#endif + + default: + goto bad_family; + } + + return INT2NUM(port); +} + +static int +extract_in_addr(VALUE self, uint32_t *addrp) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + if (family != AF_INET) return 0; + *addrp = ntohl(((struct sockaddr_in *)&rai->addr)->sin_addr.s_addr); + return 1; +} + +/* + * Returns true for IPv4 private address (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv4_private_p(VALUE self) +{ + uint32_t a; + if (!extract_in_addr(self, &a)) return Qfalse; + if ((a & 0xff000000) == 0x0a000000 || /* 10.0.0.0/8 */ + (a & 0xfff00000) == 0xac100000 || /* 172.16.0.0/12 */ + (a & 0xffff0000) == 0xc0a80000) /* 192.168.0.0/16 */ + return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv4 loopback address (127.0.0.0/8). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv4_loopback_p(VALUE self) +{ + uint32_t a; + if (!extract_in_addr(self, &a)) return Qfalse; + if ((a & 0xff000000) == 0x7f000000) /* 127.0.0.0/8 */ + return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv4 multicast address (224.0.0.0/4). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv4_multicast_p(VALUE self) +{ + uint32_t a; + if (!extract_in_addr(self, &a)) return Qfalse; + if ((a & 0xf0000000) == 0xe0000000) /* 224.0.0.0/4 */ + return Qtrue; + return Qfalse; +} + +#ifdef INET6 + +static struct in6_addr * +extract_in6_addr(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + if (family != AF_INET6) return NULL; + return &((struct sockaddr_in6 *)&rai->addr)->sin6_addr; +} + +/* + * Returns true for IPv6 unspecified address (::). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_unspecified_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_UNSPECIFIED(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 loopback address (::1). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_loopback_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_LOOPBACK(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast address (ff00::/8). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_multicast_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MULTICAST(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 link local address (ff80::/10). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_linklocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_LINKLOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 site local address (ffc0::/10). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_sitelocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_SITELOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv4-mapped IPv6 address (::ffff:0:0/80). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_v4mapped_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_V4MAPPED(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv4-compatible IPv6 address (::/80). + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_v4compat_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_V4COMPAT(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast node-local scope address. + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_mc_nodelocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MC_NODELOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast link-local scope address. + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_mc_linklocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MC_LINKLOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast site-local scope address. + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_mc_sitelocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MC_SITELOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast organization-local scope address. + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_mc_orglocal_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MC_ORGLOCAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns true for IPv6 multicast global scope address. + * It returns false otherwise. + */ +static VALUE +addrinfo_ipv6_mc_global_p(VALUE self) +{ + struct in6_addr *addr = extract_in6_addr(self); + if (addr && IN6_IS_ADDR_MC_GLOBAL(addr)) return Qtrue; + return Qfalse; +} + +/* + * Returns IPv4 address of IPv4 mapped/compatible IPv6 address. + * It returns nil if +self+ is not IPv4 mapped/compatible IPv6 address. + * + * Addrinfo.ip("::192.0.2.3").ipv6_to_ipv4 #=> #<Addrinfo: 192.0.2.3> + * Addrinfo.ip("::ffff:192.0.2.3").ipv6_to_ipv4 #=> #<Addrinfo: 192.0.2.3> + * Addrinfo.ip("::1").ipv6_to_ipv4 #=> nil + * Addrinfo.ip("192.0.2.3").ipv6_to_ipv4 #=> nil + * Addrinfo.unix("/tmp/sock").ipv6_to_ipv4 #=> nil + */ +static VALUE +addrinfo_ipv6_to_ipv4(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + struct in6_addr *addr; + int family = ai_get_afamily(rai); + if (family != AF_INET6) return Qnil; + addr = &((struct sockaddr_in6 *)&rai->addr)->sin6_addr; + if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) { + struct sockaddr_in sin4; + MEMZERO(&sin4, struct sockaddr_in, 1); + sin4.sin_family = AF_INET; + SET_SIN_LEN(&sin4, sizeof(sin4)); + memcpy(&sin4.sin_addr, (char*)addr + sizeof(*addr) - sizeof(sin4.sin_addr), sizeof(sin4.sin_addr)); + return rsock_addrinfo_new((struct sockaddr *)&sin4, (socklen_t)sizeof(sin4), + PF_INET, rai->socktype, rai->protocol, + rai->canonname, rai->inspectname); + } + else { + return Qnil; + } +} + +#endif + +#ifdef HAVE_SYS_UN_H +/* + * call-seq: + * addrinfo.unix_path => path + * + * Returns the socket path as a string. + * + * Addrinfo.unix("/tmp/sock").unix_path #=> "/tmp/sock" + */ +static VALUE +addrinfo_unix_path(VALUE self) +{ + rb_addrinfo_t *rai = get_addrinfo(self); + int family = ai_get_afamily(rai); + struct sockaddr_un *addr; + char *s, *e; + + if (family != AF_UNIX) + rb_raise(rb_eSocket, "need AF_UNIX address"); + + addr = (struct sockaddr_un *)&rai->addr; + + s = addr->sun_path; + e = (char*)addr + rai->sockaddr_len; + if (e < s) + rb_raise(rb_eSocket, "too short AF_UNIX address"); + if (addr->sun_path + sizeof(addr->sun_path) < e) + rb_raise(rb_eSocket, "too long AF_UNIX address"); + while (s < e && *(e-1) == '\0') + e--; + return rb_str_new(s, e-s); +} +#endif + +/* + * call-seq: + * Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags) => [addrinfo, ...] + * Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol) => [addrinfo, ...] + * Addrinfo.getaddrinfo(nodename, service, family, socktype) => [addrinfo, ...] + * Addrinfo.getaddrinfo(nodename, service, family) => [addrinfo, ...] + * Addrinfo.getaddrinfo(nodename, service) => [addrinfo, ...] + * + * returns a list of addrinfo objects as an array. + * + * This method converts nodename (hostname) and service (port) to addrinfo. + * Since the conversion is not unique, the result is a list of addrinfo objects. + * + * nodename or service can be nil if no conversion intended. + * + * family, socktype and protocol are hint for preferred protocol. + * If the result will be used for a socket with SOCK_STREAM, + * SOCK_STREAM should be specified as socktype. + * If so, Addrinfo.getaddrinfo returns addrinfo list appropriate for SOCK_STREAM. + * If they are omitted or nil is given, the result is not restricted. + * + * Similarly, PF_INET6 as family restricts for IPv6. + * + * flags should be bitwise OR of Socket::AI_??? constants. + * + * Note that socktype should be specified whenever application knows the usage of the address. + * Some platform causes an error when socktype is omitted and servname is specified as an integer + * because some port numbers, 512 for example, are ambiguous without socktype. + * + * Addrinfo.getaddrinfo("www.kame.net", 80, nil, :STREAM) + * #=> [#<Addrinfo: 203.178.141.194:80 TCP (www.kame.net:80)>, + * # #<Addrinfo: [2001:200:0:8002:203:47ff:fea5:3085]:80 TCP (www.kame.net:80)>] + * + */ +static VALUE +addrinfo_s_getaddrinfo(int argc, VALUE *argv, VALUE self) +{ + VALUE node, service, family, socktype, protocol, flags; + + rb_scan_args(argc, argv, "24", &node, &service, &family, &socktype, &protocol, &flags); + return addrinfo_list_new(node, service, family, socktype, protocol, flags); +} + +/* + * call-seq: + * Addrinfo.ip(host) => addrinfo + * + * returns an addrinfo object for IP address. + * + * The port, socktype, protocol of the result is filled by zero. + * So, it is not appropriate to create a socket. + * + * Addrinfo.ip("localhost") #=> #<Addrinfo: 127.0.0.1 (localhost)> + */ +static VALUE +addrinfo_s_ip(VALUE self, VALUE host) +{ + VALUE ret; + rb_addrinfo_t *rai; + ret = addrinfo_firstonly_new(host, Qnil, + INT2NUM(PF_UNSPEC), INT2FIX(0), INT2FIX(0), INT2FIX(0)); + rai = get_addrinfo(ret); + rai->socktype = 0; + rai->protocol = 0; + return ret; +} + +/* + * call-seq: + * Addrinfo.tcp(host, port) => addrinfo + * + * returns an addrinfo object for TCP address. + * + * Addrinfo.tcp("localhost", "smtp") #=> #<Addrinfo: 127.0.0.1:25 TCP (localhost:smtp)> + */ +static VALUE +addrinfo_s_tcp(VALUE self, VALUE host, VALUE port) +{ + return addrinfo_firstonly_new(host, port, + INT2NUM(PF_UNSPEC), INT2NUM(SOCK_STREAM), INT2NUM(IPPROTO_TCP), INT2FIX(0)); +} + +/* + * call-seq: + * Addrinfo.udp(host, port) => addrinfo + * + * returns an addrinfo object for UDP address. + * + * Addrinfo.udp("localhost", "daytime") #=> #<Addrinfo: 127.0.0.1:13 UDP (localhost:daytime)> + */ +static VALUE +addrinfo_s_udp(VALUE self, VALUE host, VALUE port) +{ + return addrinfo_firstonly_new(host, port, + INT2NUM(PF_UNSPEC), INT2NUM(SOCK_DGRAM), INT2NUM(IPPROTO_UDP), INT2FIX(0)); +} + +#ifdef HAVE_SYS_UN_H + +/* + * call-seq: + * Addrinfo.unix(path [, socktype]) => addrinfo + * + * returns an addrinfo object for UNIX socket address. + * + * _socktype_ specifies the socket type. + * If it is omitted, :STREAM is used. + * + * Addrinfo.unix("/tmp/sock") #=> #<Addrinfo: /tmp/sock SOCK_STREAM> + * Addrinfo.unix("/tmp/sock", :DGRAM) #=> #<Addrinfo: /tmp/sock SOCK_DGRAM> + */ +static VALUE +addrinfo_s_unix(int argc, VALUE *argv, VALUE self) +{ + VALUE path, vsocktype, addr; + int socktype; + rb_addrinfo_t *rai; + + rb_scan_args(argc, argv, "11", &path, &vsocktype); + + if (NIL_P(vsocktype)) + socktype = SOCK_STREAM; + else + socktype = rsock_socktype_arg(vsocktype); + + addr = addrinfo_s_allocate(rb_cAddrinfo); + DATA_PTR(addr) = rai = alloc_addrinfo(); + init_unix_addrinfo(rai, path, socktype); + OBJ_INFECT(addr, path); + return addr; +} + +#endif + +VALUE +rsock_sockaddr_string_value(volatile VALUE *v) +{ + VALUE val = *v; + if (IS_ADDRINFO(val)) { + *v = addrinfo_to_sockaddr(val); + } + StringValue(*v); + return *v; +} + +char * +rsock_sockaddr_string_value_ptr(volatile VALUE *v) +{ + rsock_sockaddr_string_value(v); + return RSTRING_PTR(*v); +} + +VALUE +rb_check_sockaddr_string_type(VALUE val) +{ + if (IS_ADDRINFO(val)) + return addrinfo_to_sockaddr(val); + return rb_check_string_type(val); +} + +VALUE +rsock_fd_socket_addrinfo(int fd, struct sockaddr *addr, socklen_t len) +{ + int family; + int socktype; + int ret; + socklen_t optlen = (socklen_t)sizeof(socktype); + + /* assumes protocol family and address family are identical */ + family = get_afamily(addr, len); + + ret = getsockopt(fd, SOL_SOCKET, SO_TYPE, (void*)&socktype, &optlen); + if (ret == -1) { + rb_sys_fail("getsockopt(SO_TYPE)"); + } + + return rsock_addrinfo_new(addr, len, family, socktype, 0, Qnil, Qnil); +} + +VALUE +rsock_io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len) +{ + rb_io_t *fptr; + + switch (TYPE(io)) { + case T_FIXNUM: + return rsock_fd_socket_addrinfo(FIX2INT(io), addr, len); + + case T_BIGNUM: + return rsock_fd_socket_addrinfo(NUM2INT(io), addr, len); + + case T_FILE: + GetOpenFile(io, fptr); + return rsock_fd_socket_addrinfo(fptr->fd, addr, len); + + default: + rb_raise(rb_eTypeError, "neither IO nor file descriptor"); + } +} + +/* + * Addrinfo class + */ +void +rsock_init_addrinfo(void) +{ + rb_cAddrinfo = rb_define_class("Addrinfo", rb_cData); + rb_define_alloc_func(rb_cAddrinfo, addrinfo_s_allocate); + rb_define_method(rb_cAddrinfo, "initialize", addrinfo_initialize, -1); + rb_define_method(rb_cAddrinfo, "inspect", addrinfo_inspect, 0); + rb_define_method(rb_cAddrinfo, "inspect_sockaddr", addrinfo_inspect_sockaddr, 0); + rb_define_singleton_method(rb_cAddrinfo, "getaddrinfo", addrinfo_s_getaddrinfo, -1); + rb_define_singleton_method(rb_cAddrinfo, "ip", addrinfo_s_ip, 1); + rb_define_singleton_method(rb_cAddrinfo, "tcp", addrinfo_s_tcp, 2); + rb_define_singleton_method(rb_cAddrinfo, "udp", addrinfo_s_udp, 2); +#ifdef HAVE_SYS_UN_H + rb_define_singleton_method(rb_cAddrinfo, "unix", addrinfo_s_unix, -1); +#endif + + rb_define_method(rb_cAddrinfo, "afamily", addrinfo_afamily, 0); + rb_define_method(rb_cAddrinfo, "pfamily", addrinfo_pfamily, 0); + rb_define_method(rb_cAddrinfo, "socktype", addrinfo_socktype, 0); + rb_define_method(rb_cAddrinfo, "protocol", addrinfo_protocol, 0); + rb_define_method(rb_cAddrinfo, "canonname", addrinfo_canonname, 0); + + rb_define_method(rb_cAddrinfo, "ipv4?", addrinfo_ipv4_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6?", addrinfo_ipv6_p, 0); + rb_define_method(rb_cAddrinfo, "unix?", addrinfo_unix_p, 0); + + rb_define_method(rb_cAddrinfo, "ip?", addrinfo_ip_p, 0); + rb_define_method(rb_cAddrinfo, "ip_unpack", addrinfo_ip_unpack, 0); + rb_define_method(rb_cAddrinfo, "ip_address", addrinfo_ip_address, 0); + rb_define_method(rb_cAddrinfo, "ip_port", addrinfo_ip_port, 0); + + rb_define_method(rb_cAddrinfo, "ipv4_private?", addrinfo_ipv4_private_p, 0); + rb_define_method(rb_cAddrinfo, "ipv4_loopback?", addrinfo_ipv4_loopback_p, 0); + rb_define_method(rb_cAddrinfo, "ipv4_multicast?", addrinfo_ipv4_multicast_p, 0); + +#ifdef INET6 + rb_define_method(rb_cAddrinfo, "ipv6_unspecified?", addrinfo_ipv6_unspecified_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_loopback?", addrinfo_ipv6_loopback_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_multicast?", addrinfo_ipv6_multicast_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_linklocal?", addrinfo_ipv6_linklocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_sitelocal?", addrinfo_ipv6_sitelocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_v4mapped?", addrinfo_ipv6_v4mapped_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_v4compat?", addrinfo_ipv6_v4compat_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_mc_nodelocal?", addrinfo_ipv6_mc_nodelocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_mc_linklocal?", addrinfo_ipv6_mc_linklocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_mc_sitelocal?", addrinfo_ipv6_mc_sitelocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_mc_orglocal?", addrinfo_ipv6_mc_orglocal_p, 0); + rb_define_method(rb_cAddrinfo, "ipv6_mc_global?", addrinfo_ipv6_mc_global_p, 0); + + rb_define_method(rb_cAddrinfo, "ipv6_to_ipv4", addrinfo_ipv6_to_ipv4, 0); +#endif + +#ifdef HAVE_SYS_UN_H + rb_define_method(rb_cAddrinfo, "unix_path", addrinfo_unix_path, 0); +#endif + + rb_define_method(rb_cAddrinfo, "to_sockaddr", addrinfo_to_sockaddr, 0); + rb_define_method(rb_cAddrinfo, "to_s", addrinfo_to_sockaddr, 0); /* compatibility for ruby before 1.9.2 */ + + rb_define_method(rb_cAddrinfo, "getnameinfo", addrinfo_getnameinfo, -1); + + rb_define_method(rb_cAddrinfo, "marshal_dump", addrinfo_mdump, 0); + rb_define_method(rb_cAddrinfo, "marshal_load", addrinfo_mload, 1); +} diff --git a/ext/socket/rubysocket.h b/ext/socket/rubysocket.h new file mode 100644 index 0000000000..60ac25fbbd --- /dev/null +++ b/ext/socket/rubysocket.h @@ -0,0 +1,306 @@ +#ifndef RUBY_SOCKET_H +#define RUBY_SOCKET_H 1 + +#include "ruby/ruby.h" +#include "ruby/io.h" +#include "ruby/util.h" +#include <stdio.h> +#include <sys/types.h> +#include <sys/stat.h> + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif + +#ifdef HAVE_SYS_UIO_H +#include <sys/uio.h> +#endif + +#ifdef HAVE_XTI_H +#include <xti.h> +#endif + +#ifndef _WIN32 +#if defined(__BEOS__) && !defined(__HAIKU__) && !defined(BONE) +# include <net/socket.h> +#else +# include <sys/socket.h> +#endif +#include <netinet/in.h> +#ifdef HAVE_NETINET_IN_SYSTM_H +# include <netinet/in_systm.h> +#endif +#ifdef HAVE_NETINET_TCP_H +# include <netinet/tcp.h> +#endif +#ifdef HAVE_NETINET_UDP_H +# include <netinet/udp.h> +#endif +#ifdef HAVE_ARPA_INET_H +# include <arpa/inet.h> +#endif +#include <netdb.h> +#endif +#include <errno.h> +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> +#endif + +#if defined(HAVE_FCNTL) +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#endif + +#ifdef HAVE_IFADDRS_H +#include <ifaddrs.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_SYS_SOCKIO_H +#include <sys/sockio.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif + +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> +#endif +#ifdef HAVE_SYS_UCRED_H +#include <sys/ucred.h> +#endif +#ifdef HAVE_UCRED_H +#include <ucred.h> +#endif + +#ifndef EWOULDBLOCK +#define EWOULDBLOCK EAGAIN +#endif + +/* + * workaround for NetBSD, OpenBSD and etc. + * The problem is since 4.4BSD-Lite. + * FreeBSD fix the problem at FreeBSD 2.2.0. + * NetBSD fix the problem at NetBSD 3.0 by kern/29624. + * OpenBSD fix the problem at OpenBSD 3.8. + */ +#define pseudo_AF_FTIP pseudo_AF_RTIP + +#ifndef HAVE_GETADDRINFO +#include "addrinfo.h" +#endif +#include "sockport.h" + +#ifndef NI_MAXHOST +# define NI_MAXHOST 1025 +#endif +#ifndef NI_MAXSERV +# define NI_MAXSERV 32 +#endif + +#ifdef AF_INET6 +# define IS_IP_FAMILY(af) ((af) == AF_INET || (af) == AF_INET6) +#else +# define IS_IP_FAMILY(af) ((af) == AF_INET) +#endif + +#ifndef HAVE_SOCKADDR_STORAGE +/* + * RFC 2553: protocol-independent placeholder for socket addresses + */ +#define _SS_MAXSIZE 128 +#define _SS_ALIGNSIZE (sizeof(double)) +#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2) +#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \ + _SS_PAD1SIZE - _SS_ALIGNSIZE) + +struct sockaddr_storage { +#ifdef HAVE_SA_LEN + unsigned char ss_len; /* address length */ + unsigned char ss_family; /* address family */ +#else + unsigned short ss_family; +#endif + char __ss_pad1[_SS_PAD1SIZE]; + double __ss_align; /* force desired structure storage alignment */ + char __ss_pad2[_SS_PAD2SIZE]; +}; +#endif + +#if defined __APPLE__ && defined __MACH__ +/* + * CMSG_ macros are broken on 64bit darwin, because __DARWIN_ALIGN + * aligns up to __darwin_size_t which is 64bit, but CMSG_DATA is + * 32bit-aligned. + */ +#undef __DARWIN_ALIGNBYTES +#define __DARWIN_ALIGNBYTES (sizeof(unsigned int) - 1) +#endif + +#if defined(_AIX) +#ifndef CMSG_SPACE +# define CMSG_SPACE(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + _CMSG_ALIGN(len)) +#endif +#ifndef CMSG_LEN +# define CMSG_LEN(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + (len)) +#endif +#endif + +#ifdef __BEOS__ +#undef close +#define close closesocket +#endif + +#define INET_CLIENT 0 +#define INET_SERVER 1 +#define INET_SOCKS 2 + +extern int rsock_do_not_reverse_lookup; +#define FMODE_NOREVLOOKUP 0x100 + +extern VALUE rb_cBasicSocket; +extern VALUE rb_cIPSocket; +extern VALUE rb_cTCPSocket; +extern VALUE rb_cTCPServer; +extern VALUE rb_cUDPSocket; +#ifdef HAVE_SYS_UN_H +extern VALUE rb_cUNIXSocket; +extern VALUE rb_cUNIXServer; +#endif +extern VALUE rb_cSocket; +extern VALUE rb_cAddrinfo; +extern VALUE rb_cSockOpt; + +extern VALUE rb_eSocket; + +#ifdef SOCKS +extern VALUE rb_cSOCKSSocket; +#ifdef SOCKS5 +#include <socks.h> +#else +void SOCKSinit(); +int Rconnect(); +#endif +#endif + +#include "constdefs.h" + +#define BLOCKING_REGION(func, arg) (long)rb_thread_blocking_region((func), (arg), RUBY_UBF_IO, 0) + +#define SockAddrStringValue(v) rsock_sockaddr_string_value(&(v)) +#define SockAddrStringValuePtr(v) rsock_sockaddr_string_value_ptr(&(v)) +VALUE rsock_sockaddr_string_value(volatile VALUE *); +char *rsock_sockaddr_string_value_ptr(volatile VALUE *); +VALUE rb_check_sockaddr_string_type(VALUE); + +NORETURN(void rsock_raise_socket_error(const char *, int)); + +int rsock_family_arg(VALUE domain); +int rsock_socktype_arg(VALUE type); +int rsock_level_arg(int family, VALUE level); +int rsock_optname_arg(int family, int level, VALUE optname); +int rsock_cmsg_type_arg(int family, int level, VALUE type); +int rsock_shutdown_how_arg(VALUE how); + +int rsock_getfamily(int sockfd); + +int rb_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res); +int rb_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags); +struct addrinfo *rsock_addrinfo(VALUE host, VALUE port, int socktype, int flags); +struct addrinfo *rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack); +VALUE rsock_fd_socket_addrinfo(int fd, struct sockaddr *addr, socklen_t len); +VALUE rsock_io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len); + +VALUE rsock_addrinfo_new(struct sockaddr *addr, socklen_t len, int family, int socktype, int protocol, VALUE canonname, VALUE inspectname); + +VALUE rsock_make_ipaddr(struct sockaddr *addr); +VALUE rsock_ipaddr(struct sockaddr *sockaddr, int norevlookup); +VALUE rsock_make_hostent(VALUE host, struct addrinfo *addr, VALUE (*ipaddr)(struct sockaddr *, size_t)); + +int rsock_revlookup_flag(VALUE revlookup, int *norevlookup); + +#ifdef HAVE_SYS_UN_H +const char* rsock_unixpath(struct sockaddr_un *sockaddr, socklen_t len); +VALUE rsock_unixaddr(struct sockaddr_un *sockaddr, socklen_t len); +#endif + +int rsock_socket(int domain, int type, int proto); +VALUE rsock_init_sock(VALUE sock, int fd); +VALUE rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass); +VALUE rsock_init_inetsock(VALUE sock, VALUE remote_host, VALUE remote_serv, VALUE local_host, VALUE local_serv, int type); +VALUE rsock_init_unixsock(VALUE sock, VALUE path, int server); + +struct rsock_send_arg { + int fd, flags; + VALUE mesg; + struct sockaddr *to; + socklen_t tolen; +}; + +VALUE rsock_sendto_blocking(void *data); +VALUE rsock_send_blocking(void *data); +VALUE rsock_bsock_send(int argc, VALUE *argv, VALUE sock); + +enum sock_recv_type { + RECV_RECV, /* BasicSocket#recv(no from) */ + RECV_IP, /* IPSocket#recvfrom */ + RECV_UNIX, /* UNIXSocket#recvfrom */ + RECV_SOCKET /* Socket#recvfrom */ +}; + +VALUE rsock_s_recvfrom_nonblock(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from); +VALUE rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from); + +int rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks); + +VALUE rsock_s_accept(VALUE klass, int fd, struct sockaddr *sockaddr, socklen_t *len); +VALUE rsock_s_accept_nonblock(VALUE klass, rb_io_t *fptr, struct sockaddr *sockaddr, socklen_t *len); +VALUE rsock_sock_listen(VALUE sock, VALUE log); + +VALUE rsock_sockopt_new(int family, int level, int optname, VALUE data); + +#if defined(HAVE_SENDMSG) +VALUE rsock_bsock_sendmsg(int argc, VALUE *argv, VALUE sock); +VALUE rsock_bsock_sendmsg_nonblock(int argc, VALUE *argv, VALUE sock); +#else +#define rsock_bsock_sendmsg rb_f_notimplement +#define rsock_bsock_sendmsg_nonblock rb_f_notimplement +#endif +#if defined(HAVE_RECVMSG) +VALUE rsock_bsock_recvmsg(int argc, VALUE *argv, VALUE sock); +VALUE rsock_bsock_recvmsg_nonblock(int argc, VALUE *argv, VALUE sock); +#else +#define rsock_bsock_recvmsg rb_f_notimplement +#define rsock_bsock_recvmsg_nonblock rb_f_notimplement +#endif + +#ifdef HAVE_ST_MSG_CONTROL +void rsock_discard_cmsg_resource(struct msghdr *mh); +#endif + +void rsock_init_basicsocket(void); +void rsock_init_ipsocket(void); +void rsock_init_tcpsocket(void); +void rsock_init_tcpserver(void); +void rsock_init_sockssocket(void); +void rsock_init_udpsocket(void); +void rsock_init_unixsocket(void); +void rsock_init_unixserver(void); +void rsock_init_socket_constants(void); +void rsock_init_ancdata(void); +void rsock_init_addrinfo(void); +void rsock_init_sockopt(void); +void rsock_init_socket_init(void); + +#endif diff --git a/ext/socket/socket.c b/ext/socket/socket.c index 5c91c390ec..63586fc002 100644 --- a/ext/socket/socket.c +++ b/ext/socket/socket.c @@ -2,2316 +2,112 @@ socket.c - - $Author: matz $ - $Date: 2006/08/07 07:50:28 $ created at: Thu Mar 31 12:21:29 JST 1994 - Copyright (C) 1993-2001 Yukihiro Matsumoto + Copyright (C) 1993-2007 Yukihiro Matsumoto ************************************************/ -#include "ruby.h" -#include "rubyio.h" -#include "rubysig.h" -#include "util.h" -#include <stdio.h> -#include <sys/types.h> +#include "rubysocket.h" -#ifdef HAVE_UNISTD_H -#include <unistd.h> -#endif - -#ifdef HAVE_SYS_UIO_H -#include <sys/uio.h> -#endif - -#ifndef _WIN32 -#if defined(__BEOS__) -# include <net/socket.h> -#else -# include <sys/socket.h> -# define pseudo_AF_FTIP pseudo_AF_RTIP /* workaround for NetBSD and etc. */ -#endif -#include <netinet/in.h> -#ifdef HAVE_NETINET_IN_SYSTM_H -# include <netinet/in_systm.h> -#endif -#ifdef HAVE_NETINET_TCP_H -# include <netinet/tcp.h> -#endif -#ifdef HAVE_NETINET_UDP_H -# include <netinet/udp.h> -#endif -#include <netdb.h> -#endif -#include <errno.h> -#ifdef HAVE_SYS_UN_H -#include <sys/un.h> -#endif - -#if defined(HAVE_FCNTL) -#ifdef HAVE_SYS_SELECT_H -#include <sys/select.h> -#endif -#ifdef HAVE_SYS_TYPES_H -#include <sys/types.h> -#endif -#ifdef HAVE_SYS_TIME_H -#include <sys/time.h> -#endif -#ifdef HAVE_FCNTL_H -#include <fcntl.h> -#endif -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK EAGAIN -#endif -#ifndef HAVE_GETADDRINFO -# include "addrinfo.h" -#endif -#include "sockport.h" - -#if defined(__vms) -#include <tcp.h> -#endif - -static int do_not_reverse_lookup = 0; - -VALUE rb_cBasicSocket; -VALUE rb_cIPSocket; -VALUE rb_cTCPSocket; -VALUE rb_cTCPServer; -VALUE rb_cUDPSocket; -#ifdef AF_UNIX -VALUE rb_cUNIXSocket; -VALUE rb_cUNIXServer; -#endif -VALUE rb_cSocket; - -static VALUE rb_eSocket; - -#ifdef SOCKS -VALUE rb_cSOCKSSocket; -#ifdef SOCKS5 -#include <socks.h> -#else -void SOCKSinit(); -int Rconnect(); -#endif -#endif - -#define INET_CLIENT 0 -#define INET_SERVER 1 -#define INET_SOCKS 2 - -#ifndef HAVE_SOCKADDR_STORAGE -/* - * RFC 2553: protocol-independent placeholder for socket addresses - */ -#define _SS_MAXSIZE 128 -#define _SS_ALIGNSIZE (sizeof(double)) -#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2) -#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) - -struct sockaddr_storage { -#ifdef HAVE_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ -#else - unsigned short ss_family; -#endif - char __ss_pad1[_SS_PAD1SIZE]; - double __ss_align; /* force desired structure storage alignment */ - char __ss_pad2[_SS_PAD2SIZE]; -}; -#endif - -#if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6)) -#define LOOKUP_ORDERS 3 -static int lookup_order_table[LOOKUP_ORDERS] = { -#if defined(LOOKUP_ORDER_HACK_INET) - PF_INET, PF_INET6, PF_UNSPEC, -#elif defined(LOOKUP_ORDER_HACK_INET6) - PF_INET6, PF_INET, PF_UNSPEC, -#else - /* should not happen */ -#endif -}; - -static int -ruby_getaddrinfo(nodename, servname, hints, res) - char *nodename; - char *servname; - struct addrinfo *hints; - struct addrinfo **res; -{ - struct addrinfo tmp_hints; - int i, af, error; - - if (hints->ai_family != PF_UNSPEC) { - return getaddrinfo(nodename, servname, hints, res); - } - - for (i = 0; i < LOOKUP_ORDERS; i++) { - af = lookup_order_table[i]; - MEMCPY(&tmp_hints, hints, struct addrinfo, 1); - tmp_hints.ai_family = af; - error = getaddrinfo(nodename, servname, &tmp_hints, res); - if (error) { - if (tmp_hints.ai_family == PF_UNSPEC) { - break; - } - } - else { - break; - } - } - - return error; -} -#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res)) -#endif - -#if defined(_AIX) -static int -ruby_getaddrinfo__aix(nodename, servname, hints, res) - char *nodename; - char *servname; - struct addrinfo *hints; - struct addrinfo **res; -{ - int error = getaddrinfo(nodename, servname, hints, res); - struct addrinfo *r; - if (error) - return error; - for (r = *res; r != NULL; r = r->ai_next) { - if (r->ai_addr->sa_family == 0) - r->ai_addr->sa_family = r->ai_family; - if (r->ai_addr->sa_len == 0) - r->ai_addr->sa_len = r->ai_addrlen; - } - return 0; -} -#undef getaddrinfo -#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res)) -#ifndef CMSG_SPACE -# define CMSG_SPACE(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + _CMSG_ALIGN(len)) -#endif -#ifndef CMSG_LEN -# define CMSG_LEN(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + (len)) -#endif -#endif - -#ifdef HAVE_CLOSESOCKET -#undef close -#define close closesocket -#endif - -static VALUE -init_sock(sock, fd) - VALUE sock; - int fd; -{ - OpenFile *fp; - - MakeOpenFile(sock, fp); - fp->f = rb_fdopen(fd, "r"); - fp->f2 = rb_fdopen(fd, "w"); - fp->mode = FMODE_READWRITE; - rb_io_synchronized(fp); - - return sock; -} - -static VALUE -bsock_s_for_fd(klass, fd) - VALUE klass, fd; -{ - OpenFile *fptr; - VALUE sock = init_sock(rb_obj_alloc(klass), NUM2INT(fd)); - - GetOpenFile(sock, fptr); - - return sock; -} - -static VALUE -bsock_shutdown(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE howto; - int how; - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket"); - } - rb_scan_args(argc, argv, "01", &howto); - if (howto == Qnil) - how = 2; - else { - how = NUM2INT(howto); - if (how < 0 || 2 < how) { - rb_raise(rb_eArgError, "`how' should be either 0, 1, 2"); - } - } - GetOpenFile(sock, fptr); - if (shutdown(fileno(fptr->f), how) == -1) - rb_sys_fail(0); - - return INT2FIX(0); -} - -static VALUE -bsock_close_read(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - shutdown(fileno(fptr->f), 0); - if (!(fptr->mode & FMODE_WRITABLE)) { - return rb_io_close(sock); - } - fptr->mode &= ~FMODE_READABLE; - - return Qnil; -} - -static VALUE -bsock_close_write(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - if (!(fptr->mode & FMODE_READABLE)) { - return rb_io_close(sock); - } - shutdown(fileno(fptr->f2), 1); - fptr->mode &= ~FMODE_WRITABLE; - - return Qnil; -} - -/* - * Document-method: setsockopt - * call-seq: setsockopt(level, optname, optval) - * - * Sets a socket option. These are protocol and system specific, see your - * local sytem documentation for details. - * - * === Parameters - * * +level+ is an integer, usually one of the SOL_ constants such as - * Socket::SOL_SOCKET, or a protocol level. - * * +optname+ is an integer, usually one of the SO_ constants, such - * as Socket::SO_REUSEADDR. - * * +optval+ is the value of the option, it is passed to the underlying - * setsockopt() as a pointer to a certain number of bytes. How this is - * done depends on the type: - * - Fixnum: value is assigned to an int, and a pointer to the int is - * passed, with length of sizeof(int). - * - true or false: 1 or 0 (respectively) is assigned to an int, and the - * int is passed as for a Fixnum. Note that +false+ must be passed, - * not +nil+. - * - String: the string's data and length is passed to the socket. - * - * === Examples - * - * Some socket options are integers with boolean values, in this case - * #setsockopt could be called like this: - * sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true) - * - * Some socket options are integers with numeric values, in this case - * #setsockopt could be called like this: - * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255) - * - * Option values may be structs. Passing them can be complex as it involves - * examining your system headers to determine the correct definition. An - * example is an +ip_mreq+, which may be defined in your system headers as: - * struct ip_mreq { - * struct in_addr imr_multiaddr; - * struct in_addr imr_interface; - * }; - * - * In this case #setsockopt could be called like this: - * optval = IPAddr.new("224.0.0.251") + Socket::INADDR_ANY - * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval) - * -*/ -static VALUE -bsock_setsockopt(sock, lev, optname, val) - VALUE sock, lev, optname, val; -{ - int level, option; - OpenFile *fptr; - int i; - char *v; - int vlen; - - rb_secure(2); - level = NUM2INT(lev); - option = NUM2INT(optname); - - switch (TYPE(val)) { - case T_FIXNUM: - i = FIX2INT(val); - goto numval; - case T_FALSE: - i = 0; - goto numval; - case T_TRUE: - i = 1; - numval: - v = (char*)&i; vlen = sizeof(i); - break; - default: - StringValue(val); - v = RSTRING(val)->ptr; - vlen = RSTRING(val)->len; - break; - } - - GetOpenFile(sock, fptr); - if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0) - rb_sys_fail(fptr->path); - - return INT2FIX(0); -} - -/* - * Document-method: getsockopt - * call-seq: getsockopt(level, optname) - * - * Gets a socket option. These are protocol and system specific, see your - * local sytem documentation for details. The option is returned as - * a String with the data being the binary value of the socket option. - * - * === Parameters - * * +level+ is an integer, usually one of the SOL_ constants such as - * Socket::SOL_SOCKET, or a protocol level. - * * +optname+ is an integer, usually one of the SO_ constants, such - * as Socket::SO_REUSEADDR. - * - * === Examples - * - * Some socket options are integers with boolean values, in this case - * #getsockopt could be called like this: - * optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR) - * optval = optval.unpack "i" - * reuseaddr = optval[0] == 0 ? false : true - * - * Some socket options are integers with numeric values, in this case - * #getsockopt could be called like this: - * optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL) - * ipttl = optval.unpack("i")[0] - * - * Option values may be structs. Decoding them can be complex as it involves - * examining your system headers to determine the correct definition. An - * example is a +struct linger+, which may be defined in your system headers - * as: - * struct linger { - * int l_onoff; - * int l_linger; - * }; - * - * In this case #getsockopt could be called like this: - * optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER) - * onoff, linger = optval.unpack "ii" -*/ -static VALUE -bsock_getsockopt(sock, lev, optname) - VALUE sock, lev, optname; -{ -#if !defined(__BEOS__) - int level, option; - socklen_t len; - char *buf; - OpenFile *fptr; - - level = NUM2INT(lev); - option = NUM2INT(optname); - len = 256; - buf = ALLOCA_N(char,len); - GetOpenFile(sock, fptr); - - GetOpenFile(sock, fptr); - if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0) - rb_sys_fail(fptr->path); - - return rb_str_new(buf, len); -#else - rb_notimplement(); -#endif -} - -static VALUE -bsock_getsockname(sock) - VALUE sock; -{ - char buf[1024]; - socklen_t len = sizeof buf; - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (getsockname(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0) - rb_sys_fail("getsockname(2)"); - return rb_str_new(buf, len); -} - -static VALUE -bsock_getpeername(sock) - VALUE sock; -{ - char buf[1024]; - socklen_t len = sizeof buf; - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (getpeername(fileno(fptr->f), (struct sockaddr*)buf, &len) < 0) - rb_sys_fail("getpeername(2)"); - return rb_str_new(buf, len); -} - -static VALUE -bsock_send(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE mesg, to; - VALUE flags; - OpenFile *fptr; - FILE *f; - int fd, n; - - rb_secure(4); - rb_scan_args(argc, argv, "21", &mesg, &flags, &to); - - StringValue(mesg); - if (!NIL_P(to)) StringValue(to); - GetOpenFile(sock, fptr); - f = GetWriteFile(fptr); - fd = fileno(f); - rb_thread_fd_writable(fd); - retry: - if (!NIL_P(to)) { - TRAP_BEG; - n = sendto(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags), - (struct sockaddr*)RSTRING(to)->ptr, RSTRING(to)->len); - TRAP_END; - } - else { - TRAP_BEG; - n = send(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags)); - TRAP_END; - } - if (n < 0) { - if (rb_io_wait_writable(fd)) { - goto retry; - } - rb_sys_fail("send(2)"); - } - return INT2FIX(n); -} - -static VALUE ipaddr _((struct sockaddr*)); -#ifdef HAVE_SYS_UN_H -static VALUE unixaddr _((struct sockaddr_un*, socklen_t)); -#endif - -enum sock_recv_type { - RECV_RECV, /* BasicSocket#recv(no from) */ - RECV_IP, /* IPSocket#recvfrom */ - RECV_UNIX, /* UNIXSocket#recvfrom */ - RECV_SOCKET /* Socket#recvfrom */ -}; - -static VALUE -s_recvfrom(sock, argc, argv, from) - VALUE sock; - int argc; - VALUE *argv; - enum sock_recv_type from; -{ - OpenFile *fptr; - VALUE str; - char buf[1024]; - socklen_t alen = sizeof buf; - VALUE len, flg; - long buflen; - long slen; - int fd, flags; - - rb_scan_args(argc, argv, "11", &len, &flg); - - if (flg == Qnil) flags = 0; - else flags = NUM2INT(flg); - buflen = NUM2INT(len); - - GetOpenFile(sock, fptr); - if (rb_read_pending(fptr->f)) { - rb_raise(rb_eIOError, "recv for buffered IO"); - } - fd = fileno(fptr->f); - - str = rb_tainted_str_new(0, buflen); - - retry: - rb_str_locktmp(str); - rb_thread_wait_fd(fd); - TRAP_BEG; - slen = recvfrom(fd, RSTRING(str)->ptr, buflen, flags, (struct sockaddr*)buf, &alen); - TRAP_END; - rb_str_unlocktmp(str); - - if (slen < 0) { - if (rb_io_wait_readable(fd)) { - goto retry; - } - rb_sys_fail("recvfrom(2)"); - } - if (slen < RSTRING(str)->len) { - RSTRING(str)->len = slen; - RSTRING(str)->ptr[slen] = '\0'; - } - rb_obj_taint(str); - switch (from) { - case RECV_RECV: - return (VALUE)str; - case RECV_IP: -#if 0 - if (alen != sizeof(struct sockaddr_in)) { - rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); - } -#endif - if (alen && alen != sizeof(buf)) /* OSX doesn't return a 'from' result from recvfrom for connection-oriented sockets */ - return rb_assoc_new(str, ipaddr((struct sockaddr*)buf)); - else - return rb_assoc_new(str, Qnil); - -#ifdef HAVE_SYS_UN_H - case RECV_UNIX: - return rb_assoc_new(str, unixaddr((struct sockaddr_un*)buf, alen)); -#endif - case RECV_SOCKET: - return rb_assoc_new(str, rb_str_new(buf, alen)); - default: - rb_bug("s_recvfrom called with bad value"); - } -} - -static VALUE -s_recvfrom_nonblock(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from) -{ - OpenFile *fptr; - VALUE str; - char buf[1024]; - socklen_t alen = sizeof buf; - VALUE len, flg; - long buflen; - long slen; - int fd, flags; - VALUE addr = Qnil; - - rb_scan_args(argc, argv, "11", &len, &flg); - - if (flg == Qnil) flags = 0; - else flags = NUM2INT(flg); - buflen = NUM2INT(len); - -#ifdef MSG_DONTWAIT - /* MSG_DONTWAIT avoids the race condition between fcntl and recvfrom. - It is not portable, though. */ - flags |= MSG_DONTWAIT; -#endif - - GetOpenFile(sock, fptr); - if (rb_read_pending(fptr->f)) { - rb_raise(rb_eIOError, "recvfrom for buffered IO"); - } - fd = fileno(fptr->f); - - str = rb_tainted_str_new(0, buflen); - - rb_io_check_closed(fptr); - rb_io_set_nonblock(fptr); - slen = recvfrom(fd, RSTRING(str)->ptr, buflen, flags, (struct sockaddr*)buf, &alen); - - if (slen < 0) { - rb_sys_fail("recvfrom(2)"); - } - if (slen < RSTRING(str)->len) { - RSTRING(str)->len = slen; - RSTRING(str)->ptr[slen] = '\0'; - } - rb_obj_taint(str); - switch (from) { - case RECV_RECV: - return str; - - case RECV_IP: - if (alen && alen != sizeof(buf)) /* connection-oriented socket may not return a from result */ - addr = ipaddr((struct sockaddr*)buf); - break; - - case RECV_SOCKET: - addr = rb_str_new(buf, alen); - break; - - default: - rb_bug("s_recvfrom_nonblock called with bad value"); - } - return rb_assoc_new(str, addr); -} - -static VALUE -bsock_recv(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; +static void +setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv) { - return s_recvfrom(sock, argc, argv, RECV_RECV); + *dv = rsock_family_arg(domain); + *tv = rsock_socktype_arg(type); } /* * call-seq: - * basicsocket.recv_nonblock(maxlen) => mesg - * basicsocket.recv_nonblock(maxlen, flags) => mesg - * - * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after - * O_NONBLOCK is set for the underlying file descriptor. - * _flags_ is zero or more of the +MSG_+ options. - * The result, _mesg_, is the data received. + * Socket.new(domain, socktype [, protocol]) => socket * - * When recvfrom(2) returns 0, Socket#recv_nonblock returns - * an empty string as data. - * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc. - * - * === Parameters - * * +maxlen+ - the number of bytes to receive from the socket - * * +flags+ - zero or more of the +MSG_+ options - * - * === Example - * serv = TCPServer.new("127.0.0.1", 0) - * af, port, host, addr = serv.addr - * c = TCPSocket.new(addr, port) - * s = serv.accept - * c.send "aaa", 0 - * IO.select([s]) - * p s.recv_nonblock(10) #=> "aaa" + * Creates a new socket object. * - * Refer to Socket#recvfrom for the exceptions that may be thrown if the call - * to _recv_nonblock_ fails. + * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc. * - * BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure, - * including Errno::EAGAIN. + * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc. * - * === See - * * Socket#recvfrom - */ - -static VALUE -bsock_recv_nonblock(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom_nonblock(sock, argc, argv, RECV_RECV); -} - -static VALUE -bsock_do_not_rev_lookup() -{ - return do_not_reverse_lookup?Qtrue:Qfalse; -} - -static VALUE -bsock_do_not_rev_lookup_set(self, val) - VALUE self, val; -{ - rb_secure(4); - do_not_reverse_lookup = RTEST(val); - return val; -} - -static void -make_ipaddr0(addr, buf, len) - struct sockaddr *addr; - char *buf; - size_t len; -{ - int error; - - error = getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST); - if (error) { - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); - } -} - -static VALUE -make_ipaddr(addr) - struct sockaddr *addr; -{ - char buf[1024]; - - make_ipaddr0(addr, buf, sizeof(buf)); - return rb_str_new2(buf); -} - -static void -make_inetaddr(host, buf, len) - long host; - char *buf; - size_t len; -{ - struct sockaddr_in sin; - - MEMZERO(&sin, struct sockaddr_in, 1); - sin.sin_family = AF_INET; - SET_SIN_LEN(&sin, sizeof(sin)); - sin.sin_addr.s_addr = host; - make_ipaddr0((struct sockaddr*)&sin, buf, len); -} - -static int -str_isnumber(p) - const char *p; -{ - char *ep; - - if (!p || *p == '\0') - return 0; - ep = NULL; - (void)strtoul(p, &ep, 10); - if (ep && *ep == '\0') - return 1; - else - return 0; -} - -static char * -host_str(host, hbuf, len) - VALUE host; - char *hbuf; - size_t len; -{ - if (NIL_P(host)) { - return NULL; - } - else if (rb_obj_is_kind_of(host, rb_cInteger)) { - long i = NUM2LONG(host); - - make_inetaddr(htonl(i), hbuf, len); - return hbuf; - } - else { - char *name; - - SafeStringValue(host); - name = RSTRING(host)->ptr; - if (!name || *name == 0 || (name[0] == '<' && strcmp(name, "<any>") == 0)) { - make_inetaddr(INADDR_ANY, hbuf, len); - } - else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) { - make_inetaddr(INADDR_BROADCAST, hbuf, len); - } - else if (strlen(name) >= len) { - rb_raise(rb_eArgError, "hostname too long (%d)", strlen(name)); - } - else { - strcpy(hbuf, name); - } - return hbuf; - } -} - -static char * -port_str(port, pbuf, len) - VALUE port; - char *pbuf; - size_t len; -{ - if (NIL_P(port)) { - return 0; - } - else if (FIXNUM_P(port)) { - snprintf(pbuf, len, "%ld", FIX2LONG(port)); - return pbuf; - } - else { - char *serv; - - SafeStringValue(port); - serv = RSTRING(port)->ptr; - if (strlen(serv) >= len) { - rb_raise(rb_eArgError, "service name too long (%d)", strlen(serv)); - } - strcpy(pbuf, serv); - return pbuf; - } -} - -#ifndef NI_MAXHOST -# define 1025 -#endif -#ifndef NI_MAXSERV -# define 32 -#endif - -static struct addrinfo* -sock_addrinfo(host, port, socktype, flags) - VALUE host, port; - int socktype, flags; -{ - struct addrinfo hints; - struct addrinfo* res = NULL; - char *hostp, *portp; - int error; - char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; - - hostp = host_str(host, hbuf, sizeof(hbuf)); - portp = port_str(port, pbuf, sizeof(pbuf)); - - if (socktype == 0 && flags == 0 && str_isnumber(portp)) { - socktype = SOCK_DGRAM; - } - - MEMZERO(&hints, struct addrinfo, 1); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = socktype; - hints.ai_flags = flags; - error = getaddrinfo(hostp, portp, &hints, &res); - if (error) { - if (hostp && hostp[strlen(hostp)-1] == '\n') { - rb_raise(rb_eSocket, "newline at the end of hostname"); - } - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); - } - -#if defined(__APPLE__) && defined(__MACH__) - { - struct addrinfo *r; - r = res; - while (r) { - if (! r->ai_socktype) r->ai_socktype = hints.ai_socktype; - if (! r->ai_protocol) { - if (r->ai_socktype == SOCK_DGRAM) { - r->ai_protocol = IPPROTO_UDP; - } else if (r->ai_socktype == SOCK_STREAM) { - r->ai_protocol = IPPROTO_TCP; - } - } - r = r->ai_next; - } - } -#endif - return res; -} - -static VALUE -ipaddr(sockaddr) - struct sockaddr *sockaddr; -{ - VALUE family, port, addr1, addr2; - VALUE ary; - int error; - char hbuf[1024], pbuf[1024]; - - switch (sockaddr->sa_family) { - case AF_UNSPEC: - family = rb_str_new2("AF_UNSPEC"); - break; - case AF_INET: - family = rb_str_new2("AF_INET"); - break; -#ifdef INET6 - case AF_INET6: - family = rb_str_new2("AF_INET6"); - break; -#endif -#ifdef AF_LOCAL - case AF_LOCAL: - family = rb_str_new2("AF_LOCAL"); - break; -#elif AF_UNIX - case AF_UNIX: - family = rb_str_new2("AF_UNIX"); - break; -#endif - default: - sprintf(pbuf, "unknown:%d", sockaddr->sa_family); - family = rb_str_new2(pbuf); - break; - } - addr1 = Qnil; - if (!do_not_reverse_lookup) { - error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), - NULL, 0, 0); - if (! error) { - addr1 = rb_str_new2(hbuf); - } - } - error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV); - if (error) { - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); - } - addr2 = rb_str_new2(hbuf); - if (addr1 == Qnil) { - addr1 = addr2; - } - port = INT2FIX(atoi(pbuf)); - ary = rb_ary_new3(4, family, port, addr1, addr2); - - return ary; -} - -static int -ruby_socket(domain, type, proto) - int domain, type, proto; -{ - int fd; - - fd = socket(domain, type, proto); - if (fd < 0) { - if (errno == EMFILE || errno == ENFILE) { - rb_gc(); - fd = socket(domain, type, proto); - } - } - return fd; -} - -static int -wait_connectable(fd) - int fd; -{ - int sockerr; - socklen_t sockerrlen; - fd_set fds_w; - fd_set fds_e; - - for (;;) { - FD_ZERO(&fds_w); - FD_ZERO(&fds_e); - - FD_SET(fd, &fds_w); - FD_SET(fd, &fds_e); - - rb_thread_select(fd+1, 0, &fds_w, &fds_e, 0); - - if (FD_ISSET(fd, &fds_w)) { - return 0; - } - else if (FD_ISSET(fd, &fds_e)) { - sockerrlen = sizeof(sockerr); - if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, - &sockerrlen) == 0) { - if (sockerr == 0) - continue; /* workaround for winsock */ - errno = sockerr; - } - return -1; - } - } - - return 0; -} - -#ifdef __CYGWIN__ -#define WAIT_IN_PROGRESS 10 -#endif -#ifdef __APPLE__ -#define WAIT_IN_PROGRESS 10 -#endif -#ifdef __linux__ -/* returns correct error */ -#define WAIT_IN_PROGRESS 0 -#endif -#ifndef WAIT_IN_PROGRESS -/* BSD origin code apparently has a problem */ -#define WAIT_IN_PROGRESS 1 -#endif - -static int -ruby_connect(fd, sockaddr, len, socks) - int fd; - struct sockaddr *sockaddr; - int len; - int socks; -{ - int status; - int mode; -#if WAIT_IN_PROGRESS > 0 - int wait_in_progress = -1; - int sockerr, sockerrlen; -#endif - -#if defined(HAVE_FCNTL) -# if defined(F_GETFL) - mode = fcntl(fd, F_GETFL, 0); -# else - mode = 0; -# endif - -#ifdef O_NDELAY -# define NONBLOCKING O_NDELAY -#else -#ifdef O_NBIO -# define NONBLOCKING O_NBIO -#else -# define NONBLOCKING O_NONBLOCK -#endif -#endif -#ifdef SOCKS5 - if (!socks) -#endif - fcntl(fd, F_SETFL, mode|NONBLOCKING); -#endif /* HAVE_FCNTL */ - - for (;;) { -#if defined(SOCKS) && !defined(SOCKS5) - if (socks) { - status = Rconnect(fd, sockaddr, len); - } - else -#endif - { - status = connect(fd, sockaddr, len); - } - if (status < 0) { - switch (errno) { - case EAGAIN: -#ifdef EINPROGRESS - case EINPROGRESS: -#endif -#if WAIT_IN_PROGRESS > 0 - sockerrlen = sizeof(sockerr); - status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen); - if (status) break; - if (sockerr) { - status = -1; - errno = sockerr; - break; - } -#endif -#ifdef EALREADY - case EALREADY: -#endif -#if WAIT_IN_PROGRESS > 0 - wait_in_progress = WAIT_IN_PROGRESS; -#endif - status = wait_connectable(fd); - if (status) { - break; - } - errno = 0; - continue; - -#if WAIT_IN_PROGRESS > 0 - case EINVAL: - if (wait_in_progress-- > 0) { - /* - * connect() after EINPROGRESS returns EINVAL on - * some platforms, need to check true error - * status. - */ - sockerrlen = sizeof(sockerr); - status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen); - if (!status && !sockerr) { - struct timeval tv = {0, 100000}; - rb_thread_wait_for(tv); - continue; - } - status = -1; - errno = sockerr; - } - break; -#endif - -#ifdef EISCONN - case EISCONN: - status = 0; - errno = 0; - break; -#endif - default: - break; - } - } -#ifdef HAVE_FCNTL - fcntl(fd, F_SETFL, mode); -#endif - return status; - } -} - -struct inetsock_arg -{ - VALUE sock; - struct { - VALUE host, serv; - struct addrinfo *res; - } remote, local; - int type; - int fd; -}; - -static VALUE -inetsock_cleanup(arg) - struct inetsock_arg *arg; -{ - if (arg->remote.res) { - freeaddrinfo(arg->remote.res); - arg->remote.res = 0; - } - if (arg->local.res) { - freeaddrinfo(arg->local.res); - arg->local.res = 0; - } - if (arg->fd >= 0) { - close(arg->fd); - } - return Qnil; -} - -static VALUE -init_inetsock_internal(arg) - struct inetsock_arg *arg; -{ - int type = arg->type; - struct addrinfo *res; - int fd, status = 0; - char *syscall; - - arg->remote.res = sock_addrinfo(arg->remote.host, arg->remote.serv, SOCK_STREAM, - (type == INET_SERVER) ? AI_PASSIVE : 0); - /* - * Maybe also accept a local address - */ - - if (type != INET_SERVER && (!NIL_P(arg->local.host) || !NIL_P(arg->local.serv))) { - arg->local.res = sock_addrinfo(arg->local.host, arg->local.serv, SOCK_STREAM, 0); - } - - arg->fd = fd = -1; - for (res = arg->remote.res; res; res = res->ai_next) { - status = ruby_socket(res->ai_family,res->ai_socktype,res->ai_protocol); - syscall = "socket(2)"; - fd = status; - if (fd < 0) { - continue; - } - arg->fd = fd; - if (type == INET_SERVER) { -#if !defined(_WIN32) && !defined(__CYGWIN__) - status = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, - (char*)&status, sizeof(status)); -#endif - status = bind(fd, res->ai_addr, res->ai_addrlen); - syscall = "bind(2)"; - } - else { - if (arg->local.res) { - status = bind(fd, arg->local.res->ai_addr, arg->local.res->ai_addrlen); - syscall = "bind(2)"; - } - - if (status >= 0) { - status = ruby_connect(fd, res->ai_addr, res->ai_addrlen, - (type == INET_SOCKS)); - syscall = "connect(2)"; - } - } - - if (status < 0) { - close(fd); - arg->fd = fd = -1; - continue; - } else - break; - } - if (status < 0) { - rb_sys_fail(syscall); - } - - arg->fd = -1; - - if (type == INET_SERVER) - listen(fd, 5); - - /* create new instance */ - return init_sock(arg->sock, fd); -} - -static VALUE -init_inetsock(sock, remote_host, remote_serv, local_host, local_serv, type) - VALUE sock, remote_host, remote_serv, local_host, local_serv; - int type; -{ - struct inetsock_arg arg; - arg.sock = sock; - arg.remote.host = remote_host; - arg.remote.serv = remote_serv; - arg.remote.res = 0; - arg.local.host = local_host; - arg.local.serv = local_serv; - arg.local.res = 0; - arg.type = type; - arg.fd = -1; - return rb_ensure(init_inetsock_internal, (VALUE)&arg, - inetsock_cleanup, (VALUE)&arg); -} - -static VALUE -tcp_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE remote_host, remote_serv; - VALUE local_host, local_serv; - - rb_scan_args(argc, argv, "22", &remote_host, &remote_serv, - &local_host, &local_serv); - - return init_inetsock(sock, remote_host, remote_serv, - local_host, local_serv, INET_CLIENT); -} - -#ifdef SOCKS -static VALUE -socks_init(sock, host, serv) - VALUE sock, host, serv; -{ - static init = 0; - - if (init == 0) { - SOCKSinit("ruby"); - init = 1; - } - - return init_inetsock(sock, host, serv, Qnil, Qnil, INET_SOCKS); -} - -#ifdef SOCKS5 -static VALUE -socks_s_close(sock) - VALUE sock; -{ - OpenFile *fptr; - - if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { - rb_raise(rb_eSecurityError, "Insecure: can't close socket"); - } - GetOpenFile(sock, fptr); - shutdown(fileno(fptr->f), 2); - shutdown(fileno(fptr->f2), 2); - return rb_io_close(sock); -} -#endif -#endif - -struct hostent_arg { - VALUE host; - struct addrinfo* addr; - VALUE (*ipaddr)_((struct sockaddr*, size_t)); -}; - -static VALUE -make_hostent_internal(arg) - struct hostent_arg *arg; -{ - VALUE host = arg->host; - struct addrinfo* addr = arg->addr; - VALUE (*ipaddr)_((struct sockaddr*, size_t)) = arg->ipaddr; - - struct addrinfo *ai; - struct hostent *h; - VALUE ary, names; - char **pch; - const char* hostp; - char hbuf[NI_MAXHOST]; - - ary = rb_ary_new(); - if (addr->ai_canonname) { - hostp = addr->ai_canonname; - } - else { - hostp = host_str(host, hbuf, sizeof(hbuf)); - } - rb_ary_push(ary, rb_str_new2(hostp)); - - if (addr->ai_canonname && (h = gethostbyname(addr->ai_canonname))) { - names = rb_ary_new(); - if (h->h_aliases != NULL) { - for (pch = h->h_aliases; *pch; pch++) { - rb_ary_push(names, rb_str_new2(*pch)); - } - } - } - else { - names = rb_ary_new2(0); - } - rb_ary_push(ary, names); - rb_ary_push(ary, INT2NUM(addr->ai_family)); - for (ai = addr; ai; ai = ai->ai_next) { - /* Pushing all addresses regardless of address family is not the - * behaviour expected of gethostbyname(). All the addresses in struct - * hostent->h_addr_list must be of the same family. - */ - if(ai->ai_family == addr->ai_family) { - rb_ary_push(ary, (*ipaddr)(ai->ai_addr, ai->ai_addrlen)); - } - } - - return ary; -} - -static VALUE -make_hostent(host, addr, ipaddr) - VALUE host; - struct addrinfo* addr; - VALUE (*ipaddr)_((struct sockaddr*, size_t)); -{ - struct hostent_arg arg; - - arg.host = host; - arg.addr = addr; - arg.ipaddr = ipaddr; - return rb_ensure(make_hostent_internal, (VALUE)&arg, - RUBY_METHOD_FUNC(freeaddrinfo), (VALUE)addr); -} - -VALUE -tcp_sockaddr(addr, len) - struct sockaddr *addr; - size_t len; -{ - return make_ipaddr(addr); -} - -static VALUE -tcp_s_gethostbyname(obj, host) - VALUE obj, host; -{ - rb_secure(3); - return make_hostent(host, sock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), tcp_sockaddr); -} - -static VALUE -tcp_svr_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE arg1, arg2; - - if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) - return init_inetsock(sock, arg1, arg2, Qnil, Qnil, INET_SERVER); - else - return init_inetsock(sock, Qnil, arg1, Qnil, Qnil, INET_SERVER); -} - -static VALUE -s_accept_nonblock(VALUE klass, OpenFile *fptr, struct sockaddr *sockaddr, socklen_t *len) -{ - int fd2; - - rb_secure(3); - rb_io_set_nonblock(fptr); - fd2 = accept(fileno(fptr->f), (struct sockaddr*)sockaddr, len); - if (fd2 < 0) { - rb_sys_fail("accept(2)"); - } - return init_sock(rb_obj_alloc(klass), fd2); -} - -static VALUE -s_accept(klass, fd, sockaddr, len) - VALUE klass; - int fd; - struct sockaddr *sockaddr; - socklen_t *len; -{ - int fd2; - int retry = 0; - - rb_secure(3); - retry: - rb_thread_wait_fd(fd); -#if defined(_nec_ews) - fd2 = accept(fd, sockaddr, len); -#else - TRAP_BEG; - fd2 = accept(fd, sockaddr, len); - TRAP_END; -#endif - if (fd2 < 0) { - switch (errno) { - case EMFILE: - case ENFILE: - if (retry) break; - rb_gc(); - retry = 1; - goto retry; - case EWOULDBLOCK: - break; - default: - if (!rb_io_wait_readable(fd)) break; - retry = 0; - goto retry; - } - rb_sys_fail(0); - } - if (!klass) return INT2NUM(fd2); - return init_sock(rb_obj_alloc(klass), fd2); -} - -static VALUE -tcp_accept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(from); - return s_accept(rb_cTCPSocket, fileno(fptr->f), - (struct sockaddr*)&from, &fromlen); -} - -/* - * call-seq: - * tcpserver.accept_nonblock => tcpsocket - * - * Accepts an incoming connection using accept(2) after - * O_NONBLOCK is set for the underlying file descriptor. - * It returns an accepted TCPSocket for the incoming connection. - * - * === Example - * require 'socket' - * serv = TCPServer.new(2202) - * begin - * sock = serv.accept_nonblock - * rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR - * IO.select([serv]) - * retry - * end - * # sock is an accepted socket. - * - * Refer to Socket#accept for the exceptions that may be thrown if the call - * to TCPServer#accept_nonblock fails. + * _protocol_ should be a protocol defined in the domain. + * This is optional. + * If it is not given, 0 is used internally. * - * TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure, - * including Errno::EAGAIN. - * - * === See - * * TCPServer#accept - * * Socket#accept + * Socket.new(:INET, :STREAM) # TCP socket + * Socket.new(:INET, :DGRAM) # UDP socket + * Socket.new(:UNIX, :STREAM) # UNIX stream socket + * Socket.new(:UNIX, :DGRAM) # UNIX datagram socket */ static VALUE -tcp_accept_nonblock(sock) - VALUE sock; +sock_initialize(int argc, VALUE *argv, VALUE sock) { - OpenFile *fptr; - struct sockaddr_storage from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(from); - return s_accept_nonblock(rb_cTCPSocket, fptr, - (struct sockaddr *)&from, &fromlen); -} - -static VALUE -tcp_sysaccept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(from); - return s_accept(0, fileno(fptr->f), (struct sockaddr*)&from, &fromlen); -} - -#ifdef HAVE_SYS_UN_H -struct unixsock_arg { - struct sockaddr_un *sockaddr; + VALUE domain, type, protocol; int fd; -}; - -static VALUE -unixsock_connect_internal(arg) - struct unixsock_arg *arg; -{ - return (VALUE)ruby_connect(arg->fd, arg->sockaddr, sizeof(*arg->sockaddr), - 0); -} - -static VALUE -init_unixsock(sock, path, server) - VALUE sock; - VALUE path; - int server; -{ - struct sockaddr_un sockaddr; - int fd, status; - OpenFile *fptr; - - SafeStringValue(path); - fd = ruby_socket(AF_UNIX, SOCK_STREAM, 0); - if (fd < 0) { - rb_sys_fail("socket(2)"); - } - - MEMZERO(&sockaddr, struct sockaddr_un, 1); - sockaddr.sun_family = AF_UNIX; - if (sizeof(sockaddr.sun_path) <= RSTRING(path)->len) { - rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)", - (int)sizeof(sockaddr.sun_path)-1); - } - strcpy(sockaddr.sun_path, StringValueCStr(path)); - - if (server) { - status = bind(fd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)); - } - else { - int prot; - struct unixsock_arg arg; - arg.sockaddr = &sockaddr; - arg.fd = fd; - status = rb_protect(unixsock_connect_internal, (VALUE)&arg, &prot); - if (prot) { - close(fd); - rb_jump_tag(prot); - } - } - - if (status < 0) { - close(fd); - rb_sys_fail(sockaddr.sun_path); - } - - if (server) listen(fd, 5); - - init_sock(sock, fd); - GetOpenFile(sock, fptr); - if (server) { - fptr->path = strdup(RSTRING(path)->ptr); - } - - return sock; -} -#endif - -static VALUE -ip_addr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - return ipaddr((struct sockaddr*)&addr); -} - -static VALUE -ip_peeraddr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_storage addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getpeername(2)"); - return ipaddr((struct sockaddr*)&addr); -} - -static VALUE -ip_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_IP); -} - -static VALUE -ip_s_getaddress(obj, host) - VALUE obj, host; -{ - struct sockaddr_storage addr; - struct addrinfo *res = sock_addrinfo(host, Qnil, SOCK_STREAM, 0); - - /* just take the first one */ - memcpy(&addr, res->ai_addr, res->ai_addrlen); - freeaddrinfo(res); - - return make_ipaddr((struct sockaddr*)&addr); -} + int d, t; -static VALUE -udp_init(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - VALUE arg; - int socktype = AF_INET; - int fd; + rb_scan_args(argc, argv, "21", &domain, &type, &protocol); + if (NIL_P(protocol)) + protocol = INT2FIX(0); rb_secure(3); - if (rb_scan_args(argc, argv, "01", &arg) == 1) { - socktype = NUM2INT(arg); - } - fd = ruby_socket(socktype, SOCK_DGRAM, 0); - if (fd < 0) { - rb_sys_fail("socket(2) - udp"); - } - - return init_sock(sock, fd); -} - -struct udp_arg -{ - struct addrinfo *res; - int fd; -}; - -static VALUE -udp_connect_internal(arg) - struct udp_arg *arg; -{ - int fd = arg->fd; - struct addrinfo *res; + setup_domain_and_type(domain, &d, type, &t); + fd = rsock_socket(d, t, NUM2INT(protocol)); + if (fd < 0) rb_sys_fail("socket(2)"); - for (res = arg->res; res; res = res->ai_next) { - if (ruby_connect(fd, res->ai_addr, res->ai_addrlen, 0) >= 0) { - return Qtrue; - } - } - return Qfalse; + return rsock_init_sock(sock, fd); } +#if defined HAVE_SOCKETPAIR static VALUE -udp_connect(sock, host, port) - VALUE sock, host, port; +io_call_close(VALUE io) { - OpenFile *fptr; - struct udp_arg arg; - VALUE ret; - - rb_secure(3); - arg.res = sock_addrinfo(host, port, SOCK_DGRAM, 0); - GetOpenFile(sock, fptr); - arg.fd = fileno(fptr->f); - ret = rb_ensure(udp_connect_internal, (VALUE)&arg, - RUBY_METHOD_FUNC(freeaddrinfo), (VALUE)arg.res); - if (!ret) rb_sys_fail("connect(2)"); - return INT2FIX(0); + return rb_funcall(io, rb_intern("close"), 0, 0); } static VALUE -udp_bind(sock, host, port) - VALUE sock, host, port; +io_close(VALUE io) { - OpenFile *fptr; - struct addrinfo *res0, *res; - - rb_secure(3); - res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0); - GetOpenFile(sock, fptr); - for (res = res0; res; res = res->ai_next) { - if (bind(fileno(fptr->f), res->ai_addr, res->ai_addrlen) < 0) { - continue; - } - freeaddrinfo(res0); - return INT2FIX(0); - } - freeaddrinfo(res0); - rb_sys_fail("bind(2)"); - return INT2FIX(0); + return rb_rescue(io_call_close, io, 0, 0); } static VALUE -udp_send(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; +pair_yield(VALUE pair) { - VALUE mesg, flags, host, port; - OpenFile *fptr; - FILE *f; - int n; - struct addrinfo *res0, *res; - - if (argc == 2 || argc == 3) { - return bsock_send(argc, argv, sock); - } - rb_secure(4); - rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port); - - StringValue(mesg); - res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0); - GetOpenFile(sock, fptr); - f = GetWriteFile(fptr); - for (res = res0; res; res = res->ai_next) { - retry: - n = sendto(fileno(f), RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags), - res->ai_addr, res->ai_addrlen); - if (n >= 0) { - freeaddrinfo(res0); - return INT2FIX(n); - } - if (rb_io_wait_writable(fileno(f))) { - goto retry; - } - } - freeaddrinfo(res0); - rb_sys_fail("sendto(2)"); - return INT2FIX(n); + return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1)); } +#endif +#if defined HAVE_SOCKETPAIR /* * call-seq: - * udpsocket.recvfrom_nonblock(maxlen) => [mesg, sender_inet_addr] - * udpsocket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_inet_addr] - * - * Receives up to _maxlen_ bytes from +udpsocket+ using recvfrom(2) after - * O_NONBLOCK is set for the underlying file descriptor. - * _flags_ is zero or more of the +MSG_+ options. - * The first element of the results, _mesg_, is the data received. - * The second element, _sender_inet_addr_, is an array to represent the sender address. + * Socket.pair(domain, type, protocol) => [socket1, socket2] + * Socket.socketpair(domain, type, protocol) => [socket1, socket2] * - * When recvfrom(2) returns 0, - * Socket#recvfrom_nonblock returns an empty string as data. - * It means an empty packet. - * - * === Parameters - * * +maxlen+ - the number of bytes to receive from the socket - * * +flags+ - zero or more of the +MSG_+ options - * - * === Example - * require 'socket' - * s1 = UDPSocket.new - * s1.bind("127.0.0.1", 0) - * s2 = UDPSocket.new - * s2.bind("127.0.0.1", 0) - * s2.connect(*s1.addr.values_at(3,1)) - * s1.connect(*s2.addr.values_at(3,1)) - * s1.send "aaa", 0 - * IO.select([s2]) - * p s2.recvfrom_nonblock(10) #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]] + * Creates a pair of sockets connected each other. * - * Refer to Socket#recvfrom for the exceptions that may be thrown if the call - * to _recvfrom_nonblock_ fails. + * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc. * - * UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure, - * including Errno::EAGAIN. + * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc. * - * === See - * * Socket#recvfrom - */ -static VALUE -udp_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock) -{ - return s_recvfrom_nonblock(sock, argc, argv, RECV_IP); -} - -#ifdef HAVE_SYS_UN_H -static VALUE -unix_init(sock, path) - VALUE sock, path; -{ - return init_unixsock(sock, path, 0); -} - -static char * -unixpath(struct sockaddr_un *sockaddr, socklen_t len) -{ - if (sockaddr->sun_path < (char*)sockaddr + len) - return sockaddr->sun_path; - else - return ""; -} - -static VALUE -unix_path(sock) - VALUE sock; -{ - OpenFile *fptr; - - GetOpenFile(sock, fptr); - if (fptr->path == 0) { - struct sockaddr_un addr; - socklen_t len = sizeof(addr); - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail(0); - fptr->path = strdup(unixpath(&addr, len)); - } - return rb_str_new2(fptr->path); -} - -static VALUE -unix_svr_init(sock, path) - VALUE sock, path; -{ - return init_unixsock(sock, path, 1); -} - -static VALUE -unix_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ - return s_recvfrom(sock, argc, argv, RECV_UNIX); -} - -#if defined(HAVE_ST_MSG_CONTROL) && defined(SCM_RIGHTS) -#define FD_PASSING_BY_MSG_CONTROL 1 -#else -#define FD_PASSING_BY_MSG_CONTROL 0 -#endif - -#if defined(HAVE_ST_MSG_ACCRIGHTS) -#define FD_PASSING_BY_MSG_ACCRIGHTS 1 -#else -#define FD_PASSING_BY_MSG_ACCRIGHTS 0 -#endif - -static VALUE -unix_send_io(sock, val) - VALUE sock, val; -{ -#if defined(HAVE_SENDMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS) - int fd; - OpenFile *fptr; - struct msghdr msg; - struct iovec vec[1]; - char buf[1]; - -#if FD_PASSING_BY_MSG_CONTROL - struct { - struct cmsghdr hdr; - int fd; - } cmsg; -#endif - - if (rb_obj_is_kind_of(val, rb_cIO)) { - OpenFile *valfptr; - GetOpenFile(val, valfptr); - fd = fileno(valfptr->f); - } - else if (FIXNUM_P(val)) { - fd = FIX2INT(val); - } - else { - rb_raise(rb_eTypeError, "neither IO nor file descriptor"); - } - - GetOpenFile(sock, fptr); - - msg.msg_name = NULL; - msg.msg_namelen = 0; - - /* Linux and Solaris doesn't work if msg_iov is NULL. */ - buf[0] = '\0'; - vec[0].iov_base = buf; - vec[0].iov_len = 1; - msg.msg_iov = vec; - msg.msg_iovlen = 1; - -#if FD_PASSING_BY_MSG_CONTROL - msg.msg_control = (caddr_t)&cmsg; - msg.msg_controllen = CMSG_SPACE(sizeof(int)); - msg.msg_flags = 0; - cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int)); - cmsg.hdr.cmsg_level = SOL_SOCKET; - cmsg.hdr.cmsg_type = SCM_RIGHTS; - cmsg.fd = fd; -#else - msg.msg_accrights = (caddr_t)&fd; - msg.msg_accrightslen = sizeof(fd); -#endif - - if (sendmsg(fileno(fptr->f), &msg, 0) == -1) - rb_sys_fail("sendmsg(2)"); - - return Qnil; -#else - rb_notimplement(); - return Qnil; /* not reached */ -#endif -} - -#if defined(HAVE_RECVMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS) -static void -thread_read_select(fd) - int fd; -{ - fd_set fds; - - FD_ZERO(&fds); - FD_SET(fd, &fds); - rb_thread_select(fd+1, &fds, 0, 0, 0); -} -#endif - -static VALUE -unix_recv_io(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; -{ -#if defined(HAVE_RECVMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS) - VALUE klass, mode; - OpenFile *fptr; - struct msghdr msg; - struct iovec vec[2]; - char buf[1]; - - int fd; -#if FD_PASSING_BY_MSG_CONTROL - struct { - struct cmsghdr hdr; - int fd; - } cmsg; -#endif - - rb_scan_args(argc, argv, "02", &klass, &mode); - if (argc == 0) - klass = rb_cIO; - if (argc <= 1) - mode = Qnil; - - GetOpenFile(sock, fptr); - - thread_read_select(fileno(fptr->f)); - - msg.msg_name = NULL; - msg.msg_namelen = 0; - - vec[0].iov_base = buf; - vec[0].iov_len = sizeof(buf); - msg.msg_iov = vec; - msg.msg_iovlen = 1; - -#if FD_PASSING_BY_MSG_CONTROL - msg.msg_control = (caddr_t)&cmsg; - msg.msg_controllen = CMSG_SPACE(sizeof(int)); - msg.msg_flags = 0; - cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int)); - cmsg.hdr.cmsg_level = SOL_SOCKET; - cmsg.hdr.cmsg_type = SCM_RIGHTS; - cmsg.fd = -1; -#else - msg.msg_accrights = (caddr_t)&fd; - msg.msg_accrightslen = sizeof(fd); - fd = -1; -#endif - - if (recvmsg(fileno(fptr->f), &msg, 0) == -1) - rb_sys_fail("recvmsg(2)"); - -#if FD_PASSING_BY_MSG_CONTROL - if (msg.msg_controllen != CMSG_SPACE(sizeof(int))) { - rb_raise(rb_eSocket, - "file descriptor was not passed (msg_controllen : %d != %d)", - msg.msg_controllen, CMSG_SPACE(sizeof(int))); - } - if (cmsg.hdr.cmsg_len != CMSG_SPACE(0) + sizeof(int)) { - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_len : %d != %d)", - cmsg.hdr.cmsg_len, CMSG_SPACE(0) + sizeof(int)); - } - if (cmsg.hdr.cmsg_level != SOL_SOCKET) { - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_level : %d != %d)", - cmsg.hdr.cmsg_level, SOL_SOCKET); - } - if (cmsg.hdr.cmsg_type != SCM_RIGHTS) { - rb_raise(rb_eSocket, - "file descriptor was not passed (cmsg_type : %d != %d)", - cmsg.hdr.cmsg_type, SCM_RIGHTS); - } -#else - if (msg.msg_accrightslen != sizeof(fd)) { - rb_raise(rb_eSocket, - "file descriptor was not passed (accrightslen) : %d != %d", - msg.msg_accrightslen, sizeof(fd)); - } -#endif - -#if FD_PASSING_BY_MSG_CONTROL - fd = cmsg.fd; -#endif - - if (klass == Qnil) - return INT2FIX(fd); - else { - static ID for_fd = 0; - int ff_argc; - VALUE ff_argv[2]; - if (!for_fd) - for_fd = rb_intern("for_fd"); - ff_argc = mode == Qnil ? 1 : 2; - ff_argv[0] = INT2FIX(fd); - ff_argv[1] = mode; - return rb_funcall2(klass, for_fd, ff_argc, ff_argv); - } -#else - rb_notimplement(); - return Qnil; /* not reached */ -#endif -} - -static VALUE -unix_accept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(struct sockaddr_un); - return s_accept(rb_cUNIXSocket, fileno(fptr->f), - (struct sockaddr*)&from, &fromlen); -} - -/* - * call-seq: - * unixserver.accept_nonblock => unixsocket - * - * Accepts an incoming connection using accept(2) after - * O_NONBLOCK is set for the underlying file descriptor. - * It returns an accepted UNIXSocket for the incoming connection. - * - * === Example - * require 'socket' - * serv = UNIXServer.new("/tmp/sock") - * begin - * sock = serv.accept_nonblock - * rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR - * IO.select([serv]) - * retry - * end - * # sock is an accepted socket. - * - * Refer to Socket#accept for the exceptions that may be thrown if the call - * to UNIXServer#accept_nonblock fails. + * _protocol_ should be a protocol defined in the domain. + * 0 is default protocol for the domain. + * + * s1, s2 = Socket.pair(:UNIX, :DGRAM, 0) + * s1.send "a", 0 + * s1.send "b", 0 + * p s2.recv(10) #=> "a" + * p s2.recv(10) #=> "b" * - * UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure, - * including Errno::EAGAIN. - * - * === See - * * UNIXServer#accept - * * Socket#accept */ -static VALUE -unix_accept_nonblock(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(from); - return s_accept_nonblock(rb_cUNIXSocket, fptr, - (struct sockaddr *)&from, &fromlen); -} - -static VALUE -unix_sysaccept(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un from; - socklen_t fromlen; - - GetOpenFile(sock, fptr); - fromlen = sizeof(struct sockaddr_un); - return s_accept(0, fileno(fptr->f), (struct sockaddr*)&from, &fromlen); -} - -static VALUE -unixaddr(sockaddr, len) - struct sockaddr_un *sockaddr; - socklen_t len; -{ - return rb_assoc_new(rb_str_new2("AF_UNIX"), - rb_str_new2(unixpath(sockaddr, len))); -} - -static VALUE -unix_addr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getsockname(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - return unixaddr(&addr, len); -} - -static VALUE -unix_peeraddr(sock) - VALUE sock; -{ - OpenFile *fptr; - struct sockaddr_un addr; - socklen_t len = sizeof addr; - - GetOpenFile(sock, fptr); - - if (getpeername(fileno(fptr->f), (struct sockaddr*)&addr, &len) < 0) - rb_sys_fail("getsockname(2)"); - return unixaddr(&addr, len); -} -#endif - -static void -setup_domain_and_type(domain, dv, type, tv) - VALUE domain, type; - int *dv, *tv; -{ - VALUE tmp; - char *ptr; - - tmp = rb_check_string_type(domain); - if (!NIL_P(tmp)) { - domain = tmp; - rb_check_safe_obj(domain); - ptr = RSTRING(domain)->ptr; - if (strcmp(ptr, "AF_INET") == 0) - *dv = AF_INET; -#ifdef AF_UNIX - else if (strcmp(ptr, "AF_UNIX") == 0) - *dv = AF_UNIX; -#endif -#ifdef AF_ISO - else if (strcmp(ptr, "AF_ISO") == 0) - *dv = AF_ISO; -#endif -#ifdef AF_NS - else if (strcmp(ptr, "AF_NS") == 0) - *dv = AF_NS; -#endif -#ifdef AF_IMPLINK - else if (strcmp(ptr, "AF_IMPLINK") == 0) - *dv = AF_IMPLINK; -#endif -#ifdef PF_INET - else if (strcmp(ptr, "PF_INET") == 0) - *dv = PF_INET; -#endif -#ifdef PF_UNIX - else if (strcmp(ptr, "PF_UNIX") == 0) - *dv = PF_UNIX; -#endif -#ifdef PF_IMPLINK - else if (strcmp(ptr, "PF_IMPLINK") == 0) - *dv = PF_IMPLINK; - else if (strcmp(ptr, "AF_IMPLINK") == 0) - *dv = AF_IMPLINK; -#endif -#ifdef PF_AX25 - else if (strcmp(ptr, "PF_AX25") == 0) - *dv = PF_AX25; -#endif -#ifdef PF_IPX - else if (strcmp(ptr, "PF_IPX") == 0) - *dv = PF_IPX; -#endif - else - rb_raise(rb_eSocket, "unknown socket domain %s", ptr); - } - else { - *dv = NUM2INT(domain); - } - tmp = rb_check_string_type(type); - if (!NIL_P(tmp)) { - type = tmp; - rb_check_safe_obj(type); - ptr = RSTRING(type)->ptr; - if (strcmp(ptr, "SOCK_STREAM") == 0) - *tv = SOCK_STREAM; - else if (strcmp(ptr, "SOCK_DGRAM") == 0) - *tv = SOCK_DGRAM; -#ifdef SOCK_RAW - else if (strcmp(ptr, "SOCK_RAW") == 0) - *tv = SOCK_RAW; -#endif -#ifdef SOCK_SEQPACKET - else if (strcmp(ptr, "SOCK_SEQPACKET") == 0) - *tv = SOCK_SEQPACKET; -#endif -#ifdef SOCK_RDM - else if (strcmp(ptr, "SOCK_RDM") == 0) - *tv = SOCK_RDM; -#endif -#ifdef SOCK_PACKET - else if (strcmp(ptr, "SOCK_PACKET") == 0) - *tv = SOCK_PACKET; -#endif - else - rb_raise(rb_eSocket, "unknown socket type %s", ptr); - } - else { - *tv = NUM2INT(type); - } -} - -static VALUE -sock_initialize(sock, domain, type, protocol) - VALUE sock, domain, type, protocol; -{ - int fd; - int d, t; - - rb_secure(3); - setup_domain_and_type(domain, &d, type, &t); - fd = ruby_socket(d, t, NUM2INT(protocol)); - if (fd < 0) rb_sys_fail("socket(2)"); - - return init_sock(sock, fd); -} - -static VALUE -sock_s_socketpair(klass, domain, type, protocol) - VALUE klass, domain, type, protocol; +VALUE +rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass) { -#if defined HAVE_SOCKETPAIR + VALUE domain, type, protocol; int d, t, p, sp[2]; int ret; + VALUE s1, s2, r; + + rb_scan_args(argc, argv, "21", &domain, &type, &protocol); + if (NIL_P(protocol)) + protocol = INT2FIX(0); setup_domain_and_type(domain, &d, type, &t); p = NUM2INT(protocol); @@ -2324,43 +120,28 @@ sock_s_socketpair(klass, domain, type, protocol) rb_sys_fail("socketpair(2)"); } - return rb_assoc_new(init_sock(rb_obj_alloc(klass), sp[0]), - init_sock(rb_obj_alloc(klass), sp[1])); -#else - rb_notimplement(); -#endif -} - -#ifdef HAVE_SYS_UN_H -static VALUE -unix_s_socketpair(argc, argv, klass) - int argc; - VALUE *argv; - VALUE klass; -{ - VALUE domain, type, protocol; - domain = INT2FIX(PF_UNIX); - - rb_scan_args(argc, argv, "02", &type, &protocol); - if (argc == 0) - type = INT2FIX(SOCK_STREAM); - if (argc <= 1) - protocol = INT2FIX(0); - - return sock_s_socketpair(klass, domain, type, protocol); + s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]); + s2 = rsock_init_sock(rb_obj_alloc(klass), sp[1]); + r = rb_assoc_new(s1, s2); + if (rb_block_given_p()) { + return rb_ensure(pair_yield, r, io_close, s1); + } + return r; } +#else +#define rsock_sock_s_socketpair rb_f_notimplement #endif /* * call-seq: - * socket.connect(server_sockaddr) => 0 - * - * Requests a connection to be made on the given +server_sockaddr+. Returns 0 if + * socket.connect(remote_sockaddr) => 0 + * + * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if * successful, otherwise an exception is raised. - * + * * === Parameter - * * +server_sockaddr+ - the +struct+ sockaddr contained in a string - * + * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object + * * === Example: * # Pull down Google's web page * require 'socket' @@ -2369,17 +150,17 @@ unix_s_socketpair(argc, argv, klass) * sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' ) * socket.connect( sockaddr ) * socket.write( "GET / HTTP/1.0\r\n\r\n" ) - * results = socket.read - * + * results = socket.read + * * === Unix-based Exceptions - * On unix-based systems the following system exceptions may be raised if + * On unix-based systems the following system exceptions may be raised if * the call to _connect_ fails: * * Errno::EACCES - search permission is denied for a component of the prefix - * path or write access to the +socket+ is denided + * path or write access to the +socket+ is denied * * Errno::EADDRINUSE - the _sockaddr_ is already in use * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the * local machine - * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for + * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for * the address family of the specified +socket+ * * Errno::EALREADY - a connection is already in progress for the specified * socket @@ -2388,56 +169,56 @@ unix_s_socketpair(argc, argv, klass) * refused the connection request * * Errno::ECONNRESET - the remote host reset the connection request * * Errno::EFAULT - the _sockaddr_ cannot be accessed - * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably + * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably * because the host is down or a remote router cannot reach it) * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the - * connection cnanot be immediately established; the connection will be + * connection cannot be immediately established; the connection will be * established asynchronously * * Errno::EINTR - the attempt to establish the connection was interrupted by * delivery of a signal that was caught; the connection will be established * asynchronously * * Errno::EISCONN - the specified +socket+ is already connected * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid - * length for the address family or there is an invalid family in _sockaddr_ + * length for the address family or there is an invalid family in _sockaddr_ * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded * PATH_MAX * * Errno::ENETDOWN - the local interface used to reach the destination is down * * Errno::ENETUNREACH - no route to the network is present * * Errno::ENOBUFS - no buffer space is available - * * Errno::ENOSR - there were insufficient STREAMS resources available to + * * Errno::ENOSR - there were insufficient STREAMS resources available to * complete the operation * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected - * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket + * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket * bound to the specified peer address * * Errno::ETIMEDOUT - the attempt to connect time out before a connection * was made. - * + * * On unix-based systems if the address family of the calling +socket+ is * AF_UNIX the follow exceptions may be raised if the call to _connect_ * fails: - * * Errno::EIO - an i/o error occured while reading from or writing to the + * * Errno::EIO - an i/o error occurred while reading from or writing to the * file system * * Errno::ELOOP - too many symbolic links were encountered in translating * the pathname in _sockaddr_ - * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX - * characters, or an entired pathname exceeded PATH_MAX characters + * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX + * characters, or an entire pathname exceeded PATH_MAX characters * * Errno::ENOENT - a component of the pathname does not name an existing file * or the pathname is an empty string * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_ - * is not a directory - * + * is not a directory + * * === Windows Exceptions - * On Windows systems the following system exceptions may be raised if + * On Windows systems the following system exceptions may be raised if * the call to _connect_ fails: * * Errno::ENETDOWN - the network is down * * Errno::EADDRINUSE - the socket's local address is already in use * * Errno::EINTR - the socket was cancelled * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider - * is still processing a callback function. Or a nonblocking connect call is + * is still processing a callback function. Or a nonblocking connect call is * in progress on the +socket+. * * Errno::EALREADY - see Errno::EINVAL - * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as + * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as * ADDR_ANY TODO check ADDRANY TO INADDR_ANY * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with * with this +socket+ @@ -2453,84 +234,89 @@ unix_s_socketpair(argc, argv, klass) * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket * * Errno::ETIMEDOUT - the attempt to connect time out before a connection * was made. - * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the + * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the * connection cannot be completed immediately - * * Errno::EACCES - the attempt to connect the datagram socket to the + * * Errno::EACCES - the attempt to connect the datagram socket to the * broadcast address failed - * + * * === See * * connect manual pages on unix-based systems * * connect function in Microsoft's Winsock functions reference */ static VALUE -sock_connect(sock, addr) - VALUE sock, addr; +sock_connect(VALUE sock, VALUE addr) { - OpenFile *fptr; - int fd; + rb_io_t *fptr; + int fd, n; - StringValue(addr); + SockAddrStringValue(addr); addr = rb_str_new4(addr); GetOpenFile(sock, fptr); - fd = fileno(fptr->f); - if (ruby_connect(fd, (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len, 0) < 0) { + fd = fptr->fd; + n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr), 0); + if (n < 0) { rb_sys_fail("connect(2)"); } - return INT2FIX(0); + return INT2FIX(n); } /* * call-seq: - * socket.connect_nonblock(server_sockaddr) => 0 - * - * Requests a connection to be made on the given +server_sockaddr+ after + * socket.connect_nonblock(remote_sockaddr) => 0 + * + * Requests a connection to be made on the given +remote_sockaddr+ after * O_NONBLOCK is set for the underlying file descriptor. * Returns 0 if successful, otherwise an exception is raised. - * + * * === Parameter - * * +server_sockaddr+ - the +struct+ sockaddr contained in a string - * + * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object + * * === Example: * # Pull down Google's web page * require 'socket' * include Socket::Constants * socket = Socket.new(AF_INET, SOCK_STREAM, 0) * sockaddr = Socket.sockaddr_in(80, 'www.google.com') - * begin + * begin # emulate blocking connect * socket.connect_nonblock(sockaddr) - * rescue Errno::EINPROGRESS - * IO.select(nil, [socket]) + * rescue IO::WaitWritable + * IO.select(nil, [socket]) # wait 3-way handshake completion * begin - * socket.connect_nonblock(sockaddr) + * socket.connect_nonblock(sockaddr) # check connection failure * rescue Errno::EISCONN * end * end * socket.write("GET / HTTP/1.0\r\n\r\n") - * results = socket.read - * + * results = socket.read + * * Refer to Socket#connect for the exceptions that may be thrown if the call - * to _connect_nonblock_ fails. + * to _connect_nonblock_ fails. * * Socket#connect_nonblock may raise any error corresponding to connect(2) failure, * including Errno::EINPROGRESS. * + * If the exception is Errno::EINPROGRESS, + * it is extended by IO::WaitWritable. + * So IO::WaitWritable can be used to rescue the exceptions for retrying connect_nonblock. + * * === See * * Socket#connect */ static VALUE -sock_connect_nonblock(sock, addr) - VALUE sock, addr; +sock_connect_nonblock(VALUE sock, VALUE addr) { - OpenFile *fptr; + rb_io_t *fptr; int n; - StringValue(addr); + SockAddrStringValue(addr); addr = rb_str_new4(addr); GetOpenFile(sock, fptr); rb_io_set_nonblock(fptr); - n = connect(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len); + n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr)); if (n < 0) { + if (errno == EINPROGRESS) + rb_mod_sys_fail(rb_mWaitWritable, "connect(2) would block"); rb_sys_fail("connect(2)"); } @@ -2539,33 +325,40 @@ sock_connect_nonblock(sock, addr) /* * call-seq: - * socket.bind(server_sockaddr) => 0 - * - * Binds to the given +struct+ sockaddr. - * + * socket.bind(local_sockaddr) => 0 + * + * Binds to the given local address. + * * === Parameter - * * +server_sockaddr+ - the +struct+ sockaddr contained in a string + * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object * * === Example * require 'socket' + * + * # use Addrinfo + * socket = Socket.new(:INET, :STREAM, 0) + * socket.bind(Addrinfo.tcp("127.0.0.1", 2222)) + * p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP> + * + * # use struct sockaddr * include Socket::Constants * socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.bind( sockaddr ) - * + * * === Unix-based Exceptions - * On unix-based based systems the following system exceptions may be raised if + * On unix-based based systems the following system exceptions may be raised if * the call to _bind_ fails: * * Errno::EACCES - the specified _sockaddr_ is protected and the current * user does not have permission to bind to it * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the * local machine - * * Errno::EAFNOSUPPORT - the specified _sockaddr_ isnot a valid address for + * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for * the family of the calling +socket+ * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed - * * Errno::EINVAL - the +socket+ is already bound to an address, and the + * * Errno::EINVAL - the +socket+ is already bound to an address, and the * protocol does not support binding to the new _sockaddr_ or the +socket+ * has been shut down. * * Errno::EINVAL - the address length is not a valid length for the address @@ -2573,35 +366,35 @@ sock_connect_nonblock(sock, addr) * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded * PATH_MAX * * Errno::ENOBUFS - no buffer space is available - * * Errno::ENOSR - there were insufficient STREAMS resources available to + * * Errno::ENOSR - there were insufficient STREAMS resources available to * complete the operation * * Errno::ENOTSOCK - the +socket+ does not refer to a socket - * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support + * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support * binding to an address - * + * * On unix-based based systems if the address family of the calling +socket+ is * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_ * fails: * * Errno::EACCES - search permission is denied for a component of the prefix - * path or write access to the +socket+ is denided + * path or write access to the +socket+ is denied * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer * * Errno::EISDIR - same as Errno::EDESTADDRREQ * * Errno::EIO - an i/o error occurred * * Errno::ELOOP - too many symbolic links were encountered in translating * the pathname in _sockaddr_ - * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX - * characters, or an entired pathname exceeded PATH_MAX characters + * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX + * characters, or an entire pathname exceeded PATH_MAX characters * * Errno::ENOENT - a component of the pathname does not name an existing file * or the pathname is an empty string * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_ * is not a directory * * Errno::EROFS - the name would reside on a read only filesystem - * + * * === Windows Exceptions - * On Windows systems the following system exceptions may be raised if + * On Windows systems the following system exceptions may be raised if * the call to _bind_ fails: * * Errno::ENETDOWN-- the network is down - * * Errno::EACCES - the attempt to connect the datagram socket to the + * * Errno::EACCES - the attempt to connect the datagram socket to the * broadcast address failed * * Errno::EADDRINUSE - the socket's local address is already in use * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this @@ -2611,20 +404,19 @@ sock_connect_nonblock(sock, addr) * * Errno::EINVAL - the +socket+ is already bound to an address * * Errno::ENOBUFS - no buffer space is available * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket - * + * * === See * * bind manual pages on unix-based systems * * bind function in Microsoft's Winsock functions reference - */ + */ static VALUE -sock_bind(sock, addr) - VALUE sock, addr; +sock_bind(VALUE sock, VALUE addr) { - OpenFile *fptr; + rb_io_t *fptr; - StringValue(addr); + SockAddrStringValue(addr); GetOpenFile(sock, fptr); - if (bind(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len) < 0) + if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr)) < 0) rb_sys_fail("bind(2)"); return INT2FIX(0); @@ -2633,14 +425,14 @@ sock_bind(sock, addr) /* * call-seq: * socket.listen( int ) => 0 - * + * * Listens for connections, using the specified +int+ as the backlog. A call - * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or + * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or * SOCK_SEQPACKET. - * + * * === Parameter * * +backlog+ - the maximum length of the queue for pending connections. - * + * * === Example 1 * require 'socket' * include Socket::Constants @@ -2648,43 +440,43 @@ sock_bind(sock, addr) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.bind( sockaddr ) * socket.listen( 5 ) - * - * === Example 2 (listening on an arbitary port, unix-based systems only): + * + * === Example 2 (listening on an arbitrary port, unix-based systems only): * require 'socket' * include Socket::Constants * socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) * socket.listen( 1 ) - * + * * === Unix-based Exceptions * On unix based systems the above will work because a new +sockaddr+ struct * is created on the address ADDR_ANY, for an arbitrary port number as handed * off by the kernel. It will not work on Windows, because Windows requires that * the +socket+ is bound by calling _bind_ before it can _listen_. - * + * * If the _backlog_ amount exceeds the implementation-dependent maximum * queue length, the implementation's maximum queue length will be used. - * + * * On unix-based based systems the following system exceptions may be raised if the * call to _listen_ fails: * * Errno::EBADF - the _socket_ argument is not a valid file descriptor - * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and + * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and * the protocol does not support listening on an unbound socket * * Errno::EINVAL - the _socket_ is already connected * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen - * * Errno::EACCES - the calling process does not have approriate privileges + * * Errno::EACCES - the calling process does not have appropriate privileges * * Errno::EINVAL - the _socket_ has been shut down - * * Errno::ENOBUFS - insufficient resources are available in the system to + * * Errno::ENOBUFS - insufficient resources are available in the system to * complete the call - * + * * === Windows Exceptions - * On Windows systems the following system exceptions may be raised if + * On Windows systems the following system exceptions may be raised if * the call to _listen_ fails: * * Errno::ENETDOWN - the network is down - * * Errno::EADDRINUSE - the socket's local address is already in use. This + * * Errno::EADDRINUSE - the socket's local address is already in use. This * usually occurs during the execution of _bind_ but could be delayed * if the call to _bind_ was to a partially wildcard address (involving - * ADDR_ANY) and if a specific address needs to be commmitted at the + * ADDR_ANY) and if a specific address needs to be committed at the * time of the call to _listen_ * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the * service provider is still processing a callback function @@ -2695,22 +487,21 @@ sock_bind(sock, addr) * * Errno::ENOTSOC - +socket+ is not a socket * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports * the _listen_ method - * + * * === See * * listen manual pages on unix-based systems * * listen function in Microsoft's Winsock functions reference */ -static VALUE -sock_listen(sock, log) - VALUE sock, log; +VALUE +rsock_sock_listen(VALUE sock, VALUE log) { - OpenFile *fptr; + rb_io_t *fptr; int backlog; rb_secure(4); backlog = NUM2INT(log); GetOpenFile(sock, fptr); - if (listen(fileno(fptr->f), backlog) < 0) + if (listen(fptr->fd, backlog) < 0) rb_sys_fail("listen(2)"); return INT2FIX(0); @@ -2718,18 +509,18 @@ sock_listen(sock, log) /* * call-seq: - * socket.recvfrom(maxlen) => [mesg, sender_sockaddr] - * socket.recvfrom(maxlen, flags) => [mesg, sender_sockaddr] - * + * socket.recvfrom(maxlen) => [mesg, sender_addrinfo] + * socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo] + * * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more * of the +MSG_+ options. The first element of the results, _mesg_, is the data - * received. The second element, _sender_sockaddr_, contains protocol-specific information - * on the sender. - * + * received. The second element, _sender_addrinfo_, contains protocol-specific + * address information of the sender. + * * === Parameters - * * +maxlen+ - the number of bytes to receive from the socket - * * +flags+ - zero or more of the +MSG_+ options - * + * * +maxlen+ - the maximum number of bytes to receive from the socket + * * +flags+ - zero or more of the +MSG_+ options + * * === Example * # In one file, start this first * require 'socket' @@ -2738,12 +529,12 @@ sock_listen(sock, log) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.bind( sockaddr ) * socket.listen( 5 ) - * client, client_sockaddr = socket.accept + * client, client_addrinfo = socket.accept * data = client.recvfrom( 20 )[0].chomp * puts "I only received 20 bytes '#{data}'" * sleep 1 * socket.close - * + * * # In another file, start this second * require 'socket' * include Socket::Constants @@ -2751,29 +542,29 @@ sock_listen(sock, log) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.connect( sockaddr ) * socket.puts "Watch this get cut short!" - * socket.close - * + * socket.close + * * === Unix-based Exceptions * On unix-based based systems the following system exceptions may be raised if the * call to _recvfrom_ fails: * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no * data is waiting to be received; or MSG_OOB is set and no out-of-band data - * is available and either the +socket+ file descriptor is marked as - * O_NONBLOCK or the +socket+ does not support blocking to wait for + * is available and either the +socket+ file descriptor is marked as + * O_NONBLOCK or the +socket+ does not support blocking to wait for * out-of-band-data * * Errno::EWOULDBLOCK - see Errno::EAGAIN * * Errno::EBADF - the +socket+ is not a valid file descriptor * * Errno::ECONNRESET - a connection was forcibly closed by a peer - * * Errno::EFAULT - the socket's internal buffer, address or address length + * * Errno::EFAULT - the socket's internal buffer, address or address length * cannot be accessed or written - * * Errno::EINTR - a signal interupted _recvfrom_ before any data was available + * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available - * * Errno::EIO - an i/o error occurred while reading from or writing to the + * * Errno::EIO - an i/o error occurred while reading from or writing to the * filesystem - * * Errno::ENOBUFS - insufficient resources were available in the system to + * * Errno::ENOBUFS - insufficient resources were available in the system to * perform the operation * * Errno::ENOMEM - insufficient memory was available to fulfill the request - * * Errno::ENOSR - there were insufficient STREAMS resources available to + * * Errno::ENOSR - there were insufficient STREAMS resources available to * complete the operation * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that * is not connected @@ -2781,75 +572,72 @@ sock_listen(sock, log) * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type * * Errno::ETIMEDOUT - the connection timed out during connection establishment * or due to a transmission timeout on an active connection - * + * * === Windows Exceptions - * On Windows systems the following system exceptions may be raised if + * On Windows systems the following system exceptions may be raised if * the call to _recvfrom_ fails: * * Errno::ENETDOWN - the network is down * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not * part of the user address space, or the internal fromlen parameter is - * too small to accomodate the peer address + * too small to accommodate the peer address * * Errno::EINTR - the (blocking) call was cancelled by an internal call to * the WinSock function WSACancelBlockingCall - * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or + * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or * the service provider is still processing a callback function * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an * unknown flag was specified, or MSG_OOB was specified for a socket with * SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal * len parameter on +socket+ was zero or negative * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is - * not permitted with a connected socket on a socket that is connetion + * not permitted with a connected socket on a socket that is connection * oriented or connectionless. - * * Errno::ENETRESET - the connection has been broken due to the keep-alive + * * Errno::ENETRESET - the connection has been broken due to the keep-alive * activity detecting a failure while the operation was in progress. * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style * such as type SOCK_STREAM. OOB data is not supported in the communication - * domain associated with +socket+, or +socket+ is unidirectional and + * domain associated with +socket+, or +socket+ is unidirectional and * supports only send operations - * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to + * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to * call _recvfrom_ on a socket after _shutdown_ has been invoked. - * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to + * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to * _recvfrom_ would block. * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer * and was truncated. * * Errno::ETIMEDOUT - the connection has been dropped, because of a network * failure or because the system on the other end went down without * notice - * * Errno::ECONNRESET - the virtual circuit was reset by the remote side + * * Errno::ECONNRESET - the virtual circuit was reset by the remote side * executing a hard or abortive close. The application should close the * socket; it is no longer usable. On a UDP-datagram socket this error * indicates a previous send operation resulted in an ICMP Port Unreachable * message. */ static VALUE -sock_recvfrom(argc, argv, sock) - int argc; - VALUE *argv; - VALUE sock; +sock_recvfrom(int argc, VALUE *argv, VALUE sock) { - return s_recvfrom(sock, argc, argv, RECV_SOCKET); + return rsock_s_recvfrom(sock, argc, argv, RECV_SOCKET); } /* * call-seq: - * socket.recvfrom_nonblock(maxlen) => [mesg, sender_sockaddr] - * socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_sockaddr] - * + * socket.recvfrom_nonblock(maxlen) => [mesg, sender_addrinfo] + * socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_addrinfo] + * * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after * O_NONBLOCK is set for the underlying file descriptor. * _flags_ is zero or more of the +MSG_+ options. * The first element of the results, _mesg_, is the data received. - * The second element, _sender_sockaddr_, contains protocol-specific information - * on the sender. + * The second element, _sender_addrinfo_, contains protocol-specific address + * information of the sender. * * When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns * an empty string as data. * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc. - * + * * === Parameters - * * +maxlen+ - the number of bytes to receive from the socket - * * +flags+ - zero or more of the +MSG_+ options - * + * * +maxlen+ - the maximum number of bytes to receive from the socket + * * +flags+ - zero or more of the +MSG_+ options + * * === Example * # In one file, start this first * require 'socket' @@ -2858,10 +646,10 @@ sock_recvfrom(argc, argv, sock) * sockaddr = Socket.sockaddr_in(2200, 'localhost') * socket.bind(sockaddr) * socket.listen(5) - * client, client_sockaddr = socket.accept - * begin + * client, client_addrinfo = socket.accept + * begin # emulate blocking recvfrom * pair = client.recvfrom_nonblock(20) - * rescue Errno::EAGAIN + * rescue IO::WaitReadable * IO.select([client]) * retry * end @@ -2869,7 +657,7 @@ sock_recvfrom(argc, argv, sock) * puts "I only received 20 bytes '#{data}'" * sleep 1 * socket.close - * + * * # In another file, start this second * require 'socket' * include Socket::Constants @@ -2877,13 +665,17 @@ sock_recvfrom(argc, argv, sock) * sockaddr = Socket.sockaddr_in(2200, 'localhost') * socket.connect(sockaddr) * socket.puts "Watch this get cut short!" - * socket.close - * + * socket.close + * * Refer to Socket#recvfrom for the exceptions that may be thrown if the call - * to _recvfrom_nonblock_ fails. + * to _recvfrom_nonblock_ fails. * * Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure, - * including Errno::EAGAIN. + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock. * * === See * * Socket#recvfrom @@ -2891,117 +683,47 @@ sock_recvfrom(argc, argv, sock) static VALUE sock_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock) { - return s_recvfrom_nonblock(sock, argc, argv, RECV_SOCKET); + return rsock_s_recvfrom_nonblock(sock, argc, argv, RECV_SOCKET); } /* * call-seq: - * socket.accept => [ socket, string ] - * - * Accepts an incoming connection returning an array containing a new - * Socket object and a string holding the +struct+ sockaddr information about - * the caller. - * - * === Example - * # In one script, start this first - * require 'socket' - * include Socket::Constants - * socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) - * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) - * socket.bind( sockaddr ) - * socket.listen( 5 ) - * client, client_sockaddr = socket.accept - * puts "The client said, '#{socket.readline.chomp}'" - * client.puts "Hello from script one!" - * socket.close - * - * # In another script, start this second - * require 'socket' - * include Socket::Constants - * socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) - * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) - * socket.connect( sockaddr ) - * socket.puts "Hello from script 2." - * puts "The server said, '#{socket.readline.chomp}'" - * socket.close - * - * === Unix-based Exceptions - * On unix-based based systems the following system exceptions may be raised if the - * call to _accept_ fails: - * * Errno::EAGAIN - O_NONBLOCK is set for the +socket+ file descriptor and no - * connections are parent to be accepted - * * Errno::EWOULDBLOCK - same as Errno::EAGAIN - * * Errno::EBADF - the +socket+ is not a valid file descriptor - * * Errno::ECONNABORTED - a connection has been aborted - * * Errno::EFAULT - the socket's internal address or address length parameter - * cannot be access or written - * * Errno::EINTR - the _accept_ method was interrupted by a signal that was - * caught before a valid connection arrived - * * Errno::EINVAL - the +socket+ is not accepting connections - * * Errno::EMFILE - OPEN_MAX file descriptors are currently open in the calling - * process - * * Errno::ENOBUFS - no buffer space is available - * * Errno::ENOMEM - there was insufficient memory available to complete the - * operation - * * Errno::ENOSR - there was insufficient STREAMS resources available to - * complete the operation - * * Errno::ENFILE - the maximum number of file descriptors in the system are - * already open - * * Errno::ENOTSOCK - the +socket+ does not refer to a socket - * * Errno::EOPNOTSUPP - the socket type for the calling +socket+ does not - * support accept connections - * * Errno::EPROTO - a protocol error has occurred - * - * === Windows Exceptions - * On Windows systems the following system exceptions may be raised if - * the call to _accept_ fails: - * * Errno::ECONNRESET - an incoming connection was indicated, but was - * terminated by the remote peer prior to accepting the connection - * * Errno::EFAULT - the socket's internal address or address length parameter - * is too small or is not a valid part of the user space address - * * Errno::EINVAL - the _listen_ method was not invoked prior to calling _accept_ - * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or - * the service provider is still processing a callback function - * * Errno::EMFILE - the queue is not empty, upong etry to _accept_ and there are - * no socket descriptors available - * * Errno::ENETDOWN - the network is down - * * Errno::ENOBUFS - no buffer space is available - * * Errno::ENOTSOCK - +socket+ is not a socket - * * Errno::EOPNOTSUPP - +socket+ is not a type that supports connection-oriented - * service. - * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and no connections are - * present to be accepted - * - * === See - * * accept manual pages on unix-based systems - * * accept function in Microsoft's Winsock functions reference + * socket.accept => [client_socket, client_addrinfo] + * + * Accepts a next connection. + * Returns a new Socket object and Addrinfo object. + * + * serv = Socket.new(:INET, :STREAM, 0) + * serv.listen(5) + * c = Socket.new(:INET, :STREAM, 0) + * c.connect(serv.connect_address) + * p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>] + * */ static VALUE -sock_accept(sock) - VALUE sock; +sock_accept(VALUE sock) { - OpenFile *fptr; + rb_io_t *fptr; VALUE sock2; - char buf[1024]; - socklen_t len = sizeof buf; + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; GetOpenFile(sock, fptr); - sock2 = s_accept(rb_cSocket,fileno(fptr->f),(struct sockaddr*)buf,&len); + sock2 = rsock_s_accept(rb_cSocket,fptr->fd,(struct sockaddr*)&buf,&len); - return rb_assoc_new(sock2, rb_str_new(buf, len)); + return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len)); } /* * call-seq: - * socket.accept_nonblock => [client_socket, client_sockaddr] - * + * socket.accept_nonblock => [client_socket, client_addrinfo] + * * Accepts an incoming connection using accept(2) after * O_NONBLOCK is set for the underlying file descriptor. - * It returns an array containg the accpeted socket + * It returns an array containing the accepted socket * for the incoming connection, _client_socket_, - * and a string that contains the +struct+ sockaddr information - * about the caller, _client_sockaddr_. - * + * and an Addrinfo, _client_addrinfo_. + * * === Example * # In one script, start this first * require 'socket' @@ -3010,13 +732,13 @@ sock_accept(sock) * sockaddr = Socket.sockaddr_in(2200, 'localhost') * socket.bind(sockaddr) * socket.listen(5) - * begin - * client_socket, client_sockaddr = socket.accept_nonblock - * rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR + * begin # emulate blocking accept + * client_socket, client_addrinfo = socket.accept_nonblock + * rescue IO::WaitReadable, Errno::EINTR * IO.select([socket]) * retry * end - * puts "The client said, '#{socket.readline.chomp}'" + * puts "The client said, '#{client_socket.readline.chomp}'" * client_socket.puts "Hello from script one!" * socket.close * @@ -3026,42 +748,44 @@ sock_accept(sock) * socket = Socket.new(AF_INET, SOCK_STREAM, 0) * sockaddr = Socket.sockaddr_in(2200, 'localhost') * socket.connect(sockaddr) - * socket.puts "Hello from script 2." + * socket.puts "Hello from script 2." * puts "The server said, '#{socket.readline.chomp}'" * socket.close - * + * * Refer to Socket#accept for the exceptions that may be thrown if the call - * to _accept_nonblock_ fails. + * to _accept_nonblock_ fails. * * Socket#accept_nonblock may raise any error corresponding to accept(2) failure, - * including Errno::EAGAIN. - * + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED or Errno::EPROTO, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock. + * * === See * * Socket#accept */ static VALUE -sock_accept_nonblock(sock) - VALUE sock; +sock_accept_nonblock(VALUE sock) { - OpenFile *fptr; + rb_io_t *fptr; VALUE sock2; - char buf[1024]; - socklen_t len = sizeof buf; + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; GetOpenFile(sock, fptr); - sock2 = s_accept_nonblock(rb_cSocket, fptr, (struct sockaddr *)buf, &len); - return rb_assoc_new(sock2, rb_str_new(buf, len)); + sock2 = rsock_s_accept_nonblock(rb_cSocket, fptr, (struct sockaddr *)&buf, &len); + return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len)); } /* * call-seq: - * socket.sysaccept => [client_socket_fd, client_sockaddr] - * - * Accepts an incoming connection returnings an array containg the (integer) + * socket.sysaccept => [client_socket_fd, client_addrinfo] + * + * Accepts an incoming connection returning an array containing the (integer) * file descriptor for the incoming connection, _client_socket_fd_, - * and a string that contains the +struct+ sockaddr information - * about the caller, _client_sockaddr_. - * + * and an Addrinfo, _client_addrinfo_. + * * === Example * # In one script, start this first * require 'socket' @@ -3070,49 +794,61 @@ sock_accept_nonblock(sock) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.bind( sockaddr ) * socket.listen( 5 ) - * client_fd, client_sockaddr = socket.sysaccept - * puts "The client said, '#{socket.readline.chomp}'" + * client_fd, client_addrinfo = socket.sysaccept * client_socket = Socket.for_fd( client_fd ) + * puts "The client said, '#{client_socket.readline.chomp}'" * client_socket.puts "Hello from script one!" * socket.close - * + * * # In another script, start this second * require 'socket' * include Socket::Constants * socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) * socket.connect( sockaddr ) - * socket.puts "Hello from script 2." + * socket.puts "Hello from script 2." * puts "The server said, '#{socket.readline.chomp}'" * socket.close - * + * * Refer to Socket#accept for the exceptions that may be thrown if the call - * to _sysaccept_ fails. - * + * to _sysaccept_ fails. + * * === See * * Socket#accept */ static VALUE -sock_sysaccept(sock) - VALUE sock; +sock_sysaccept(VALUE sock) { - OpenFile *fptr; + rb_io_t *fptr; VALUE sock2; - char buf[1024]; - socklen_t len = sizeof buf; + struct sockaddr_storage buf; + socklen_t len = (socklen_t)sizeof buf; GetOpenFile(sock, fptr); - sock2 = s_accept(0,fileno(fptr->f),(struct sockaddr*)buf,&len); + sock2 = rsock_s_accept(0,fptr->fd,(struct sockaddr*)&buf,&len); - return rb_assoc_new(sock2, rb_str_new(buf, len)); + return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len)); } #ifdef HAVE_GETHOSTNAME +/* + * call-seq: + * Socket.gethostname => hostname + * + * Returns the hostname. + * + * p Socket.gethostname #=> "hal" + * + * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc. + * If you need local IP address, use Socket.ip_address_list. + */ static VALUE -sock_gethostname(obj) - VALUE obj; +sock_gethostname(VALUE obj) { - char buf[1024]; +#ifndef HOST_NAME_MAX +# define HOST_NAME_MAX 1024 +#endif + char buf[HOST_NAME_MAX+1]; rb_secure(3); if (gethostname(buf, (int)sizeof buf - 1) < 0) @@ -3127,8 +863,7 @@ sock_gethostname(obj) #include <sys/utsname.h> static VALUE -sock_gethostname(obj) - VALUE obj; +sock_gethostname(VALUE obj) { struct utsname un; @@ -3137,18 +872,12 @@ sock_gethostname(obj) return rb_str_new2(un.nodename); } #else -static VALUE -sock_gethostname(obj) - VALUE obj; -{ - rb_notimplement(); -} +#define sock_gethostname rb_f_notimplement #endif #endif static VALUE -make_addrinfo(res0) - struct addrinfo *res0; +make_addrinfo(struct addrinfo *res0, int norevlookup) { VALUE base, ary; struct addrinfo *res; @@ -3158,7 +887,10 @@ make_addrinfo(res0) } base = rb_ary_new(); for (res = res0; res; res = res->ai_next) { - ary = ipaddr(res->ai_addr); + ary = rsock_ipaddr(res->ai_addr, norevlookup); + if (res->ai_canonname) { + RARRAY_PTR(ary)[2] = rb_str_new2(res->ai_canonname); + } rb_ary_push(ary, INT2FIX(res->ai_family)); rb_ary_push(ary, INT2FIX(res->ai_socktype)); rb_ary_push(ary, INT2FIX(res->ai_protocol)); @@ -3167,11 +899,8 @@ make_addrinfo(res0) return base; } -/* Returns a String containing the binary value of a struct sockaddr. */ -VALUE -sock_sockaddr(addr, len) - struct sockaddr *addr; - size_t len; +static VALUE +sock_sockaddr(struct sockaddr *addr, size_t len) { char *ptr; @@ -3180,7 +909,7 @@ sock_sockaddr(addr, len) ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr; len = sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr); break; -#ifdef INET6 +#ifdef AF_INET6 case AF_INET6: ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr; len = sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr); @@ -3194,132 +923,51 @@ sock_sockaddr(addr, len) } /* - * Document-class: IPSocket - * - * IPSocket is the parent of TCPSocket and UDPSocket and implements - * functionality common to them. - * - * A number of APIs in IPSocket, Socket, and their descendants return an - * address as an array. The members of that array are: - * - address family: A string like "AF_INET" or "AF_INET6" if it is one of the - * commonly used families, the string "unknown:#" (where `#' is the address - * family number) if it is not one of the common ones. The strings map to - * the Socket::AF_* constants. - * - port: The port number. - * - name: Either the canonical name from looking the address up in the DNS, or - * the address in presentation format - * - address: The address in presentation format (a dotted decimal string for - * IPv4, a hex string for IPv6). - * - * The address and port can be used directly to create sockets and to bind or - * connect them to the address. - */ - -/* - * Document-class: Socket + * call-seq: + * Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list] + * + * Obtains the host information for _hostname_. + * + * p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"] * - * Socket contains a number of generally useful singleton methods and - * constants, as well as offering low-level interfaces that can be used to - * develop socket applications using protocols other than TCP, UDP, and UNIX - * domain sockets. - */ - -/* - * Document-method: gethostbyname - * call-seq: Socket.gethostbyname(host) => hostent - * - * Resolve +host+ and return name and address information for it, similarly to - * gethostbyname(3). +host+ can be a domain name or the presentation format of - * an address. - * - * Returns an array of information similar to that found in a +struct hostent+: - * - cannonical name: the cannonical name for host in the DNS, or a - * string representing the address - * - aliases: an array of aliases for the canonical name, there may be no aliases - * - address family: usually one of Socket::AF_INET or Socket::AF_INET6 - * - address: a string, the binary value of the +struct sockaddr+ for this name, in - * the indicated address family - * - ...: if there are multiple addresses for this host, a series of - * strings/+struct sockaddr+s may follow, not all necessarily in the same - * address family. Note that the fact that they may not be all in the same - * address family is a departure from the behaviour of gethostbyname(3). - * - * Note: I believe that the fact that the multiple addresses returned are not - * necessarily in the same address family may be a bug, since if this function - * actually called gethostbyname(3), ALL the addresses returned in the trailing - * address list (h_addr_list from struct hostent) would be of the same address - * family! Examples from my system, OS X 10.3: - * - * ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"] - * and - * ["ensemble.local", [], 30, "\376\200\000\004\000\000\000\000\002\003\223\377\376\255\010\214", "\300\250{\232" ] - * - * Similar information can be returned by Socket.getaddrinfo if called as: - * - * Socket.getaddrinfo(+host+, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) - * - * == Examples - * - * Socket.gethostbyname "example.com" - * => ["example.com", [], 2, "\300\000\"\246"] - * - * This name has no DNS aliases, and a single IPv4 address. - * - * Socket.gethostbyname "smtp.telus.net" - * => ["smtp.svc.telus.net", ["smtp.telus.net"], 2, "\307\271\334\371"] - * - * This name is an an alias so the canonical name is returned, as well as the - * alias and a single IPv4 address. - * - * Socket.gethostbyname "localhost" - * => ["localhost", [], 30, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001", "\177\000\000\001"] - * - * This machine has no aliases, returns an IPv6 address, and has an additional IPv4 address. - * - * +host+ can also be an IP address in presentation format, in which case a - * reverse lookup is done on the address: - * - * Socket.gethostbyname("127.0.0.1") - * => ["localhost", [], 2, "\177\000\000\001"] - * - * Socket.gethostbyname("192.0.34.166") - * => ["www.example.com", [], 2, "\300\000\"\246"] - * - * - * == See - * See: Socket.getaddrinfo */ static VALUE -sock_s_gethostbyname(obj, host) - VALUE obj, host; +sock_s_gethostbyname(VALUE obj, VALUE host) { rb_secure(3); - return make_hostent(host, sock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), sock_sockaddr); + return rsock_make_hostent(host, rsock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), sock_sockaddr); } +/* + * call-seq: + * Socket.gethostbyaddr(address_string [, address_family]) => hostent + * + * Obtains the host information for _address_. + * + * p Socket.gethostbyaddr([221,186,184,68].pack("CCCC")) + * #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"] + */ static VALUE -sock_s_gethostbyaddr(argc, argv) - int argc; - VALUE *argv; +sock_s_gethostbyaddr(int argc, VALUE *argv) { - VALUE addr, type; + VALUE addr, family; struct hostent *h; struct sockaddr *sa; char **pch; VALUE ary, names; int t = AF_INET; - rb_scan_args(argc, argv, "11", &addr, &type); + rb_scan_args(argc, argv, "11", &addr, &family); sa = (struct sockaddr*)StringValuePtr(addr); - if (!NIL_P(type)) { - t = NUM2INT(type); + if (!NIL_P(family)) { + t = rsock_family_arg(family); } -#ifdef INET6 - else if (RSTRING(addr)->len == 16) { +#ifdef AF_INET6 + else if (RSTRING_LEN(addr) == 16) { t = AF_INET6; } #endif - h = gethostbyaddr(RSTRING(addr)->ptr, RSTRING(addr)->len, t); + h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_LENINT(addr), t); if (h == NULL) { #ifdef HAVE_HSTRERROR extern int h_errno; @@ -3350,215 +998,129 @@ sock_s_gethostbyaddr(argc, argv) } /* - * Document-method: getservbyname - * call-seq: Socket.getservbyname(name, proto="tcp") => port + * call-seq: + * Socket.getservbyname(service_name) => port_number + * Socket.getservbyname(service_name, protocol_name) => port_number * - * +name+ is a service name ("ftp", "telnet", ...) and proto is a protocol name - * ("udp", "tcp", ...). '/etc/services' (or your system's equivalent) is - * searched for a service for +name+ and +proto+, and the port number is - * returned. + * Obtains the port number for _service_name_. * - * Note that unlike Socket.getaddrinfo, +proto+ may not be specified using the - * Socket::SOCK_* constants, a string must must be used. + * If _protocol_name_ is not given, "tcp" is assumed. + * + * Socket.getservbyname("smtp") #=> 25 + * Socket.getservbyname("shell") #=> 514 + * Socket.getservbyname("syslog", "udp") #=> 514 */ static VALUE -sock_s_getservbyaname(argc, argv) - int argc; - VALUE *argv; +sock_s_getservbyname(int argc, VALUE *argv) { VALUE service, proto; struct servent *sp; - int port; + long port; + const char *servicename, *protoname = "tcp"; rb_scan_args(argc, argv, "11", &service, &proto); - if (NIL_P(proto)) proto = rb_str_new2("tcp"); StringValue(service); - StringValue(proto); - - sp = getservbyname(StringValueCStr(service), StringValueCStr(proto)); + if (!NIL_P(proto)) StringValue(proto); + servicename = StringValueCStr(service); + if (!NIL_P(proto)) protoname = StringValueCStr(proto); + sp = getservbyname(servicename, protoname); if (sp) { port = ntohs(sp->s_port); } else { - char *s = RSTRING(service)->ptr; char *end; - port = strtoul(s, &end, 0); + port = STRTOUL(servicename, &end, 0); if (*end != '\0') { - rb_raise(rb_eSocket, "no such service %s/%s", s, RSTRING(proto)->ptr); + rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname); } } return INT2FIX(port); } /* -Documentation should explain the following: - - $ pp Socket.getaddrinfo("", 1, Socket::AF_UNSPEC, Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE) - [["AF_INET", 1, "0.0.0.0", "0.0.0.0", 2, 1, 6]] - - $ pp Socket.getaddrinfo(nil, 1, Socket::AF_UNSPEC, Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE) - [["AF_INET6", 1, "::", "::", 30, 1, 6], - ["AF_INET", 1, "0.0.0.0", "0.0.0.0", 2, 1, 6]] - - $ pp Socket.getaddrinfo("localhost", 1, Socket::AF_UNSPEC, Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE) - [["AF_INET6", 1, "localhost", "::1", 30, 1, 6], - ["AF_INET", 1, "localhost", "127.0.0.1", 2, 1, 6]] - - $ pp Socket.getaddrinfo("ensemble.local.", 1, Socket::AF_UNSPEC, Socket::SOCK_STREAM, 0, Socket::AI_PASSIVE) - [["AF_INET", 1, "localhost", "192.168.123.154", 2, 1, 6]] + * call-seq: + * Socket.getservbyport(port [, protocol_name]) => service + * + * Obtains the port number for _port_. + * + * If _protocol_name_ is not given, "tcp" is assumed. + * + * Socket.getservbyport(80) #=> "www" + * Socket.getservbyport(514, "tcp") #=> "shell" + * Socket.getservbyport(514, "udp") #=> "syslog" + * + */ +static VALUE +sock_s_getservbyport(int argc, VALUE *argv) +{ + VALUE port, proto; + struct servent *sp; + long portnum; + const char *protoname = "tcp"; -Does it? + rb_scan_args(argc, argv, "11", &port, &proto); + portnum = NUM2LONG(port); + if (portnum != (uint16_t)portnum) { + const char *s = portnum > 0 ? "big" : "small"; + rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s); + } + if (!NIL_P(proto)) protoname = StringValueCStr(proto); -API suggestion: this method has too many arguments, it would be backwards compatible and easier -to understand if limit args were accepted as :family=>..., :flags=>... -*/ + sp = getservbyport((int)htons((uint16_t)portnum), protoname); + if (!sp) { + rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname); + } + return rb_tainted_str_new2(sp->s_name); +} /* - * Document-method: getaddrinfo - * call-seq: Socket.getaddrinfo(host, service, family=nil, socktype=nil, protocol=nil, flags=nil) => addrinfo + * call-seq: + * Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array * - * Return address information for +host+ and +port+. The remaining arguments - * are hints that limit the address information returned. + * Obtains address information for _nodename_:_servname_. * - * This method corresponds closely to the POSIX.1g getaddrinfo() definition. + * _family_ should be an address family such as: :INET, :INET6, :UNIX, etc. * - * === Parameters - * - +host+ is a host name or an address string (dotted decimal for IPv4, or a hex string - * for IPv6) for which to return information. A nil is also allowed, its meaning - * depends on +flags+, see below. - * - +service+ is a service name ("http", "ssh", ...), or - * a port number (80, 22, ...), see Socket.getservbyname for more - * information. A nil is also allowed, meaning zero. - * - +family+ limits the output to a specific address family, one of the - * Socket::AF_* constants. Socket::AF_INET (IPv4) and Socket::AF_INET6 (IPv6) - * are the most commonly used families. You will usually pass either nil or - * Socket::AF_UNSPEC, allowing the IPv6 information to be returned first if - * +host+ is reachable via IPv6, and IPv4 information otherwise. The two - * strings "AF_INET" or "AF_INET6" are also allowed, they are converted to - * their respective Socket::AF_* constants. - * - +socktype+ limits the output to a specific type of socket, one of the - * Socket::SOCK_* constants. Socket::SOCK_STREAM (for TCP) and - * Socket::SOCK_DGRAM (for UDP) are the most commonly used socket types. If - * nil, then information for all types of sockets supported by +service+ will - * be returned. You will usually know what type of socket you intend to - * create, and should pass that socket type in. - * - +protocol+ limits the output to a specific protocol numpber, one of the - * Socket::IPPROTO_* constants. It is usually implied by the socket type - * (Socket::SOCK_STREAM => Socket::IPPROTO_TCP, ...), if you pass other than - * nil you already know what this is for. - * - +flags+ is one of the Socket::AI_* constants. They mean: - * - Socket::AI_PASSIVE: when set, if +host+ is nil the 'any' address will be - * returned, Socket::INADDR_ANY or 0 for IPv4, "0::0" or "::" for IPv6. This - * address is suitable for use by servers that will bind their socket and do - * a passive listen, thus the name of the flag. Otherwise the local or - * loopback address will be returned, this is "127.0.0.1" for IPv4 and "::1' - * for IPv6. - * - ... - * - * - * === Returns - * - * Returns an array of arrays, where each subarray contains: - * - address family, a string like "AF_INET" or "AF_INET6" - * - port number, the port number for +service+ - * - host name, either a canonical name for +host+, or it's address in presentation - * format if the address could not be looked up. - * - host IP, the address of +host+ in presentation format - * - address family, as a numeric value (one of the Socket::AF_* constants). - * - socket type, as a numeric value (one of the Socket::SOCK_* constants). - * - protocol number, as a numeric value (one of the Socket::IPPROTO_* constants). - * - * The first four values are identical to what is commonly returned as an - * address array, see IPSocket for more information. - * - * === Examples - * - * Not all input combinations are valid, and while there are many combinations, - * only a few cases are common. - * - * A typical client will call getaddrinfo with the +host+ and +service+ it - * wants to connect to. It knows that it will attempt to connect with either - * TCP or UDP, and specifies +socktype+ accordingly. It loops through all - * returned addresses, and try to connect to them in turn: - * - * addrinfo = Socket::getaddrinfo('www.example.com', 'www', nil, Socket::SOCK_STREAM) - * addrinfo.each do |af, port, name, addr| - * begin - * sock = TCPSocket.new(addr, port) - * # ... - * exit 1 - * rescue - * end - * end - * - * With UDP you don't know if connect suceeded, but if communication fails, - * the next address can be tried. - * - * A typical server will call getaddrinfo with a +host+ of nil, the +service+ - * it listens to, and a +flags+ of Socket::AI_PASSIVE. It will listen for - * connections on the first returned address: - * addrinfo = Socket::getaddrinfo(nil, 'www', nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE) - * af, port, name, addr = addrinfo.first - * sock = TCPServer(addr, port) - * while( client = s.accept ) - * # ... - * end + * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc. + * + * _protocol_ should be a protocol defined in the family. + * 0 is default protocol for the family. + * + * _flags_ should be bitwise OR of Socket::AI_* constants. + * + * Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM) + * #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP + * + * Socket.getaddrinfo("localhost", nil) + * #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6], # PF_INET/SOCK_STREAM/IPPROTO_TCP + * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP + * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]] # PF_INET/SOCK_RAW/IPPROTO_IP + * + * _reverse_lookup_ directs the form of the third element, and has to + * be one of below. + * If it is ommitted, the default value is +nil+. + * + * +true+, +:hostname+: hostname is obtained from numeric address using reverse lookup, which may take a time. + * +false+, +:numeric+: hostname is same as numeric address. + * +nil+: obey to the current +do_not_reverse_lookup+ flag. + * + * If Addrinfo object is preferred, use Addrinfo.getaddrinfo. */ static VALUE -sock_s_getaddrinfo(argc, argv) - int argc; - VALUE *argv; +sock_s_getaddrinfo(int argc, VALUE *argv) { - VALUE host, port, family, socktype, protocol, flags, ret; - char hbuf[1024], pbuf[1024]; - char *hptr, *pptr, *ap; + VALUE host, port, family, socktype, protocol, flags, ret, revlookup; struct addrinfo hints, *res; - int error; + int norevlookup; - host = port = family = socktype = protocol = flags = Qnil; - rb_scan_args(argc, argv, "24", &host, &port, &family, &socktype, &protocol, &flags); - if (NIL_P(host)) { - hptr = NULL; - } - else { - strncpy(hbuf, StringValuePtr(host), sizeof(hbuf)); - hbuf[sizeof(hbuf) - 1] = '\0'; - hptr = hbuf; - } - if (NIL_P(port)) { - pptr = NULL; - } - else if (FIXNUM_P(port)) { - snprintf(pbuf, sizeof(pbuf), "%ld", FIX2LONG(port)); - pptr = pbuf; - } - else { - strncpy(pbuf, StringValuePtr(port), sizeof(pbuf)); - pbuf[sizeof(pbuf) - 1] = '\0'; - pptr = pbuf; - } + rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup); MEMZERO(&hints, struct addrinfo, 1); - if (NIL_P(family)) { - hints.ai_family = PF_UNSPEC; - } - else if (FIXNUM_P(family)) { - hints.ai_family = FIX2INT(family); - } - else if ((ap = StringValuePtr(family)) != 0) { - if (strcmp(ap, "AF_INET") == 0) { - hints.ai_family = PF_INET; - } -#ifdef INET6 - else if (strcmp(ap, "AF_INET6") == 0) { - hints.ai_family = PF_INET6; - } -#endif - } + hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family); if (!NIL_P(socktype)) { - hints.ai_socktype = NUM2INT(socktype); + hints.ai_socktype = rsock_socktype_arg(socktype); } if (!NIL_P(protocol)) { hints.ai_protocol = NUM2INT(protocol); @@ -3566,20 +1128,39 @@ sock_s_getaddrinfo(argc, argv) if (!NIL_P(flags)) { hints.ai_flags = NUM2INT(flags); } - error = getaddrinfo(hptr, pptr, &hints, &res); - if (error) { - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); + if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) { + norevlookup = rsock_do_not_reverse_lookup; } + res = rsock_getaddrinfo(host, port, &hints, 0); - ret = make_addrinfo(res); + ret = make_addrinfo(res, norevlookup); freeaddrinfo(res); return ret; } +/* + * call-seq: + * Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename] + * + * Obtains name information for _sockaddr_. + * + * _sockaddr_ should be one of follows. + * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1") + * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"] + * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"] + * + * _flags_ should be bitwise OR of Socket::NI_* constants. + * + * Note that the last form is compatible with IPSocket#{addr,peeraddr}. + * + * Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1")) #=> ["localhost", "www"] + * Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"]) #=> ["localhost", "www"] + * Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"] + * + * If Addrinfo object is preferred, use Addrinfo#getnameinfo. + */ static VALUE -sock_s_getnameinfo(argc, argv) - int argc; - VALUE *argv; +sock_s_getnameinfo(int argc, VALUE *argv) { VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp; char *hptr, *pptr; @@ -3589,7 +1170,6 @@ sock_s_getnameinfo(argc, argv) int error; struct sockaddr_storage ss; struct sockaddr *sap; - char *ap; sa = flags = Qnil; rb_scan_args(argc, argv, "11", &sa, &flags); @@ -3598,14 +1178,14 @@ sock_s_getnameinfo(argc, argv) if (!NIL_P(flags)) { fl = NUM2INT(flags); } - tmp = rb_check_string_type(sa); + tmp = rb_check_sockaddr_string_type(sa); if (!NIL_P(tmp)) { sa = tmp; - if (sizeof(ss) < RSTRING(sa)->len) { + if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) { rb_raise(rb_eTypeError, "sockaddr length too big"); } - memcpy(&ss, RSTRING(sa)->ptr, RSTRING(sa)->len); - if (RSTRING(sa)->len != SA_LEN((struct sockaddr*)&ss)) { + memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa)); + if ((size_t)RSTRING_LEN(sa) != SS_LEN(&ss)) { rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); } sap = (struct sockaddr*)&ss; @@ -3615,22 +1195,22 @@ sock_s_getnameinfo(argc, argv) if (!NIL_P(tmp)) { sa = tmp; MEMZERO(&hints, struct addrinfo, 1); - if (RARRAY(sa)->len == 3) { - af = RARRAY(sa)->ptr[0]; - port = RARRAY(sa)->ptr[1]; - host = RARRAY(sa)->ptr[2]; + if (RARRAY_LEN(sa) == 3) { + af = RARRAY_PTR(sa)[0]; + port = RARRAY_PTR(sa)[1]; + host = RARRAY_PTR(sa)[2]; } - else if (RARRAY(sa)->len >= 4) { - af = RARRAY(sa)->ptr[0]; - port = RARRAY(sa)->ptr[1]; - host = RARRAY(sa)->ptr[3]; + else if (RARRAY_LEN(sa) >= 4) { + af = RARRAY_PTR(sa)[0]; + port = RARRAY_PTR(sa)[1]; + host = RARRAY_PTR(sa)[3]; if (NIL_P(host)) { - host = RARRAY(sa)->ptr[2]; + host = RARRAY_PTR(sa)[2]; } else { /* * 4th element holds numeric form, don't resolve. - * see ipaddr(). + * see rsock_ipaddr(). */ #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */ hints.ai_flags |= AI_NUMERICHOST; @@ -3639,7 +1219,7 @@ sock_s_getnameinfo(argc, argv) } else { rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given", - RARRAY(sa)->len); + RARRAY_LEN(sa)); } /* host */ if (NIL_P(host)) { @@ -3666,23 +1246,8 @@ sock_s_getnameinfo(argc, argv) } hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; /* af */ - if (NIL_P(af)) { - hints.ai_family = PF_UNSPEC; - } - else if (FIXNUM_P(af)) { - hints.ai_family = FIX2INT(af); - } - else if ((ap = StringValuePtr(af)) != 0) { - if (strcmp(ap, "AF_INET") == 0) { - hints.ai_family = PF_INET; - } -#ifdef INET6 - else if (strcmp(ap, "AF_INET6") == 0) { - hints.ai_family = PF_INET6; - } -#endif - } - error = getaddrinfo(hptr, pptr, &hints, &res); + hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af); + error = rb_getaddrinfo(hptr, pptr, &hints, &res); if (error) goto error_exit_addr; sap = res->ai_addr; } @@ -3691,16 +1256,16 @@ sock_s_getnameinfo(argc, argv) } call_nameinfo: - error = getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf), - pbuf, sizeof(pbuf), fl); + error = rb_getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf), + pbuf, sizeof(pbuf), fl); if (error) goto error_exit_name; if (res) { for (r = res->ai_next; r; r = r->ai_next) { char hbuf2[1024], pbuf2[1024]; sap = r->ai_addr; - error = getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2), - pbuf2, sizeof(pbuf2), fl); + error = rb_getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2), + pbuf2, sizeof(pbuf2), fl); if (error) goto error_exit_name; if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) { freeaddrinfo(res); @@ -3713,18 +1278,31 @@ sock_s_getnameinfo(argc, argv) error_exit_addr: if (res) freeaddrinfo(res); - rb_raise(rb_eSocket, "getaddrinfo: %s", gai_strerror(error)); + rsock_raise_socket_error("getaddrinfo", error); error_exit_name: if (res) freeaddrinfo(res); - rb_raise(rb_eSocket, "getnameinfo: %s", gai_strerror(error)); + rsock_raise_socket_error("getnameinfo", error); } +/* + * call-seq: + * Socket.sockaddr_in(port, host) => sockaddr + * Socket.pack_sockaddr_in(port, host) => sockaddr + * + * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string. + * + * Socket.sockaddr_in(80, "127.0.0.1") + * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" + * + * Socket.sockaddr_in(80, "::1") + * #=> "\n\x00\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00" + * + */ static VALUE -sock_s_pack_sockaddr_in(self, port, host) - VALUE self, port, host; +sock_s_pack_sockaddr_in(VALUE self, VALUE port, VALUE host) { - struct addrinfo *res = sock_addrinfo(host, port, 0, 0); + struct addrinfo *res = rsock_addrinfo(host, port, 0, 0); VALUE addr = rb_str_new((char*)res->ai_addr, res->ai_addrlen); freeaddrinfo(res); @@ -3734,14 +1312,31 @@ sock_s_pack_sockaddr_in(self, port, host) return addr; } +/* + * call-seq: + * Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address] + * + * Unpacks _sockaddr_ into port and ip_address. + * + * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6. + * + * sockaddr = Socket.sockaddr_in(80, "127.0.0.1") + * p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" + * p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"] + * + */ static VALUE -sock_s_unpack_sockaddr_in(self, addr) - VALUE self, addr; +sock_s_unpack_sockaddr_in(VALUE self, VALUE addr) { struct sockaddr_in * sockaddr; VALUE host; - sockaddr = (struct sockaddr_in*)StringValuePtr(addr); + sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr); + if (RSTRING_LEN(addr) < + (char*)&((struct sockaddr *)sockaddr)->sa_family + + sizeof(((struct sockaddr *)sockaddr)->sa_family) - + (char*)sockaddr) + rb_raise(rb_eArgError, "too short sockaddr"); if (((struct sockaddr *)sockaddr)->sa_family != AF_INET #ifdef INET6 && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6 @@ -3753,15 +1348,25 @@ sock_s_unpack_sockaddr_in(self, addr) rb_raise(rb_eArgError, "not an AF_INET sockaddr"); #endif } - host = make_ipaddr((struct sockaddr*)sockaddr); + host = rsock_make_ipaddr((struct sockaddr*)sockaddr); OBJ_INFECT(host, addr); return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host); } #ifdef HAVE_SYS_UN_H + +/* + * call-seq: + * Socket.sockaddr_un(path) => sockaddr + * Socket.pack_sockaddr_un(path) => sockaddr + * + * Packs _path_ as an AF_UNIX sockaddr string. + * + * Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..." + * + */ static VALUE -sock_s_pack_sockaddr_un(self, path) - VALUE self, path; +sock_s_pack_sockaddr_un(VALUE self, VALUE path) { struct sockaddr_un sockaddr; char *sun_path; @@ -3781,26 +1386,42 @@ sock_s_pack_sockaddr_un(self, path) return addr; } +/* + * call-seq: + * Socket.unpack_sockaddr_un(sockaddr) => path + * + * Unpacks _sockaddr_ into path. + * + * _sockaddr_ should be a string or an addrinfo for AF_UNIX. + * + * sockaddr = Socket.sockaddr_un("/tmp/sock") + * p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock" + * + */ static VALUE -sock_s_unpack_sockaddr_un(self, addr) - VALUE self, addr; +sock_s_unpack_sockaddr_un(VALUE self, VALUE addr) { struct sockaddr_un * sockaddr; - char *sun_path; + const char *sun_path; VALUE path; - sockaddr = (struct sockaddr_un*)StringValuePtr(addr); + sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr); + if (RSTRING_LEN(addr) < + (char*)&((struct sockaddr *)sockaddr)->sa_family + + sizeof(((struct sockaddr *)sockaddr)->sa_family) - + (char*)sockaddr) + rb_raise(rb_eArgError, "too short sockaddr"); if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) { rb_raise(rb_eArgError, "not an AF_UNIX sockaddr"); } - if (sizeof(struct sockaddr_un) < RSTRING(addr)->len) { - rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d", - RSTRING(addr)->len, sizeof(struct sockaddr_un)); + if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) { + rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d", + RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un)); } - sun_path = unixpath(sockaddr, RSTRING(addr)->len); - if (sizeof(struct sockaddr_un) == RSTRING(addr)->len && + sun_path = rsock_unixpath(sockaddr, RSTRING_LENINT(addr)); + if (sizeof(struct sockaddr_un) == RSTRING_LEN(addr) && sun_path == sockaddr->sun_path && - sun_path + strlen(sun_path) == RSTRING(addr)->ptr + RSTRING(addr)->len) { + sun_path + strlen(sun_path) == RSTRING_PTR(addr) + RSTRING_LEN(addr)) { rb_raise(rb_eArgError, "sockaddr_un.sun_path not NUL terminated"); } path = rb_str_new2(sun_path); @@ -3809,133 +1430,417 @@ sock_s_unpack_sockaddr_un(self, addr) } #endif -static VALUE mConst; +#if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32) +static VALUE +sockaddr_obj(struct sockaddr *addr) +{ + socklen_t len; +#if defined(AF_INET6) && defined(__KAME__) + struct sockaddr_in6 addr6; +#endif -static void -sock_define_const(name, value) - char *name; - int value; + if (addr == NULL) + return Qnil; + + switch (addr->sa_family) { + case AF_INET: + len = (socklen_t)sizeof(struct sockaddr_in); + break; + +#ifdef AF_INET6 + case AF_INET6: + len = (socklen_t)sizeof(struct sockaddr_in6); +# ifdef __KAME__ + /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */ + /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */ + /* convert fe80:1::1 to fe80::1%1 */ + memcpy(&addr6, addr, len); + addr = (struct sockaddr *)&addr6; + if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) && + addr6.sin6_scope_id == 0 && + (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) { + addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3]; + addr6.sin6_addr.s6_addr[2] = 0; + addr6.sin6_addr.s6_addr[3] = 0; + } +# endif + break; +#endif + +#ifdef HAVE_SYS_UN_H + case AF_UNIX: + len = (socklen_t)sizeof(struct sockaddr_un); + break; +#endif + + default: + len = (socklen_t)sizeof(struct sockaddr_in); + break; + } +#ifdef SA_LEN + if (len < (socklen_t)SA_LEN(addr)) + len = (socklen_t)SA_LEN(addr); +#endif + + return rsock_addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil); +} +#endif + +#if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) || defined(_WIN32) +/* + * call-seq: + * Socket.ip_address_list => array + * + * Returns local IP addresses as an array. + * + * The array contains Addrinfo objects. + * + * pp Socket.ip_address_list + * #=> [#<Addrinfo: 127.0.0.1>, + * #<Addrinfo: 192.168.0.128>, + * #<Addrinfo: ::1>, + * ...] + * + */ +static VALUE +socket_s_ip_address_list(VALUE self) { - rb_define_const(rb_cSocket, name, INT2FIX(value)); - rb_define_const(mConst, name, INT2FIX(value)); +#if defined(HAVE_GETIFADDRS) + struct ifaddrs *ifp = NULL; + struct ifaddrs *p; + int ret; + VALUE list; + + ret = getifaddrs(&ifp); + if (ret == -1) { + rb_sys_fail("getifaddrs"); + } + + list = rb_ary_new(); + for (p = ifp; p; p = p->ifa_next) { + if (p->ifa_addr != NULL && IS_IP_FAMILY(p->ifa_addr->sa_family)) { + rb_ary_push(list, sockaddr_obj(p->ifa_addr)); + } + } + + freeifaddrs(ifp); + + return list; +#elif defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux) + /* Solaris if_tcp(7P) */ + /* HP-UX has SIOCGLIFCONF too. But it uses different struct */ + int fd = -1; + int ret; + struct lifnum ln; + struct lifconf lc; + char *reason = NULL; + int save_errno; + int i; + VALUE list = Qnil; + + lc.lifc_buf = NULL; + + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd == -1) + rb_sys_fail("socket"); + + memset(&ln, 0, sizeof(ln)); + ln.lifn_family = AF_UNSPEC; + + ret = ioctl(fd, SIOCGLIFNUM, &ln); + if (ret == -1) { + reason = "SIOCGLIFNUM"; + goto finish; + } + + memset(&lc, 0, sizeof(lc)); + lc.lifc_family = AF_UNSPEC; + lc.lifc_flags = 0; + lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count; + lc.lifc_req = xmalloc(lc.lifc_len); + + ret = ioctl(fd, SIOCGLIFCONF, &lc); + if (ret == -1) { + reason = "SIOCGLIFCONF"; + goto finish; + } + + list = rb_ary_new(); + for (i = 0; i < ln.lifn_count; i++) { + struct lifreq *req = &lc.lifc_req[i]; + if (IS_IP_FAMILY(req->lifr_addr.ss_family)) { + if (req->lifr_addr.ss_family == AF_INET6 && + IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) && + ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id == 0) { + struct lifreq req2; + memcpy(req2.lifr_name, req->lifr_name, LIFNAMSIZ); + ret = ioctl(fd, SIOCGLIFINDEX, &req2); + if (ret == -1) { + reason = "SIOCGLIFINDEX"; + goto finish; + } + ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id = req2.lifr_index; + } + rb_ary_push(list, sockaddr_obj((struct sockaddr *)&req->lifr_addr)); + } + } + + finish: + save_errno = errno; + if (lc.lifc_buf != NULL) + xfree(lc.lifc_req); + if (fd != -1) + close(fd); + errno = save_errno; + + if (reason) + rb_sys_fail(reason); + return list; + +#elif defined(SIOCGIFCONF) + int fd = -1; + int ret; +#define EXTRA_SPACE (sizeof(struct ifconf) + sizeof(struct sockaddr_storage)) + char initbuf[4096+EXTRA_SPACE]; + char *buf = initbuf; + int bufsize; + struct ifconf conf; + struct ifreq *req; + VALUE list = Qnil; + const char *reason = NULL; + int save_errno; + + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd == -1) + rb_sys_fail("socket"); + + bufsize = sizeof(initbuf); + buf = initbuf; + + retry: + conf.ifc_len = bufsize; + conf.ifc_req = (struct ifreq *)buf; + + /* fprintf(stderr, "bufsize: %d\n", bufsize); */ + + ret = ioctl(fd, SIOCGIFCONF, &conf); + if (ret == -1) { + reason = "SIOCGIFCONF"; + goto finish; + } + + /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */ + + if (bufsize - EXTRA_SPACE < conf.ifc_len) { + if (bufsize < conf.ifc_len) { + /* NetBSD returns required size for all interfaces. */ + bufsize = conf.ifc_len + EXTRA_SPACE; + } + else { + bufsize = bufsize << 1; + } + if (buf == initbuf) + buf = NULL; + buf = xrealloc(buf, bufsize); + goto retry; + } + + close(fd); + fd = -1; + + list = rb_ary_new(); + req = conf.ifc_req; + while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) { + struct sockaddr *addr = &req->ifr_addr; + if (IS_IP_FAMILY(addr->sa_family)) { + rb_ary_push(list, sockaddr_obj(addr)); + } +#ifdef HAVE_SA_LEN +# ifndef _SIZEOF_ADDR_IFREQ +# define _SIZEOF_ADDR_IFREQ(r) \ + (sizeof(struct ifreq) + \ + (sizeof(struct sockaddr) < (r).ifr_addr.sa_len ? \ + (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \ + 0)) +# endif + req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req)); +#else + req = (struct ifreq *)((char*)req + sizeof(struct ifreq)); +#endif + } + + finish: + + save_errno = errno; + if (buf != initbuf) + xfree(buf); + if (fd != -1) + close(fd); + errno = save_errno; + + if (reason) + rb_sys_fail(reason); + return list; + +#undef EXTRA_SPACE +#elif defined(_WIN32) + typedef struct ip_adapter_unicast_address_st { + unsigned LONG_LONG dummy0; + struct ip_adapter_unicast_address_st *Next; + struct { + struct sockaddr *lpSockaddr; + int iSockaddrLength; + } Address; + int dummy1; + int dummy2; + int dummy3; + long dummy4; + long dummy5; + long dummy6; + } ip_adapter_unicast_address_t; + typedef struct ip_adapter_anycast_address_st { + unsigned LONG_LONG dummy0; + struct ip_adapter_anycast_address_st *Next; + struct { + struct sockaddr *lpSockaddr; + int iSockaddrLength; + } Address; + } ip_adapter_anycast_address_t; + typedef struct ip_adapter_addresses_st { + unsigned LONG_LONG dummy0; + struct ip_adapter_addresses_st *Next; + void *dummy1; + ip_adapter_unicast_address_t *FirstUnicastAddress; + ip_adapter_anycast_address_t *FirstAnycastAddress; + void *dummy2; + void *dummy3; + void *dummy4; + void *dummy5; + void *dummy6; + BYTE dummy7[8]; + DWORD dummy8; + DWORD dummy9; + DWORD dummy10; + DWORD IfType; + int OperStatus; + DWORD dummy12; + DWORD dummy13[16]; + void *dummy14; + } ip_adapter_addresses_t; + typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG); + HMODULE h; + GetAdaptersAddresses_t pGetAdaptersAddresses; + ULONG len; + DWORD ret; + ip_adapter_addresses_t *adapters; + VALUE list; + + h = LoadLibrary("iphlpapi.dll"); + if (!h) + rb_notimplement(); + pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses"); + if (!pGetAdaptersAddresses) { + FreeLibrary(h); + rb_notimplement(); + } + + ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len); + if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) { + errno = rb_w32_map_errno(ret); + FreeLibrary(h); + rb_sys_fail("GetAdaptersAddresses"); + } + adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len); + ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len); + if (ret != ERROR_SUCCESS) { + errno = rb_w32_map_errno(ret); + FreeLibrary(h); + rb_sys_fail("GetAdaptersAddresses"); + } + + list = rb_ary_new(); + for (; adapters; adapters = adapters->Next) { + ip_adapter_unicast_address_t *uni; + ip_adapter_anycast_address_t *any; + if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */ + continue; + for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) { +#ifndef INET6 + if (uni->Address.lpSockaddr->sa_family == AF_INET) +#else + if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family)) +#endif + rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr)); + } + for (any = adapters->FirstAnycastAddress; any; any = any->Next) { +#ifndef INET6 + if (any->Address.lpSockaddr->sa_family == AF_INET) +#else + if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family)) +#endif + rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr)); + } + } + + FreeLibrary(h); + return list; +#endif } +#else +#define socket_s_ip_address_list rb_f_notimplement +#endif /* + * Document-class: ::Socket < BasicSocket + * * Class +Socket+ provides access to the underlying operating system * socket implementations. It can be used to provide more operating system - * specific functionality than the protocol-specific socket classes but at the - * expense of greater complexity. In particular, the class handles addresses - * using +struct sockaddr+ structures packed into Ruby strings, which can be - * a joy to manipulate. - * + * specific functionality than the protocol-specific socket classes. + * + * The constants defined under Socket::Constants are also defined under Socket. + * For example, Socket::AF_INET is usable as well as Socket::Constants::AF_INET. + * See Socket::Constants for the list of constants. + * * === Exception Handling * Ruby's implementation of +Socket+ causes an exception to be raised * based on the error generated by the system dependent implementation. * This is why the methods are documented in a way that isolate * Unix-based system exceptions from Windows based exceptions. If more - * information on particular exception is needed please refer to the + * information on particular exception is needed please refer to the * Unix manual pages or the Windows WinSock reference. - * - * + * + * === Convenient methods + * + * Although the general way to create socket is Socket.new, + * there are several methods for socket creation for most cases. + * + * * TCP client socket: Socket.tcp, TCPSocket.open + * * TCP server socket: Socket.tcp_server_loop, TCPServer.open + * * UNIX client socket: Socket.unix, UNIXSocket.open + * * UNIX server socket: Socket.unix_server_loop, UNIXServer.open + * * === Documentation by * * Zach Dennis * * Sam Roberts - * * <em>Programming Ruby</em> from The Pragmatic Bookshelf. - * - * Much material in this documentation is taken with permission from - * <em>Programming Ruby</em> from The Pragmatic Bookshelf. + * * <em>Programming Ruby</em> from The Pragmatic Bookshelf. + * + * Much material in this documentation is taken with permission from + * <em>Programming Ruby</em> from The Pragmatic Bookshelf. */ void Init_socket() { - rb_eSocket = rb_define_class("SocketError", rb_eStandardError); - - rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO); - rb_undef_method(rb_cBasicSocket, "initialize"); - - rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup", - bsock_do_not_rev_lookup, 0); - rb_define_singleton_method(rb_cBasicSocket, "do_not_reverse_lookup=", - bsock_do_not_rev_lookup_set, 1); - rb_define_singleton_method(rb_cBasicSocket, "for_fd", bsock_s_for_fd, 1); - - rb_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0); - rb_define_method(rb_cBasicSocket, "close_write", bsock_close_write, 0); - rb_define_method(rb_cBasicSocket, "shutdown", bsock_shutdown, -1); - rb_define_method(rb_cBasicSocket, "setsockopt", bsock_setsockopt, 3); - rb_define_method(rb_cBasicSocket, "getsockopt", bsock_getsockopt, 2); - rb_define_method(rb_cBasicSocket, "getsockname", bsock_getsockname, 0); - rb_define_method(rb_cBasicSocket, "getpeername", bsock_getpeername, 0); - rb_define_method(rb_cBasicSocket, "send", bsock_send, -1); - rb_define_method(rb_cBasicSocket, "recv", bsock_recv, -1); - rb_define_method(rb_cBasicSocket, "recv_nonblock", bsock_recv_nonblock, -1); - - rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket); - rb_define_global_const("IPsocket", rb_cIPSocket); - rb_define_method(rb_cIPSocket, "addr", ip_addr, 0); - rb_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, 0); - rb_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1); - rb_define_singleton_method(rb_cIPSocket, "getaddress", ip_s_getaddress, 1); - - rb_cTCPSocket = rb_define_class("TCPSocket", rb_cIPSocket); - rb_define_global_const("TCPsocket", rb_cTCPSocket); - rb_define_singleton_method(rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1); - rb_define_method(rb_cTCPSocket, "initialize", tcp_init, -1); - -#ifdef SOCKS - rb_cSOCKSSocket = rb_define_class("SOCKSSocket", rb_cTCPSocket); - rb_define_global_const("SOCKSsocket", rb_cSOCKSSocket); - rb_define_method(rb_cSOCKSSocket, "initialize", socks_init, 2); -#ifdef SOCKS5 - rb_define_method(rb_cSOCKSSocket, "close", socks_s_close, 0); -#endif -#endif - - rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket); - rb_define_global_const("TCPserver", rb_cTCPServer); - rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0); - rb_define_method(rb_cTCPServer, "accept_nonblock", tcp_accept_nonblock, 0); - rb_define_method(rb_cTCPServer, "sysaccept", tcp_sysaccept, 0); - rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1); - rb_define_method(rb_cTCPServer, "listen", sock_listen, 1); - - rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket); - rb_define_global_const("UDPsocket", rb_cUDPSocket); - rb_define_method(rb_cUDPSocket, "initialize", udp_init, -1); - rb_define_method(rb_cUDPSocket, "connect", udp_connect, 2); - rb_define_method(rb_cUDPSocket, "bind", udp_bind, 2); - rb_define_method(rb_cUDPSocket, "send", udp_send, -1); - rb_define_method(rb_cUDPSocket, "recvfrom_nonblock", udp_recvfrom_nonblock, -1); - -#ifdef HAVE_SYS_UN_H - rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket); - rb_define_global_const("UNIXsocket", rb_cUNIXSocket); - rb_define_method(rb_cUNIXSocket, "initialize", unix_init, 1); - rb_define_method(rb_cUNIXSocket, "path", unix_path, 0); - rb_define_method(rb_cUNIXSocket, "addr", unix_addr, 0); - rb_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0); - rb_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1); - rb_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1); - rb_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1); - rb_define_singleton_method(rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1); - rb_define_singleton_method(rb_cUNIXSocket, "pair", unix_s_socketpair, -1); - - rb_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket); - rb_define_global_const("UNIXserver", rb_cUNIXServer); - rb_define_method(rb_cUNIXServer, "initialize", unix_svr_init, 1); - rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0); - rb_define_method(rb_cUNIXServer, "accept_nonblock", unix_accept_nonblock, 0); - rb_define_method(rb_cUNIXServer, "sysaccept", unix_sysaccept, 0); - rb_define_method(rb_cUNIXServer, "listen", sock_listen, 1); -#endif + rsock_init_basicsocket(); rb_cSocket = rb_define_class("Socket", rb_cBasicSocket); - rb_define_method(rb_cSocket, "initialize", sock_initialize, 3); + rsock_init_socket_init(); + + rb_define_method(rb_cSocket, "initialize", sock_initialize, -1); rb_define_method(rb_cSocket, "connect", sock_connect, 1); rb_define_method(rb_cSocket, "connect_nonblock", sock_connect_nonblock, 1); rb_define_method(rb_cSocket, "bind", sock_bind, 1); - rb_define_method(rb_cSocket, "listen", sock_listen, 1); + rb_define_method(rb_cSocket, "listen", rsock_sock_listen, 1); rb_define_method(rb_cSocket, "accept", sock_accept, 0); rb_define_method(rb_cSocket, "accept_nonblock", sock_accept_nonblock, 0); rb_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0); @@ -3943,12 +1848,13 @@ Init_socket() rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1); rb_define_method(rb_cSocket, "recvfrom_nonblock", sock_recvfrom_nonblock, -1); - rb_define_singleton_method(rb_cSocket, "socketpair", sock_s_socketpair, 3); - rb_define_singleton_method(rb_cSocket, "pair", sock_s_socketpair, 3); + rb_define_singleton_method(rb_cSocket, "socketpair", rsock_sock_s_socketpair, -1); + rb_define_singleton_method(rb_cSocket, "pair", rsock_sock_s_socketpair, -1); rb_define_singleton_method(rb_cSocket, "gethostname", sock_gethostname, 0); rb_define_singleton_method(rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1); rb_define_singleton_method(rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1); - rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyaname, -1); + rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyname, -1); + rb_define_singleton_method(rb_cSocket, "getservbyport", sock_s_getservbyport, -1); rb_define_singleton_method(rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1); rb_define_singleton_method(rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1); rb_define_singleton_method(rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2); @@ -3960,702 +1866,5 @@ Init_socket() rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1); #endif - /* constants */ - mConst = rb_define_module_under(rb_cSocket, "Constants"); - sock_define_const("SOCK_STREAM", SOCK_STREAM); - sock_define_const("SOCK_DGRAM", SOCK_DGRAM); -#ifdef SOCK_RAW - sock_define_const("SOCK_RAW", SOCK_RAW); -#endif -#ifdef SOCK_RDM - sock_define_const("SOCK_RDM", SOCK_RDM); -#endif -#ifdef SOCK_SEQPACKET - sock_define_const("SOCK_SEQPACKET", SOCK_SEQPACKET); -#endif -#ifdef SOCK_PACKET - sock_define_const("SOCK_PACKET", SOCK_PACKET); -#endif - - sock_define_const("AF_INET", AF_INET); -#ifdef PF_INET - sock_define_const("PF_INET", PF_INET); -#endif -#ifdef AF_UNIX - sock_define_const("AF_UNIX", AF_UNIX); - sock_define_const("PF_UNIX", PF_UNIX); -#endif -#ifdef AF_AX25 - sock_define_const("AF_AX25", AF_AX25); - sock_define_const("PF_AX25", PF_AX25); -#endif -#ifdef AF_IPX - sock_define_const("AF_IPX", AF_IPX); - sock_define_const("PF_IPX", PF_IPX); -#endif -#ifdef AF_APPLETALK - sock_define_const("AF_APPLETALK", AF_APPLETALK); - sock_define_const("PF_APPLETALK", PF_APPLETALK); -#endif -#ifdef AF_UNSPEC - sock_define_const("AF_UNSPEC", AF_UNSPEC); - sock_define_const("PF_UNSPEC", PF_UNSPEC); -#endif -#ifdef INET6 - sock_define_const("AF_INET6", AF_INET6); -#endif -#ifdef INET6 - sock_define_const("PF_INET6", PF_INET6); -#endif -#ifdef AF_LOCAL - sock_define_const("AF_LOCAL", AF_LOCAL); -#endif -#ifdef PF_LOCAL - sock_define_const("PF_LOCAL", PF_LOCAL); -#endif -#ifdef AF_IMPLINK - sock_define_const("AF_IMPLINK", AF_IMPLINK); -#endif -#ifdef PF_IMPLINK - sock_define_const("PF_IMPLINK", PF_IMPLINK); -#endif -#ifdef AF_PUP - sock_define_const("AF_PUP", AF_PUP); -#endif -#ifdef PF_PUP - sock_define_const("PF_PUP", PF_PUP); -#endif -#ifdef AF_CHAOS - sock_define_const("AF_CHAOS", AF_CHAOS); -#endif -#ifdef PF_CHAOS - sock_define_const("PF_CHAOS", PF_CHAOS); -#endif -#ifdef AF_NS - sock_define_const("AF_NS", AF_NS); -#endif -#ifdef PF_NS - sock_define_const("PF_NS", PF_NS); -#endif -#ifdef AF_ISO - sock_define_const("AF_ISO", AF_ISO); -#endif -#ifdef PF_ISO - sock_define_const("PF_ISO", PF_ISO); -#endif -#ifdef AF_OSI - sock_define_const("AF_OSI", AF_OSI); -#endif -#ifdef PF_OSI - sock_define_const("PF_OSI", PF_OSI); -#endif -#ifdef AF_ECMA - sock_define_const("AF_ECMA", AF_ECMA); -#endif -#ifdef PF_ECMA - sock_define_const("PF_ECMA", PF_ECMA); -#endif -#ifdef AF_DATAKIT - sock_define_const("AF_DATAKIT", AF_DATAKIT); -#endif -#ifdef PF_DATAKIT - sock_define_const("PF_DATAKIT", PF_DATAKIT); -#endif -#ifdef AF_CCITT - sock_define_const("AF_CCITT", AF_CCITT); -#endif -#ifdef PF_CCITT - sock_define_const("PF_CCITT", PF_CCITT); -#endif -#ifdef AF_SNA - sock_define_const("AF_SNA", AF_SNA); -#endif -#ifdef PF_SNA - sock_define_const("PF_SNA", PF_SNA); -#endif -#ifdef AF_DEC - sock_define_const("AF_DEC", AF_DEC); -#endif -#ifdef PF_DEC - sock_define_const("PF_DEC", PF_DEC); -#endif -#ifdef AF_DLI - sock_define_const("AF_DLI", AF_DLI); -#endif -#ifdef PF_DLI - sock_define_const("PF_DLI", PF_DLI); -#endif -#ifdef AF_LAT - sock_define_const("AF_LAT", AF_LAT); -#endif -#ifdef PF_LAT - sock_define_const("PF_LAT", PF_LAT); -#endif -#ifdef AF_HYLINK - sock_define_const("AF_HYLINK", AF_HYLINK); -#endif -#ifdef PF_HYLINK - sock_define_const("PF_HYLINK", PF_HYLINK); -#endif -#ifdef AF_ROUTE - sock_define_const("AF_ROUTE", AF_ROUTE); -#endif -#ifdef PF_ROUTE - sock_define_const("PF_ROUTE", PF_ROUTE); -#endif -#ifdef AF_LINK - sock_define_const("AF_LINK", AF_LINK); -#endif -#ifdef PF_LINK - sock_define_const("PF_LINK", PF_LINK); -#endif -#ifdef AF_COIP - sock_define_const("AF_COIP", AF_COIP); -#endif -#ifdef PF_COIP - sock_define_const("PF_COIP", PF_COIP); -#endif -#ifdef AF_CNT - sock_define_const("AF_CNT", AF_CNT); -#endif -#ifdef PF_CNT - sock_define_const("PF_CNT", PF_CNT); -#endif -#ifdef AF_SIP - sock_define_const("AF_SIP", AF_SIP); -#endif -#ifdef PF_SIP - sock_define_const("PF_SIP", PF_SIP); -#endif -#ifdef AF_NDRV - sock_define_const("AF_NDRV", AF_NDRV); -#endif -#ifdef PF_NDRV - sock_define_const("PF_NDRV", PF_NDRV); -#endif -#ifdef AF_ISDN - sock_define_const("AF_ISDN", AF_ISDN); -#endif -#ifdef PF_ISDN - sock_define_const("PF_ISDN", PF_ISDN); -#endif -#ifdef AF_NATM - sock_define_const("AF_NATM", AF_NATM); -#endif -#ifdef PF_NATM - sock_define_const("PF_NATM", PF_NATM); -#endif -#ifdef AF_SYSTEM - sock_define_const("AF_SYSTEM", AF_SYSTEM); -#endif -#ifdef PF_SYSTEM - sock_define_const("PF_SYSTEM", PF_SYSTEM); -#endif -#ifdef AF_NETBIOS - sock_define_const("AF_NETBIOS", AF_NETBIOS); -#endif -#ifdef PF_NETBIOS - sock_define_const("PF_NETBIOS", PF_NETBIOS); -#endif -#ifdef AF_PPP - sock_define_const("AF_PPP", AF_PPP); -#endif -#ifdef PF_PPP - sock_define_const("PF_PPP", PF_PPP); -#endif -#ifdef AF_ATM - sock_define_const("AF_ATM", AF_ATM); -#endif -#ifdef PF_ATM - sock_define_const("PF_ATM", PF_ATM); -#endif -#ifdef AF_NETGRAPH - sock_define_const("AF_NETGRAPH", AF_NETGRAPH); -#endif -#ifdef PF_NETGRAPH - sock_define_const("PF_NETGRAPH", PF_NETGRAPH); -#endif -#ifdef AF_MAX - sock_define_const("AF_MAX", AF_MAX); -#endif -#ifdef PF_MAX - sock_define_const("PF_MAX", PF_MAX); -#endif -#ifdef AF_E164 - sock_define_const("AF_E164", AF_E164); -#endif -#ifdef PF_XTP - sock_define_const("PF_XTP", PF_XTP); -#endif -#ifdef PF_RTIP - sock_define_const("PF_RTIP", PF_RTIP); -#endif -#ifdef PF_PIP - sock_define_const("PF_PIP", PF_PIP); -#endif -#ifdef PF_KEY - sock_define_const("PF_KEY", PF_KEY); -#endif - - sock_define_const("MSG_OOB", MSG_OOB); -#ifdef MSG_PEEK - sock_define_const("MSG_PEEK", MSG_PEEK); -#endif -#ifdef MSG_DONTROUTE - sock_define_const("MSG_DONTROUTE", MSG_DONTROUTE); -#endif -#ifdef MSG_EOR - sock_define_const("MSG_EOR", MSG_EOR); -#endif -#ifdef MSG_TRUNC - sock_define_const("MSG_TRUNC", MSG_TRUNC); -#endif -#ifdef MSG_CTRUNC - sock_define_const("MSG_CTRUNC", MSG_CTRUNC); -#endif -#ifdef MSG_WAITALL - sock_define_const("MSG_WAITALL", MSG_WAITALL); -#endif -#ifdef MSG_DONTWAIT - sock_define_const("MSG_DONTWAIT", MSG_DONTWAIT); -#endif -#ifdef MSG_EOF - sock_define_const("MSG_EOF", MSG_EOF); -#endif -#ifdef MSG_FLUSH - sock_define_const("MSG_FLUSH", MSG_FLUSH); -#endif -#ifdef MSG_HOLD - sock_define_const("MSG_HOLD", MSG_HOLD); -#endif -#ifdef MSG_SEND - sock_define_const("MSG_SEND", MSG_SEND); -#endif -#ifdef MSG_HAVEMORE - sock_define_const("MSG_HAVEMORE", MSG_HAVEMORE); -#endif -#ifdef MSG_RCVMORE - sock_define_const("MSG_RCVMORE", MSG_RCVMORE); -#endif -#ifdef MSG_COMPAT - sock_define_const("MSG_COMPAT", MSG_COMPAT); -#endif - - sock_define_const("SOL_SOCKET", SOL_SOCKET); -#ifdef SOL_IP - sock_define_const("SOL_IP", SOL_IP); -#endif -#ifdef SOL_IPX - sock_define_const("SOL_IPX", SOL_IPX); -#endif -#ifdef SOL_AX25 - sock_define_const("SOL_AX25", SOL_AX25); -#endif -#ifdef SOL_ATALK - sock_define_const("SOL_ATALK", SOL_ATALK); -#endif -#ifdef SOL_TCP - sock_define_const("SOL_TCP", SOL_TCP); -#endif -#ifdef SOL_UDP - sock_define_const("SOL_UDP", SOL_UDP); -#endif - -#ifdef IPPROTO_IP - sock_define_const("IPPROTO_IP", IPPROTO_IP); -#else - sock_define_const("IPPROTO_IP", 0); -#endif -#ifdef IPPROTO_ICMP - sock_define_const("IPPROTO_ICMP", IPPROTO_ICMP); -#else - sock_define_const("IPPROTO_ICMP", 1); -#endif -#ifdef IPPROTO_IGMP - sock_define_const("IPPROTO_IGMP", IPPROTO_IGMP); -#endif -#ifdef IPPROTO_GGP - sock_define_const("IPPROTO_GGP", IPPROTO_GGP); -#endif -#ifdef IPPROTO_TCP - sock_define_const("IPPROTO_TCP", IPPROTO_TCP); -#else - sock_define_const("IPPROTO_TCP", 6); -#endif -#ifdef IPPROTO_EGP - sock_define_const("IPPROTO_EGP", IPPROTO_EGP); -#endif -#ifdef IPPROTO_PUP - sock_define_const("IPPROTO_PUP", IPPROTO_PUP); -#endif -#ifdef IPPROTO_UDP - sock_define_const("IPPROTO_UDP", IPPROTO_UDP); -#else - sock_define_const("IPPROTO_UDP", 17); -#endif -#ifdef IPPROTO_IDP - sock_define_const("IPPROTO_IDP", IPPROTO_IDP); -#endif -#ifdef IPPROTO_HELLO - sock_define_const("IPPROTO_HELLO", IPPROTO_HELLO); -#endif -#ifdef IPPROTO_ND - sock_define_const("IPPROTO_ND", IPPROTO_ND); -#endif -#ifdef IPPROTO_TP - sock_define_const("IPPROTO_TP", IPPROTO_TP); -#endif -#ifdef IPPROTO_XTP - sock_define_const("IPPROTO_XTP", IPPROTO_XTP); -#endif -#ifdef IPPROTO_EON - sock_define_const("IPPROTO_EON", IPPROTO_EON); -#endif -#ifdef IPPROTO_BIP - sock_define_const("IPPROTO_BIP", IPPROTO_BIP); -#endif -/**/ -#ifdef IPPROTO_RAW - sock_define_const("IPPROTO_RAW", IPPROTO_RAW); -#else - sock_define_const("IPPROTO_RAW", 255); -#endif -#ifdef IPPROTO_MAX - sock_define_const("IPPROTO_MAX", IPPROTO_MAX); -#endif - - /* Some port configuration */ -#ifdef IPPORT_RESERVED - sock_define_const("IPPORT_RESERVED", IPPORT_RESERVED); -#else - sock_define_const("IPPORT_RESERVED", 1024); -#endif -#ifdef IPPORT_USERRESERVED - sock_define_const("IPPORT_USERRESERVED", IPPORT_USERRESERVED); -#else - sock_define_const("IPPORT_USERRESERVED", 5000); -#endif - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - sock_define_const("INADDR_ANY", INADDR_ANY); -#else - sock_define_const("INADDR_ANY", 0x00000000); -#endif -#ifdef INADDR_BROADCAST - sock_define_const("INADDR_BROADCAST", INADDR_BROADCAST); -#else - sock_define_const("INADDR_BROADCAST", 0xffffffff); -#endif -#ifdef INADDR_LOOPBACK - sock_define_const("INADDR_LOOPBACK", INADDR_LOOPBACK); -#else - sock_define_const("INADDR_LOOPBACK", 0x7F000001); -#endif -#ifdef INADDR_UNSPEC_GROUP - sock_define_const("INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); -#else - sock_define_const("INADDR_UNSPEC_GROUP", 0xe0000000); -#endif -#ifdef INADDR_ALLHOSTS_GROUP - sock_define_const("INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP); -#else - sock_define_const("INADDR_ALLHOSTS_GROUP", 0xe0000001); -#endif -#ifdef INADDR_MAX_LOCAL_GROUP - sock_define_const("INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP); -#else - sock_define_const("INADDR_MAX_LOCAL_GROUP", 0xe00000ff); -#endif -#ifdef INADDR_NONE - sock_define_const("INADDR_NONE", INADDR_NONE); -#else - sock_define_const("INADDR_NONE", 0xffffffff); -#endif - /* IP [gs]etsockopt options */ -#ifdef IP_OPTIONS - sock_define_const("IP_OPTIONS", IP_OPTIONS); -#endif -#ifdef IP_HDRINCL - sock_define_const("IP_HDRINCL", IP_HDRINCL); -#endif -#ifdef IP_TOS - sock_define_const("IP_TOS", IP_TOS); -#endif -#ifdef IP_TTL - sock_define_const("IP_TTL", IP_TTL); -#endif -#ifdef IP_RECVOPTS - sock_define_const("IP_RECVOPTS", IP_RECVOPTS); -#endif -#ifdef IP_RECVRETOPTS - sock_define_const("IP_RECVRETOPTS", IP_RECVRETOPTS); -#endif -#ifdef IP_RECVDSTADDR - sock_define_const("IP_RECVDSTADDR", IP_RECVDSTADDR); -#endif -#ifdef IP_RETOPTS - sock_define_const("IP_RETOPTS", IP_RETOPTS); -#endif -#ifdef IP_MULTICAST_IF - sock_define_const("IP_MULTICAST_IF", IP_MULTICAST_IF); -#endif -#ifdef IP_MULTICAST_TTL - sock_define_const("IP_MULTICAST_TTL", IP_MULTICAST_TTL); -#endif -#ifdef IP_MULTICAST_LOOP - sock_define_const("IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); -#endif -#ifdef IP_ADD_MEMBERSHIP - sock_define_const("IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); -#endif -#ifdef IP_DROP_MEMBERSHIP - sock_define_const("IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); -#endif -#ifdef IP_DEFAULT_MULTICAST_TTL - sock_define_const("IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL); -#endif -#ifdef IP_DEFAULT_MULTICAST_LOOP - sock_define_const("IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP); -#endif -#ifdef IP_MAX_MEMBERSHIPS - sock_define_const("IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); -#endif -#ifdef SO_DEBUG - sock_define_const("SO_DEBUG", SO_DEBUG); -#endif - sock_define_const("SO_REUSEADDR", SO_REUSEADDR); -#ifdef SO_REUSEPORT - sock_define_const("SO_REUSEPORT", SO_REUSEPORT); -#endif -#ifdef SO_TYPE - sock_define_const("SO_TYPE", SO_TYPE); -#endif -#ifdef SO_ERROR - sock_define_const("SO_ERROR", SO_ERROR); -#endif -#ifdef SO_DONTROUTE - sock_define_const("SO_DONTROUTE", SO_DONTROUTE); -#endif -#ifdef SO_BROADCAST - sock_define_const("SO_BROADCAST", SO_BROADCAST); -#endif -#ifdef SO_SNDBUF - sock_define_const("SO_SNDBUF", SO_SNDBUF); -#endif -#ifdef SO_RCVBUF - sock_define_const("SO_RCVBUF", SO_RCVBUF); -#endif -#ifdef SO_KEEPALIVE - sock_define_const("SO_KEEPALIVE", SO_KEEPALIVE); -#endif -#ifdef SO_OOBINLINE - sock_define_const("SO_OOBINLINE", SO_OOBINLINE); -#endif -#ifdef SO_NO_CHECK - sock_define_const("SO_NO_CHECK", SO_NO_CHECK); -#endif -#ifdef SO_PRIORITY - sock_define_const("SO_PRIORITY", SO_PRIORITY); -#endif -#ifdef SO_LINGER - sock_define_const("SO_LINGER", SO_LINGER); -#endif -#ifdef SO_PASSCRED - sock_define_const("SO_PASSCRED", SO_PASSCRED); -#endif -#ifdef SO_PEERCRED - sock_define_const("SO_PEERCRED", SO_PEERCRED); -#endif -#ifdef SO_RCVLOWAT - sock_define_const("SO_RCVLOWAT", SO_RCVLOWAT); -#endif -#ifdef SO_SNDLOWAT - sock_define_const("SO_SNDLOWAT", SO_SNDLOWAT); -#endif -#ifdef SO_RCVTIMEO - sock_define_const("SO_RCVTIMEO", SO_RCVTIMEO); -#endif -#ifdef SO_SNDTIMEO - sock_define_const("SO_SNDTIMEO", SO_SNDTIMEO); -#endif -#ifdef SO_ACCEPTCONN - sock_define_const("SO_ACCEPTCONN", SO_ACCEPTCONN); -#endif -#ifdef SO_USELOOPBACK - sock_define_const("SO_USELOOPBACK", SO_USELOOPBACK); -#endif -#ifdef SO_ACCEPTFILTER - sock_define_const("SO_ACCEPTFILTER", SO_ACCEPTFILTER); -#endif -#ifdef SO_DONTTRUNC - sock_define_const("SO_DONTTRUNC", SO_DONTTRUNC); -#endif -#ifdef SO_WANTMORE - sock_define_const("SO_WANTMORE", SO_WANTMORE); -#endif -#ifdef SO_WANTOOBFLAG - sock_define_const("SO_WANTOOBFLAG", SO_WANTOOBFLAG); -#endif -#ifdef SO_NREAD - sock_define_const("SO_NREAD", SO_NREAD); -#endif -#ifdef SO_NKE - sock_define_const("SO_NKE", SO_NKE); -#endif -#ifdef SO_NOSIGPIPE - sock_define_const("SO_NOSIGPIPE", SO_NOSIGPIPE); -#endif - -#ifdef SO_SECURITY_AUTHENTICATION - sock_define_const("SO_SECURITY_AUTHENTICATION", SO_SECURITY_AUTHENTICATION); -#endif -#ifdef SO_SECURITY_ENCRYPTION_TRANSPORT - sock_define_const("SO_SECURITY_ENCRYPTION_TRANSPORT", SO_SECURITY_ENCRYPTION_TRANSPORT); -#endif -#ifdef SO_SECURITY_ENCRYPTION_NETWORK - sock_define_const("SO_SECURITY_ENCRYPTION_NETWORK", SO_SECURITY_ENCRYPTION_NETWORK); -#endif - -#ifdef SO_BINDTODEVICE - sock_define_const("SO_BINDTODEVICE", SO_BINDTODEVICE); -#endif -#ifdef SO_ATTACH_FILTER - sock_define_const("SO_ATTACH_FILTER", SO_ATTACH_FILTER); -#endif -#ifdef SO_DETACH_FILTER - sock_define_const("SO_DETACH_FILTER", SO_DETACH_FILTER); -#endif -#ifdef SO_PEERNAME - sock_define_const("SO_PEERNAME", SO_PEERNAME); -#endif -#ifdef SO_TIMESTAMP - sock_define_const("SO_TIMESTAMP", SO_TIMESTAMP); -#endif - -#ifdef SOPRI_INTERACTIVE - sock_define_const("SOPRI_INTERACTIVE", SOPRI_INTERACTIVE); -#endif -#ifdef SOPRI_NORMAL - sock_define_const("SOPRI_NORMAL", SOPRI_NORMAL); -#endif -#ifdef SOPRI_BACKGROUND - sock_define_const("SOPRI_BACKGROUND", SOPRI_BACKGROUND); -#endif - -#ifdef IPX_TYPE - sock_define_const("IPX_TYPE", IPX_TYPE); -#endif - -#ifdef TCP_NODELAY - sock_define_const("TCP_NODELAY", TCP_NODELAY); -#endif -#ifdef TCP_MAXSEG - sock_define_const("TCP_MAXSEG", TCP_MAXSEG); -#endif - -#ifdef EAI_ADDRFAMILY - sock_define_const("EAI_ADDRFAMILY", EAI_ADDRFAMILY); -#endif -#ifdef EAI_AGAIN - sock_define_const("EAI_AGAIN", EAI_AGAIN); -#endif -#ifdef EAI_BADFLAGS - sock_define_const("EAI_BADFLAGS", EAI_BADFLAGS); -#endif -#ifdef EAI_FAIL - sock_define_const("EAI_FAIL", EAI_FAIL); -#endif -#ifdef EAI_FAMILY - sock_define_const("EAI_FAMILY", EAI_FAMILY); -#endif -#ifdef EAI_MEMORY - sock_define_const("EAI_MEMORY", EAI_MEMORY); -#endif -#ifdef EAI_NODATA - sock_define_const("EAI_NODATA", EAI_NODATA); -#endif -#ifdef EAI_NONAME - sock_define_const("EAI_NONAME", EAI_NONAME); -#endif -#ifdef EAI_SERVICE - sock_define_const("EAI_SERVICE", EAI_SERVICE); -#endif -#ifdef EAI_SOCKTYPE - sock_define_const("EAI_SOCKTYPE", EAI_SOCKTYPE); -#endif -#ifdef EAI_SYSTEM - sock_define_const("EAI_SYSTEM", EAI_SYSTEM); -#endif -#ifdef EAI_BADHINTS - sock_define_const("EAI_BADHINTS", EAI_BADHINTS); -#endif -#ifdef EAI_PROTOCOL - sock_define_const("EAI_PROTOCOL", EAI_PROTOCOL); -#endif -#ifdef EAI_MAX - sock_define_const("EAI_MAX", EAI_MAX); -#endif -#ifdef AI_PASSIVE - sock_define_const("AI_PASSIVE", AI_PASSIVE); -#endif -#ifdef AI_CANONNAME - sock_define_const("AI_CANONNAME", AI_CANONNAME); -#endif -#ifdef AI_NUMERICHOST - sock_define_const("AI_NUMERICHOST", AI_NUMERICHOST); -#endif -#ifdef AI_MASK - sock_define_const("AI_MASK", AI_MASK); -#endif -#ifdef AI_ALL - sock_define_const("AI_ALL", AI_ALL); -#endif -#ifdef AI_V4MAPPED_CFG - sock_define_const("AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); -#endif -#ifdef AI_ADDRCONFIG - sock_define_const("AI_ADDRCONFIG", AI_ADDRCONFIG); -#endif -#ifdef AI_V4MAPPED - sock_define_const("AI_V4MAPPED", AI_V4MAPPED); -#endif -#ifdef AI_DEFAULT - sock_define_const("AI_DEFAULT", AI_DEFAULT); -#endif -#ifdef NI_MAXHOST - sock_define_const("NI_MAXHOST", NI_MAXHOST); -#endif -#ifdef NI_MAXSERV - sock_define_const("NI_MAXSERV", NI_MAXSERV); -#endif -#ifdef NI_NOFQDN - sock_define_const("NI_NOFQDN", NI_NOFQDN); -#endif -#ifdef NI_NUMERICHOST - sock_define_const("NI_NUMERICHOST", NI_NUMERICHOST); -#endif -#ifdef NI_NAMEREQD - sock_define_const("NI_NAMEREQD", NI_NAMEREQD); -#endif -#ifdef NI_NUMERICSERV - sock_define_const("NI_NUMERICSERV", NI_NUMERICSERV); -#endif -#ifdef NI_DGRAM - sock_define_const("NI_DGRAM", NI_DGRAM); -#endif -#ifdef SHUT_RD - sock_define_const("SHUT_RD", SHUT_RD); -#else - sock_define_const("SHUT_RD", 0); -#endif -#ifdef SHUT_WR - sock_define_const("SHUT_WR", SHUT_WR); -#else - sock_define_const("SHUT_WR", 1); -#endif -#ifdef SHUT_RDWR - sock_define_const("SHUT_RDWR", SHUT_RDWR); -#else - sock_define_const("SHUT_RDWR", 2); -#endif + rb_define_singleton_method(rb_cSocket, "ip_address_list", socket_s_ip_address_list, 0); } diff --git a/ext/socket/sockport.h b/ext/socket/sockport.h index 8c7bebf558..5f2fd24530 100644 --- a/ext/socket/sockport.h +++ b/ext/socket/sockport.h @@ -2,8 +2,7 @@ sockport.h - - $Author: eban $ - $Date: 2000/08/24 06:29:30 $ + $Author$ created at: Fri Apr 30 23:19:34 JST 1999 ************************************************/ @@ -11,25 +10,34 @@ #ifndef SOCKPORT_H #define SOCKPORT_H -#ifndef SA_LEN +#ifdef SA_LEN +# define SS_LEN(ss) (ss)->ss_len +#else # ifdef HAVE_SA_LEN # define SA_LEN(sa) (sa)->sa_len +# define SS_LEN(ss) (ss)->ss_len # else -# ifdef INET6 +# ifdef AF_INET6 # define SA_LEN(sa) \ (((sa)->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) \ : sizeof(struct sockaddr)) +# define SS_LEN(ss) \ + (((ss)->ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) \ + : sizeof(struct sockaddr)) # else /* by tradition, sizeof(struct sockaddr) covers most of the sockaddrs */ # define SA_LEN(sa) (sizeof(struct sockaddr)) +# define SS_LEN(ss) (sizeof(struct sockaddr)) # endif # endif #endif #ifdef HAVE_SA_LEN -# define SET_SA_LEN(sa, len) (sa)->sa_len = (len) +# define SET_SA_LEN(sa, len) (void)((sa)->sa_len = (len)) +# define SET_SS_LEN(ss, len) (void)((ss)->ss_len = (len)) #else -# define SET_SA_LEN(sa, len) (len) +# define SET_SA_LEN(sa, len) (void)(len) +# define SET_SS_LEN(ss, len) (void)(len) #endif #ifdef HAVE_SIN_LEN diff --git a/ext/socket/sockssocket.c b/ext/socket/sockssocket.c new file mode 100644 index 0000000000..cbe8792271 --- /dev/null +++ b/ext/socket/sockssocket.c @@ -0,0 +1,58 @@ +/************************************************ + + sockssocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +#ifdef SOCKS +static VALUE +socks_init(VALUE sock, VALUE host, VALUE serv) +{ + static int init = 0; + + if (init == 0) { + SOCKSinit("ruby"); + init = 1; + } + + return rsock_init_inetsock(sock, host, serv, Qnil, Qnil, INET_SOCKS); +} + +#ifdef SOCKS5 +static VALUE +socks_s_close(VALUE sock) +{ + rb_io_t *fptr; + + if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) { + rb_raise(rb_eSecurityError, "Insecure: can't close socket"); + } + GetOpenFile(sock, fptr); + shutdown(fptr->fd, 2); + return rb_io_close(sock); +} +#endif +#endif + +/* + * Document-class: ::SOCKSSocket < TCPSocket + * + * SOCKSSocket class + */ +void +rsock_init_sockssocket(void) +{ +#ifdef SOCKS + rb_cSOCKSSocket = rb_define_class("SOCKSSocket", rb_cTCPSocket); + rb_define_method(rb_cSOCKSSocket, "initialize", socks_init, 2); +#ifdef SOCKS5 + rb_define_method(rb_cSOCKSSocket, "close", socks_s_close, 0); +#endif +#endif +} diff --git a/ext/socket/tcpserver.c b/ext/socket/tcpserver.c new file mode 100644 index 0000000000..7bb02d91f0 --- /dev/null +++ b/ext/socket/tcpserver.c @@ -0,0 +1,145 @@ +/************************************************ + + tcpserver.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +/* + * call-seq: + * TCPServer.new([hostname,] port) => tcpserver + * + * Creates a new server socket bound to _port_. + * + * If _hostname_ is given, the socket is bound to it. + * + * serv = TCPServer.new("127.0.0.1", 28561) + * s = serv.accept + * s.puts Time.now + * s.close + */ +static VALUE +tcp_svr_init(int argc, VALUE *argv, VALUE sock) +{ + VALUE hostname, port; + + rb_scan_args(argc, argv, "011", &hostname, &port); + return rsock_init_inetsock(sock, hostname, port, Qnil, Qnil, INET_SERVER); +} + +/* + * call-seq: + * tcpserver.accept => tcpsocket + * + * TCPServer.open("127.0.0.1", 14641) {|serv| + * s = serv.accept + * s.puts Time.now + * s.close + * } + * + */ +static VALUE +tcp_accept(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_storage from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(from); + return rsock_s_accept(rb_cTCPSocket, fptr->fd, + (struct sockaddr*)&from, &fromlen); +} + +/* + * call-seq: + * tcpserver.accept_nonblock => tcpsocket + * + * Accepts an incoming connection using accept(2) after + * O_NONBLOCK is set for the underlying file descriptor. + * It returns an accepted TCPSocket for the incoming connection. + * + * === Example + * require 'socket' + * serv = TCPServer.new(2202) + * begin # emulate blocking accept + * sock = serv.accept_nonblock + * rescue IO::WaitReadable, Errno::EINTR + * IO.select([serv]) + * retry + * end + * # sock is an accepted socket. + * + * Refer to Socket#accept for the exceptions that may be thrown if the call + * to TCPServer#accept_nonblock fails. + * + * TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure, + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED, Errno::EPROTO, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock. + * + * === See + * * TCPServer#accept + * * Socket#accept + */ +static VALUE +tcp_accept_nonblock(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_storage from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(from); + return rsock_s_accept_nonblock(rb_cTCPSocket, fptr, + (struct sockaddr *)&from, &fromlen); +} + +/* + * call-seq: + * tcpserver.sysaccept => file_descriptor + * + * Returns a file descriptor of a accepted connection. + * + * TCPServer.open("127.0.0.1", 28561) {|serv| + * fd = serv.sysaccept + * s = IO.for_fd(fd) + * s.puts Time.now + * s.close + * } + * + */ +static VALUE +tcp_sysaccept(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_storage from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(from); + return rsock_s_accept(0, fptr->fd, (struct sockaddr*)&from, &fromlen); +} + +/* + * Document-class: ::TCPServer < TCPSocket + * + * TCPServer represents a TCP/IP server socket. + */ +void +rsock_init_tcpserver(void) +{ + rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket); + rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0); + rb_define_method(rb_cTCPServer, "accept_nonblock", tcp_accept_nonblock, 0); + rb_define_method(rb_cTCPServer, "sysaccept", tcp_sysaccept, 0); + rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1); + rb_define_method(rb_cTCPServer, "listen", rsock_sock_listen, 1); /* in socket.c */ +} diff --git a/ext/socket/tcpsocket.c b/ext/socket/tcpsocket.c new file mode 100644 index 0000000000..42d75d6015 --- /dev/null +++ b/ext/socket/tcpsocket.c @@ -0,0 +1,69 @@ +/************************************************ + + tcpsocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +/* + * call-seq: + * TCPSocket.new(remote_host, remote_port, local_host=nil, local_port=nil) + * + * Opens a TCP connection to +remote_host+ on +remote_port+. If +local_host+ + * and +local_port+ are specified, then those parameters are used on the local + * end to establish the connection. + */ +static VALUE +tcp_init(int argc, VALUE *argv, VALUE sock) +{ + VALUE remote_host, remote_serv; + VALUE local_host, local_serv; + + rb_scan_args(argc, argv, "22", &remote_host, &remote_serv, + &local_host, &local_serv); + + return rsock_init_inetsock(sock, remote_host, remote_serv, + local_host, local_serv, INET_CLIENT); +} + +static VALUE +tcp_sockaddr(struct sockaddr *addr, size_t len) +{ + return rsock_make_ipaddr(addr); +} + +/* + * call-seq: + * TCPSocket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list] + * + * Lookups host information by _hostname_. + * + * TCPSocket.gethostbyname("localhost") + * #=> ["localhost", ["hal"], 2, "127.0.0.1"] + * + */ +static VALUE +tcp_s_gethostbyname(VALUE obj, VALUE host) +{ + rb_secure(3); + return rsock_make_hostent(host, rsock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), + tcp_sockaddr); +} + +/* + * Document-class: ::TCPSocket < IPSocket + * + * TCPSocket represents a TCP/IP client socket. + */ +void +rsock_init_tcpsocket(void) +{ + rb_cTCPSocket = rb_define_class("TCPSocket", rb_cIPSocket); + rb_define_singleton_method(rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1); + rb_define_method(rb_cTCPSocket, "initialize", tcp_init, -1); +} diff --git a/ext/socket/udpsocket.c b/ext/socket/udpsocket.c new file mode 100644 index 0000000000..b278523eba --- /dev/null +++ b/ext/socket/udpsocket.c @@ -0,0 +1,264 @@ +/************************************************ + + udpsocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +/* + * call-seq: + * UDPSocket.new([address_family]) => socket + * + * Creates a new UDPSocket object. + * + * _address_family_ should be an integer, a string or a symbol: + * Socket::AF_INET, "AF_INET", :INET, etc. + * + * UDPSocket.new #=> #<UDPSocket:fd 3> + * UDPSocket.new(Socket::AF_INET6) #=> #<UDPSocket:fd 4> + * + */ +static VALUE +udp_init(int argc, VALUE *argv, VALUE sock) +{ + VALUE arg; + int family = AF_INET; + int fd; + + rb_secure(3); + if (rb_scan_args(argc, argv, "01", &arg) == 1) { + family = rsock_family_arg(arg); + } + fd = rsock_socket(family, SOCK_DGRAM, 0); + if (fd < 0) { + rb_sys_fail("socket(2) - udp"); + } + + return rsock_init_sock(sock, fd); +} + +struct udp_arg +{ + struct addrinfo *res; + int fd; +}; + +static VALUE +udp_connect_internal(struct udp_arg *arg) +{ + int fd = arg->fd; + struct addrinfo *res; + + for (res = arg->res; res; res = res->ai_next) { + if (rsock_connect(fd, res->ai_addr, res->ai_addrlen, 0) >= 0) { + return Qtrue; + } + } + return Qfalse; +} + +VALUE rsock_freeaddrinfo(struct addrinfo *addr); + +/* + * call-seq: + * udpsocket.connect(host, port) => 0 + * + * Connects _udpsocket_ to _host_:_port_. + * + * This makes possible to send without destination address. + * + * u1 = UDPSocket.new + * u1.bind("127.0.0.1", 4913) + * u2 = UDPSocket.new + * u2.connect("127.0.0.1", 4913) + * u2.send "uuuu", 0 + * p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]] + * + */ +static VALUE +udp_connect(VALUE sock, VALUE host, VALUE port) +{ + rb_io_t *fptr; + struct udp_arg arg; + VALUE ret; + + rb_secure(3); + arg.res = rsock_addrinfo(host, port, SOCK_DGRAM, 0); + GetOpenFile(sock, fptr); + arg.fd = fptr->fd; + ret = rb_ensure(udp_connect_internal, (VALUE)&arg, + rsock_freeaddrinfo, (VALUE)arg.res); + if (!ret) rb_sys_fail("connect(2)"); + return INT2FIX(0); +} + +/* + * call-seq: + * udpsocket.bind(host, port) #=> 0 + * + * Binds _udpsocket_ to _host_:_port_. + * + * u1 = UDPSocket.new + * u1.bind("127.0.0.1", 4913) + * u1.send "message-to-self", 0, "127.0.0.1", 4913 + * p u1.recvfrom(10) #=> ["message-to", ["AF_INET", 4913, "localhost", "127.0.0.1"]] + * + */ +static VALUE +udp_bind(VALUE sock, VALUE host, VALUE port) +{ + rb_io_t *fptr; + struct addrinfo *res0, *res; + + rb_secure(3); + res0 = rsock_addrinfo(host, port, SOCK_DGRAM, 0); + GetOpenFile(sock, fptr); + for (res = res0; res; res = res->ai_next) { + if (bind(fptr->fd, res->ai_addr, res->ai_addrlen) < 0) { + continue; + } + freeaddrinfo(res0); + return INT2FIX(0); + } + freeaddrinfo(res0); + rb_sys_fail("bind(2)"); + return INT2FIX(0); +} + +/* + * call-seq: + * udpsocket.send(mesg, flags, host, port) => numbytes_sent + * udpsocket.send(mesg, flags, sockaddr_to) => numbytes_sent + * udpsocket.send(mesg, flags) => numbytes_sent + * + * Sends _mesg_ via _udpsocket_. + * + * _flags_ should be a bitwise OR of Socket::MSG_* constants. + * + * u1 = UDPSocket.new + * u1.bind("127.0.0.1", 4913) + * + * u2 = UDPSocket.new + * u2.send "hi", 0, "127.0.0.1", 4913 + * + * mesg, addr = u1.recvfrom(10) + * u1.send mesg, 0, addr[3], addr[1] + * + * p u2.recv(100) #=> "hi" + * + */ +static VALUE +udp_send(int argc, VALUE *argv, VALUE sock) +{ + VALUE flags, host, port; + rb_io_t *fptr; + int n; + struct addrinfo *res0, *res; + struct rsock_send_arg arg; + + if (argc == 2 || argc == 3) { + return rsock_bsock_send(argc, argv, sock); + } + rb_secure(4); + rb_scan_args(argc, argv, "4", &arg.mesg, &flags, &host, &port); + + StringValue(arg.mesg); + res0 = rsock_addrinfo(host, port, SOCK_DGRAM, 0); + GetOpenFile(sock, fptr); + arg.fd = fptr->fd; + arg.flags = NUM2INT(flags); + for (res = res0; res; res = res->ai_next) { + retry: + arg.to = res->ai_addr; + arg.tolen = res->ai_addrlen; + rb_thread_fd_writable(arg.fd); + n = (int)BLOCKING_REGION(rsock_sendto_blocking, &arg); + if (n >= 0) { + freeaddrinfo(res0); + return INT2FIX(n); + } + if (rb_io_wait_writable(fptr->fd)) { + goto retry; + } + } + freeaddrinfo(res0); + rb_sys_fail("sendto(2)"); + return INT2FIX(n); +} + +/* + * call-seq: + * udpsocket.recvfrom_nonblock(maxlen) => [mesg, sender_inet_addr] + * udpsocket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_inet_addr] + * + * Receives up to _maxlen_ bytes from +udpsocket+ using recvfrom(2) after + * O_NONBLOCK is set for the underlying file descriptor. + * If _maxlen_ is omitted, its default value is 65536. + * _flags_ is zero or more of the +MSG_+ options. + * The first element of the results, _mesg_, is the data received. + * The second element, _sender_inet_addr_, is an array to represent the sender address. + * + * When recvfrom(2) returns 0, + * Socket#recvfrom_nonblock returns an empty string as data. + * It means an empty packet. + * + * === Parameters + * * +maxlen+ - the number of bytes to receive from the socket + * * +flags+ - zero or more of the +MSG_+ options + * + * === Example + * require 'socket' + * s1 = UDPSocket.new + * s1.bind("127.0.0.1", 0) + * s2 = UDPSocket.new + * s2.bind("127.0.0.1", 0) + * s2.connect(*s1.addr.values_at(3,1)) + * s1.connect(*s2.addr.values_at(3,1)) + * s1.send "aaa", 0 + * begin # emulate blocking recvfrom + * p s2.recvfrom_nonblock(10) #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]] + * rescue IO::WaitReadable + * IO.select([s2]) + * retry + * end + * + * Refer to Socket#recvfrom for the exceptions that may be thrown if the call + * to _recvfrom_nonblock_ fails. + * + * UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure, + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock. + * + * === See + * * Socket#recvfrom + */ +static VALUE +udp_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock) +{ + return rsock_s_recvfrom_nonblock(sock, argc, argv, RECV_IP); +} + +/* + * Document-class: ::UDPSocket < IPSocket + * + * UDPSocket represents a UDP/IP socket. + */ +void +rsock_init_udpsocket(void) +{ + rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket); + rb_define_method(rb_cUDPSocket, "initialize", udp_init, -1); + rb_define_method(rb_cUDPSocket, "connect", udp_connect, 2); + rb_define_method(rb_cUDPSocket, "bind", udp_bind, 2); + rb_define_method(rb_cUDPSocket, "send", udp_send, -1); + rb_define_method(rb_cUDPSocket, "recvfrom_nonblock", udp_recvfrom_nonblock, -1); +} + diff --git a/ext/socket/unixserver.c b/ext/socket/unixserver.c new file mode 100644 index 0000000000..4fdc1d709d --- /dev/null +++ b/ext/socket/unixserver.c @@ -0,0 +1,154 @@ +/************************************************ + + unixserver.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +#ifdef HAVE_SYS_UN_H +/* + * call-seq: + * UNIXServer.new(path) => unixserver + * + * Creates a new UNIX server socket bound to _path_. + * + * serv = UNIXServer.new("/tmp/sock") + * s = serv.accept + * p s.read + */ +static VALUE +unix_svr_init(VALUE sock, VALUE path) +{ + return rsock_init_unixsock(sock, path, 1); +} + +/* + * call-seq: + * unixserver.accept => unixsocket + * + * Accepts a new connection. + * It returns new UNIXSocket object. + * + * UNIXServer.open("/tmp/sock") {|serv| + * UNIXSocket.open("/tmp/sock") {|c| + * s = serv.accept + * s.puts "hi" + * s.close + * p c.read #=> "hi\n" + * } + * } + * + */ +static VALUE +unix_accept(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_un from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(struct sockaddr_un); + return rsock_s_accept(rb_cUNIXSocket, fptr->fd, + (struct sockaddr*)&from, &fromlen); +} + +/* + * call-seq: + * unixserver.accept_nonblock => unixsocket + * + * Accepts an incoming connection using accept(2) after + * O_NONBLOCK is set for the underlying file descriptor. + * It returns an accepted UNIXSocket for the incoming connection. + * + * === Example + * require 'socket' + * serv = UNIXServer.new("/tmp/sock") + * begin # emulate blocking accept + * sock = serv.accept_nonblock + * rescue IO::WaitReadable, Errno::EINTR + * IO.select([serv]) + * retry + * end + * # sock is an accepted socket. + * + * Refer to Socket#accept for the exceptions that may be thrown if the call + * to UNIXServer#accept_nonblock fails. + * + * UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure, + * including Errno::EWOULDBLOCK. + * + * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED or Errno::EPROTO, + * it is extended by IO::WaitReadable. + * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock. + * + * === See + * * UNIXServer#accept + * * Socket#accept + */ +static VALUE +unix_accept_nonblock(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_un from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(from); + return rsock_s_accept_nonblock(rb_cUNIXSocket, fptr, + (struct sockaddr *)&from, &fromlen); +} + +/* + * call-seq: + * unixserver.sysaccept => file_descriptor + * + * Accepts a new connection. + * It returns the new file descriptor which is an integer. + * + * UNIXServer.open("/tmp/sock") {|serv| + * UNIXSocket.open("/tmp/sock") {|c| + * fd = serv.sysaccept + * s = IO.new(fd) + * s.puts "hi" + * s.close + * p c.read #=> "hi\n" + * } + * } + * + */ +static VALUE +unix_sysaccept(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_un from; + socklen_t fromlen; + + GetOpenFile(sock, fptr); + fromlen = (socklen_t)sizeof(struct sockaddr_un); + return rsock_s_accept(0, fptr->fd, (struct sockaddr*)&from, &fromlen); +} + +#endif + +/* + * Document-class: ::UNIXServer < UNIXSocket + * + * UNIXServer represents a UNIX domain stream server socket. + */ +void +rsock_init_unixserver(void) +{ +#ifdef HAVE_SYS_UN_H + rb_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket); + rb_define_method(rb_cUNIXServer, "initialize", unix_svr_init, 1); + rb_define_method(rb_cUNIXServer, "accept", unix_accept, 0); + rb_define_method(rb_cUNIXServer, "accept_nonblock", unix_accept_nonblock, 0); + rb_define_method(rb_cUNIXServer, "sysaccept", unix_sysaccept, 0); + rb_define_method(rb_cUNIXServer, "listen", rsock_sock_listen, 1); /* in socket.c */ +#endif +} diff --git a/ext/socket/unixsocket.c b/ext/socket/unixsocket.c new file mode 100644 index 0000000000..3e3a8ba0d7 --- /dev/null +++ b/ext/socket/unixsocket.c @@ -0,0 +1,514 @@ +/************************************************ + + unixsocket.c - + + created at: Thu Mar 31 12:21:29 JST 1994 + + Copyright (C) 1993-2007 Yukihiro Matsumoto + +************************************************/ + +#include "rubysocket.h" + +#ifdef HAVE_SYS_UN_H +struct unixsock_arg { + struct sockaddr_un *sockaddr; + int fd; +}; + +static VALUE +unixsock_connect_internal(VALUE a) +{ + struct unixsock_arg *arg = (struct unixsock_arg *)a; + return (VALUE)rsock_connect(arg->fd, (struct sockaddr*)arg->sockaddr, + (socklen_t)sizeof(*arg->sockaddr), 0); +} + +VALUE +rsock_init_unixsock(VALUE sock, VALUE path, int server) +{ + struct sockaddr_un sockaddr; + int fd, status; + rb_io_t *fptr; + + SafeStringValue(path); + fd = rsock_socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { + rb_sys_fail("socket(2)"); + } + + MEMZERO(&sockaddr, struct sockaddr_un, 1); + sockaddr.sun_family = AF_UNIX; + if (sizeof(sockaddr.sun_path) <= (size_t)RSTRING_LEN(path)) { + rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)", + (int)sizeof(sockaddr.sun_path)-1); + } + memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path)); + + if (server) { + status = bind(fd, (struct sockaddr*)&sockaddr, (socklen_t)sizeof(sockaddr)); + } + else { + int prot; + struct unixsock_arg arg; + arg.sockaddr = &sockaddr; + arg.fd = fd; + status = (int)rb_protect(unixsock_connect_internal, (VALUE)&arg, &prot); + if (prot) { + close(fd); + rb_jump_tag(prot); + } + } + + if (status < 0) { + close(fd); + rb_sys_fail(sockaddr.sun_path); + } + + if (server) { + if (listen(fd, 5) < 0) { + close(fd); + rb_sys_fail("listen(2)"); + } + } + + rsock_init_sock(sock, fd); + if (server) { + GetOpenFile(sock, fptr); + fptr->pathv = rb_str_new_frozen(path); + } + + return sock; +} + +/* + * call-seq: + * UNIXSocket.new(path) => unixsocket + * + * Creates a new UNIX client socket connected to _path_. + * + * s = UNIXSocket.new("/tmp/sock") + * s.send "hello", 0 + * + */ +static VALUE +unix_init(VALUE sock, VALUE path) +{ + return rsock_init_unixsock(sock, path, 0); +} + +/* + * call-seq: + * unixsocket.path => path + * + * Returns the path of the local address of unixsocket. + * + * s = UNIXServer.new("/tmp/sock") + * p s.path #=> "/tmp/sock" + * + */ +static VALUE +unix_path(VALUE sock) +{ + rb_io_t *fptr; + + GetOpenFile(sock, fptr); + if (NIL_P(fptr->pathv)) { + struct sockaddr_un addr; + socklen_t len = (socklen_t)sizeof(addr); + if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + rb_sys_fail(0); + fptr->pathv = rb_obj_freeze(rb_str_new_cstr(rsock_unixpath(&addr, len))); + } + return rb_str_dup(fptr->pathv); +} + +/* + * call-seq: + * unixsocket.recvfrom(maxlen [, flags]) => [mesg, unixaddress] + * + * Receives a message via _unixsocket_. + * + * _maxlen_ is the maximum number of bytes to receive. + * + * _flags_ should be a bitwise OR of Socket::MSG_* constants. + * + * s1 = Socket.new(:UNIX, :DGRAM, 0) + * s1_ai = Addrinfo.unix("/tmp/sock1") + * s1.bind(s1_ai) + * + * s2 = Socket.new(:UNIX, :DGRAM, 0) + * s2_ai = Addrinfo.unix("/tmp/sock2") + * s2.bind(s2_ai) + * s3 = UNIXSocket.for_fd(s2.fileno) + * + * s1.send "a", 0, s2_ai + * p s3.recvfrom(10) #=> ["a", ["AF_UNIX", "/tmp/sock1"]] + * + */ +static VALUE +unix_recvfrom(int argc, VALUE *argv, VALUE sock) +{ + return rsock_s_recvfrom(sock, argc, argv, RECV_UNIX); +} + +#if defined(HAVE_ST_MSG_CONTROL) && defined(SCM_RIGHTS) +#define FD_PASSING_BY_MSG_CONTROL 1 +#else +#define FD_PASSING_BY_MSG_CONTROL 0 +#endif + +#if defined(HAVE_ST_MSG_ACCRIGHTS) +#define FD_PASSING_BY_MSG_ACCRIGHTS 1 +#else +#define FD_PASSING_BY_MSG_ACCRIGHTS 0 +#endif + +struct iomsg_arg { + int fd; + struct msghdr msg; +}; + +#if defined(HAVE_SENDMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS) +static VALUE +sendmsg_blocking(void *data) +{ + struct iomsg_arg *arg = data; + return sendmsg(arg->fd, &arg->msg, 0); +} + +/* + * call-seq: + * unixsocket.send_io(io) => nil + * + * Sends _io_ as file descriptor passing. + * + * s1, s2 = UNIXSocket.pair + * + * s1.send_io STDOUT + * stdout = s2.recv_io + * + * p STDOUT.fileno #=> 1 + * p stdout.fileno #=> 6 + * + * stdout.puts "hello" # outputs "hello\n" to standard output. + */ +static VALUE +unix_send_io(VALUE sock, VALUE val) +{ + int fd; + rb_io_t *fptr; + struct iomsg_arg arg; + struct iovec vec[1]; + char buf[1]; + +#if FD_PASSING_BY_MSG_CONTROL + struct { + struct cmsghdr hdr; + char pad[8+sizeof(int)+8]; + } cmsg; +#endif + + if (rb_obj_is_kind_of(val, rb_cIO)) { + rb_io_t *valfptr; + GetOpenFile(val, valfptr); + fd = valfptr->fd; + } + else if (FIXNUM_P(val)) { + fd = FIX2INT(val); + } + else { + rb_raise(rb_eTypeError, "neither IO nor file descriptor"); + } + + GetOpenFile(sock, fptr); + + arg.msg.msg_name = NULL; + arg.msg.msg_namelen = 0; + + /* Linux and Solaris doesn't work if msg_iov is NULL. */ + buf[0] = '\0'; + vec[0].iov_base = buf; + vec[0].iov_len = 1; + arg.msg.msg_iov = vec; + arg.msg.msg_iovlen = 1; + +#if FD_PASSING_BY_MSG_CONTROL + arg.msg.msg_control = (caddr_t)&cmsg; + arg.msg.msg_controllen = (socklen_t)CMSG_LEN(sizeof(int)); + arg.msg.msg_flags = 0; + MEMZERO((char*)&cmsg, char, sizeof(cmsg)); + cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int)); + cmsg.hdr.cmsg_level = SOL_SOCKET; + cmsg.hdr.cmsg_type = SCM_RIGHTS; + memcpy(CMSG_DATA(&cmsg.hdr), &fd, sizeof(int)); +#else + arg.msg.msg_accrights = (caddr_t)&fd; + arg.msg.msg_accrightslen = sizeof(fd); +#endif + + arg.fd = fptr->fd; + while ((int)BLOCKING_REGION(sendmsg_blocking, &arg) == -1) { + if (!rb_io_wait_writable(arg.fd)) + rb_sys_fail("sendmsg(2)"); + } + + return Qnil; +} +#else +#define unix_send_io rb_f_notimplement +#endif + +#if defined(HAVE_RECVMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS) +static VALUE +recvmsg_blocking(void *data) +{ + struct iomsg_arg *arg = data; + return recvmsg(arg->fd, &arg->msg, 0); +} + +/* + * call-seq: + * unixsocket.recv_io([klass [, mode]]) => io + * + * UNIXServer.open("/tmp/sock") {|serv| + * UNIXSocket.open("/tmp/sock") {|c| + * s = serv.accept + * + * c.send_io STDOUT + * stdout = s.recv_io + * + * p STDOUT.fileno #=> 1 + * p stdout.fileno #=> 7 + * + * stdout.puts "hello" # outputs "hello\n" to standard output. + * } + * } + * + */ +static VALUE +unix_recv_io(int argc, VALUE *argv, VALUE sock) +{ + VALUE klass, mode; + rb_io_t *fptr; + struct iomsg_arg arg; + struct iovec vec[2]; + char buf[1]; + + int fd; +#if FD_PASSING_BY_MSG_CONTROL + struct { + struct cmsghdr hdr; + char pad[8+sizeof(int)+8]; + } cmsg; +#endif + + rb_scan_args(argc, argv, "02", &klass, &mode); + if (argc == 0) + klass = rb_cIO; + if (argc <= 1) + mode = Qnil; + + GetOpenFile(sock, fptr); + + arg.msg.msg_name = NULL; + arg.msg.msg_namelen = 0; + + vec[0].iov_base = buf; + vec[0].iov_len = sizeof(buf); + arg.msg.msg_iov = vec; + arg.msg.msg_iovlen = 1; + +#if FD_PASSING_BY_MSG_CONTROL + arg.msg.msg_control = (caddr_t)&cmsg; + arg.msg.msg_controllen = (socklen_t)CMSG_SPACE(sizeof(int)); + arg.msg.msg_flags = 0; + cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int)); + cmsg.hdr.cmsg_level = SOL_SOCKET; + cmsg.hdr.cmsg_type = SCM_RIGHTS; + fd = -1; + memcpy(CMSG_DATA(&cmsg.hdr), &fd, sizeof(int)); +#else + arg.msg.msg_accrights = (caddr_t)&fd; + arg.msg.msg_accrightslen = sizeof(fd); + fd = -1; +#endif + + arg.fd = fptr->fd; + while ((int)BLOCKING_REGION(recvmsg_blocking, &arg) == -1) { + if (!rb_io_wait_readable(arg.fd)) + rb_sys_fail("recvmsg(2)"); + } + +#if FD_PASSING_BY_MSG_CONTROL + if (arg.msg.msg_controllen < sizeof(struct cmsghdr)) { + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d smaller than sizeof(struct cmsghdr)=%d)", + (int)arg.msg.msg_controllen, (int)sizeof(struct cmsghdr)); + } + if (cmsg.hdr.cmsg_level != SOL_SOCKET) { + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_level=%d, %d expected)", + cmsg.hdr.cmsg_level, SOL_SOCKET); + } + if (cmsg.hdr.cmsg_type != SCM_RIGHTS) { + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_type=%d, %d expected)", + cmsg.hdr.cmsg_type, SCM_RIGHTS); + } + if (arg.msg.msg_controllen < CMSG_LEN(sizeof(int))) { + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d smaller than CMSG_LEN(sizeof(int))=%d)", + (int)arg.msg.msg_controllen, (int)CMSG_LEN(sizeof(int))); + } + if (CMSG_SPACE(sizeof(int)) < arg.msg.msg_controllen) { + rb_raise(rb_eSocket, + "file descriptor was not passed (msg_controllen=%d bigger than CMSG_SPACE(sizeof(int))=%d)", + (int)arg.msg.msg_controllen, (int)CMSG_SPACE(sizeof(int))); + } + if (cmsg.hdr.cmsg_len != CMSG_LEN(sizeof(int))) { + rsock_discard_cmsg_resource(&arg.msg); + rb_raise(rb_eSocket, + "file descriptor was not passed (cmsg_len=%d, %d expected)", + (int)cmsg.hdr.cmsg_len, (int)CMSG_LEN(sizeof(int))); + } +#else + if (arg.msg.msg_accrightslen != sizeof(fd)) { + rb_raise(rb_eSocket, + "file descriptor was not passed (accrightslen) : %d != %d", + arg.msg.msg_accrightslen, (int)sizeof(fd)); + } +#endif + +#if FD_PASSING_BY_MSG_CONTROL + memcpy(&fd, CMSG_DATA(&cmsg.hdr), sizeof(int)); +#endif + + if (klass == Qnil) + return INT2FIX(fd); + else { + ID for_fd; + int ff_argc; + VALUE ff_argv[2]; + CONST_ID(for_fd, "for_fd"); + ff_argc = mode == Qnil ? 1 : 2; + ff_argv[0] = INT2FIX(fd); + ff_argv[1] = mode; + return rb_funcall2(klass, for_fd, ff_argc, ff_argv); + } +} +#else +#define unix_recv_io rb_f_notimplement +#endif + +/* + * call-seq: + * unixsocket.addr => [address_family, unix_path] + * + * Returns the local address as an array which contains + * address_family and unix_path. + * + * Example + * serv = UNIXServer.new("/tmp/sock") + * p serv.addr #=> ["AF_UNIX", "/tmp/sock"] + */ +static VALUE +unix_addr(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_un addr; + socklen_t len = (socklen_t)sizeof addr; + + GetOpenFile(sock, fptr); + + if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + rb_sys_fail("getsockname(2)"); + return rsock_unixaddr(&addr, len); +} + +/* + * call-seq: + * unixsocket.peeraddr => [address_family, unix_path] + * + * Returns the remote address as an array which contains + * address_family and unix_path. + * + * Example + * serv = UNIXServer.new("/tmp/sock") + * c = UNIXSocket.new("/tmp/sock") + * p c.peeraddr #=> ["AF_UNIX", "/tmp/sock"] + */ +static VALUE +unix_peeraddr(VALUE sock) +{ + rb_io_t *fptr; + struct sockaddr_un addr; + socklen_t len = (socklen_t)sizeof addr; + + GetOpenFile(sock, fptr); + + if (getpeername(fptr->fd, (struct sockaddr*)&addr, &len) < 0) + rb_sys_fail("getpeername(2)"); + return rsock_unixaddr(&addr, len); +} + +/* + * call-seq: + * UNIXSocket.pair([type [, protocol]]) => [unixsocket1, unixsocket2] + * UNIXSocket.socketpair([type [, protocol]]) => [unixsocket1, unixsocket2] + * + * Creates a pair of sockets connected each other. + * + * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc. + * + * _protocol_ should be a protocol defined in the domain. + * 0 is default protocol for the domain. + * + * s1, s2 = UNIXSocket.pair + * s1.send "a", 0 + * s1.send "b", 0 + * p s2.recv(10) #=> "ab" + * + */ +static VALUE +unix_s_socketpair(int argc, VALUE *argv, VALUE klass) +{ + VALUE domain, type, protocol; + VALUE args[3]; + + domain = INT2FIX(PF_UNIX); + rb_scan_args(argc, argv, "02", &type, &protocol); + if (argc == 0) + type = INT2FIX(SOCK_STREAM); + if (argc <= 1) + protocol = INT2FIX(0); + + args[0] = domain; + args[1] = type; + args[2] = protocol; + + return rsock_sock_s_socketpair(3, args, klass); +} +#endif + +/* + * Document-class: ::UNIXSocket < BasicSocket + * + * UNIXSocket represents a UNIX domain stream client socket. + */ +void +rsock_init_unixsocket(void) +{ +#ifdef HAVE_SYS_UN_H + rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket); + rb_define_method(rb_cUNIXSocket, "initialize", unix_init, 1); + rb_define_method(rb_cUNIXSocket, "path", unix_path, 0); + rb_define_method(rb_cUNIXSocket, "addr", unix_addr, 0); + rb_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0); + rb_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1); + rb_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1); + rb_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1); + rb_define_singleton_method(rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1); + rb_define_singleton_method(rb_cUNIXSocket, "pair", unix_s_socketpair, -1); +#endif +} |
