ext/socket/socket.c

Go to the documentation of this file.
00001 /************************************************
00002 
00003   socket.c -
00004 
00005   created at: Thu Mar 31 12:21:29 JST 1994
00006 
00007   Copyright (C) 1993-2007 Yukihiro Matsumoto
00008 
00009 ************************************************/
00010 
00011 #include "rubysocket.h"
00012 
00013 static VALUE sock_s_unpack_sockaddr_in(VALUE, VALUE);
00014 
00015 void
00016 rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
00017 {
00018     rsock_syserr_fail_host_port(errno, mesg, host, port);
00019 }
00020 
00021 void
00022 rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
00023 {
00024     VALUE message;
00025 
00026     port = rb_String(port);
00027 
00028     message = rb_sprintf("%s for \"%s\" port %s",
00029             mesg, StringValueCStr(host), StringValueCStr(port));
00030 
00031     rb_syserr_fail_str(err, message);
00032 }
00033 
00034 void
00035 rsock_sys_fail_path(const char *mesg, VALUE path)
00036 {
00037     rsock_syserr_fail_path(errno, mesg, path);
00038 }
00039 
00040 void
00041 rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
00042 {
00043     VALUE message;
00044 
00045     if (RB_TYPE_P(path, T_STRING)) {
00046         if (memchr(RSTRING_PTR(path), '\0', RSTRING_LEN(path))) {
00047             path = rb_str_inspect(path);
00048             message = rb_sprintf("%s for %s", mesg,
00049                     StringValueCStr(path));
00050         }
00051         else {
00052             message = rb_sprintf("%s for \"%s\"", mesg,
00053                     StringValueCStr(path));
00054         }
00055         rb_syserr_fail_str(err, message);
00056     }
00057     else {
00058         rb_syserr_fail(err, mesg);
00059     }
00060 }
00061 
00062 void
00063 rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
00064 {
00065     rsock_syserr_fail_sockaddr(errno, mesg, addr, len);
00066 }
00067 
00068 void
00069 rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
00070 {
00071     VALUE rai;
00072 
00073     rai = rsock_addrinfo_new(addr, len, PF_UNSPEC, 0, 0, Qnil, Qnil);
00074 
00075     rsock_syserr_fail_raddrinfo(err, mesg, rai);
00076 }
00077 
00078 void
00079 rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
00080 {
00081     rsock_syserr_fail_raddrinfo(errno, mesg, rai);
00082 }
00083 
00084 void
00085 rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
00086 {
00087     VALUE str, message;
00088 
00089     str = rsock_addrinfo_inspect_sockaddr(rai);
00090     message = rb_sprintf("%s for %s", mesg, StringValueCStr(str));
00091 
00092     rb_syserr_fail_str(err, message);
00093 }
00094 
00095 void
00096 rsock_sys_fail_raddrinfo_or_sockaddr(const char *mesg, VALUE addr, VALUE rai)
00097 {
00098     rsock_syserr_fail_raddrinfo_or_sockaddr(errno, mesg, addr, rai);
00099 }
00100 
00101 void
00102 rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
00103 {
00104     if (NIL_P(rai)) {
00105         StringValue(addr);
00106 
00107         rsock_syserr_fail_sockaddr(err, mesg,
00108             (struct sockaddr *)RSTRING_PTR(addr),
00109             (socklen_t)RSTRING_LEN(addr)); /* overflow should be checked already */
00110     }
00111     else
00112         rsock_syserr_fail_raddrinfo(err, mesg, rai);
00113 }
00114 
00115 static void
00116 setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
00117 {
00118     *dv = rsock_family_arg(domain);
00119     *tv = rsock_socktype_arg(type);
00120 }
00121 
00122 /*
00123  * call-seq:
00124  *   Socket.new(domain, socktype [, protocol]) => socket
00125  *
00126  * Creates a new socket object.
00127  *
00128  * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
00129  *
00130  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
00131  *
00132  * _protocol_ is optional and should be a protocol defined in the domain.
00133  * If protocol is not given, 0 is used internally.
00134  *
00135  *   Socket.new(:INET, :STREAM) # TCP socket
00136  *   Socket.new(:INET, :DGRAM)  # UDP socket
00137  *   Socket.new(:UNIX, :STREAM) # UNIX stream socket
00138  *   Socket.new(:UNIX, :DGRAM)  # UNIX datagram socket
00139  */
00140 static VALUE
00141 sock_initialize(int argc, VALUE *argv, VALUE sock)
00142 {
00143     VALUE domain, type, protocol;
00144     int fd;
00145     int d, t;
00146 
00147     rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
00148     if (NIL_P(protocol))
00149         protocol = INT2FIX(0);
00150 
00151     rb_secure(3);
00152     setup_domain_and_type(domain, &d, type, &t);
00153     fd = rsock_socket(d, t, NUM2INT(protocol));
00154     if (fd < 0) rb_sys_fail("socket(2)");
00155 
00156     return rsock_init_sock(sock, fd);
00157 }
00158 
00159 #if defined HAVE_SOCKETPAIR
00160 static VALUE
00161 io_call_close(VALUE io)
00162 {
00163     return rb_funcall(io, rb_intern("close"), 0, 0);
00164 }
00165 
00166 static VALUE
00167 io_close(VALUE io)
00168 {
00169     return rb_rescue(io_call_close, io, 0, 0);
00170 }
00171 
00172 static VALUE
00173 pair_yield(VALUE pair)
00174 {
00175     return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1));
00176 }
00177 #endif
00178 
00179 #if defined HAVE_SOCKETPAIR
00180 
00181 static int
00182 rsock_socketpair0(int domain, int type, int protocol, int sv[2])
00183 {
00184     int ret;
00185 
00186 #ifdef SOCK_CLOEXEC
00187     static int try_sock_cloexec = 1;
00188     if (try_sock_cloexec) {
00189         ret = socketpair(domain, type|SOCK_CLOEXEC, protocol, sv);
00190         if (ret == -1 && errno == EINVAL) {
00191             /* SOCK_CLOEXEC is available since Linux 2.6.27.  Linux 2.6.18 fails with EINVAL */
00192             ret = socketpair(domain, type, protocol, sv);
00193             if (ret != -1) {
00194                 /* The reason of EINVAL may be other than SOCK_CLOEXEC.
00195                  * So disable SOCK_CLOEXEC only if socketpair() succeeds without SOCK_CLOEXEC.
00196                  * Ex. Socket.pair(:UNIX, 0xff) fails with EINVAL.
00197                  */
00198                 try_sock_cloexec = 0;
00199             }
00200         }
00201     }
00202     else {
00203         ret = socketpair(domain, type, protocol, sv);
00204     }
00205 #else
00206     ret = socketpair(domain, type, protocol, sv);
00207 #endif
00208 
00209     if (ret == -1) {
00210         return -1;
00211     }
00212 
00213     rb_fd_fix_cloexec(sv[0]);
00214     rb_fd_fix_cloexec(sv[1]);
00215 
00216     return ret;
00217 }
00218 
00219 static int
00220 rsock_socketpair(int domain, int type, int protocol, int sv[2])
00221 {
00222     int ret;
00223 
00224     ret = rsock_socketpair0(domain, type, protocol, sv);
00225     if (ret < 0 && (errno == EMFILE || errno == ENFILE)) {
00226         rb_gc();
00227         ret = rsock_socketpair0(domain, type, protocol, sv);
00228     }
00229 
00230     return ret;
00231 }
00232 
00233 /*
00234  * call-seq:
00235  *   Socket.pair(domain, type, protocol)       => [socket1, socket2]
00236  *   Socket.socketpair(domain, type, protocol) => [socket1, socket2]
00237  *
00238  * Creates a pair of sockets connected each other.
00239  *
00240  * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
00241  *
00242  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
00243  *
00244  * _protocol_ should be a protocol defined in the domain,
00245  * defaults to 0 for the domain.
00246  *
00247  *   s1, s2 = Socket.pair(:UNIX, :STREAM, 0)
00248  *   s1.send "a", 0
00249  *   s1.send "b", 0
00250  *   s1.close
00251  *   p s2.recv(10) #=> "ab"
00252  *   p s2.recv(10) #=> ""
00253  *   p s2.recv(10) #=> ""
00254  *
00255  *   s1, s2 = Socket.pair(:UNIX, :DGRAM, 0)
00256  *   s1.send "a", 0
00257  *   s1.send "b", 0
00258  *   p s2.recv(10) #=> "a"
00259  *   p s2.recv(10) #=> "b"
00260  *
00261  */
00262 VALUE
00263 rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass)
00264 {
00265     VALUE domain, type, protocol;
00266     int d, t, p, sp[2];
00267     int ret;
00268     VALUE s1, s2, r;
00269 
00270     rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
00271     if (NIL_P(protocol))
00272         protocol = INT2FIX(0);
00273 
00274     setup_domain_and_type(domain, &d, type, &t);
00275     p = NUM2INT(protocol);
00276     ret = rsock_socketpair(d, t, p, sp);
00277     if (ret < 0) {
00278         rb_sys_fail("socketpair(2)");
00279     }
00280     rb_fd_fix_cloexec(sp[0]);
00281     rb_fd_fix_cloexec(sp[1]);
00282 
00283     s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]);
00284     s2 = rsock_init_sock(rb_obj_alloc(klass), sp[1]);
00285     r = rb_assoc_new(s1, s2);
00286     if (rb_block_given_p()) {
00287         return rb_ensure(pair_yield, r, io_close, s1);
00288     }
00289     return r;
00290 }
00291 #else
00292 #define rsock_sock_s_socketpair rb_f_notimplement
00293 #endif
00294 
00295 /*
00296  * call-seq:
00297  *   socket.connect(remote_sockaddr) => 0
00298  *
00299  * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if
00300  * successful, otherwise an exception is raised.
00301  *
00302  * === Parameter
00303  * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
00304  *
00305  * === Example:
00306  *      # Pull down Google's web page
00307  *      require 'socket'
00308  *      include Socket::Constants
00309  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00310  *      sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
00311  *      socket.connect( sockaddr )
00312  *      socket.write( "GET / HTTP/1.0\r\n\r\n" )
00313  *      results = socket.read
00314  *
00315  * === Unix-based Exceptions
00316  * On unix-based systems the following system exceptions may be raised if
00317  * the call to _connect_ fails:
00318  * * Errno::EACCES - search permission is denied for a component of the prefix
00319  *   path or write access to the +socket+ is denied
00320  * * Errno::EADDRINUSE - the _sockaddr_ is already in use
00321  * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
00322  *   local machine
00323  * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
00324  *   the address family of the specified +socket+
00325  * * Errno::EALREADY - a connection is already in progress for the specified
00326  *   socket
00327  * * Errno::EBADF - the +socket+ is not a valid file descriptor
00328  * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
00329  *   refused the connection request
00330  * * Errno::ECONNRESET - the remote host reset the connection request
00331  * * Errno::EFAULT - the _sockaddr_ cannot be accessed
00332  * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
00333  *   because the host is down or a remote router cannot reach it)
00334  * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
00335  *   connection cannot be immediately established; the connection will be
00336  *   established asynchronously
00337  * * Errno::EINTR - the attempt to establish the connection was interrupted by
00338  *   delivery of a signal that was caught; the connection will be established
00339  *   asynchronously
00340  * * Errno::EISCONN - the specified +socket+ is already connected
00341  * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
00342  *   length for the address family or there is an invalid family in _sockaddr_
00343  * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
00344  *   PATH_MAX
00345  * * Errno::ENETDOWN - the local interface used to reach the destination is down
00346  * * Errno::ENETUNREACH - no route to the network is present
00347  * * Errno::ENOBUFS - no buffer space is available
00348  * * Errno::ENOSR - there were insufficient STREAMS resources available to
00349  *   complete the operation
00350  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
00351  * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
00352  * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
00353  *   bound to the specified peer address
00354  * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
00355  *   was made.
00356  *
00357  * On unix-based systems if the address family of the calling +socket+ is
00358  * AF_UNIX the follow exceptions may be raised if the call to _connect_
00359  * fails:
00360  * * Errno::EIO - an i/o error occurred while reading from or writing to the
00361  *   file system
00362  * * Errno::ELOOP - too many symbolic links were encountered in translating
00363  *   the pathname in _sockaddr_
00364  * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
00365  *   characters, or an entire pathname exceeded PATH_MAX characters
00366  * * Errno::ENOENT - a component of the pathname does not name an existing file
00367  *   or the pathname is an empty string
00368  * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
00369  *   is not a directory
00370  *
00371  * === Windows Exceptions
00372  * On Windows systems the following system exceptions may be raised if
00373  * the call to _connect_ fails:
00374  * * Errno::ENETDOWN - the network is down
00375  * * Errno::EADDRINUSE - the socket's local address is already in use
00376  * * Errno::EINTR - the socket was cancelled
00377  * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
00378  *   is still processing a callback function. Or a nonblocking connect call is
00379  *   in progress on the +socket+.
00380  * * Errno::EALREADY - see Errno::EINVAL
00381  * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
00382  *   ADDR_ANY TODO check ADDRANY TO INADDR_ANY
00383  * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
00384  *   with this +socket+
00385  * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
00386  *   refused the connection request
00387  * * Errno::EFAULT - the socket's internal address or address length parameter
00388  *   is too small or is not a valid part of the user space address
00389  * * Errno::EINVAL - the +socket+ is a listening socket
00390  * * Errno::EISCONN - the +socket+ is already connected
00391  * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
00392  * * Errno::EHOSTUNREACH - no route to the network is present
00393  * * Errno::ENOBUFS - no buffer space is available
00394  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
00395  * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
00396  *   was made.
00397  * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
00398  *   connection cannot be completed immediately
00399  * * Errno::EACCES - the attempt to connect the datagram socket to the
00400  *   broadcast address failed
00401  *
00402  * === See
00403  * * connect manual pages on unix-based systems
00404  * * connect function in Microsoft's Winsock functions reference
00405  */
00406 static VALUE
00407 sock_connect(VALUE sock, VALUE addr)
00408 {
00409     VALUE rai;
00410     rb_io_t *fptr;
00411     int fd, n;
00412 
00413     SockAddrStringValueWithAddrinfo(addr, rai);
00414     addr = rb_str_new4(addr);
00415     GetOpenFile(sock, fptr);
00416     fd = fptr->fd;
00417     n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), 0);
00418     if (n < 0) {
00419         rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai);
00420     }
00421 
00422     return INT2FIX(n);
00423 }
00424 
00425 /*
00426  * call-seq:
00427  *   socket.connect_nonblock(remote_sockaddr) => 0
00428  *
00429  * Requests a connection to be made on the given +remote_sockaddr+ after
00430  * O_NONBLOCK is set for the underlying file descriptor.
00431  * Returns 0 if successful, otherwise an exception is raised.
00432  *
00433  * === Parameter
00434  * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
00435  *
00436  * === Example:
00437  *      # Pull down Google's web page
00438  *      require 'socket'
00439  *      include Socket::Constants
00440  *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
00441  *      sockaddr = Socket.sockaddr_in(80, 'www.google.com')
00442  *      begin # emulate blocking connect
00443  *        socket.connect_nonblock(sockaddr)
00444  *      rescue IO::WaitWritable
00445  *        IO.select(nil, [socket]) # wait 3-way handshake completion
00446  *        begin
00447  *          socket.connect_nonblock(sockaddr) # check connection failure
00448  *        rescue Errno::EISCONN
00449  *        end
00450  *      end
00451  *      socket.write("GET / HTTP/1.0\r\n\r\n")
00452  *      results = socket.read
00453  *
00454  * Refer to Socket#connect for the exceptions that may be thrown if the call
00455  * to _connect_nonblock_ fails.
00456  *
00457  * Socket#connect_nonblock may raise any error corresponding to connect(2) failure,
00458  * including Errno::EINPROGRESS.
00459  *
00460  * If the exception is Errno::EINPROGRESS,
00461  * it is extended by IO::WaitWritable.
00462  * So IO::WaitWritable can be used to rescue the exceptions for retrying connect_nonblock.
00463  *
00464  * === See
00465  * * Socket#connect
00466  */
00467 static VALUE
00468 sock_connect_nonblock(VALUE sock, VALUE addr)
00469 {
00470     VALUE rai;
00471     rb_io_t *fptr;
00472     int n;
00473 
00474     SockAddrStringValueWithAddrinfo(addr, rai);
00475     addr = rb_str_new4(addr);
00476     GetOpenFile(sock, fptr);
00477     rb_io_set_nonblock(fptr);
00478     n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr));
00479     if (n < 0) {
00480         if (errno == EINPROGRESS)
00481             rb_readwrite_sys_fail(RB_IO_WAIT_WRITABLE, "connect(2) would block");
00482         rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai);
00483     }
00484 
00485     return INT2FIX(n);
00486 }
00487 
00488 /*
00489  * call-seq:
00490  *   socket.bind(local_sockaddr) => 0
00491  *
00492  * Binds to the given local address.
00493  *
00494  * === Parameter
00495  * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object
00496  *
00497  * === Example
00498  *      require 'socket'
00499  *
00500  *      # use Addrinfo
00501  *      socket = Socket.new(:INET, :STREAM, 0)
00502  *      socket.bind(Addrinfo.tcp("127.0.0.1", 2222))
00503  *      p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>
00504  *
00505  *      # use struct sockaddr
00506  *      include Socket::Constants
00507  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00508  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00509  *      socket.bind( sockaddr )
00510  *
00511  * === Unix-based Exceptions
00512  * On unix-based based systems the following system exceptions may be raised if
00513  * the call to _bind_ fails:
00514  * * Errno::EACCES - the specified _sockaddr_ is protected and the current
00515  *   user does not have permission to bind to it
00516  * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
00517  * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
00518  *   local machine
00519  * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
00520  *   the family of the calling +socket+
00521  * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
00522  * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
00523  * * Errno::EINVAL - the +socket+ is already bound to an address, and the
00524  *   protocol does not support binding to the new _sockaddr_ or the +socket+
00525  *   has been shut down.
00526  * * Errno::EINVAL - the address length is not a valid length for the address
00527  *   family
00528  * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
00529  *   PATH_MAX
00530  * * Errno::ENOBUFS - no buffer space is available
00531  * * Errno::ENOSR - there were insufficient STREAMS resources available to
00532  *   complete the operation
00533  * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
00534  * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
00535  *   binding to an address
00536  *
00537  * On unix-based based systems if the address family of the calling +socket+ is
00538  * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
00539  * fails:
00540  * * Errno::EACCES - search permission is denied for a component of the prefix
00541  *   path or write access to the +socket+ is denied
00542  * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
00543  * * Errno::EISDIR - same as Errno::EDESTADDRREQ
00544  * * Errno::EIO - an i/o error occurred
00545  * * Errno::ELOOP - too many symbolic links were encountered in translating
00546  *   the pathname in _sockaddr_
00547  * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
00548  *   characters, or an entire pathname exceeded PATH_MAX characters
00549  * * Errno::ENOENT - a component of the pathname does not name an existing file
00550  *   or the pathname is an empty string
00551  * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
00552  *   is not a directory
00553  * * Errno::EROFS - the name would reside on a read only filesystem
00554  *
00555  * === Windows Exceptions
00556  * On Windows systems the following system exceptions may be raised if
00557  * the call to _bind_ fails:
00558  * * Errno::ENETDOWN-- the network is down
00559  * * Errno::EACCES - the attempt to connect the datagram socket to the
00560  *   broadcast address failed
00561  * * Errno::EADDRINUSE - the socket's local address is already in use
00562  * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
00563  *   computer
00564  * * Errno::EFAULT - the socket's internal address or address length parameter
00565  *   is too small or is not a valid part of the user space addressed
00566  * * Errno::EINVAL - the +socket+ is already bound to an address
00567  * * Errno::ENOBUFS - no buffer space is available
00568  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
00569  *
00570  * === See
00571  * * bind manual pages on unix-based systems
00572  * * bind function in Microsoft's Winsock functions reference
00573  */
00574 static VALUE
00575 sock_bind(VALUE sock, VALUE addr)
00576 {
00577     VALUE rai;
00578     rb_io_t *fptr;
00579 
00580     SockAddrStringValueWithAddrinfo(addr, rai);
00581     GetOpenFile(sock, fptr);
00582     if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)) < 0)
00583         rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai);
00584 
00585     return INT2FIX(0);
00586 }
00587 
00588 /*
00589  * call-seq:
00590  *   socket.listen( int ) => 0
00591  *
00592  * Listens for connections, using the specified +int+ as the backlog. A call
00593  * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
00594  * SOCK_SEQPACKET.
00595  *
00596  * === Parameter
00597  * * +backlog+ - the maximum length of the queue for pending connections.
00598  *
00599  * === Example 1
00600  *      require 'socket'
00601  *      include Socket::Constants
00602  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00603  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00604  *      socket.bind( sockaddr )
00605  *      socket.listen( 5 )
00606  *
00607  * === Example 2 (listening on an arbitrary port, unix-based systems only):
00608  *      require 'socket'
00609  *      include Socket::Constants
00610  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00611  *      socket.listen( 1 )
00612  *
00613  * === Unix-based Exceptions
00614  * On unix based systems the above will work because a new +sockaddr+ struct
00615  * is created on the address ADDR_ANY, for an arbitrary port number as handed
00616  * off by the kernel. It will not work on Windows, because Windows requires that
00617  * the +socket+ is bound by calling _bind_ before it can _listen_.
00618  *
00619  * If the _backlog_ amount exceeds the implementation-dependent maximum
00620  * queue length, the implementation's maximum queue length will be used.
00621  *
00622  * On unix-based based systems the following system exceptions may be raised if the
00623  * call to _listen_ fails:
00624  * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
00625  * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
00626  *   the protocol does not support listening on an unbound socket
00627  * * Errno::EINVAL - the _socket_ is already connected
00628  * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
00629  * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
00630  * * Errno::EACCES - the calling process does not have appropriate privileges
00631  * * Errno::EINVAL - the _socket_ has been shut down
00632  * * Errno::ENOBUFS - insufficient resources are available in the system to
00633  *   complete the call
00634  *
00635  * === Windows Exceptions
00636  * On Windows systems the following system exceptions may be raised if
00637  * the call to _listen_ fails:
00638  * * Errno::ENETDOWN - the network is down
00639  * * Errno::EADDRINUSE - the socket's local address is already in use. This
00640  *   usually occurs during the execution of _bind_ but could be delayed
00641  *   if the call to _bind_ was to a partially wildcard address (involving
00642  *   ADDR_ANY) and if a specific address needs to be committed at the
00643  *   time of the call to _listen_
00644  * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
00645  *   service provider is still processing a callback function
00646  * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
00647  * * Errno::EISCONN - the +socket+ is already connected
00648  * * Errno::EMFILE - no more socket descriptors are available
00649  * * Errno::ENOBUFS - no buffer space is available
00650  * * Errno::ENOTSOC - +socket+ is not a socket
00651  * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
00652  *   the _listen_ method
00653  *
00654  * === See
00655  * * listen manual pages on unix-based systems
00656  * * listen function in Microsoft's Winsock functions reference
00657  */
00658 VALUE
00659 rsock_sock_listen(VALUE sock, VALUE log)
00660 {
00661     rb_io_t *fptr;
00662     int backlog;
00663 
00664     backlog = NUM2INT(log);
00665     GetOpenFile(sock, fptr);
00666     if (listen(fptr->fd, backlog) < 0)
00667         rb_sys_fail("listen(2)");
00668 
00669     return INT2FIX(0);
00670 }
00671 
00672 /*
00673  * call-seq:
00674  *   socket.recvfrom(maxlen) => [mesg, sender_addrinfo]
00675  *   socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo]
00676  *
00677  * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
00678  * of the +MSG_+ options. The first element of the results, _mesg_, is the data
00679  * received. The second element, _sender_addrinfo_, contains protocol-specific
00680  * address information of the sender.
00681  *
00682  * === Parameters
00683  * * +maxlen+ - the maximum number of bytes to receive from the socket
00684  * * +flags+ - zero or more of the +MSG_+ options
00685  *
00686  * === Example
00687  *      # In one file, start this first
00688  *      require 'socket'
00689  *      include Socket::Constants
00690  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00691  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00692  *      socket.bind( sockaddr )
00693  *      socket.listen( 5 )
00694  *      client, client_addrinfo = socket.accept
00695  *      data = client.recvfrom( 20 )[0].chomp
00696  *      puts "I only received 20 bytes '#{data}'"
00697  *      sleep 1
00698  *      socket.close
00699  *
00700  *      # In another file, start this second
00701  *      require 'socket'
00702  *      include Socket::Constants
00703  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00704  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00705  *      socket.connect( sockaddr )
00706  *      socket.puts "Watch this get cut short!"
00707  *      socket.close
00708  *
00709  * === Unix-based Exceptions
00710  * On unix-based based systems the following system exceptions may be raised if the
00711  * call to _recvfrom_ fails:
00712  * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
00713  *   data is waiting to be received; or MSG_OOB is set and no out-of-band data
00714  *   is available and either the +socket+ file descriptor is marked as
00715  *   O_NONBLOCK or the +socket+ does not support blocking to wait for
00716  *   out-of-band-data
00717  * * Errno::EWOULDBLOCK - see Errno::EAGAIN
00718  * * Errno::EBADF - the +socket+ is not a valid file descriptor
00719  * * Errno::ECONNRESET - a connection was forcibly closed by a peer
00720  * * Errno::EFAULT - the socket's internal buffer, address or address length
00721  *   cannot be accessed or written
00722  * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available
00723  * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
00724  * * Errno::EIO - an i/o error occurred while reading from or writing to the
00725  *   filesystem
00726  * * Errno::ENOBUFS - insufficient resources were available in the system to
00727  *   perform the operation
00728  * * Errno::ENOMEM - insufficient memory was available to fulfill the request
00729  * * Errno::ENOSR - there were insufficient STREAMS resources available to
00730  *   complete the operation
00731  * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
00732  *   is not connected
00733  * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
00734  * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
00735  * * Errno::ETIMEDOUT - the connection timed out during connection establishment
00736  *   or due to a transmission timeout on an active connection
00737  *
00738  * === Windows Exceptions
00739  * On Windows systems the following system exceptions may be raised if
00740  * the call to _recvfrom_ fails:
00741  * * Errno::ENETDOWN - the network is down
00742  * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
00743  *   part of the user address space, or the internal fromlen parameter is
00744  *   too small to accommodate the peer address
00745  * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
00746  *   the WinSock function WSACancelBlockingCall
00747  * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
00748  *   the service provider is still processing a callback function
00749  * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
00750  *   unknown flag was specified, or MSG_OOB was specified for a socket with
00751  *   SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
00752  *   len parameter on +socket+ was zero or negative
00753  * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
00754  *   not permitted with a connected socket on a socket that is connection
00755  *   oriented or connectionless.
00756  * * Errno::ENETRESET - the connection has been broken due to the keep-alive
00757  *   activity detecting a failure while the operation was in progress.
00758  * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
00759  *   such as type SOCK_STREAM. OOB data is not supported in the communication
00760  *   domain associated with +socket+, or +socket+ is unidirectional and
00761  *   supports only send operations
00762  * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
00763  *   call _recvfrom_ on a socket after _shutdown_ has been invoked.
00764  * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a  call to
00765  *   _recvfrom_ would block.
00766  * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
00767  *   and was truncated.
00768  * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
00769  *   failure or because the system on the other end went down without
00770  *   notice
00771  * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
00772  *   executing a hard or abortive close. The application should close the
00773  *   socket; it is no longer usable. On a UDP-datagram socket this error
00774  *   indicates a previous send operation resulted in an ICMP Port Unreachable
00775  *   message.
00776  */
00777 static VALUE
00778 sock_recvfrom(int argc, VALUE *argv, VALUE sock)
00779 {
00780     return rsock_s_recvfrom(sock, argc, argv, RECV_SOCKET);
00781 }
00782 
00783 /*
00784  * call-seq:
00785  *   socket.recvfrom_nonblock(maxlen) => [mesg, sender_addrinfo]
00786  *   socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_addrinfo]
00787  *
00788  * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
00789  * O_NONBLOCK is set for the underlying file descriptor.
00790  * _flags_ is zero or more of the +MSG_+ options.
00791  * The first element of the results, _mesg_, is the data received.
00792  * The second element, _sender_addrinfo_, contains protocol-specific address
00793  * information of the sender.
00794  *
00795  * When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns
00796  * an empty string as data.
00797  * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
00798  *
00799  * === Parameters
00800  * * +maxlen+ - the maximum number of bytes to receive from the socket
00801  * * +flags+ - zero or more of the +MSG_+ options
00802  *
00803  * === Example
00804  *      # In one file, start this first
00805  *      require 'socket'
00806  *      include Socket::Constants
00807  *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
00808  *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
00809  *      socket.bind(sockaddr)
00810  *      socket.listen(5)
00811  *      client, client_addrinfo = socket.accept
00812  *      begin # emulate blocking recvfrom
00813  *        pair = client.recvfrom_nonblock(20)
00814  *      rescue IO::WaitReadable
00815  *        IO.select([client])
00816  *        retry
00817  *      end
00818  *      data = pair[0].chomp
00819  *      puts "I only received 20 bytes '#{data}'"
00820  *      sleep 1
00821  *      socket.close
00822  *
00823  *      # In another file, start this second
00824  *      require 'socket'
00825  *      include Socket::Constants
00826  *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
00827  *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
00828  *      socket.connect(sockaddr)
00829  *      socket.puts "Watch this get cut short!"
00830  *      socket.close
00831  *
00832  * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
00833  * to _recvfrom_nonblock_ fails.
00834  *
00835  * Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
00836  * including Errno::EWOULDBLOCK.
00837  *
00838  * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
00839  * it is extended by IO::WaitReadable.
00840  * So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock.
00841  *
00842  * === See
00843  * * Socket#recvfrom
00844  */
00845 static VALUE
00846 sock_recvfrom_nonblock(int argc, VALUE *argv, VALUE sock)
00847 {
00848     return rsock_s_recvfrom_nonblock(sock, argc, argv, RECV_SOCKET);
00849 }
00850 
00851 /*
00852  * call-seq:
00853  *   socket.accept => [client_socket, client_addrinfo]
00854  *
00855  * Accepts a next connection.
00856  * Returns a new Socket object and Addrinfo object.
00857  *
00858  *   serv = Socket.new(:INET, :STREAM, 0)
00859  *   serv.listen(5)
00860  *   c = Socket.new(:INET, :STREAM, 0)
00861  *   c.connect(serv.connect_address)
00862  *   p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>]
00863  *
00864  */
00865 static VALUE
00866 sock_accept(VALUE sock)
00867 {
00868     rb_io_t *fptr;
00869     VALUE sock2;
00870     union_sockaddr buf;
00871     socklen_t len = (socklen_t)sizeof buf;
00872 
00873     GetOpenFile(sock, fptr);
00874     sock2 = rsock_s_accept(rb_cSocket,fptr->fd,&buf.addr,&len);
00875 
00876     return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
00877 }
00878 
00879 /*
00880  * call-seq:
00881  *   socket.accept_nonblock => [client_socket, client_addrinfo]
00882  *
00883  * Accepts an incoming connection using accept(2) after
00884  * O_NONBLOCK is set for the underlying file descriptor.
00885  * It returns an array containing the accepted socket
00886  * for the incoming connection, _client_socket_,
00887  * and an Addrinfo, _client_addrinfo_.
00888  *
00889  * === Example
00890  *      # In one script, start this first
00891  *      require 'socket'
00892  *      include Socket::Constants
00893  *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
00894  *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
00895  *      socket.bind(sockaddr)
00896  *      socket.listen(5)
00897  *      begin # emulate blocking accept
00898  *        client_socket, client_addrinfo = socket.accept_nonblock
00899  *      rescue IO::WaitReadable, Errno::EINTR
00900  *        IO.select([socket])
00901  *        retry
00902  *      end
00903  *      puts "The client said, '#{client_socket.readline.chomp}'"
00904  *      client_socket.puts "Hello from script one!"
00905  *      socket.close
00906  *
00907  *      # In another script, start this second
00908  *      require 'socket'
00909  *      include Socket::Constants
00910  *      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
00911  *      sockaddr = Socket.sockaddr_in(2200, 'localhost')
00912  *      socket.connect(sockaddr)
00913  *      socket.puts "Hello from script 2."
00914  *      puts "The server said, '#{socket.readline.chomp}'"
00915  *      socket.close
00916  *
00917  * Refer to Socket#accept for the exceptions that may be thrown if the call
00918  * to _accept_nonblock_ fails.
00919  *
00920  * Socket#accept_nonblock may raise any error corresponding to accept(2) failure,
00921  * including Errno::EWOULDBLOCK.
00922  *
00923  * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED or Errno::EPROTO,
00924  * it is extended by IO::WaitReadable.
00925  * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
00926  *
00927  * === See
00928  * * Socket#accept
00929  */
00930 static VALUE
00931 sock_accept_nonblock(VALUE sock)
00932 {
00933     rb_io_t *fptr;
00934     VALUE sock2;
00935     union_sockaddr buf;
00936     socklen_t len = (socklen_t)sizeof buf;
00937 
00938     GetOpenFile(sock, fptr);
00939     sock2 = rsock_s_accept_nonblock(rb_cSocket, fptr, &buf.addr, &len);
00940     return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
00941 }
00942 
00943 /*
00944  * call-seq:
00945  *   socket.sysaccept => [client_socket_fd, client_addrinfo]
00946  *
00947  * Accepts an incoming connection returning an array containing the (integer)
00948  * file descriptor for the incoming connection, _client_socket_fd_,
00949  * and an Addrinfo, _client_addrinfo_.
00950  *
00951  * === Example
00952  *      # In one script, start this first
00953  *      require 'socket'
00954  *      include Socket::Constants
00955  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00956  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00957  *      socket.bind( sockaddr )
00958  *      socket.listen( 5 )
00959  *      client_fd, client_addrinfo = socket.sysaccept
00960  *      client_socket = Socket.for_fd( client_fd )
00961  *      puts "The client said, '#{client_socket.readline.chomp}'"
00962  *      client_socket.puts "Hello from script one!"
00963  *      socket.close
00964  *
00965  *      # In another script, start this second
00966  *      require 'socket'
00967  *      include Socket::Constants
00968  *      socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
00969  *      sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
00970  *      socket.connect( sockaddr )
00971  *      socket.puts "Hello from script 2."
00972  *      puts "The server said, '#{socket.readline.chomp}'"
00973  *      socket.close
00974  *
00975  * Refer to Socket#accept for the exceptions that may be thrown if the call
00976  * to _sysaccept_ fails.
00977  *
00978  * === See
00979  * * Socket#accept
00980  */
00981 static VALUE
00982 sock_sysaccept(VALUE sock)
00983 {
00984     rb_io_t *fptr;
00985     VALUE sock2;
00986     union_sockaddr buf;
00987     socklen_t len = (socklen_t)sizeof buf;
00988 
00989     GetOpenFile(sock, fptr);
00990     sock2 = rsock_s_accept(0,fptr->fd,&buf.addr,&len);
00991 
00992     return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
00993 }
00994 
00995 #ifdef HAVE_GETHOSTNAME
00996 /*
00997  * call-seq:
00998  *   Socket.gethostname => hostname
00999  *
01000  * Returns the hostname.
01001  *
01002  *   p Socket.gethostname #=> "hal"
01003  *
01004  * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc.
01005  * If you need local IP address, use Socket.ip_address_list.
01006  */
01007 static VALUE
01008 sock_gethostname(VALUE obj)
01009 {
01010 #ifndef HOST_NAME_MAX
01011 #  define HOST_NAME_MAX 1024
01012 #endif
01013     char buf[HOST_NAME_MAX+1];
01014 
01015     rb_secure(3);
01016     if (gethostname(buf, (int)sizeof buf - 1) < 0)
01017         rb_sys_fail("gethostname(3)");
01018 
01019     buf[sizeof buf - 1] = '\0';
01020     return rb_str_new2(buf);
01021 }
01022 #else
01023 #ifdef HAVE_UNAME
01024 
01025 #include <sys/utsname.h>
01026 
01027 static VALUE
01028 sock_gethostname(VALUE obj)
01029 {
01030     struct utsname un;
01031 
01032     rb_secure(3);
01033     uname(&un);
01034     return rb_str_new2(un.nodename);
01035 }
01036 #else
01037 #define sock_gethostname rb_f_notimplement
01038 #endif
01039 #endif
01040 
01041 static VALUE
01042 make_addrinfo(struct rb_addrinfo *res0, int norevlookup)
01043 {
01044     VALUE base, ary;
01045     struct addrinfo *res;
01046 
01047     if (res0 == NULL) {
01048         rb_raise(rb_eSocket, "host not found");
01049     }
01050     base = rb_ary_new();
01051     for (res = res0->ai; res; res = res->ai_next) {
01052         ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup);
01053         if (res->ai_canonname) {
01054             RARRAY_PTR(ary)[2] = rb_str_new2(res->ai_canonname);
01055         }
01056         rb_ary_push(ary, INT2FIX(res->ai_family));
01057         rb_ary_push(ary, INT2FIX(res->ai_socktype));
01058         rb_ary_push(ary, INT2FIX(res->ai_protocol));
01059         rb_ary_push(base, ary);
01060     }
01061     return base;
01062 }
01063 
01064 static VALUE
01065 sock_sockaddr(struct sockaddr *addr, socklen_t len)
01066 {
01067     char *ptr;
01068 
01069     switch (addr->sa_family) {
01070       case AF_INET:
01071         ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr;
01072         len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr);
01073         break;
01074 #ifdef AF_INET6
01075       case AF_INET6:
01076         ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr;
01077         len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr);
01078         break;
01079 #endif
01080       default:
01081         rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family);
01082         break;
01083     }
01084     return rb_str_new(ptr, len);
01085 }
01086 
01087 /*
01088  * call-seq:
01089  *   Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
01090  *
01091  * Obtains the host information for _hostname_.
01092  *
01093  *   p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"]
01094  *
01095  */
01096 static VALUE
01097 sock_s_gethostbyname(VALUE obj, VALUE host)
01098 {
01099     rb_secure(3);
01100     return rsock_make_hostent(host, rsock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), sock_sockaddr);
01101 }
01102 
01103 /*
01104  * call-seq:
01105  *   Socket.gethostbyaddr(address_string [, address_family]) => hostent
01106  *
01107  * Obtains the host information for _address_.
01108  *
01109  *   p Socket.gethostbyaddr([221,186,184,68].pack("CCCC"))
01110  *   #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"]
01111  */
01112 static VALUE
01113 sock_s_gethostbyaddr(int argc, VALUE *argv)
01114 {
01115     VALUE addr, family;
01116     struct hostent *h;
01117     char **pch;
01118     VALUE ary, names;
01119     int t = AF_INET;
01120 
01121     rb_scan_args(argc, argv, "11", &addr, &family);
01122     StringValue(addr);
01123     if (!NIL_P(family)) {
01124         t = rsock_family_arg(family);
01125     }
01126 #ifdef AF_INET6
01127     else if (RSTRING_LEN(addr) == 16) {
01128         t = AF_INET6;
01129     }
01130 #endif
01131     h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), t);
01132     if (h == NULL) {
01133 #ifdef HAVE_HSTRERROR
01134         extern int h_errno;
01135         rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno));
01136 #else
01137         rb_raise(rb_eSocket, "host not found");
01138 #endif
01139     }
01140     ary = rb_ary_new();
01141     rb_ary_push(ary, rb_str_new2(h->h_name));
01142     names = rb_ary_new();
01143     rb_ary_push(ary, names);
01144     if (h->h_aliases != NULL) {
01145         for (pch = h->h_aliases; *pch; pch++) {
01146             rb_ary_push(names, rb_str_new2(*pch));
01147         }
01148     }
01149     rb_ary_push(ary, INT2NUM(h->h_addrtype));
01150 #ifdef h_addr
01151     for (pch = h->h_addr_list; *pch; pch++) {
01152         rb_ary_push(ary, rb_str_new(*pch, h->h_length));
01153     }
01154 #else
01155     rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length));
01156 #endif
01157 
01158     return ary;
01159 }
01160 
01161 /*
01162  * call-seq:
01163  *   Socket.getservbyname(service_name)                => port_number
01164  *   Socket.getservbyname(service_name, protocol_name) => port_number
01165  *
01166  * Obtains the port number for _service_name_.
01167  *
01168  * If _protocol_name_ is not given, "tcp" is assumed.
01169  *
01170  *   Socket.getservbyname("smtp")          #=> 25
01171  *   Socket.getservbyname("shell")         #=> 514
01172  *   Socket.getservbyname("syslog", "udp") #=> 514
01173  */
01174 static VALUE
01175 sock_s_getservbyname(int argc, VALUE *argv)
01176 {
01177     VALUE service, proto;
01178     struct servent *sp;
01179     long port;
01180     const char *servicename, *protoname = "tcp";
01181 
01182     rb_scan_args(argc, argv, "11", &service, &proto);
01183     StringValue(service);
01184     if (!NIL_P(proto)) StringValue(proto);
01185     servicename = StringValueCStr(service);
01186     if (!NIL_P(proto)) protoname = StringValueCStr(proto);
01187     sp = getservbyname(servicename, protoname);
01188     if (sp) {
01189         port = ntohs(sp->s_port);
01190     }
01191     else {
01192         char *end;
01193 
01194         port = STRTOUL(servicename, &end, 0);
01195         if (*end != '\0') {
01196             rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname);
01197         }
01198     }
01199     return INT2FIX(port);
01200 }
01201 
01202 /*
01203  * call-seq:
01204  *   Socket.getservbyport(port [, protocol_name]) => service
01205  *
01206  * Obtains the port number for _port_.
01207  *
01208  * If _protocol_name_ is not given, "tcp" is assumed.
01209  *
01210  *   Socket.getservbyport(80)         #=> "www"
01211  *   Socket.getservbyport(514, "tcp") #=> "shell"
01212  *   Socket.getservbyport(514, "udp") #=> "syslog"
01213  *
01214  */
01215 static VALUE
01216 sock_s_getservbyport(int argc, VALUE *argv)
01217 {
01218     VALUE port, proto;
01219     struct servent *sp;
01220     long portnum;
01221     const char *protoname = "tcp";
01222 
01223     rb_scan_args(argc, argv, "11", &port, &proto);
01224     portnum = NUM2LONG(port);
01225     if (portnum != (uint16_t)portnum) {
01226         const char *s = portnum > 0 ? "big" : "small";
01227         rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s);
01228     }
01229     if (!NIL_P(proto)) protoname = StringValueCStr(proto);
01230 
01231     sp = getservbyport((int)htons((uint16_t)portnum), protoname);
01232     if (!sp) {
01233         rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname);
01234     }
01235     return rb_tainted_str_new2(sp->s_name);
01236 }
01237 
01238 /*
01239  * call-seq:
01240  *   Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array
01241  *
01242  * Obtains address information for _nodename_:_servname_.
01243  *
01244  * _family_ should be an address family such as: :INET, :INET6, :UNIX, etc.
01245  *
01246  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
01247  *
01248  * _protocol_ should be a protocol defined in the family,
01249  * and defaults to 0 for the family.
01250  *
01251  * _flags_ should be bitwise OR of Socket::AI_* constants.
01252  *
01253  *   Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM)
01254  *   #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP
01255  *
01256  *   Socket.getaddrinfo("localhost", nil)
01257  *   #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6],  # PF_INET/SOCK_STREAM/IPPROTO_TCP
01258  *   #    ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP
01259  *   #    ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]]  # PF_INET/SOCK_RAW/IPPROTO_IP
01260  *
01261  * _reverse_lookup_ directs the form of the third element, and has to
01262  * be one of below.  If _reverse_lookup_ is omitted, the default value is +nil+.
01263  *
01264  *   +true+, +:hostname+:  hostname is obtained from numeric address using reverse lookup, which may take a time.
01265  *   +false+, +:numeric+:  hostname is same as numeric address.
01266  *   +nil+:              obey to the current +do_not_reverse_lookup+ flag.
01267  *
01268  * If Addrinfo object is preferred, use Addrinfo.getaddrinfo.
01269  */
01270 static VALUE
01271 sock_s_getaddrinfo(int argc, VALUE *argv)
01272 {
01273     VALUE host, port, family, socktype, protocol, flags, ret, revlookup;
01274     struct addrinfo hints;
01275     struct rb_addrinfo *res;
01276     int norevlookup;
01277 
01278     rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup);
01279 
01280     MEMZERO(&hints, struct addrinfo, 1);
01281     hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
01282 
01283     if (!NIL_P(socktype)) {
01284         hints.ai_socktype = rsock_socktype_arg(socktype);
01285     }
01286     if (!NIL_P(protocol)) {
01287         hints.ai_protocol = NUM2INT(protocol);
01288     }
01289     if (!NIL_P(flags)) {
01290         hints.ai_flags = NUM2INT(flags);
01291     }
01292     if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) {
01293         norevlookup = rsock_do_not_reverse_lookup;
01294     }
01295     res = rsock_getaddrinfo(host, port, &hints, 0);
01296 
01297     ret = make_addrinfo(res, norevlookup);
01298     rb_freeaddrinfo(res);
01299     return ret;
01300 }
01301 
01302 /*
01303  * call-seq:
01304  *   Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename]
01305  *
01306  * Obtains name information for _sockaddr_.
01307  *
01308  * _sockaddr_ should be one of follows.
01309  * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1")
01310  * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"]
01311  * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"]
01312  *
01313  * _flags_ should be bitwise OR of Socket::NI_* constants.
01314  *
01315  * Note:
01316  * The last form is compatible with IPSocket#addr and IPSocket#peeraddr.
01317  *
01318  *   Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1"))       #=> ["localhost", "www"]
01319  *   Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"])              #=> ["localhost", "www"]
01320  *   Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"]
01321  *
01322  * If Addrinfo object is preferred, use Addrinfo#getnameinfo.
01323  */
01324 static VALUE
01325 sock_s_getnameinfo(int argc, VALUE *argv)
01326 {
01327     VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
01328     char *hptr, *pptr;
01329     char hbuf[1024], pbuf[1024];
01330     int fl;
01331     struct rb_addrinfo *res = NULL;
01332     struct addrinfo hints, *r;
01333     int error, saved_errno;
01334     union_sockaddr ss;
01335     struct sockaddr *sap;
01336     socklen_t salen;
01337 
01338     sa = flags = Qnil;
01339     rb_scan_args(argc, argv, "11", &sa, &flags);
01340 
01341     fl = 0;
01342     if (!NIL_P(flags)) {
01343         fl = NUM2INT(flags);
01344     }
01345     tmp = rb_check_sockaddr_string_type(sa);
01346     if (!NIL_P(tmp)) {
01347         sa = tmp;
01348         if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
01349             rb_raise(rb_eTypeError, "sockaddr length too big");
01350         }
01351         memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
01352         if (!VALIDATE_SOCKLEN(&ss.addr, RSTRING_LEN(sa))) {
01353             rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
01354         }
01355         sap = &ss.addr;
01356         salen = RSTRING_SOCKLEN(sa);
01357         goto call_nameinfo;
01358     }
01359     tmp = rb_check_array_type(sa);
01360     if (!NIL_P(tmp)) {
01361         sa = tmp;
01362         MEMZERO(&hints, struct addrinfo, 1);
01363         if (RARRAY_LEN(sa) == 3) {
01364             af = RARRAY_PTR(sa)[0];
01365             port = RARRAY_PTR(sa)[1];
01366             host = RARRAY_PTR(sa)[2];
01367         }
01368         else if (RARRAY_LEN(sa) >= 4) {
01369             af = RARRAY_PTR(sa)[0];
01370             port = RARRAY_PTR(sa)[1];
01371             host = RARRAY_PTR(sa)[3];
01372             if (NIL_P(host)) {
01373                 host = RARRAY_PTR(sa)[2];
01374             }
01375             else {
01376                 /*
01377                  * 4th element holds numeric form, don't resolve.
01378                  * see rsock_ipaddr().
01379                  */
01380 #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
01381                 hints.ai_flags |= AI_NUMERICHOST;
01382 #endif
01383             }
01384         }
01385         else {
01386             rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
01387                      RARRAY_LEN(sa));
01388         }
01389         /* host */
01390         if (NIL_P(host)) {
01391             hptr = NULL;
01392         }
01393         else {
01394             strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
01395             hbuf[sizeof(hbuf) - 1] = '\0';
01396             hptr = hbuf;
01397         }
01398         /* port */
01399         if (NIL_P(port)) {
01400             strcpy(pbuf, "0");
01401             pptr = NULL;
01402         }
01403         else if (FIXNUM_P(port)) {
01404             snprintf(pbuf, sizeof(pbuf), "%ld", NUM2LONG(port));
01405             pptr = pbuf;
01406         }
01407         else {
01408             strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
01409             pbuf[sizeof(pbuf) - 1] = '\0';
01410             pptr = pbuf;
01411         }
01412         hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
01413         /* af */
01414         hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af);
01415         error = rb_getaddrinfo(hptr, pptr, &hints, &res);
01416         if (error) goto error_exit_addr;
01417         sap = res->ai->ai_addr;
01418         salen = res->ai->ai_addrlen;
01419     }
01420     else {
01421         rb_raise(rb_eTypeError, "expecting String or Array");
01422     }
01423 
01424   call_nameinfo:
01425     error = rb_getnameinfo(sap, salen, hbuf, sizeof(hbuf),
01426                            pbuf, sizeof(pbuf), fl);
01427     if (error) goto error_exit_name;
01428     if (res) {
01429         for (r = res->ai->ai_next; r; r = r->ai_next) {
01430             char hbuf2[1024], pbuf2[1024];
01431 
01432             sap = r->ai_addr;
01433             salen = r->ai_addrlen;
01434             error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2),
01435                                    pbuf2, sizeof(pbuf2), fl);
01436             if (error) goto error_exit_name;
01437             if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
01438                 rb_freeaddrinfo(res);
01439                 rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
01440             }
01441         }
01442         rb_freeaddrinfo(res);
01443     }
01444     return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
01445 
01446   error_exit_addr:
01447     saved_errno = errno;
01448     if (res) rb_freeaddrinfo(res);
01449     errno = saved_errno;
01450     rsock_raise_socket_error("getaddrinfo", error);
01451 
01452   error_exit_name:
01453     saved_errno = errno;
01454     if (res) rb_freeaddrinfo(res);
01455     errno = saved_errno;
01456     rsock_raise_socket_error("getnameinfo", error);
01457 
01458     UNREACHABLE;
01459 }
01460 
01461 /*
01462  * call-seq:
01463  *   Socket.sockaddr_in(port, host)      => sockaddr
01464  *   Socket.pack_sockaddr_in(port, host) => sockaddr
01465  *
01466  * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string.
01467  *
01468  *   Socket.sockaddr_in(80, "127.0.0.1")
01469  *   #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
01470  *
01471  *   Socket.sockaddr_in(80, "::1")
01472  *   #=> "\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"
01473  *
01474  */
01475 static VALUE
01476 sock_s_pack_sockaddr_in(VALUE self, VALUE port, VALUE host)
01477 {
01478     struct rb_addrinfo *res = rsock_addrinfo(host, port, 0, 0);
01479     VALUE addr = rb_str_new((char*)res->ai->ai_addr, res->ai->ai_addrlen);
01480 
01481     rb_freeaddrinfo(res);
01482     OBJ_INFECT(addr, port);
01483     OBJ_INFECT(addr, host);
01484 
01485     return addr;
01486 }
01487 
01488 /*
01489  * call-seq:
01490  *   Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address]
01491  *
01492  * Unpacks _sockaddr_ into port and ip_address.
01493  *
01494  * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6.
01495  *
01496  *   sockaddr = Socket.sockaddr_in(80, "127.0.0.1")
01497  *   p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
01498  *   p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"]
01499  *
01500  */
01501 static VALUE
01502 sock_s_unpack_sockaddr_in(VALUE self, VALUE addr)
01503 {
01504     struct sockaddr_in * sockaddr;
01505     VALUE host;
01506 
01507     sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr);
01508     if (RSTRING_LEN(addr) <
01509         (char*)&((struct sockaddr *)sockaddr)->sa_family +
01510         sizeof(((struct sockaddr *)sockaddr)->sa_family) -
01511         (char*)sockaddr)
01512         rb_raise(rb_eArgError, "too short sockaddr");
01513     if (((struct sockaddr *)sockaddr)->sa_family != AF_INET
01514 #ifdef INET6
01515         && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6
01516 #endif
01517         ) {
01518 #ifdef INET6
01519         rb_raise(rb_eArgError, "not an AF_INET/AF_INET6 sockaddr");
01520 #else
01521         rb_raise(rb_eArgError, "not an AF_INET sockaddr");
01522 #endif
01523     }
01524     host = rsock_make_ipaddr((struct sockaddr*)sockaddr, RSTRING_SOCKLEN(addr));
01525     OBJ_INFECT(host, addr);
01526     return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host);
01527 }
01528 
01529 #ifdef HAVE_SYS_UN_H
01530 
01531 /*
01532  * call-seq:
01533  *   Socket.sockaddr_un(path)      => sockaddr
01534  *   Socket.pack_sockaddr_un(path) => sockaddr
01535  *
01536  * Packs _path_ as an AF_UNIX sockaddr string.
01537  *
01538  *   Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..."
01539  *
01540  */
01541 static VALUE
01542 sock_s_pack_sockaddr_un(VALUE self, VALUE path)
01543 {
01544     struct sockaddr_un sockaddr;
01545     VALUE addr;
01546 
01547     StringValue(path);
01548     INIT_SOCKADDR_UN(&sockaddr, sizeof(struct sockaddr_un));
01549     if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
01550         rb_raise(rb_eArgError, "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
01551             (size_t)RSTRING_LEN(path), sizeof(sockaddr.sun_path));
01552     }
01553     memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
01554     addr = rb_str_new((char*)&sockaddr, rsock_unix_sockaddr_len(path));
01555     OBJ_INFECT(addr, path);
01556 
01557     return addr;
01558 }
01559 
01560 /*
01561  * call-seq:
01562  *   Socket.unpack_sockaddr_un(sockaddr) => path
01563  *
01564  * Unpacks _sockaddr_ into path.
01565  *
01566  * _sockaddr_ should be a string or an addrinfo for AF_UNIX.
01567  *
01568  *   sockaddr = Socket.sockaddr_un("/tmp/sock")
01569  *   p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock"
01570  *
01571  */
01572 static VALUE
01573 sock_s_unpack_sockaddr_un(VALUE self, VALUE addr)
01574 {
01575     struct sockaddr_un * sockaddr;
01576     VALUE path;
01577 
01578     sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr);
01579     if (RSTRING_LEN(addr) <
01580         (char*)&((struct sockaddr *)sockaddr)->sa_family +
01581         sizeof(((struct sockaddr *)sockaddr)->sa_family) -
01582         (char*)sockaddr)
01583         rb_raise(rb_eArgError, "too short sockaddr");
01584     if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) {
01585         rb_raise(rb_eArgError, "not an AF_UNIX sockaddr");
01586     }
01587     if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) {
01588         rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d",
01589                  RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un));
01590     }
01591     path = rsock_unixpath_str(sockaddr, RSTRING_SOCKLEN(addr));
01592     OBJ_INFECT(path, addr);
01593     return path;
01594 }
01595 #endif
01596 
01597 #if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32)
01598 
01599 static socklen_t
01600 sockaddr_len(struct sockaddr *addr)
01601 {
01602     if (addr == NULL)
01603         return 0;
01604 
01605 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
01606     if (addr->sa_len != 0)
01607         return addr->sa_len;
01608 #endif
01609 
01610     switch (addr->sa_family) {
01611       case AF_INET:
01612         return (socklen_t)sizeof(struct sockaddr_in);
01613 
01614 #ifdef AF_INET6
01615       case AF_INET6:
01616         return (socklen_t)sizeof(struct sockaddr_in6);
01617 #endif
01618 
01619 #ifdef HAVE_SYS_UN_H
01620       case AF_UNIX:
01621         return (socklen_t)sizeof(struct sockaddr_un);
01622 #endif
01623 
01624 #ifdef AF_PACKET
01625       case AF_PACKET:
01626         return (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + ((struct sockaddr_ll *)addr)->sll_halen);
01627 #endif
01628 
01629       default:
01630         return (socklen_t)(offsetof(struct sockaddr, sa_family) + sizeof(addr->sa_family));
01631     }
01632 }
01633 
01634 socklen_t
01635 rsock_sockaddr_len(struct sockaddr *addr)
01636 {
01637     return sockaddr_len(addr);
01638 }
01639 
01640 static VALUE
01641 sockaddr_obj(struct sockaddr *addr, socklen_t len)
01642 {
01643 #if defined(AF_INET6) && defined(__KAME__)
01644     struct sockaddr_in6 addr6;
01645 #endif
01646 
01647     if (addr == NULL)
01648         return Qnil;
01649 
01650     len = sockaddr_len(addr);
01651 
01652 #if defined(__KAME__) && defined(AF_INET6)
01653     if (addr->sa_family == AF_INET6) {
01654         /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */
01655         /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */
01656         /* convert fe80:1::1 to fe80::1%1 */
01657         len = (socklen_t)sizeof(struct sockaddr_in6);
01658         memcpy(&addr6, addr, len);
01659         addr = (struct sockaddr *)&addr6;
01660         if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
01661             addr6.sin6_scope_id == 0 &&
01662             (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) {
01663             addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3];
01664             addr6.sin6_addr.s6_addr[2] = 0;
01665             addr6.sin6_addr.s6_addr[3] = 0;
01666         }
01667     }
01668 #endif
01669 
01670     return rsock_addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil);
01671 }
01672 
01673 VALUE
01674 rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
01675 {
01676     return sockaddr_obj(addr, len);
01677 }
01678 
01679 #endif
01680 
01681 #if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) ||  defined(_WIN32)
01682 /*
01683  * call-seq:
01684  *   Socket.ip_address_list => array
01685  *
01686  * Returns local IP addresses as an array.
01687  *
01688  * The array contains Addrinfo objects.
01689  *
01690  *  pp Socket.ip_address_list
01691  *  #=> [#<Addrinfo: 127.0.0.1>,
01692  *       #<Addrinfo: 192.168.0.128>,
01693  *       #<Addrinfo: ::1>,
01694  *       ...]
01695  *
01696  */
01697 static VALUE
01698 socket_s_ip_address_list(VALUE self)
01699 {
01700 #if defined(HAVE_GETIFADDRS)
01701     struct ifaddrs *ifp = NULL;
01702     struct ifaddrs *p;
01703     int ret;
01704     VALUE list;
01705 
01706     ret = getifaddrs(&ifp);
01707     if (ret == -1) {
01708         rb_sys_fail("getifaddrs");
01709     }
01710 
01711     list = rb_ary_new();
01712     for (p = ifp; p; p = p->ifa_next) {
01713         if (p->ifa_addr != NULL && IS_IP_FAMILY(p->ifa_addr->sa_family)) {
01714             struct sockaddr *addr = p->ifa_addr;
01715 #if defined(AF_INET6) && defined(__sun)
01716             /*
01717              * OpenIndiana SunOS 5.11 getifaddrs() returns IPv6 link local
01718              * address with sin6_scope_id == 0.
01719              * So fill it from the interface name (ifa_name).
01720              */
01721             struct sockaddr_in6 addr6;
01722             if (addr->sa_family == AF_INET6) {
01723                 socklen_t len = (socklen_t)sizeof(struct sockaddr_in6);
01724                 memcpy(&addr6, addr, len);
01725                 addr = (struct sockaddr *)&addr6;
01726                 if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
01727                     addr6.sin6_scope_id == 0) {
01728                     unsigned int ifindex = if_nametoindex(p->ifa_name);
01729                     if (ifindex != 0) {
01730                         addr6.sin6_scope_id = ifindex;
01731                     }
01732                 }
01733             }
01734 #endif
01735             rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
01736         }
01737     }
01738 
01739     freeifaddrs(ifp);
01740 
01741     return list;
01742 #elif defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)
01743     /* Solaris if_tcp(7P) */
01744     /* HP-UX has SIOCGLIFCONF too.  But it uses different struct */
01745     int fd = -1;
01746     int ret;
01747     struct lifnum ln;
01748     struct lifconf lc;
01749     char *reason = NULL;
01750     int save_errno;
01751     int i;
01752     VALUE list = Qnil;
01753 
01754     lc.lifc_buf = NULL;
01755 
01756     fd = socket(AF_INET, SOCK_DGRAM, 0);
01757     if (fd == -1)
01758         rb_sys_fail("socket(2)");
01759 
01760     memset(&ln, 0, sizeof(ln));
01761     ln.lifn_family = AF_UNSPEC;
01762 
01763     ret = ioctl(fd, SIOCGLIFNUM, &ln);
01764     if (ret == -1) {
01765         reason = "SIOCGLIFNUM";
01766         goto finish;
01767     }
01768 
01769     memset(&lc, 0, sizeof(lc));
01770     lc.lifc_family = AF_UNSPEC;
01771     lc.lifc_flags = 0;
01772     lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count;
01773     lc.lifc_req = xmalloc(lc.lifc_len);
01774 
01775     ret = ioctl(fd, SIOCGLIFCONF, &lc);
01776     if (ret == -1) {
01777         reason = "SIOCGLIFCONF";
01778         goto finish;
01779     }
01780 
01781     list = rb_ary_new();
01782     for (i = 0; i < ln.lifn_count; i++) {
01783         struct lifreq *req = &lc.lifc_req[i];
01784         if (IS_IP_FAMILY(req->lifr_addr.ss_family)) {
01785             if (req->lifr_addr.ss_family == AF_INET6 &&
01786                 IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) &&
01787                 ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id == 0) {
01788                 struct lifreq req2;
01789                 memcpy(req2.lifr_name, req->lifr_name, LIFNAMSIZ);
01790                 ret = ioctl(fd, SIOCGLIFINDEX, &req2);
01791                 if (ret == -1) {
01792                     reason = "SIOCGLIFINDEX";
01793                     goto finish;
01794                 }
01795                 ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id = req2.lifr_index;
01796             }
01797             rb_ary_push(list, sockaddr_obj((struct sockaddr *)&req->lifr_addr, req->lifr_addrlen));
01798         }
01799     }
01800 
01801   finish:
01802     save_errno = errno;
01803     if (lc.lifc_buf != NULL)
01804         xfree(lc.lifc_req);
01805     if (fd != -1)
01806         close(fd);
01807     errno = save_errno;
01808 
01809     if (reason)
01810         rb_sys_fail(reason);
01811     return list;
01812 
01813 #elif defined(SIOCGIFCONF)
01814     int fd = -1;
01815     int ret;
01816 #define EXTRA_SPACE ((int)(sizeof(struct ifconf) + sizeof(union_sockaddr)))
01817     char initbuf[4096+EXTRA_SPACE];
01818     char *buf = initbuf;
01819     int bufsize;
01820     struct ifconf conf;
01821     struct ifreq *req;
01822     VALUE list = Qnil;
01823     const char *reason = NULL;
01824     int save_errno;
01825 
01826     fd = socket(AF_INET, SOCK_DGRAM, 0);
01827     if (fd == -1)
01828         rb_sys_fail("socket(2)");
01829 
01830     bufsize = sizeof(initbuf);
01831     buf = initbuf;
01832 
01833   retry:
01834     conf.ifc_len = bufsize;
01835     conf.ifc_req = (struct ifreq *)buf;
01836 
01837     /* fprintf(stderr, "bufsize: %d\n", bufsize); */
01838 
01839     ret = ioctl(fd, SIOCGIFCONF, &conf);
01840     if (ret == -1) {
01841         reason = "SIOCGIFCONF";
01842         goto finish;
01843     }
01844 
01845     /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */
01846 
01847     if (bufsize - EXTRA_SPACE < conf.ifc_len) {
01848         if (bufsize < conf.ifc_len) {
01849             /* NetBSD returns required size for all interfaces. */
01850             bufsize = conf.ifc_len + EXTRA_SPACE;
01851         }
01852         else {
01853             bufsize = bufsize << 1;
01854         }
01855         if (buf == initbuf)
01856             buf = NULL;
01857         buf = xrealloc(buf, bufsize);
01858         goto retry;
01859     }
01860 
01861     close(fd);
01862     fd = -1;
01863 
01864     list = rb_ary_new();
01865     req = conf.ifc_req;
01866     while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) {
01867         struct sockaddr *addr = &req->ifr_addr;
01868         if (IS_IP_FAMILY(addr->sa_family)) {
01869             rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
01870         }
01871 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
01872 # ifndef _SIZEOF_ADDR_IFREQ
01873 #  define _SIZEOF_ADDR_IFREQ(r) \
01874           (sizeof(struct ifreq) + \
01875            (sizeof(struct sockaddr) < (r).ifr_addr.sa_len ? \
01876             (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \
01877             0))
01878 # endif
01879         req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req));
01880 #else
01881         req = (struct ifreq *)((char*)req + sizeof(struct ifreq));
01882 #endif
01883     }
01884 
01885   finish:
01886 
01887     save_errno = errno;
01888     if (buf != initbuf)
01889         xfree(buf);
01890     if (fd != -1)
01891         close(fd);
01892     errno = save_errno;
01893 
01894     if (reason)
01895         rb_sys_fail(reason);
01896     return list;
01897 
01898 #undef EXTRA_SPACE
01899 #elif defined(_WIN32)
01900     typedef struct ip_adapter_unicast_address_st {
01901         unsigned LONG_LONG dummy0;
01902         struct ip_adapter_unicast_address_st *Next;
01903         struct {
01904             struct sockaddr *lpSockaddr;
01905             int iSockaddrLength;
01906         } Address;
01907         int dummy1;
01908         int dummy2;
01909         int dummy3;
01910         long dummy4;
01911         long dummy5;
01912         long dummy6;
01913     } ip_adapter_unicast_address_t;
01914     typedef struct ip_adapter_anycast_address_st {
01915         unsigned LONG_LONG dummy0;
01916         struct ip_adapter_anycast_address_st *Next;
01917         struct {
01918             struct sockaddr *lpSockaddr;
01919             int iSockaddrLength;
01920         } Address;
01921     } ip_adapter_anycast_address_t;
01922     typedef struct ip_adapter_addresses_st {
01923         unsigned LONG_LONG dummy0;
01924         struct ip_adapter_addresses_st *Next;
01925         void *dummy1;
01926         ip_adapter_unicast_address_t *FirstUnicastAddress;
01927         ip_adapter_anycast_address_t *FirstAnycastAddress;
01928         void *dummy2;
01929         void *dummy3;
01930         void *dummy4;
01931         void *dummy5;
01932         void *dummy6;
01933         BYTE dummy7[8];
01934         DWORD dummy8;
01935         DWORD dummy9;
01936         DWORD dummy10;
01937         DWORD IfType;
01938         int OperStatus;
01939         DWORD dummy12;
01940         DWORD dummy13[16];
01941         void *dummy14;
01942     } ip_adapter_addresses_t;
01943     typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG);
01944     HMODULE h;
01945     GetAdaptersAddresses_t pGetAdaptersAddresses;
01946     ULONG len;
01947     DWORD ret;
01948     ip_adapter_addresses_t *adapters;
01949     VALUE list;
01950 
01951     h = LoadLibrary("iphlpapi.dll");
01952     if (!h)
01953         rb_notimplement();
01954     pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses");
01955     if (!pGetAdaptersAddresses) {
01956         FreeLibrary(h);
01957         rb_notimplement();
01958     }
01959 
01960     ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len);
01961     if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) {
01962         errno = rb_w32_map_errno(ret);
01963         FreeLibrary(h);
01964         rb_sys_fail("GetAdaptersAddresses");
01965     }
01966     adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len);
01967     ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len);
01968     if (ret != ERROR_SUCCESS) {
01969         errno = rb_w32_map_errno(ret);
01970         FreeLibrary(h);
01971         rb_sys_fail("GetAdaptersAddresses");
01972     }
01973 
01974     list = rb_ary_new();
01975     for (; adapters; adapters = adapters->Next) {
01976         ip_adapter_unicast_address_t *uni;
01977         ip_adapter_anycast_address_t *any;
01978         if (adapters->OperStatus != 1)  /* 1 means IfOperStatusUp */
01979             continue;
01980         for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) {
01981 #ifndef INET6
01982             if (uni->Address.lpSockaddr->sa_family == AF_INET)
01983 #else
01984             if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family))
01985 #endif
01986                 rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr, uni->Address.iSockaddrLength));
01987         }
01988         for (any = adapters->FirstAnycastAddress; any; any = any->Next) {
01989 #ifndef INET6
01990             if (any->Address.lpSockaddr->sa_family == AF_INET)
01991 #else
01992             if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family))
01993 #endif
01994                 rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr, any->Address.iSockaddrLength));
01995         }
01996     }
01997 
01998     FreeLibrary(h);
01999     return list;
02000 #endif
02001 }
02002 #else
02003 #define socket_s_ip_address_list rb_f_notimplement
02004 #endif
02005 
02006 void
02007 Init_socket()
02008 {
02009     rsock_init_basicsocket();
02010 
02011     /*
02012      * Document-class: Socket < BasicSocket
02013      *
02014      * Class +Socket+ provides access to the underlying operating system
02015      * socket implementations.  It can be used to provide more operating system
02016      * specific functionality than the protocol-specific socket classes.
02017      *
02018      * The constants defined under Socket::Constants are also defined under
02019      * Socket.  For example, Socket::AF_INET is usable as well as
02020      * Socket::Constants::AF_INET.  See Socket::Constants for the list of
02021      * constants.
02022      *
02023      * === What's a socket?
02024      *
02025      * Sockets are endpoints of a bidirectionnal communication channel.
02026      * Sockets can communicate within a process, between processes on the same
02027      * machine or between different machines.  There are many types of socket:
02028      * TCPSocket, UDPSocket or UNIXSocket for example.
02029      *
02030      * Sockets have their own vocabulary:
02031      *
02032      * *domain:*
02033      * The family of protocols:
02034      * *    Socket::PF_INET
02035      * *    Socket::PF_INET6
02036      * *    Socket::PF_UNIX
02037      * *    etc.
02038      *
02039      * *type:*
02040      * The type of communications between the two endpoints, typically
02041      * *    Socket::SOCK_STREAM
02042      * *    Socket::SOCK_DGRAM.
02043      *
02044      * *protocol:*
02045      * Typically _zero_.
02046      * This may be used to identify a variant of a protocol.
02047      *
02048      * *hostname:*
02049      * The identifier of a network interface:
02050      * *    a string (hostname, IPv4 or IPv6 adress or +broadcast+
02051      *      which specifies a broadcast address)
02052      * *    a zero-length string which specifies INADDR_ANY
02053      * *    an integer (interpreted as binary address in host byte order).
02054      *
02055      * === Quick start
02056      *
02057      * Many of the classes, such as TCPSocket, UDPSocket or UNIXSocket,
02058      * ease the use of sockets comparatively to the equivalent C programming interface.
02059      *
02060      * Let's create an internet socket using the IPv4 protocol in a C-like manner:
02061      *
02062      *   s = Socket.new Socket::AF_INET, Socket::SOCK_STREAM
02063      *   s.connect Socket.pack_sockaddr_in(80, 'example.com')
02064      *
02065      * You could also use the TCPSocket class:
02066      *
02067      *   s = TCPSocket.new 'example.com', 80
02068      *
02069      * A simple server might look like this:
02070      *
02071      *   require 'socket'
02072      *
02073      *   server = TCPServer.new 2000 # Server bound to port 2000
02074      *
02075      *   loop do
02076      *     client = server.accept    # Wait for a client to connect
02077      *     client.puts "Hello !"
02078      *     client.puts "Time is #{Time.now}"
02079      *     client.close
02080      *   end
02081      *
02082      * A simple client may look like this:
02083      *
02084      *   require 'socket'
02085      *
02086      *   s = TCPSocket.new 'localhost', 2000
02087      *
02088      *   while line = s.gets # Read lines from socket
02089      *     puts line         # and print them
02090      *   end
02091      *
02092      *   s.close             # close socket when done
02093      *
02094      * === Exception Handling
02095      *
02096      * Ruby's Socket implementation raises exceptions based on the error
02097      * generated by the system dependent implementation.  This is why the
02098      * methods are documented in a way that isolate Unix-based system
02099      * exceptions from Windows based exceptions. If more information on a
02100      * particular exception is needed, please refer to the Unix manual pages or
02101      * the Windows WinSock reference.
02102      *
02103      * === Convenience methods
02104      *
02105      * Although the general way to create socket is Socket.new,
02106      * there are several methods of socket creation for most cases.
02107      *
02108      * TCP client socket::
02109      *   Socket.tcp, TCPSocket.open
02110      * TCP server socket::
02111      *   Socket.tcp_server_loop, TCPServer.open
02112      * UNIX client socket::
02113      *   Socket.unix, UNIXSocket.open
02114      * UNIX server socket::
02115      *   Socket.unix_server_loop, UNIXServer.open
02116      *
02117      * === Documentation by
02118      *
02119      * * Zach Dennis
02120      * * Sam Roberts
02121      * * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
02122      *
02123      * Much material in this documentation is taken with permission from
02124      * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
02125      */
02126     rb_cSocket = rb_define_class("Socket", rb_cBasicSocket);
02127 
02128     rsock_init_socket_init();
02129 
02130     rb_define_method(rb_cSocket, "initialize", sock_initialize, -1);
02131     rb_define_method(rb_cSocket, "connect", sock_connect, 1);
02132     rb_define_method(rb_cSocket, "connect_nonblock", sock_connect_nonblock, 1);
02133     rb_define_method(rb_cSocket, "bind", sock_bind, 1);
02134     rb_define_method(rb_cSocket, "listen", rsock_sock_listen, 1);
02135     rb_define_method(rb_cSocket, "accept", sock_accept, 0);
02136     rb_define_method(rb_cSocket, "accept_nonblock", sock_accept_nonblock, 0);
02137     rb_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0);
02138 
02139     rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1);
02140     rb_define_method(rb_cSocket, "recvfrom_nonblock", sock_recvfrom_nonblock, -1);
02141 
02142     rb_define_singleton_method(rb_cSocket, "socketpair", rsock_sock_s_socketpair, -1);
02143     rb_define_singleton_method(rb_cSocket, "pair", rsock_sock_s_socketpair, -1);
02144     rb_define_singleton_method(rb_cSocket, "gethostname", sock_gethostname, 0);
02145     rb_define_singleton_method(rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1);
02146     rb_define_singleton_method(rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1);
02147     rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyname, -1);
02148     rb_define_singleton_method(rb_cSocket, "getservbyport", sock_s_getservbyport, -1);
02149     rb_define_singleton_method(rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1);
02150     rb_define_singleton_method(rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1);
02151     rb_define_singleton_method(rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2);
02152     rb_define_singleton_method(rb_cSocket, "pack_sockaddr_in", sock_s_pack_sockaddr_in, 2);
02153     rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_in", sock_s_unpack_sockaddr_in, 1);
02154 #ifdef HAVE_SYS_UN_H
02155     rb_define_singleton_method(rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1);
02156     rb_define_singleton_method(rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1);
02157     rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1);
02158 #endif
02159 
02160     rb_define_singleton_method(rb_cSocket, "ip_address_list", socket_s_ip_address_list, 0);
02161 }
02162 

Generated on 19 Jul 2016 for Ruby by  doxygen 1.4.7