Ruby  2.4.2p198(2017-09-14revision59899)
socket.c
Go to the documentation of this file.
1 /************************************************
2 
3  socket.c -
4 
5  created at: Thu Mar 31 12:21:29 JST 1994
6 
7  Copyright (C) 1993-2007 Yukihiro Matsumoto
8 
9 ************************************************/
10 
11 #include "rubysocket.h"
12 
14 
16 
17 void
18 rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
19 {
20  rsock_syserr_fail_host_port(errno, mesg, host, port);
21 }
22 
23 void
24 rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
25 {
26  VALUE message;
27 
28  message = rb_sprintf("%s for %+"PRIsVALUE" port % "PRIsVALUE"",
29  mesg, host, port);
30 
31  rb_syserr_fail_str(err, message);
32 }
33 
34 void
35 rsock_sys_fail_path(const char *mesg, VALUE path)
36 {
37  rsock_syserr_fail_path(errno, mesg, path);
38 }
39 
40 void
41 rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
42 {
43  VALUE message;
44 
45  if (RB_TYPE_P(path, T_STRING)) {
46  message = rb_sprintf("%s for % "PRIsVALUE"", mesg, path);
47  rb_syserr_fail_str(err, message);
48  }
49  else {
50  rb_syserr_fail(err, mesg);
51  }
52 }
53 
54 void
55 rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
56 {
57  rsock_syserr_fail_sockaddr(errno, mesg, addr, len);
58 }
59 
60 void
61 rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
62 {
63  VALUE rai;
64 
65  rai = rsock_addrinfo_new(addr, len, PF_UNSPEC, 0, 0, Qnil, Qnil);
66 
67  rsock_syserr_fail_raddrinfo(err, mesg, rai);
68 }
69 
70 void
71 rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
72 {
74 }
75 
76 void
77 rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
78 {
79  VALUE str, message;
80 
82  message = rb_sprintf("%s for %"PRIsVALUE"", mesg, str);
83 
84  rb_syserr_fail_str(err, message);
85 }
86 
87 void
88 rsock_sys_fail_raddrinfo_or_sockaddr(const char *mesg, VALUE addr, VALUE rai)
89 {
91 }
92 
93 void
94 rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
95 {
96  if (NIL_P(rai)) {
97  StringValue(addr);
98 
100  (struct sockaddr *)RSTRING_PTR(addr),
101  (socklen_t)RSTRING_LEN(addr)); /* overflow should be checked already */
102  }
103  else
104  rsock_syserr_fail_raddrinfo(err, mesg, rai);
105 }
106 
107 static void
108 setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
109 {
110  *dv = rsock_family_arg(domain);
111  *tv = rsock_socktype_arg(type);
112 }
113 
114 /*
115  * call-seq:
116  * Socket.new(domain, socktype [, protocol]) => socket
117  *
118  * Creates a new socket object.
119  *
120  * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
121  *
122  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
123  *
124  * _protocol_ is optional and should be a protocol defined in the domain.
125  * If protocol is not given, 0 is used internally.
126  *
127  * Socket.new(:INET, :STREAM) # TCP socket
128  * Socket.new(:INET, :DGRAM) # UDP socket
129  * Socket.new(:UNIX, :STREAM) # UNIX stream socket
130  * Socket.new(:UNIX, :DGRAM) # UNIX datagram socket
131  */
132 static VALUE
134 {
135  VALUE domain, type, protocol;
136  int fd;
137  int d, t;
138 
139  rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
140  if (NIL_P(protocol))
141  protocol = INT2FIX(0);
142 
143  setup_domain_and_type(domain, &d, type, &t);
144  fd = rsock_socket(d, t, NUM2INT(protocol));
145  if (fd < 0) rb_sys_fail("socket(2)");
146 
147  return rsock_init_sock(sock, fd);
148 }
149 
150 #if defined HAVE_SOCKETPAIR
151 static VALUE
153 {
154  return rb_funcallv(io, rb_intern("close"), 0, 0);
155 }
156 
157 static VALUE
158 io_close(VALUE io)
159 {
160  return rb_rescue(io_call_close, io, 0, 0);
161 }
162 
163 static VALUE
164 pair_yield(VALUE pair)
165 {
166  return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1));
167 }
168 #endif
169 
170 #if defined HAVE_SOCKETPAIR
171 
172 #ifdef SOCK_CLOEXEC
173 static int
174 rsock_socketpair0(int domain, int type, int protocol, int sv[2])
175 {
176  int ret;
177  static int cloexec_state = -1; /* <0: unknown, 0: ignored, >0: working */
178 
179  if (cloexec_state > 0) { /* common path, if SOCK_CLOEXEC is defined */
180  ret = socketpair(domain, type|SOCK_CLOEXEC, protocol, sv);
181  if (ret == 0 && (sv[0] <= 2 || sv[1] <= 2)) {
182  goto fix_cloexec; /* highly unlikely */
183  }
184  goto update_max_fd;
185  }
186  else if (cloexec_state < 0) { /* usually runs once only for detection */
187  ret = socketpair(domain, type|SOCK_CLOEXEC, protocol, sv);
188  if (ret == 0) {
189  cloexec_state = rsock_detect_cloexec(sv[0]);
190  if ((cloexec_state == 0) || (sv[0] <= 2 || sv[1] <= 2))
191  goto fix_cloexec;
192  goto update_max_fd;
193  }
194  else if (ret == -1 && errno == EINVAL) {
195  /* SOCK_CLOEXEC is available since Linux 2.6.27. Linux 2.6.18 fails with EINVAL */
196  ret = socketpair(domain, type, protocol, sv);
197  if (ret != -1) {
198  /* The reason of EINVAL may be other than SOCK_CLOEXEC.
199  * So disable SOCK_CLOEXEC only if socketpair() succeeds without SOCK_CLOEXEC.
200  * Ex. Socket.pair(:UNIX, 0xff) fails with EINVAL.
201  */
202  cloexec_state = 0;
203  }
204  }
205  }
206  else { /* cloexec_state == 0 */
207  ret = socketpair(domain, type, protocol, sv);
208  }
209  if (ret == -1) {
210  return -1;
211  }
212 
213 fix_cloexec:
216 
217 update_max_fd:
218  rb_update_max_fd(sv[0]);
219  rb_update_max_fd(sv[1]);
220 
221  return ret;
222 }
223 #else /* !SOCK_CLOEXEC */
224 static int
225 rsock_socketpair0(int domain, int type, int protocol, int sv[2])
226 {
227  int ret = socketpair(domain, type, protocol, sv);
228 
229  if (ret == -1)
230  return -1;
231 
232  rb_fd_fix_cloexec(sv[0]);
233  rb_fd_fix_cloexec(sv[1]);
234  return ret;
235 }
236 #endif /* !SOCK_CLOEXEC */
237 
238 static int
239 rsock_socketpair(int domain, int type, int protocol, int sv[2])
240 {
241  int ret;
242 
243  ret = rsock_socketpair0(domain, type, protocol, sv);
244  if (ret < 0 && rb_gc_for_fd(errno)) {
245  ret = rsock_socketpair0(domain, type, protocol, sv);
246  }
247 
248  return ret;
249 }
250 
251 /*
252  * call-seq:
253  * Socket.pair(domain, type, protocol) => [socket1, socket2]
254  * Socket.socketpair(domain, type, protocol) => [socket1, socket2]
255  *
256  * Creates a pair of sockets connected each other.
257  *
258  * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
259  *
260  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
261  *
262  * _protocol_ should be a protocol defined in the domain,
263  * defaults to 0 for the domain.
264  *
265  * s1, s2 = Socket.pair(:UNIX, :STREAM, 0)
266  * s1.send "a", 0
267  * s1.send "b", 0
268  * s1.close
269  * p s2.recv(10) #=> "ab"
270  * p s2.recv(10) #=> ""
271  * p s2.recv(10) #=> ""
272  *
273  * s1, s2 = Socket.pair(:UNIX, :DGRAM, 0)
274  * s1.send "a", 0
275  * s1.send "b", 0
276  * p s2.recv(10) #=> "a"
277  * p s2.recv(10) #=> "b"
278  *
279  */
280 VALUE
282 {
283  VALUE domain, type, protocol;
284  int d, t, p, sp[2];
285  int ret;
286  VALUE s1, s2, r;
287 
288  rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
289  if (NIL_P(protocol))
290  protocol = INT2FIX(0);
291 
292  setup_domain_and_type(domain, &d, type, &t);
293  p = NUM2INT(protocol);
294  ret = rsock_socketpair(d, t, p, sp);
295  if (ret < 0) {
296  rb_sys_fail("socketpair(2)");
297  }
298 
299  s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]);
300  s2 = rsock_init_sock(rb_obj_alloc(klass), sp[1]);
301  r = rb_assoc_new(s1, s2);
302  if (rb_block_given_p()) {
303  return rb_ensure(pair_yield, r, io_close, s1);
304  }
305  return r;
306 }
307 #else
308 #define rsock_sock_s_socketpair rb_f_notimplement
309 #endif
310 
311 /*
312  * call-seq:
313  * socket.connect(remote_sockaddr) => 0
314  *
315  * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if
316  * successful, otherwise an exception is raised.
317  *
318  * === Parameter
319  * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
320  *
321  * === Example:
322  * # Pull down Google's web page
323  * require 'socket'
324  * include Socket::Constants
325  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
326  * sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
327  * socket.connect( sockaddr )
328  * socket.write( "GET / HTTP/1.0\r\n\r\n" )
329  * results = socket.read
330  *
331  * === Unix-based Exceptions
332  * On unix-based systems the following system exceptions may be raised if
333  * the call to _connect_ fails:
334  * * Errno::EACCES - search permission is denied for a component of the prefix
335  * path or write access to the +socket+ is denied
336  * * Errno::EADDRINUSE - the _sockaddr_ is already in use
337  * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
338  * local machine
339  * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
340  * the address family of the specified +socket+
341  * * Errno::EALREADY - a connection is already in progress for the specified
342  * socket
343  * * Errno::EBADF - the +socket+ is not a valid file descriptor
344  * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
345  * refused the connection request
346  * * Errno::ECONNRESET - the remote host reset the connection request
347  * * Errno::EFAULT - the _sockaddr_ cannot be accessed
348  * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
349  * because the host is down or a remote router cannot reach it)
350  * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
351  * connection cannot be immediately established; the connection will be
352  * established asynchronously
353  * * Errno::EINTR - the attempt to establish the connection was interrupted by
354  * delivery of a signal that was caught; the connection will be established
355  * asynchronously
356  * * Errno::EISCONN - the specified +socket+ is already connected
357  * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
358  * length for the address family or there is an invalid family in _sockaddr_
359  * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
360  * PATH_MAX
361  * * Errno::ENETDOWN - the local interface used to reach the destination is down
362  * * Errno::ENETUNREACH - no route to the network is present
363  * * Errno::ENOBUFS - no buffer space is available
364  * * Errno::ENOSR - there were insufficient STREAMS resources available to
365  * complete the operation
366  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
367  * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
368  * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
369  * bound to the specified peer address
370  * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
371  * was made.
372  *
373  * On unix-based systems if the address family of the calling +socket+ is
374  * AF_UNIX the follow exceptions may be raised if the call to _connect_
375  * fails:
376  * * Errno::EIO - an i/o error occurred while reading from or writing to the
377  * file system
378  * * Errno::ELOOP - too many symbolic links were encountered in translating
379  * the pathname in _sockaddr_
380  * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
381  * characters, or an entire pathname exceeded PATH_MAX characters
382  * * Errno::ENOENT - a component of the pathname does not name an existing file
383  * or the pathname is an empty string
384  * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
385  * is not a directory
386  *
387  * === Windows Exceptions
388  * On Windows systems the following system exceptions may be raised if
389  * the call to _connect_ fails:
390  * * Errno::ENETDOWN - the network is down
391  * * Errno::EADDRINUSE - the socket's local address is already in use
392  * * Errno::EINTR - the socket was cancelled
393  * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
394  * is still processing a callback function. Or a nonblocking connect call is
395  * in progress on the +socket+.
396  * * Errno::EALREADY - see Errno::EINVAL
397  * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
398  * ADDR_ANY TODO check ADDRANY TO INADDR_ANY
399  * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
400  * with this +socket+
401  * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
402  * refused the connection request
403  * * Errno::EFAULT - the socket's internal address or address length parameter
404  * is too small or is not a valid part of the user space address
405  * * Errno::EINVAL - the +socket+ is a listening socket
406  * * Errno::EISCONN - the +socket+ is already connected
407  * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
408  * * Errno::EHOSTUNREACH - no route to the network is present
409  * * Errno::ENOBUFS - no buffer space is available
410  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
411  * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
412  * was made.
413  * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
414  * connection cannot be completed immediately
415  * * Errno::EACCES - the attempt to connect the datagram socket to the
416  * broadcast address failed
417  *
418  * === See
419  * * connect manual pages on unix-based systems
420  * * connect function in Microsoft's Winsock functions reference
421  */
422 static VALUE
424 {
425  VALUE rai;
426  rb_io_t *fptr;
427  int fd, n;
428 
430  addr = rb_str_new4(addr);
431  GetOpenFile(sock, fptr);
432  fd = fptr->fd;
433  n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), 0);
434  if (n < 0) {
435  rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai);
436  }
437 
438  return INT2FIX(n);
439 }
440 
441 /* :nodoc: */
442 static VALUE
444 {
445  VALUE rai;
446  rb_io_t *fptr;
447  int n;
448 
450  addr = rb_str_new4(addr);
451  GetOpenFile(sock, fptr);
452  rb_io_set_nonblock(fptr);
453  n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr));
454  if (n < 0) {
455  int e = errno;
456  if (e == EINPROGRESS) {
457  if (ex == Qfalse) {
458  return sym_wait_writable;
459  }
460  rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "connect(2) would block");
461  }
462  if (e == EISCONN) {
463  if (ex == Qfalse) {
464  return INT2FIX(0);
465  }
466  }
467  rsock_syserr_fail_raddrinfo_or_sockaddr(e, "connect(2)", addr, rai);
468  }
469 
470  return INT2FIX(n);
471 }
472 
473 /*
474  * call-seq:
475  * socket.bind(local_sockaddr) => 0
476  *
477  * Binds to the given local address.
478  *
479  * === Parameter
480  * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object
481  *
482  * === Example
483  * require 'socket'
484  *
485  * # use Addrinfo
486  * socket = Socket.new(:INET, :STREAM, 0)
487  * socket.bind(Addrinfo.tcp("127.0.0.1", 2222))
488  * p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>
489  *
490  * # use struct sockaddr
491  * include Socket::Constants
492  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
493  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
494  * socket.bind( sockaddr )
495  *
496  * === Unix-based Exceptions
497  * On unix-based based systems the following system exceptions may be raised if
498  * the call to _bind_ fails:
499  * * Errno::EACCES - the specified _sockaddr_ is protected and the current
500  * user does not have permission to bind to it
501  * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
502  * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
503  * local machine
504  * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
505  * the family of the calling +socket+
506  * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
507  * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
508  * * Errno::EINVAL - the +socket+ is already bound to an address, and the
509  * protocol does not support binding to the new _sockaddr_ or the +socket+
510  * has been shut down.
511  * * Errno::EINVAL - the address length is not a valid length for the address
512  * family
513  * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
514  * PATH_MAX
515  * * Errno::ENOBUFS - no buffer space is available
516  * * Errno::ENOSR - there were insufficient STREAMS resources available to
517  * complete the operation
518  * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
519  * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
520  * binding to an address
521  *
522  * On unix-based based systems if the address family of the calling +socket+ is
523  * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
524  * fails:
525  * * Errno::EACCES - search permission is denied for a component of the prefix
526  * path or write access to the +socket+ is denied
527  * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
528  * * Errno::EISDIR - same as Errno::EDESTADDRREQ
529  * * Errno::EIO - an i/o error occurred
530  * * Errno::ELOOP - too many symbolic links were encountered in translating
531  * the pathname in _sockaddr_
532  * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
533  * characters, or an entire pathname exceeded PATH_MAX characters
534  * * Errno::ENOENT - a component of the pathname does not name an existing file
535  * or the pathname is an empty string
536  * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
537  * is not a directory
538  * * Errno::EROFS - the name would reside on a read only filesystem
539  *
540  * === Windows Exceptions
541  * On Windows systems the following system exceptions may be raised if
542  * the call to _bind_ fails:
543  * * Errno::ENETDOWN-- the network is down
544  * * Errno::EACCES - the attempt to connect the datagram socket to the
545  * broadcast address failed
546  * * Errno::EADDRINUSE - the socket's local address is already in use
547  * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
548  * computer
549  * * Errno::EFAULT - the socket's internal address or address length parameter
550  * is too small or is not a valid part of the user space addressed
551  * * Errno::EINVAL - the +socket+ is already bound to an address
552  * * Errno::ENOBUFS - no buffer space is available
553  * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
554  *
555  * === See
556  * * bind manual pages on unix-based systems
557  * * bind function in Microsoft's Winsock functions reference
558  */
559 static VALUE
560 sock_bind(VALUE sock, VALUE addr)
561 {
562  VALUE rai;
563  rb_io_t *fptr;
564 
566  GetOpenFile(sock, fptr);
567  if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)) < 0)
568  rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai);
569 
570  return INT2FIX(0);
571 }
572 
573 /*
574  * call-seq:
575  * socket.listen( int ) => 0
576  *
577  * Listens for connections, using the specified +int+ as the backlog. A call
578  * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
579  * SOCK_SEQPACKET.
580  *
581  * === Parameter
582  * * +backlog+ - the maximum length of the queue for pending connections.
583  *
584  * === Example 1
585  * require 'socket'
586  * include Socket::Constants
587  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
588  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
589  * socket.bind( sockaddr )
590  * socket.listen( 5 )
591  *
592  * === Example 2 (listening on an arbitrary port, unix-based systems only):
593  * require 'socket'
594  * include Socket::Constants
595  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
596  * socket.listen( 1 )
597  *
598  * === Unix-based Exceptions
599  * On unix based systems the above will work because a new +sockaddr+ struct
600  * is created on the address ADDR_ANY, for an arbitrary port number as handed
601  * off by the kernel. It will not work on Windows, because Windows requires that
602  * the +socket+ is bound by calling _bind_ before it can _listen_.
603  *
604  * If the _backlog_ amount exceeds the implementation-dependent maximum
605  * queue length, the implementation's maximum queue length will be used.
606  *
607  * On unix-based based systems the following system exceptions may be raised if the
608  * call to _listen_ fails:
609  * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
610  * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
611  * the protocol does not support listening on an unbound socket
612  * * Errno::EINVAL - the _socket_ is already connected
613  * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
614  * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
615  * * Errno::EACCES - the calling process does not have appropriate privileges
616  * * Errno::EINVAL - the _socket_ has been shut down
617  * * Errno::ENOBUFS - insufficient resources are available in the system to
618  * complete the call
619  *
620  * === Windows Exceptions
621  * On Windows systems the following system exceptions may be raised if
622  * the call to _listen_ fails:
623  * * Errno::ENETDOWN - the network is down
624  * * Errno::EADDRINUSE - the socket's local address is already in use. This
625  * usually occurs during the execution of _bind_ but could be delayed
626  * if the call to _bind_ was to a partially wildcard address (involving
627  * ADDR_ANY) and if a specific address needs to be committed at the
628  * time of the call to _listen_
629  * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
630  * service provider is still processing a callback function
631  * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
632  * * Errno::EISCONN - the +socket+ is already connected
633  * * Errno::EMFILE - no more socket descriptors are available
634  * * Errno::ENOBUFS - no buffer space is available
635  * * Errno::ENOTSOC - +socket+ is not a socket
636  * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
637  * the _listen_ method
638  *
639  * === See
640  * * listen manual pages on unix-based systems
641  * * listen function in Microsoft's Winsock functions reference
642  */
643 VALUE
645 {
646  rb_io_t *fptr;
647  int backlog;
648 
649  backlog = NUM2INT(log);
650  GetOpenFile(sock, fptr);
651  if (listen(fptr->fd, backlog) < 0)
652  rb_sys_fail("listen(2)");
653 
654  return INT2FIX(0);
655 }
656 
657 /*
658  * call-seq:
659  * socket.recvfrom(maxlen) => [mesg, sender_addrinfo]
660  * socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo]
661  *
662  * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
663  * of the +MSG_+ options. The first element of the results, _mesg_, is the data
664  * received. The second element, _sender_addrinfo_, contains protocol-specific
665  * address information of the sender.
666  *
667  * === Parameters
668  * * +maxlen+ - the maximum number of bytes to receive from the socket
669  * * +flags+ - zero or more of the +MSG_+ options
670  *
671  * === Example
672  * # In one file, start this first
673  * require 'socket'
674  * include Socket::Constants
675  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
676  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
677  * socket.bind( sockaddr )
678  * socket.listen( 5 )
679  * client, client_addrinfo = socket.accept
680  * data = client.recvfrom( 20 )[0].chomp
681  * puts "I only received 20 bytes '#{data}'"
682  * sleep 1
683  * socket.close
684  *
685  * # In another file, start this second
686  * require 'socket'
687  * include Socket::Constants
688  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
689  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
690  * socket.connect( sockaddr )
691  * socket.puts "Watch this get cut short!"
692  * socket.close
693  *
694  * === Unix-based Exceptions
695  * On unix-based based systems the following system exceptions may be raised if the
696  * call to _recvfrom_ fails:
697  * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
698  * data is waiting to be received; or MSG_OOB is set and no out-of-band data
699  * is available and either the +socket+ file descriptor is marked as
700  * O_NONBLOCK or the +socket+ does not support blocking to wait for
701  * out-of-band-data
702  * * Errno::EWOULDBLOCK - see Errno::EAGAIN
703  * * Errno::EBADF - the +socket+ is not a valid file descriptor
704  * * Errno::ECONNRESET - a connection was forcibly closed by a peer
705  * * Errno::EFAULT - the socket's internal buffer, address or address length
706  * cannot be accessed or written
707  * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available
708  * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
709  * * Errno::EIO - an i/o error occurred while reading from or writing to the
710  * filesystem
711  * * Errno::ENOBUFS - insufficient resources were available in the system to
712  * perform the operation
713  * * Errno::ENOMEM - insufficient memory was available to fulfill the request
714  * * Errno::ENOSR - there were insufficient STREAMS resources available to
715  * complete the operation
716  * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
717  * is not connected
718  * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
719  * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
720  * * Errno::ETIMEDOUT - the connection timed out during connection establishment
721  * or due to a transmission timeout on an active connection
722  *
723  * === Windows Exceptions
724  * On Windows systems the following system exceptions may be raised if
725  * the call to _recvfrom_ fails:
726  * * Errno::ENETDOWN - the network is down
727  * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
728  * part of the user address space, or the internal fromlen parameter is
729  * too small to accommodate the peer address
730  * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
731  * the WinSock function WSACancelBlockingCall
732  * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
733  * the service provider is still processing a callback function
734  * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
735  * unknown flag was specified, or MSG_OOB was specified for a socket with
736  * SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
737  * len parameter on +socket+ was zero or negative
738  * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
739  * not permitted with a connected socket on a socket that is connection
740  * oriented or connectionless.
741  * * Errno::ENETRESET - the connection has been broken due to the keep-alive
742  * activity detecting a failure while the operation was in progress.
743  * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
744  * such as type SOCK_STREAM. OOB data is not supported in the communication
745  * domain associated with +socket+, or +socket+ is unidirectional and
746  * supports only send operations
747  * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
748  * call _recvfrom_ on a socket after _shutdown_ has been invoked.
749  * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to
750  * _recvfrom_ would block.
751  * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
752  * and was truncated.
753  * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
754  * failure or because the system on the other end went down without
755  * notice
756  * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
757  * executing a hard or abortive close. The application should close the
758  * socket; it is no longer usable. On a UDP-datagram socket this error
759  * indicates a previous send operation resulted in an ICMP Port Unreachable
760  * message.
761  */
762 static VALUE
764 {
765  return rsock_s_recvfrom(sock, argc, argv, RECV_SOCKET);
766 }
767 
768 /* :nodoc: */
769 static VALUE
771 {
772  return rsock_s_recvfrom_nonblock(sock, len, flg, str, ex, RECV_SOCKET);
773 }
774 
775 /*
776  * call-seq:
777  * socket.accept => [client_socket, client_addrinfo]
778  *
779  * Accepts a next connection.
780  * Returns a new Socket object and Addrinfo object.
781  *
782  * serv = Socket.new(:INET, :STREAM, 0)
783  * serv.listen(5)
784  * c = Socket.new(:INET, :STREAM, 0)
785  * c.connect(serv.connect_address)
786  * p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>]
787  *
788  */
789 static VALUE
791 {
792  rb_io_t *fptr;
793  VALUE sock2;
795  socklen_t len = (socklen_t)sizeof buf;
796 
797  GetOpenFile(sock, fptr);
798  sock2 = rsock_s_accept(rb_cSocket,fptr->fd,&buf.addr,&len);
799 
800  return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
801 }
802 
803 /* :nodoc: */
804 static VALUE
806 {
807  rb_io_t *fptr;
808  VALUE sock2;
810  struct sockaddr *addr = &buf.addr;
811  socklen_t len = (socklen_t)sizeof buf;
812 
813  GetOpenFile(sock, fptr);
814  sock2 = rsock_s_accept_nonblock(rb_cSocket, ex, fptr, addr, &len);
815 
816  if (SYMBOL_P(sock2)) /* :wait_readable */
817  return sock2;
818  return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
819 }
820 
821 /*
822  * call-seq:
823  * socket.sysaccept => [client_socket_fd, client_addrinfo]
824  *
825  * Accepts an incoming connection returning an array containing the (integer)
826  * file descriptor for the incoming connection, _client_socket_fd_,
827  * and an Addrinfo, _client_addrinfo_.
828  *
829  * === Example
830  * # In one script, start this first
831  * require 'socket'
832  * include Socket::Constants
833  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
834  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
835  * socket.bind( sockaddr )
836  * socket.listen( 5 )
837  * client_fd, client_addrinfo = socket.sysaccept
838  * client_socket = Socket.for_fd( client_fd )
839  * puts "The client said, '#{client_socket.readline.chomp}'"
840  * client_socket.puts "Hello from script one!"
841  * socket.close
842  *
843  * # In another script, start this second
844  * require 'socket'
845  * include Socket::Constants
846  * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
847  * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
848  * socket.connect( sockaddr )
849  * socket.puts "Hello from script 2."
850  * puts "The server said, '#{socket.readline.chomp}'"
851  * socket.close
852  *
853  * Refer to Socket#accept for the exceptions that may be thrown if the call
854  * to _sysaccept_ fails.
855  *
856  * === See
857  * * Socket#accept
858  */
859 static VALUE
861 {
862  rb_io_t *fptr;
863  VALUE sock2;
865  socklen_t len = (socklen_t)sizeof buf;
866 
867  GetOpenFile(sock, fptr);
868  sock2 = rsock_s_accept(0,fptr->fd,&buf.addr,&len);
869 
870  return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
871 }
872 
873 #ifdef HAVE_GETHOSTNAME
874 /*
875  * call-seq:
876  * Socket.gethostname => hostname
877  *
878  * Returns the hostname.
879  *
880  * p Socket.gethostname #=> "hal"
881  *
882  * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc.
883  * If you need local IP address, use Socket.ip_address_list.
884  */
885 static VALUE
887 {
888 #if defined(NI_MAXHOST)
889 # define RUBY_MAX_HOST_NAME_LEN NI_MAXHOST
890 #elif defined(HOST_NAME_MAX)
891 # define RUBY_MAX_HOST_NAME_LEN HOST_NAME_MAX
892 #else
893 # define RUBY_MAX_HOST_NAME_LEN 1024
894 #endif
895 
896  long len = RUBY_MAX_HOST_NAME_LEN;
897  VALUE name;
898 
899  name = rb_str_new(0, len);
900  while (gethostname(RSTRING_PTR(name), len) < 0) {
901  int e = errno;
902  switch (e) {
903  case ENAMETOOLONG:
904 #ifdef __linux__
905  case EINVAL:
906  /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */
907 #endif
908  break;
909  default:
910  rb_syserr_fail(e, "gethostname(3)");
911  }
912  rb_str_modify_expand(name, len);
913  len += len;
914  }
915  rb_str_resize(name, strlen(RSTRING_PTR(name)));
916  return name;
917 }
918 #else
919 #ifdef HAVE_UNAME
920 
921 #include <sys/utsname.h>
922 
923 static VALUE
925 {
926  struct utsname un;
927 
928  uname(&un);
929  return rb_str_new2(un.nodename);
930 }
931 #else
932 #define sock_gethostname rb_f_notimplement
933 #endif
934 #endif
935 
936 static VALUE
937 make_addrinfo(struct rb_addrinfo *res0, int norevlookup)
938 {
939  VALUE base, ary;
940  struct addrinfo *res;
941 
942  if (res0 == NULL) {
943  rb_raise(rb_eSocket, "host not found");
944  }
945  base = rb_ary_new();
946  for (res = res0->ai; res; res = res->ai_next) {
947  ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup);
948  if (res->ai_canonname) {
949  RARRAY_ASET(ary, 2, rb_str_new2(res->ai_canonname));
950  }
951  rb_ary_push(ary, INT2FIX(res->ai_family));
952  rb_ary_push(ary, INT2FIX(res->ai_socktype));
953  rb_ary_push(ary, INT2FIX(res->ai_protocol));
954  rb_ary_push(base, ary);
955  }
956  return base;
957 }
958 
959 static VALUE
960 sock_sockaddr(struct sockaddr *addr, socklen_t len)
961 {
962  char *ptr;
963 
964  switch (addr->sa_family) {
965  case AF_INET:
966  ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr;
967  len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr);
968  break;
969 #ifdef AF_INET6
970  case AF_INET6:
971  ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr;
972  len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr);
973  break;
974 #endif
975  default:
976  rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family);
977  break;
978  }
979  return rb_str_new(ptr, len);
980 }
981 
982 /*
983  * call-seq:
984  * Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
985  *
986  * Obtains the host information for _hostname_.
987  *
988  * p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"]
989  *
990  */
991 static VALUE
993 {
994  struct rb_addrinfo *res =
995  rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME);
996  return rsock_make_hostent(host, res, sock_sockaddr);
997 }
998 
999 /*
1000  * call-seq:
1001  * Socket.gethostbyaddr(address_string [, address_family]) => hostent
1002  *
1003  * Obtains the host information for _address_.
1004  *
1005  * p Socket.gethostbyaddr([221,186,184,68].pack("CCCC"))
1006  * #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"]
1007  */
1008 static VALUE
1010 {
1011  VALUE addr, family;
1012  struct hostent *h;
1013  char **pch;
1014  VALUE ary, names;
1015  int t = AF_INET;
1016 
1017  rb_scan_args(argc, argv, "11", &addr, &family);
1018  StringValue(addr);
1019  if (!NIL_P(family)) {
1020  t = rsock_family_arg(family);
1021  }
1022 #ifdef AF_INET6
1023  else if (RSTRING_LEN(addr) == 16) {
1024  t = AF_INET6;
1025  }
1026 #endif
1027  h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), t);
1028  if (h == NULL) {
1029 #ifdef HAVE_HSTRERROR
1030  extern int h_errno;
1031  rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno));
1032 #else
1033  rb_raise(rb_eSocket, "host not found");
1034 #endif
1035  }
1036  ary = rb_ary_new();
1037  rb_ary_push(ary, rb_str_new2(h->h_name));
1038  names = rb_ary_new();
1039  rb_ary_push(ary, names);
1040  if (h->h_aliases != NULL) {
1041  for (pch = h->h_aliases; *pch; pch++) {
1042  rb_ary_push(names, rb_str_new2(*pch));
1043  }
1044  }
1045  rb_ary_push(ary, INT2NUM(h->h_addrtype));
1046 #ifdef h_addr
1047  for (pch = h->h_addr_list; *pch; pch++) {
1048  rb_ary_push(ary, rb_str_new(*pch, h->h_length));
1049  }
1050 #else
1051  rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length));
1052 #endif
1053 
1054  return ary;
1055 }
1056 
1057 /*
1058  * call-seq:
1059  * Socket.getservbyname(service_name) => port_number
1060  * Socket.getservbyname(service_name, protocol_name) => port_number
1061  *
1062  * Obtains the port number for _service_name_.
1063  *
1064  * If _protocol_name_ is not given, "tcp" is assumed.
1065  *
1066  * Socket.getservbyname("smtp") #=> 25
1067  * Socket.getservbyname("shell") #=> 514
1068  * Socket.getservbyname("syslog", "udp") #=> 514
1069  */
1070 static VALUE
1072 {
1073  VALUE service, proto;
1074  struct servent *sp;
1075  long port;
1076  const char *servicename, *protoname = "tcp";
1077 
1078  rb_scan_args(argc, argv, "11", &service, &proto);
1079  StringValue(service);
1080  if (!NIL_P(proto)) StringValue(proto);
1081  servicename = StringValueCStr(service);
1082  if (!NIL_P(proto)) protoname = StringValueCStr(proto);
1083  sp = getservbyname(servicename, protoname);
1084  if (sp) {
1085  port = ntohs(sp->s_port);
1086  }
1087  else {
1088  char *end;
1089 
1090  port = STRTOUL(servicename, &end, 0);
1091  if (*end != '\0') {
1092  rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname);
1093  }
1094  }
1095  return INT2FIX(port);
1096 }
1097 
1098 /*
1099  * call-seq:
1100  * Socket.getservbyport(port [, protocol_name]) => service
1101  *
1102  * Obtains the port number for _port_.
1103  *
1104  * If _protocol_name_ is not given, "tcp" is assumed.
1105  *
1106  * Socket.getservbyport(80) #=> "www"
1107  * Socket.getservbyport(514, "tcp") #=> "shell"
1108  * Socket.getservbyport(514, "udp") #=> "syslog"
1109  *
1110  */
1111 static VALUE
1113 {
1114  VALUE port, proto;
1115  struct servent *sp;
1116  long portnum;
1117  const char *protoname = "tcp";
1118 
1119  rb_scan_args(argc, argv, "11", &port, &proto);
1120  portnum = NUM2LONG(port);
1121  if (portnum != (uint16_t)portnum) {
1122  const char *s = portnum > 0 ? "big" : "small";
1123  rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s);
1124  }
1125  if (!NIL_P(proto)) protoname = StringValueCStr(proto);
1126 
1127  sp = getservbyport((int)htons((uint16_t)portnum), protoname);
1128  if (!sp) {
1129  rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname);
1130  }
1131  return rb_tainted_str_new2(sp->s_name);
1132 }
1133 
1134 /*
1135  * call-seq:
1136  * Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array
1137  *
1138  * Obtains address information for _nodename_:_servname_.
1139  *
1140  * _family_ should be an address family such as: :INET, :INET6, etc.
1141  *
1142  * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
1143  *
1144  * _protocol_ should be a protocol defined in the family,
1145  * and defaults to 0 for the family.
1146  *
1147  * _flags_ should be bitwise OR of Socket::AI_* constants.
1148  *
1149  * Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM)
1150  * #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP
1151  *
1152  * Socket.getaddrinfo("localhost", nil)
1153  * #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6], # PF_INET/SOCK_STREAM/IPPROTO_TCP
1154  * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP
1155  * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]] # PF_INET/SOCK_RAW/IPPROTO_IP
1156  *
1157  * _reverse_lookup_ directs the form of the third element, and has to
1158  * be one of below. If _reverse_lookup_ is omitted, the default value is +nil+.
1159  *
1160  * +true+, +:hostname+: hostname is obtained from numeric address using reverse lookup, which may take a time.
1161  * +false+, +:numeric+: hostname is same as numeric address.
1162  * +nil+: obey to the current +do_not_reverse_lookup+ flag.
1163  *
1164  * If Addrinfo object is preferred, use Addrinfo.getaddrinfo.
1165  */
1166 static VALUE
1168 {
1169  VALUE host, port, family, socktype, protocol, flags, ret, revlookup;
1170  struct addrinfo hints;
1171  struct rb_addrinfo *res;
1172  int norevlookup;
1173 
1174  rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup);
1175 
1176  MEMZERO(&hints, struct addrinfo, 1);
1177  hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
1178 
1179  if (!NIL_P(socktype)) {
1180  hints.ai_socktype = rsock_socktype_arg(socktype);
1181  }
1182  if (!NIL_P(protocol)) {
1183  hints.ai_protocol = NUM2INT(protocol);
1184  }
1185  if (!NIL_P(flags)) {
1186  hints.ai_flags = NUM2INT(flags);
1187  }
1188  if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) {
1189  norevlookup = rsock_do_not_reverse_lookup;
1190  }
1191  res = rsock_getaddrinfo(host, port, &hints, 0);
1192 
1193  ret = make_addrinfo(res, norevlookup);
1194  rb_freeaddrinfo(res);
1195  return ret;
1196 }
1197 
1198 /*
1199  * call-seq:
1200  * Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename]
1201  *
1202  * Obtains name information for _sockaddr_.
1203  *
1204  * _sockaddr_ should be one of follows.
1205  * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1")
1206  * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"]
1207  * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"]
1208  *
1209  * _flags_ should be bitwise OR of Socket::NI_* constants.
1210  *
1211  * Note:
1212  * The last form is compatible with IPSocket#addr and IPSocket#peeraddr.
1213  *
1214  * Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1")) #=> ["localhost", "www"]
1215  * Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"]) #=> ["localhost", "www"]
1216  * Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"]
1217  *
1218  * If Addrinfo object is preferred, use Addrinfo#getnameinfo.
1219  */
1220 static VALUE
1222 {
1223  VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
1224  char *hptr, *pptr;
1225  char hbuf[1024], pbuf[1024];
1226  int fl;
1227  struct rb_addrinfo *res = NULL;
1228  struct addrinfo hints, *r;
1229  int error, saved_errno;
1230  union_sockaddr ss;
1231  struct sockaddr *sap;
1232  socklen_t salen;
1233 
1234  sa = flags = Qnil;
1235  rb_scan_args(argc, argv, "11", &sa, &flags);
1236 
1237  fl = 0;
1238  if (!NIL_P(flags)) {
1239  fl = NUM2INT(flags);
1240  }
1242  if (!NIL_P(tmp)) {
1243  sa = tmp;
1244  if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
1245  rb_raise(rb_eTypeError, "sockaddr length too big");
1246  }
1247  memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
1248  if (!VALIDATE_SOCKLEN(&ss.addr, RSTRING_LEN(sa))) {
1249  rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
1250  }
1251  sap = &ss.addr;
1252  salen = RSTRING_SOCKLEN(sa);
1253  goto call_nameinfo;
1254  }
1255  tmp = rb_check_array_type(sa);
1256  if (!NIL_P(tmp)) {
1257  sa = tmp;
1258  MEMZERO(&hints, struct addrinfo, 1);
1259  if (RARRAY_LEN(sa) == 3) {
1260  af = RARRAY_AREF(sa, 0);
1261  port = RARRAY_AREF(sa, 1);
1262  host = RARRAY_AREF(sa, 2);
1263  }
1264  else if (RARRAY_LEN(sa) >= 4) {
1265  af = RARRAY_AREF(sa, 0);
1266  port = RARRAY_AREF(sa, 1);
1267  host = RARRAY_AREF(sa, 3);
1268  if (NIL_P(host)) {
1269  host = RARRAY_AREF(sa, 2);
1270  }
1271  else {
1272  /*
1273  * 4th element holds numeric form, don't resolve.
1274  * see rsock_ipaddr().
1275  */
1276 #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
1277  hints.ai_flags |= AI_NUMERICHOST;
1278 #endif
1279  }
1280  }
1281  else {
1282  rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
1283  RARRAY_LEN(sa));
1284  }
1285  /* host */
1286  if (NIL_P(host)) {
1287  hptr = NULL;
1288  }
1289  else {
1290  strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
1291  hbuf[sizeof(hbuf) - 1] = '\0';
1292  hptr = hbuf;
1293  }
1294  /* port */
1295  if (NIL_P(port)) {
1296  strcpy(pbuf, "0");
1297  pptr = NULL;
1298  }
1299  else if (FIXNUM_P(port)) {
1300  snprintf(pbuf, sizeof(pbuf), "%ld", NUM2LONG(port));
1301  pptr = pbuf;
1302  }
1303  else {
1304  strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
1305  pbuf[sizeof(pbuf) - 1] = '\0';
1306  pptr = pbuf;
1307  }
1308  hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
1309  /* af */
1310  hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af);
1311  error = rb_getaddrinfo(hptr, pptr, &hints, &res);
1312  if (error) goto error_exit_addr;
1313  sap = res->ai->ai_addr;
1314  salen = res->ai->ai_addrlen;
1315  }
1316  else {
1317  rb_raise(rb_eTypeError, "expecting String or Array");
1318  }
1319 
1320  call_nameinfo:
1321  error = rb_getnameinfo(sap, salen, hbuf, sizeof(hbuf),
1322  pbuf, sizeof(pbuf), fl);
1323  if (error) goto error_exit_name;
1324  if (res) {
1325  for (r = res->ai->ai_next; r; r = r->ai_next) {
1326  char hbuf2[1024], pbuf2[1024];
1327 
1328  sap = r->ai_addr;
1329  salen = r->ai_addrlen;
1330  error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2),
1331  pbuf2, sizeof(pbuf2), fl);
1332  if (error) goto error_exit_name;
1333  if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
1334  rb_freeaddrinfo(res);
1335  rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
1336  }
1337  }
1338  rb_freeaddrinfo(res);
1339  }
1340  return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
1341 
1342  error_exit_addr:
1343  saved_errno = errno;
1344  if (res) rb_freeaddrinfo(res);
1345  errno = saved_errno;
1346  rsock_raise_socket_error("getaddrinfo", error);
1347 
1348  error_exit_name:
1349  saved_errno = errno;
1350  if (res) rb_freeaddrinfo(res);
1351  errno = saved_errno;
1352  rsock_raise_socket_error("getnameinfo", error);
1353 
1354  UNREACHABLE;
1355 }
1356 
1357 /*
1358  * call-seq:
1359  * Socket.sockaddr_in(port, host) => sockaddr
1360  * Socket.pack_sockaddr_in(port, host) => sockaddr
1361  *
1362  * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string.
1363  *
1364  * Socket.sockaddr_in(80, "127.0.0.1")
1365  * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1366  *
1367  * Socket.sockaddr_in(80, "::1")
1368  * #=> "\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"
1369  *
1370  */
1371 static VALUE
1373 {
1374  struct rb_addrinfo *res = rsock_addrinfo(host, port, AF_UNSPEC, 0, 0);
1375  VALUE addr = rb_str_new((char*)res->ai->ai_addr, res->ai->ai_addrlen);
1376 
1377  rb_freeaddrinfo(res);
1378  OBJ_INFECT(addr, port);
1379  OBJ_INFECT(addr, host);
1380 
1381  return addr;
1382 }
1383 
1384 /*
1385  * call-seq:
1386  * Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address]
1387  *
1388  * Unpacks _sockaddr_ into port and ip_address.
1389  *
1390  * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6.
1391  *
1392  * sockaddr = Socket.sockaddr_in(80, "127.0.0.1")
1393  * p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1394  * p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"]
1395  *
1396  */
1397 static VALUE
1399 {
1400  struct sockaddr_in * sockaddr;
1401  VALUE host;
1402 
1403  sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr);
1404  if (RSTRING_LEN(addr) <
1405  (char*)&((struct sockaddr *)sockaddr)->sa_family +
1406  sizeof(((struct sockaddr *)sockaddr)->sa_family) -
1407  (char*)sockaddr)
1408  rb_raise(rb_eArgError, "too short sockaddr");
1409  if (((struct sockaddr *)sockaddr)->sa_family != AF_INET
1410 #ifdef INET6
1411  && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6
1412 #endif
1413  ) {
1414 #ifdef INET6
1415  rb_raise(rb_eArgError, "not an AF_INET/AF_INET6 sockaddr");
1416 #else
1417  rb_raise(rb_eArgError, "not an AF_INET sockaddr");
1418 #endif
1419  }
1420  host = rsock_make_ipaddr((struct sockaddr*)sockaddr, RSTRING_SOCKLEN(addr));
1421  OBJ_INFECT(host, addr);
1422  return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host);
1423 }
1424 
1425 #ifdef HAVE_SYS_UN_H
1426 
1427 /*
1428  * call-seq:
1429  * Socket.sockaddr_un(path) => sockaddr
1430  * Socket.pack_sockaddr_un(path) => sockaddr
1431  *
1432  * Packs _path_ as an AF_UNIX sockaddr string.
1433  *
1434  * Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..."
1435  *
1436  */
1437 static VALUE
1438 sock_s_pack_sockaddr_un(VALUE self, VALUE path)
1439 {
1440  struct sockaddr_un sockaddr;
1441  VALUE addr;
1442 
1443  StringValue(path);
1444  INIT_SOCKADDR_UN(&sockaddr, sizeof(struct sockaddr_un));
1445  if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
1446  rb_raise(rb_eArgError, "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
1447  (size_t)RSTRING_LEN(path), sizeof(sockaddr.sun_path));
1448  }
1449  memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
1450  addr = rb_str_new((char*)&sockaddr, rsock_unix_sockaddr_len(path));
1451  OBJ_INFECT(addr, path);
1452 
1453  return addr;
1454 }
1455 
1456 /*
1457  * call-seq:
1458  * Socket.unpack_sockaddr_un(sockaddr) => path
1459  *
1460  * Unpacks _sockaddr_ into path.
1461  *
1462  * _sockaddr_ should be a string or an addrinfo for AF_UNIX.
1463  *
1464  * sockaddr = Socket.sockaddr_un("/tmp/sock")
1465  * p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock"
1466  *
1467  */
1468 static VALUE
1469 sock_s_unpack_sockaddr_un(VALUE self, VALUE addr)
1470 {
1471  struct sockaddr_un * sockaddr;
1472  VALUE path;
1473 
1474  sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr);
1475  if (RSTRING_LEN(addr) <
1476  (char*)&((struct sockaddr *)sockaddr)->sa_family +
1477  sizeof(((struct sockaddr *)sockaddr)->sa_family) -
1478  (char*)sockaddr)
1479  rb_raise(rb_eArgError, "too short sockaddr");
1480  if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) {
1481  rb_raise(rb_eArgError, "not an AF_UNIX sockaddr");
1482  }
1483  if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) {
1484  rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d",
1485  RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un));
1486  }
1487  path = rsock_unixpath_str(sockaddr, RSTRING_SOCKLEN(addr));
1488  OBJ_INFECT(path, addr);
1489  return path;
1490 }
1491 #endif
1492 
1493 #if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32)
1494 
1495 static socklen_t
1496 sockaddr_len(struct sockaddr *addr)
1497 {
1498  if (addr == NULL)
1499  return 0;
1500 
1501 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1502  if (addr->sa_len != 0)
1503  return addr->sa_len;
1504 #endif
1505 
1506  switch (addr->sa_family) {
1507  case AF_INET:
1508  return (socklen_t)sizeof(struct sockaddr_in);
1509 
1510 #ifdef AF_INET6
1511  case AF_INET6:
1512  return (socklen_t)sizeof(struct sockaddr_in6);
1513 #endif
1514 
1515 #ifdef HAVE_SYS_UN_H
1516  case AF_UNIX:
1517  return (socklen_t)sizeof(struct sockaddr_un);
1518 #endif
1519 
1520 #ifdef AF_PACKET
1521  case AF_PACKET:
1522  return (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + ((struct sockaddr_ll *)addr)->sll_halen);
1523 #endif
1524 
1525  default:
1526  return (socklen_t)(offsetof(struct sockaddr, sa_family) + sizeof(addr->sa_family));
1527  }
1528 }
1529 
1530 socklen_t
1531 rsock_sockaddr_len(struct sockaddr *addr)
1532 {
1533  return sockaddr_len(addr);
1534 }
1535 
1536 static VALUE
1537 sockaddr_obj(struct sockaddr *addr, socklen_t len)
1538 {
1539 #if defined(AF_INET6) && defined(__KAME__)
1540  struct sockaddr_in6 addr6;
1541 #endif
1542 
1543  if (addr == NULL)
1544  return Qnil;
1545 
1546  len = sockaddr_len(addr);
1547 
1548 #if defined(__KAME__) && defined(AF_INET6)
1549  if (addr->sa_family == AF_INET6) {
1550  /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */
1551  /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */
1552  /* convert fe80:1::1 to fe80::1%1 */
1553  len = (socklen_t)sizeof(struct sockaddr_in6);
1554  memcpy(&addr6, addr, len);
1555  addr = (struct sockaddr *)&addr6;
1556  if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
1557  addr6.sin6_scope_id == 0 &&
1558  (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) {
1559  addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3];
1560  addr6.sin6_addr.s6_addr[2] = 0;
1561  addr6.sin6_addr.s6_addr[3] = 0;
1562  }
1563  }
1564 #endif
1565 
1566  return rsock_addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil);
1567 }
1568 
1569 VALUE
1570 rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
1571 {
1572  return sockaddr_obj(addr, len);
1573 }
1574 
1575 #endif
1576 
1577 #if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) || defined(_WIN32)
1578 /*
1579  * call-seq:
1580  * Socket.ip_address_list => array
1581  *
1582  * Returns local IP addresses as an array.
1583  *
1584  * The array contains Addrinfo objects.
1585  *
1586  * pp Socket.ip_address_list
1587  * #=> [#<Addrinfo: 127.0.0.1>,
1588  * #<Addrinfo: 192.168.0.128>,
1589  * #<Addrinfo: ::1>,
1590  * ...]
1591  *
1592  */
1593 static VALUE
1595 {
1596 #if defined(HAVE_GETIFADDRS)
1597  struct ifaddrs *ifp = NULL;
1598  struct ifaddrs *p;
1599  int ret;
1600  VALUE list;
1601 
1602  ret = getifaddrs(&ifp);
1603  if (ret == -1) {
1604  rb_sys_fail("getifaddrs");
1605  }
1606 
1607  list = rb_ary_new();
1608  for (p = ifp; p; p = p->ifa_next) {
1609  if (p->ifa_addr != NULL && IS_IP_FAMILY(p->ifa_addr->sa_family)) {
1610  struct sockaddr *addr = p->ifa_addr;
1611 #if defined(AF_INET6) && defined(__sun)
1612  /*
1613  * OpenIndiana SunOS 5.11 getifaddrs() returns IPv6 link local
1614  * address with sin6_scope_id == 0.
1615  * So fill it from the interface name (ifa_name).
1616  */
1617  struct sockaddr_in6 addr6;
1618  if (addr->sa_family == AF_INET6) {
1619  socklen_t len = (socklen_t)sizeof(struct sockaddr_in6);
1620  memcpy(&addr6, addr, len);
1621  addr = (struct sockaddr *)&addr6;
1622  if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
1623  addr6.sin6_scope_id == 0) {
1624  unsigned int ifindex = if_nametoindex(p->ifa_name);
1625  if (ifindex != 0) {
1626  addr6.sin6_scope_id = ifindex;
1627  }
1628  }
1629  }
1630 #endif
1631  rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
1632  }
1633  }
1634 
1635  freeifaddrs(ifp);
1636 
1637  return list;
1638 #elif defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)
1639  /* Solaris if_tcp(7P) */
1640  /* HP-UX has SIOCGLIFCONF too. But it uses different struct */
1641  int fd = -1;
1642  int ret;
1643  struct lifnum ln;
1644  struct lifconf lc;
1645  const char *reason = NULL;
1646  int save_errno;
1647  int i;
1648  VALUE list = Qnil;
1649 
1650  lc.lifc_buf = NULL;
1651 
1652  fd = socket(AF_INET, SOCK_DGRAM, 0);
1653  if (fd == -1)
1654  rb_sys_fail("socket(2)");
1655 
1656  memset(&ln, 0, sizeof(ln));
1657  ln.lifn_family = AF_UNSPEC;
1658 
1659  ret = ioctl(fd, SIOCGLIFNUM, &ln);
1660  if (ret == -1) {
1661  reason = "SIOCGLIFNUM";
1662  goto finish;
1663  }
1664 
1665  memset(&lc, 0, sizeof(lc));
1666  lc.lifc_family = AF_UNSPEC;
1667  lc.lifc_flags = 0;
1668  lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count;
1669  lc.lifc_req = xmalloc(lc.lifc_len);
1670 
1671  ret = ioctl(fd, SIOCGLIFCONF, &lc);
1672  if (ret == -1) {
1673  reason = "SIOCGLIFCONF";
1674  goto finish;
1675  }
1676 
1677  list = rb_ary_new();
1678  for (i = 0; i < ln.lifn_count; i++) {
1679  struct lifreq *req = &lc.lifc_req[i];
1680  if (IS_IP_FAMILY(req->lifr_addr.ss_family)) {
1681  if (req->lifr_addr.ss_family == AF_INET6 &&
1682  IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) &&
1683  ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id == 0) {
1684  struct lifreq req2;
1685  memcpy(req2.lifr_name, req->lifr_name, LIFNAMSIZ);
1686  ret = ioctl(fd, SIOCGLIFINDEX, &req2);
1687  if (ret == -1) {
1688  reason = "SIOCGLIFINDEX";
1689  goto finish;
1690  }
1691  ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id = req2.lifr_index;
1692  }
1693  rb_ary_push(list, sockaddr_obj((struct sockaddr *)&req->lifr_addr, req->lifr_addrlen));
1694  }
1695  }
1696 
1697  finish:
1698  save_errno = errno;
1699  if (lc.lifc_buf != NULL)
1700  xfree(lc.lifc_req);
1701  if (fd != -1)
1702  close(fd);
1703  errno = save_errno;
1704 
1705  if (reason)
1706  rb_syserr_fail(save_errno, reason);
1707  return list;
1708 
1709 #elif defined(SIOCGIFCONF)
1710  int fd = -1;
1711  int ret;
1712 #define EXTRA_SPACE ((int)(sizeof(struct ifconf) + sizeof(union_sockaddr)))
1713  char initbuf[4096+EXTRA_SPACE];
1714  char *buf = initbuf;
1715  int bufsize;
1716  struct ifconf conf;
1717  struct ifreq *req;
1718  VALUE list = Qnil;
1719  const char *reason = NULL;
1720  int save_errno;
1721 
1722  fd = socket(AF_INET, SOCK_DGRAM, 0);
1723  if (fd == -1)
1724  rb_sys_fail("socket(2)");
1725 
1726  bufsize = sizeof(initbuf);
1727  buf = initbuf;
1728 
1729  retry:
1730  conf.ifc_len = bufsize;
1731  conf.ifc_req = (struct ifreq *)buf;
1732 
1733  /* fprintf(stderr, "bufsize: %d\n", bufsize); */
1734 
1735  ret = ioctl(fd, SIOCGIFCONF, &conf);
1736  if (ret == -1) {
1737  reason = "SIOCGIFCONF";
1738  goto finish;
1739  }
1740 
1741  /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */
1742 
1743  if (bufsize - EXTRA_SPACE < conf.ifc_len) {
1744  if (bufsize < conf.ifc_len) {
1745  /* NetBSD returns required size for all interfaces. */
1746  bufsize = conf.ifc_len + EXTRA_SPACE;
1747  }
1748  else {
1749  bufsize = bufsize << 1;
1750  }
1751  if (buf == initbuf)
1752  buf = NULL;
1753  buf = xrealloc(buf, bufsize);
1754  goto retry;
1755  }
1756 
1757  close(fd);
1758  fd = -1;
1759 
1760  list = rb_ary_new();
1761  req = conf.ifc_req;
1762  while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) {
1763  struct sockaddr *addr = &req->ifr_addr;
1764  if (IS_IP_FAMILY(addr->sa_family)) {
1765  rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
1766  }
1767 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1768 # ifndef _SIZEOF_ADDR_IFREQ
1769 # define _SIZEOF_ADDR_IFREQ(r) \
1770  (sizeof(struct ifreq) + \
1771  (sizeof(struct sockaddr) < (r).ifr_addr.sa_len ? \
1772  (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \
1773  0))
1774 # endif
1775  req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req));
1776 #else
1777  req = (struct ifreq *)((char*)req + sizeof(struct ifreq));
1778 #endif
1779  }
1780 
1781  finish:
1782 
1783  save_errno = errno;
1784  if (buf != initbuf)
1785  xfree(buf);
1786  if (fd != -1)
1787  close(fd);
1788  errno = save_errno;
1789 
1790  if (reason)
1791  rb_syserr_fail(save_errno, reason);
1792  return list;
1793 
1794 #undef EXTRA_SPACE
1795 #elif defined(_WIN32)
1796  typedef struct ip_adapter_unicast_address_st {
1797  unsigned LONG_LONG dummy0;
1798  struct ip_adapter_unicast_address_st *Next;
1799  struct {
1800  struct sockaddr *lpSockaddr;
1801  int iSockaddrLength;
1802  } Address;
1803  int dummy1;
1804  int dummy2;
1805  int dummy3;
1806  long dummy4;
1807  long dummy5;
1808  long dummy6;
1809  } ip_adapter_unicast_address_t;
1810  typedef struct ip_adapter_anycast_address_st {
1811  unsigned LONG_LONG dummy0;
1812  struct ip_adapter_anycast_address_st *Next;
1813  struct {
1814  struct sockaddr *lpSockaddr;
1815  int iSockaddrLength;
1816  } Address;
1817  } ip_adapter_anycast_address_t;
1818  typedef struct ip_adapter_addresses_st {
1819  unsigned LONG_LONG dummy0;
1820  struct ip_adapter_addresses_st *Next;
1821  void *dummy1;
1822  ip_adapter_unicast_address_t *FirstUnicastAddress;
1823  ip_adapter_anycast_address_t *FirstAnycastAddress;
1824  void *dummy2;
1825  void *dummy3;
1826  void *dummy4;
1827  void *dummy5;
1828  void *dummy6;
1829  BYTE dummy7[8];
1830  DWORD dummy8;
1831  DWORD dummy9;
1832  DWORD dummy10;
1833  DWORD IfType;
1834  int OperStatus;
1835  DWORD dummy12;
1836  DWORD dummy13[16];
1837  void *dummy14;
1838  } ip_adapter_addresses_t;
1839  typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG);
1840  HMODULE h;
1841  GetAdaptersAddresses_t pGetAdaptersAddresses;
1842  ULONG len;
1843  DWORD ret;
1844  ip_adapter_addresses_t *adapters;
1845  VALUE list;
1846 
1847  h = LoadLibrary("iphlpapi.dll");
1848  if (!h)
1849  rb_notimplement();
1850  pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses");
1851  if (!pGetAdaptersAddresses) {
1852  FreeLibrary(h);
1853  rb_notimplement();
1854  }
1855 
1856  ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len);
1857  if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) {
1858  errno = rb_w32_map_errno(ret);
1859  FreeLibrary(h);
1860  rb_sys_fail("GetAdaptersAddresses");
1861  }
1862  adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len);
1863  ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len);
1864  if (ret != ERROR_SUCCESS) {
1865  errno = rb_w32_map_errno(ret);
1866  FreeLibrary(h);
1867  rb_sys_fail("GetAdaptersAddresses");
1868  }
1869 
1870  list = rb_ary_new();
1871  for (; adapters; adapters = adapters->Next) {
1872  ip_adapter_unicast_address_t *uni;
1873  ip_adapter_anycast_address_t *any;
1874  if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */
1875  continue;
1876  for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) {
1877 #ifndef INET6
1878  if (uni->Address.lpSockaddr->sa_family == AF_INET)
1879 #else
1880  if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family))
1881 #endif
1882  rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr, uni->Address.iSockaddrLength));
1883  }
1884  for (any = adapters->FirstAnycastAddress; any; any = any->Next) {
1885 #ifndef INET6
1886  if (any->Address.lpSockaddr->sa_family == AF_INET)
1887 #else
1888  if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family))
1889 #endif
1890  rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr, any->Address.iSockaddrLength));
1891  }
1892  }
1893 
1894  FreeLibrary(h);
1895  return list;
1896 #endif
1897 }
1898 #else
1899 #define socket_s_ip_address_list rb_f_notimplement
1900 #endif
1901 
1902 void
1904 {
1906 
1907  /*
1908  * Document-class: Socket < BasicSocket
1909  *
1910  * Class +Socket+ provides access to the underlying operating system
1911  * socket implementations. It can be used to provide more operating system
1912  * specific functionality than the protocol-specific socket classes.
1913  *
1914  * The constants defined under Socket::Constants are also defined under
1915  * Socket. For example, Socket::AF_INET is usable as well as
1916  * Socket::Constants::AF_INET. See Socket::Constants for the list of
1917  * constants.
1918  *
1919  * === What's a socket?
1920  *
1921  * Sockets are endpoints of a bidirectional communication channel.
1922  * Sockets can communicate within a process, between processes on the same
1923  * machine or between different machines. There are many types of socket:
1924  * TCPSocket, UDPSocket or UNIXSocket for example.
1925  *
1926  * Sockets have their own vocabulary:
1927  *
1928  * *domain:*
1929  * The family of protocols:
1930  * * Socket::PF_INET
1931  * * Socket::PF_INET6
1932  * * Socket::PF_UNIX
1933  * * etc.
1934  *
1935  * *type:*
1936  * The type of communications between the two endpoints, typically
1937  * * Socket::SOCK_STREAM
1938  * * Socket::SOCK_DGRAM.
1939  *
1940  * *protocol:*
1941  * Typically _zero_.
1942  * This may be used to identify a variant of a protocol.
1943  *
1944  * *hostname:*
1945  * The identifier of a network interface:
1946  * * a string (hostname, IPv4 or IPv6 address or +broadcast+
1947  * which specifies a broadcast address)
1948  * * a zero-length string which specifies INADDR_ANY
1949  * * an integer (interpreted as binary address in host byte order).
1950  *
1951  * === Quick start
1952  *
1953  * Many of the classes, such as TCPSocket, UDPSocket or UNIXSocket,
1954  * ease the use of sockets comparatively to the equivalent C programming interface.
1955  *
1956  * Let's create an internet socket using the IPv4 protocol in a C-like manner:
1957  *
1958  * require 'socket'
1959  *
1960  * s = Socket.new Socket::AF_INET, Socket::SOCK_STREAM
1961  * s.connect Socket.pack_sockaddr_in(80, 'example.com')
1962  *
1963  * You could also use the TCPSocket class:
1964  *
1965  * s = TCPSocket.new 'example.com', 80
1966  *
1967  * A simple server might look like this:
1968  *
1969  * require 'socket'
1970  *
1971  * server = TCPServer.new 2000 # Server bound to port 2000
1972  *
1973  * loop do
1974  * client = server.accept # Wait for a client to connect
1975  * client.puts "Hello !"
1976  * client.puts "Time is #{Time.now}"
1977  * client.close
1978  * end
1979  *
1980  * A simple client may look like this:
1981  *
1982  * require 'socket'
1983  *
1984  * s = TCPSocket.new 'localhost', 2000
1985  *
1986  * while line = s.gets # Read lines from socket
1987  * puts line # and print them
1988  * end
1989  *
1990  * s.close # close socket when done
1991  *
1992  * === Exception Handling
1993  *
1994  * Ruby's Socket implementation raises exceptions based on the error
1995  * generated by the system dependent implementation. This is why the
1996  * methods are documented in a way that isolate Unix-based system
1997  * exceptions from Windows based exceptions. If more information on a
1998  * particular exception is needed, please refer to the Unix manual pages or
1999  * the Windows WinSock reference.
2000  *
2001  * === Convenience methods
2002  *
2003  * Although the general way to create socket is Socket.new,
2004  * there are several methods of socket creation for most cases.
2005  *
2006  * TCP client socket::
2007  * Socket.tcp, TCPSocket.open
2008  * TCP server socket::
2009  * Socket.tcp_server_loop, TCPServer.open
2010  * UNIX client socket::
2011  * Socket.unix, UNIXSocket.open
2012  * UNIX server socket::
2013  * Socket.unix_server_loop, UNIXServer.open
2014  *
2015  * === Documentation by
2016  *
2017  * * Zach Dennis
2018  * * Sam Roberts
2019  * * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
2020  *
2021  * Much material in this documentation is taken with permission from
2022  * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
2023  */
2025 
2027 
2028  rb_define_method(rb_cSocket, "initialize", sock_initialize, -1);
2029  rb_define_method(rb_cSocket, "connect", sock_connect, 1);
2030 
2031  /* for ext/socket/lib/socket.rb use only: */
2033  "__connect_nonblock", sock_connect_nonblock, 2);
2034 
2035  rb_define_method(rb_cSocket, "bind", sock_bind, 1);
2037  rb_define_method(rb_cSocket, "accept", sock_accept, 0);
2038 
2039  /* for ext/socket/lib/socket.rb use only: */
2041  "__accept_nonblock", sock_accept_nonblock, 1);
2042 
2043  rb_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0);
2044 
2045  rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1);
2046 
2047  /* for ext/socket/lib/socket.rb use only: */
2049  "__recvfrom_nonblock", sock_recvfrom_nonblock, 4);
2050 
2063 #ifdef HAVE_SYS_UN_H
2064  rb_define_singleton_method(rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1);
2065  rb_define_singleton_method(rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1);
2066  rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1);
2067 #endif
2068 
2070 
2071 #undef rb_intern
2072  sym_wait_writable = ID2SYM(rb_intern("wait_writable"));
2073 }
void rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
Definition: socket.c:94
static VALUE sock_s_getservbyport(int argc, VALUE *argv)
Definition: socket.c:1112
#define rb_str_new4
Definition: intern.h:859
VALUE rb_ary_entry(VALUE ary, long offset)
Definition: array.c:1196
#define RARRAY_LEN(a)
Definition: ruby.h:1026
int ioctl(int, int,...)
Definition: win32.c:2755
#define VALIDATE_SOCKLEN(addr, len)
Definition: sockport.h:16
size_t strlen(const char *)
#define Next(p, e, enc)
Definition: dir.c:197
#define INT2NUM(x)
Definition: ruby.h:1538
void rb_update_max_fd(int fd)
Definition: io.c:189
void rb_io_set_nonblock(rb_io_t *fptr)
Definition: io.c:2458
void rb_syserr_fail(int e, const char *mesg)
Definition: error.c:2314
VALUE rb_cBasicSocket
Definition: init.c:13
#define NUM2INT(x)
Definition: ruby.h:684
static VALUE io_call_close(VALUE io)
Definition: io.c:4504
static VALUE sock_initialize(int argc, VALUE *argv, VALUE sock)
Definition: socket.c:133
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
VALUE rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
#define NI_DGRAM
Definition: addrinfo.h:128
VALUE rsock_make_ipaddr(struct sockaddr *addr, socklen_t addrlen)
Definition: raddrinfo.c:396
Definition: io.h:62
int rsock_socktype_arg(VALUE type)
Definition: constants.c:50
void rb_define_private_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1527
VALUE rb_eTypeError
Definition: error.c:762
#define UNREACHABLE
Definition: ruby.h:46
st_table * names
Definition: encoding.c:58
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:905
VALUE rsock_init_sock(VALUE sock, int fd)
Definition: init.c:60
static VALUE sock_s_getaddrinfo(int argc, VALUE *argv)
Definition: socket.c:1167
int rb_gc_for_fd(int err)
Definition: io.c:876
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2207
VALUE rsock_s_accept(VALUE klass, int fd, struct sockaddr *sockaddr, socklen_t *len)
Definition: init.c:595
static VALUE sym_wait_writable
Definition: socket.c:13
VALUE rb_check_sockaddr_string_type(VALUE val)
Definition: raddrinfo.c:2509
void Init_socket(void)
Definition: socket.c:1903
struct sockaddr * ifa_addr
Definition: win32.h:221
void rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
Definition: socket.c:77
#define AI_CANONNAME
Definition: addrinfo.h:97
static VALUE sock_accept(VALUE sock)
Definition: socket.c:790
VALUE rsock_ipaddr(struct sockaddr *sockaddr, socklen_t sockaddrlen, int norevlookup)
Definition: raddrinfo.c:559
#define EINPROGRESS
Definition: win32.h:477
#define FIXNUM_P(f)
Definition: ruby.h:365
static VALUE sock_accept_nonblock(VALUE sock, VALUE ex)
Definition: socket.c:805
int rb_w32_map_errno(DWORD)
Definition: win32.c:273
VALUE rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, VALUE ex, enum sock_recv_type from)
Definition: init.c:209
#define GetOpenFile(obj, fp)
Definition: io.h:120
static const unsigned char dv[]
Definition: nkf.c:586
void freeifaddrs(struct ifaddrs *)
Definition: win32.c:4190
VALUE rsock_io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len)
Definition: raddrinfo.c:2536
VALUE rb_eRangeError
Definition: error.c:766
static VALUE sock_s_unpack_sockaddr_in(VALUE, VALUE)
Definition: socket.c:1398
socklen_t rsock_sockaddr_len(struct sockaddr *addr)
void rb_freeaddrinfo(struct rb_addrinfo *ai)
Definition: raddrinfo.c:322
static VALUE sock_s_getnameinfo(int argc, VALUE *argv)
Definition: socket.c:1221
VALUE rsock_make_hostent(VALUE host, struct rb_addrinfo *addr, VALUE(*ipaddr)(struct sockaddr *, socklen_t))
Definition: raddrinfo.c:704
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
VALUE rsock_addrinfo_new(struct sockaddr *addr, socklen_t len, int family, int socktype, int protocol, VALUE canonname, VALUE inspectname)
Definition: raddrinfo.c:800
static VALUE sock_recvfrom(int argc, VALUE *argv, VALUE sock)
Definition: socket.c:763
VALUE rsock_s_accept_nonblock(VALUE klass, VALUE ex, rb_io_t *fptr, struct sockaddr *sockaddr, socklen_t *len)
Definition: init.c:553
void rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
Definition: socket.c:24
#define MEMZERO(p, type, n)
Definition: ruby.h:1660
struct rb_addrinfo * rsock_addrinfo(VALUE host, VALUE port, int family, int socktype, int flags)
Definition: raddrinfo.c:547
int getifaddrs(struct ifaddrs **)
Definition: win32.c:4103
VALUE rb_rescue(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*r_proc)(ANYARGS), VALUE data2)
Definition: eval.c:883
#define RSTRING_SOCKLEN
Definition: rubysocket.h:124
struct ifaddrs * ifa_next
Definition: win32.h:218
int rb_block_given_p(void)
Definition: eval.c:797
int rsock_family_arg(VALUE domain)
Definition: constants.c:43
static VALUE sock_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, VALUE ex)
Definition: socket.c:770
IUnknown DWORD
Definition: win32ole.c:32
static VALUE sock_sysaccept(VALUE sock)
Definition: socket.c:860
void rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
Definition: socket.c:41
VALUE rb_ary_new(void)
Definition: array.c:493
#define STRTOUL(str, endptr, base)
Definition: ruby.h:2141
int rsock_socket(int domain, int type, int proto)
Definition: init.c:357
#define snprintf
Definition: subst.h:6
#define NIL_P(v)
Definition: ruby.h:451
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:646
int fd
Definition: io.h:64
char * ai_canonname
Definition: addrinfo.h:137
struct rb_addrinfo * rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack)
Definition: raddrinfo.c:506
#define offsetof(p_type, field)
Definition: addrinfo.h:186
#define sock_gethostname
Definition: socket.c:932
int argc
Definition: ruby.c:183
#define Qfalse
Definition: ruby.h:436
#define ALLOCA_N(type, n)
Definition: ruby.h:1593
#define rb_str_new2
Definition: intern.h:857
VALUE rb_obj_alloc(VALUE)
Definition: object.c:1845
int err
Definition: win32.c:135
VALUE rb_cSocket
Definition: init.c:22
#define SockAddrStringValuePtr(v)
Definition: rubysocket.h:265
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2562
#define IS_IP_FAMILY(af)
Definition: rubysocket.h:156
#define RSTRING_LEN(str)
Definition: ruby.h:978
VALUE rb_yield(VALUE)
Definition: vm_eval.c:1020
VALUE rsock_sock_listen(VALUE sock, VALUE log)
Definition: socket.c:644
int errno
int socklen_t
Definition: getaddrinfo.c:83
static VALUE make_addrinfo(struct rb_addrinfo *res0, int norevlookup)
Definition: socket.c:937
void rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
Definition: socket.c:61
VALUE rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
Definition: init.c:146
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1440
static VALUE io_close(VALUE io)
Definition: io.c:4524
static void setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
Definition: socket.c:108
static VALUE sock_s_pack_sockaddr_in(VALUE self, VALUE port, VALUE host)
Definition: socket.c:1372
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1919
void rb_str_modify_expand(VALUE, long)
Definition: string.c:1988
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Definition: array.c:623
#define PRIsVALUE
Definition: ruby.h:135
#define Qnil
Definition: ruby.h:438
void rsock_init_basicsocket(void)
Definition: basicsocket.c:689
int rsock_do_not_reverse_lookup
Definition: init.c:31
#define SockAddrStringValueWithAddrinfo(v, rai_ret)
Definition: rubysocket.h:266
void rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
Definition: socket.c:55
void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite writable, int n, const char *mesg)
Definition: io.c:12128
void rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
Definition: socket.c:18
unsigned long VALUE
Definition: ruby.h:85
int rsock_detect_cloexec(int fd)
Definition: init.c:284
#define AI_NUMERICHOST
Definition: addrinfo.h:98
VALUE rb_ensure(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*e_proc)(ANYARGS), VALUE data2)
Definition: eval.c:923
#define rb_tainted_str_new2
Definition: intern.h:861
static VALUE sock_connect(VALUE sock, VALUE addr)
Definition: socket.c:423
void rb_sys_fail(const char *mesg)
Definition: error.c:2326
#define rb_funcallv
Definition: console.c:21
register unsigned int len
Definition: zonetab.h:51
int ai_protocol
Definition: addrinfo.h:135
#define StringValueCStr(v)
Definition: ruby.h:571
int rb_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags)
Definition: raddrinfo.c:363
void rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
Definition: socket.c:71
#define RSTRING_PTR(str)
Definition: ruby.h:982
VALUE rb_eSocket
Definition: init.c:25
#define RARRAY_ASET(a, i, v)
Definition: ruby.h:1041
#define INT2FIX(i)
Definition: ruby.h:232
#define EISCONN
Definition: win32.h:537
#define RARRAY_AREF(a, i)
Definition: ruby.h:1040
#define PF_UNSPEC
Definition: sockport.h:105
#define xmalloc
Definition: defines.h:183
int ai_socktype
Definition: addrinfo.h:134
int rsock_revlookup_flag(VALUE revlookup, int *norevlookup)
Definition: ipsocket.c:172
void rb_fd_fix_cloexec(int fd)
Definition: io.c:231
VALUE rb_check_array_type(VALUE ary)
Definition: array.c:635
void rsock_sys_fail_raddrinfo_or_sockaddr(const char *mesg, VALUE addr, VALUE rai)
Definition: socket.c:88
#define proto(p)
Definition: sdbm.h:60
void rsock_raise_socket_error(const char *reason, int error)
Definition: init.c:35
void rb_syserr_fail_str(int e, VALUE mesg)
Definition: error.c:2320
struct addrinfo * ai
Definition: rubysocket.h:285
int rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks)
Definition: init.c:454
#define T_STRING
Definition: ruby.h:496
#define AF_UNSPEC
Definition: sockport.h:101
#define PRIuSIZE
Definition: ruby.h:177
#define OBJ_INFECT(x, s)
Definition: ruby.h:1304
struct rb_encoding_entry * list
Definition: encoding.c:55
static VALUE sock_bind(VALUE sock, VALUE addr)
Definition: socket.c:560
int rb_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct rb_addrinfo **res)
Definition: raddrinfo.c:288
void rb_notimplement(void)
Definition: error.c:2253
struct addrinfo * ai_next
Definition: addrinfo.h:139
const char * name
Definition: nkf.c:208
#define xrealloc
Definition: defines.h:186
#define ID2SYM(x)
Definition: ruby.h:383
static VALUE sock_connect_nonblock(VALUE sock, VALUE addr, VALUE ex)
Definition: socket.c:443
#define StringValuePtr(v)
Definition: ruby.h:570
static VALUE sock_s_getservbyname(int argc, VALUE *argv)
Definition: socket.c:1071
void rsock_sys_fail_path(const char *mesg, VALUE path)
Definition: socket.c:35
size_t ai_addrlen
Definition: addrinfo.h:136
#define memcpy(d, s, n)
Definition: ffi_common.h:55
#define rsock_sock_s_socketpair
Definition: socket.c:308
int socketpair(int, int, int, int *)
Definition: win32.c:4036
void void xfree(void *)
static VALUE sock_s_gethostbyaddr(int argc, VALUE *argv)
Definition: socket.c:1009
#define rb_intern(str)
int ai_flags
Definition: addrinfo.h:132
#define SYMBOL_P(x)
Definition: ruby.h:382
#define NULL
Definition: _sdbm.c:102
void rsock_init_socket_init(void)
Definition: init.c:662
VALUE rsock_addrinfo_inspect_sockaddr(VALUE self)
Definition: raddrinfo.c:1519
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
static ULONG(STDMETHODCALLTYPE AddRef)(IDispatch __RPC_FAR *This)
Definition: win32ole.c:199
struct sockaddr * ai_addr
Definition: addrinfo.h:138
VALUE rb_eArgError
Definition: error.c:763
#define NUM2LONG(x)
Definition: ruby.h:648
void rb_maygvl_fd_fix_cloexec(int fd)
Definition: io.c:208
static VALUE sock_sockaddr(struct sockaddr *addr, socklen_t len)
Definition: socket.c:960
static VALUE sock_s_gethostbyname(VALUE obj, VALUE host)
Definition: socket.c:992
char ** argv
Definition: ruby.c:184
#define StringValue(v)
Definition: ruby.h:569
char * ifa_name
Definition: win32.h:219
Definition: win32.h:217
struct sockaddr addr
Definition: rubysocket.h:187
#define socket_s_ip_address_list
Definition: socket.c:1899
VALUE rb_str_new(const char *, long)
Definition: string.c:736
int ai_family
Definition: addrinfo.h:133