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