PageRenderTime 107ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/socket/socket.c

https://github.com/wanabe/ruby
C | 2030 lines | 1031 code | 174 blank | 825 comment | 178 complexity | 43a9ba5bcc555b1b15ae4a500151057e MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, 0BSD, Unlicense, GPL-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /************************************************
  2. socket.c -
  3. created at: Thu Mar 31 12:21:29 JST 1994
  4. Copyright (C) 1993-2007 Yukihiro Matsumoto
  5. ************************************************/
  6. #include "rubysocket.h"
  7. static VALUE sym_wait_writable;
  8. static VALUE sock_s_unpack_sockaddr_in(VALUE, VALUE);
  9. void
  10. rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
  11. {
  12. rsock_syserr_fail_host_port(errno, mesg, host, port);
  13. }
  14. void
  15. rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
  16. {
  17. VALUE message;
  18. message = rb_sprintf("%s for %+"PRIsVALUE" port % "PRIsVALUE"",
  19. mesg, host, port);
  20. rb_syserr_fail_str(err, message);
  21. }
  22. void
  23. rsock_sys_fail_path(const char *mesg, VALUE path)
  24. {
  25. rsock_syserr_fail_path(errno, mesg, path);
  26. }
  27. void
  28. rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
  29. {
  30. VALUE message;
  31. if (RB_TYPE_P(path, T_STRING)) {
  32. message = rb_sprintf("%s for % "PRIsVALUE"", mesg, path);
  33. rb_syserr_fail_str(err, message);
  34. }
  35. else {
  36. rb_syserr_fail(err, mesg);
  37. }
  38. }
  39. void
  40. rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
  41. {
  42. rsock_syserr_fail_sockaddr(errno, mesg, addr, len);
  43. }
  44. void
  45. rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
  46. {
  47. VALUE rai;
  48. rai = rsock_addrinfo_new(addr, len, PF_UNSPEC, 0, 0, Qnil, Qnil);
  49. rsock_syserr_fail_raddrinfo(err, mesg, rai);
  50. }
  51. void
  52. rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
  53. {
  54. rsock_syserr_fail_raddrinfo(errno, mesg, rai);
  55. }
  56. void
  57. rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
  58. {
  59. VALUE str, message;
  60. str = rsock_addrinfo_inspect_sockaddr(rai);
  61. message = rb_sprintf("%s for %"PRIsVALUE"", mesg, str);
  62. rb_syserr_fail_str(err, message);
  63. }
  64. void
  65. rsock_sys_fail_raddrinfo_or_sockaddr(const char *mesg, VALUE addr, VALUE rai)
  66. {
  67. rsock_syserr_fail_raddrinfo_or_sockaddr(errno, mesg, addr, rai);
  68. }
  69. void
  70. rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
  71. {
  72. if (NIL_P(rai)) {
  73. StringValue(addr);
  74. rsock_syserr_fail_sockaddr(err, mesg,
  75. (struct sockaddr *)RSTRING_PTR(addr),
  76. (socklen_t)RSTRING_LEN(addr)); /* overflow should be checked already */
  77. }
  78. else
  79. rsock_syserr_fail_raddrinfo(err, mesg, rai);
  80. }
  81. static void
  82. setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
  83. {
  84. *dv = rsock_family_arg(domain);
  85. *tv = rsock_socktype_arg(type);
  86. }
  87. /*
  88. * call-seq:
  89. * Socket.new(domain, socktype [, protocol]) => socket
  90. *
  91. * Creates a new socket object.
  92. *
  93. * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
  94. *
  95. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  96. *
  97. * _protocol_ is optional and should be a protocol defined in the domain.
  98. * If protocol is not given, 0 is used internally.
  99. *
  100. * Socket.new(:INET, :STREAM) # TCP socket
  101. * Socket.new(:INET, :DGRAM) # UDP socket
  102. * Socket.new(:UNIX, :STREAM) # UNIX stream socket
  103. * Socket.new(:UNIX, :DGRAM) # UNIX datagram socket
  104. */
  105. static VALUE
  106. sock_initialize(int argc, VALUE *argv, VALUE sock)
  107. {
  108. VALUE domain, type, protocol;
  109. int fd;
  110. int d, t;
  111. rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
  112. if (NIL_P(protocol))
  113. protocol = INT2FIX(0);
  114. setup_domain_and_type(domain, &d, type, &t);
  115. fd = rsock_socket(d, t, NUM2INT(protocol));
  116. if (fd < 0) rb_sys_fail("socket(2)");
  117. return rsock_init_sock(sock, fd);
  118. }
  119. #if defined HAVE_SOCKETPAIR
  120. static VALUE
  121. io_call_close(VALUE io)
  122. {
  123. return rb_funcallv(io, rb_intern("close"), 0, 0);
  124. }
  125. static VALUE
  126. io_close(VALUE io)
  127. {
  128. return rb_rescue(io_call_close, io, 0, 0);
  129. }
  130. static VALUE
  131. pair_yield(VALUE pair)
  132. {
  133. return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1));
  134. }
  135. #endif
  136. #if defined HAVE_SOCKETPAIR
  137. static int
  138. rsock_socketpair0(int domain, int type, int protocol, int descriptors[2])
  139. {
  140. #ifdef SOCK_CLOEXEC
  141. type |= SOCK_CLOEXEC;
  142. #endif
  143. #ifdef SOCK_NONBLOCK
  144. type |= SOCK_NONBLOCK;
  145. #endif
  146. int result = socketpair(domain, type, protocol, descriptors);
  147. if (result == -1)
  148. return -1;
  149. #ifndef SOCK_CLOEXEC
  150. rb_fd_fix_cloexec(descriptors[0]);
  151. rb_fd_fix_cloexec(descriptors[1]);
  152. #endif
  153. #ifndef SOCK_NONBLOCK
  154. rsock_make_fd_nonblock(descriptors[0]);
  155. rsock_make_fd_nonblock(descriptors[1]);
  156. #endif
  157. return result;
  158. }
  159. static int
  160. rsock_socketpair(int domain, int type, int protocol, int descriptors[2])
  161. {
  162. int result;
  163. result = rsock_socketpair0(domain, type, protocol, descriptors);
  164. if (result < 0 && rb_gc_for_fd(errno)) {
  165. result = rsock_socketpair0(domain, type, protocol, descriptors);
  166. }
  167. return result;
  168. }
  169. /*
  170. * call-seq:
  171. * Socket.pair(domain, type, protocol) => [socket1, socket2]
  172. * Socket.socketpair(domain, type, protocol) => [socket1, socket2]
  173. *
  174. * Creates a pair of sockets connected each other.
  175. *
  176. * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
  177. *
  178. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  179. *
  180. * _protocol_ should be a protocol defined in the domain,
  181. * defaults to 0 for the domain.
  182. *
  183. * s1, s2 = Socket.pair(:UNIX, :STREAM, 0)
  184. * s1.send "a", 0
  185. * s1.send "b", 0
  186. * s1.close
  187. * p s2.recv(10) #=> "ab"
  188. * p s2.recv(10) #=> ""
  189. * p s2.recv(10) #=> ""
  190. *
  191. * s1, s2 = Socket.pair(:UNIX, :DGRAM, 0)
  192. * s1.send "a", 0
  193. * s1.send "b", 0
  194. * p s2.recv(10) #=> "a"
  195. * p s2.recv(10) #=> "b"
  196. *
  197. */
  198. VALUE
  199. rsock_sock_s_socketpair(int argc, VALUE *argv, VALUE klass)
  200. {
  201. VALUE domain, type, protocol;
  202. int d, t, p, sp[2];
  203. int ret;
  204. VALUE s1, s2, r;
  205. rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
  206. if (NIL_P(protocol))
  207. protocol = INT2FIX(0);
  208. setup_domain_and_type(domain, &d, type, &t);
  209. p = NUM2INT(protocol);
  210. ret = rsock_socketpair(d, t, p, sp);
  211. if (ret < 0) {
  212. rb_sys_fail("socketpair(2)");
  213. }
  214. s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]);
  215. s2 = rsock_init_sock(rb_obj_alloc(klass), sp[1]);
  216. r = rb_assoc_new(s1, s2);
  217. if (rb_block_given_p()) {
  218. return rb_ensure(pair_yield, r, io_close, s1);
  219. }
  220. return r;
  221. }
  222. #else
  223. #define rsock_sock_s_socketpair rb_f_notimplement
  224. #endif
  225. /*
  226. * call-seq:
  227. * socket.connect(remote_sockaddr) => 0
  228. *
  229. * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if
  230. * successful, otherwise an exception is raised.
  231. *
  232. * === Parameter
  233. * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
  234. *
  235. * === Example:
  236. * # Pull down Google's web page
  237. * require 'socket'
  238. * include Socket::Constants
  239. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  240. * sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
  241. * socket.connect( sockaddr )
  242. * socket.write( "GET / HTTP/1.0\r\n\r\n" )
  243. * results = socket.read
  244. *
  245. * === Unix-based Exceptions
  246. * On unix-based systems the following system exceptions may be raised if
  247. * the call to _connect_ fails:
  248. * * Errno::EACCES - search permission is denied for a component of the prefix
  249. * path or write access to the +socket+ is denied
  250. * * Errno::EADDRINUSE - the _sockaddr_ is already in use
  251. * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
  252. * local machine
  253. * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
  254. * the address family of the specified +socket+
  255. * * Errno::EALREADY - a connection is already in progress for the specified
  256. * socket
  257. * * Errno::EBADF - the +socket+ is not a valid file descriptor
  258. * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
  259. * refused the connection request
  260. * * Errno::ECONNRESET - the remote host reset the connection request
  261. * * Errno::EFAULT - the _sockaddr_ cannot be accessed
  262. * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
  263. * because the host is down or a remote router cannot reach it)
  264. * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
  265. * connection cannot be immediately established; the connection will be
  266. * established asynchronously
  267. * * Errno::EINTR - the attempt to establish the connection was interrupted by
  268. * delivery of a signal that was caught; the connection will be established
  269. * asynchronously
  270. * * Errno::EISCONN - the specified +socket+ is already connected
  271. * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
  272. * length for the address family or there is an invalid family in _sockaddr_
  273. * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
  274. * PATH_MAX
  275. * * Errno::ENETDOWN - the local interface used to reach the destination is down
  276. * * Errno::ENETUNREACH - no route to the network is present
  277. * * Errno::ENOBUFS - no buffer space is available
  278. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  279. * complete the operation
  280. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  281. * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
  282. * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
  283. * bound to the specified peer address
  284. * * Errno::ETIMEDOUT - the attempt to connect timed out before a connection
  285. * was made.
  286. *
  287. * On unix-based systems if the address family of the calling +socket+ is
  288. * AF_UNIX the follow exceptions may be raised if the call to _connect_
  289. * fails:
  290. * * Errno::EIO - an i/o error occurred while reading from or writing to the
  291. * file system
  292. * * Errno::ELOOP - too many symbolic links were encountered in translating
  293. * the pathname in _sockaddr_
  294. * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
  295. * characters, or an entire pathname exceeded PATH_MAX characters
  296. * * Errno::ENOENT - a component of the pathname does not name an existing file
  297. * or the pathname is an empty string
  298. * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
  299. * is not a directory
  300. *
  301. * === Windows Exceptions
  302. * On Windows systems the following system exceptions may be raised if
  303. * the call to _connect_ fails:
  304. * * Errno::ENETDOWN - the network is down
  305. * * Errno::EADDRINUSE - the socket's local address is already in use
  306. * * Errno::EINTR - the socket was cancelled
  307. * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
  308. * is still processing a callback function. Or a nonblocking connect call is
  309. * in progress on the +socket+.
  310. * * Errno::EALREADY - see Errno::EINVAL
  311. * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
  312. * ADDR_ANY TODO check ADDRANY TO INADDR_ANY
  313. * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
  314. * with this +socket+
  315. * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
  316. * refused the connection request
  317. * * Errno::EFAULT - the socket's internal address or address length parameter
  318. * is too small or is not a valid part of the user space address
  319. * * Errno::EINVAL - the +socket+ is a listening socket
  320. * * Errno::EISCONN - the +socket+ is already connected
  321. * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
  322. * * Errno::EHOSTUNREACH - no route to the network is present
  323. * * Errno::ENOBUFS - no buffer space is available
  324. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  325. * * Errno::ETIMEDOUT - the attempt to connect timed out before a connection
  326. * was made.
  327. * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
  328. * connection cannot be completed immediately
  329. * * Errno::EACCES - the attempt to connect the datagram socket to the
  330. * broadcast address failed
  331. *
  332. * === See
  333. * * connect manual pages on unix-based systems
  334. * * connect function in Microsoft's Winsock functions reference
  335. */
  336. static VALUE
  337. sock_connect(VALUE sock, VALUE addr)
  338. {
  339. VALUE rai;
  340. rb_io_t *fptr;
  341. int fd, n;
  342. SockAddrStringValueWithAddrinfo(addr, rai);
  343. addr = rb_str_new4(addr);
  344. GetOpenFile(sock, fptr);
  345. fd = fptr->fd;
  346. n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), 0, NULL);
  347. if (n < 0) {
  348. rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai);
  349. }
  350. return INT2FIX(n);
  351. }
  352. /* :nodoc: */
  353. static VALUE
  354. sock_connect_nonblock(VALUE sock, VALUE addr, VALUE ex)
  355. {
  356. VALUE rai;
  357. rb_io_t *fptr;
  358. int n;
  359. SockAddrStringValueWithAddrinfo(addr, rai);
  360. addr = rb_str_new4(addr);
  361. GetOpenFile(sock, fptr);
  362. rb_io_set_nonblock(fptr);
  363. n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr));
  364. if (n < 0) {
  365. int e = errno;
  366. if (e == EINPROGRESS) {
  367. if (ex == Qfalse) {
  368. return sym_wait_writable;
  369. }
  370. rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "connect(2) would block");
  371. }
  372. if (e == EISCONN) {
  373. if (ex == Qfalse) {
  374. return INT2FIX(0);
  375. }
  376. }
  377. rsock_syserr_fail_raddrinfo_or_sockaddr(e, "connect(2)", addr, rai);
  378. }
  379. return INT2FIX(n);
  380. }
  381. /*
  382. * call-seq:
  383. * socket.bind(local_sockaddr) => 0
  384. *
  385. * Binds to the given local address.
  386. *
  387. * === Parameter
  388. * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object
  389. *
  390. * === Example
  391. * require 'socket'
  392. *
  393. * # use Addrinfo
  394. * socket = Socket.new(:INET, :STREAM, 0)
  395. * socket.bind(Addrinfo.tcp("127.0.0.1", 2222))
  396. * p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>
  397. *
  398. * # use struct sockaddr
  399. * include Socket::Constants
  400. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  401. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  402. * socket.bind( sockaddr )
  403. *
  404. * === Unix-based Exceptions
  405. * On unix-based based systems the following system exceptions may be raised if
  406. * the call to _bind_ fails:
  407. * * Errno::EACCES - the specified _sockaddr_ is protected and the current
  408. * user does not have permission to bind to it
  409. * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
  410. * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
  411. * local machine
  412. * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
  413. * the family of the calling +socket+
  414. * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
  415. * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
  416. * * Errno::EINVAL - the +socket+ is already bound to an address, and the
  417. * protocol does not support binding to the new _sockaddr_ or the +socket+
  418. * has been shut down.
  419. * * Errno::EINVAL - the address length is not a valid length for the address
  420. * family
  421. * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
  422. * PATH_MAX
  423. * * Errno::ENOBUFS - no buffer space is available
  424. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  425. * complete the operation
  426. * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
  427. * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
  428. * binding to an address
  429. *
  430. * On unix-based based systems if the address family of the calling +socket+ is
  431. * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
  432. * fails:
  433. * * Errno::EACCES - search permission is denied for a component of the prefix
  434. * path or write access to the +socket+ is denied
  435. * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
  436. * * Errno::EISDIR - same as Errno::EDESTADDRREQ
  437. * * Errno::EIO - an i/o error occurred
  438. * * Errno::ELOOP - too many symbolic links were encountered in translating
  439. * the pathname in _sockaddr_
  440. * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
  441. * characters, or an entire pathname exceeded PATH_MAX characters
  442. * * Errno::ENOENT - a component of the pathname does not name an existing file
  443. * or the pathname is an empty string
  444. * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
  445. * is not a directory
  446. * * Errno::EROFS - the name would reside on a read only filesystem
  447. *
  448. * === Windows Exceptions
  449. * On Windows systems the following system exceptions may be raised if
  450. * the call to _bind_ fails:
  451. * * Errno::ENETDOWN-- the network is down
  452. * * Errno::EACCES - the attempt to connect the datagram socket to the
  453. * broadcast address failed
  454. * * Errno::EADDRINUSE - the socket's local address is already in use
  455. * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
  456. * computer
  457. * * Errno::EFAULT - the socket's internal address or address length parameter
  458. * is too small or is not a valid part of the user space addressed
  459. * * Errno::EINVAL - the +socket+ is already bound to an address
  460. * * Errno::ENOBUFS - no buffer space is available
  461. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  462. *
  463. * === See
  464. * * bind manual pages on unix-based systems
  465. * * bind function in Microsoft's Winsock functions reference
  466. */
  467. static VALUE
  468. sock_bind(VALUE sock, VALUE addr)
  469. {
  470. VALUE rai;
  471. rb_io_t *fptr;
  472. SockAddrStringValueWithAddrinfo(addr, rai);
  473. GetOpenFile(sock, fptr);
  474. if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)) < 0)
  475. rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai);
  476. return INT2FIX(0);
  477. }
  478. /*
  479. * call-seq:
  480. * socket.listen( int ) => 0
  481. *
  482. * Listens for connections, using the specified +int+ as the backlog. A call
  483. * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
  484. * SOCK_SEQPACKET.
  485. *
  486. * === Parameter
  487. * * +backlog+ - the maximum length of the queue for pending connections.
  488. *
  489. * === Example 1
  490. * require 'socket'
  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. * socket.listen( 5 )
  496. *
  497. * === Example 2 (listening on an arbitrary port, unix-based systems only):
  498. * require 'socket'
  499. * include Socket::Constants
  500. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  501. * socket.listen( 1 )
  502. *
  503. * === Unix-based Exceptions
  504. * On unix based systems the above will work because a new +sockaddr+ struct
  505. * is created on the address ADDR_ANY, for an arbitrary port number as handed
  506. * off by the kernel. It will not work on Windows, because Windows requires that
  507. * the +socket+ is bound by calling _bind_ before it can _listen_.
  508. *
  509. * If the _backlog_ amount exceeds the implementation-dependent maximum
  510. * queue length, the implementation's maximum queue length will be used.
  511. *
  512. * On unix-based based systems the following system exceptions may be raised if the
  513. * call to _listen_ fails:
  514. * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
  515. * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
  516. * the protocol does not support listening on an unbound socket
  517. * * Errno::EINVAL - the _socket_ is already connected
  518. * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
  519. * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
  520. * * Errno::EACCES - the calling process does not have appropriate privileges
  521. * * Errno::EINVAL - the _socket_ has been shut down
  522. * * Errno::ENOBUFS - insufficient resources are available in the system to
  523. * complete the call
  524. *
  525. * === Windows Exceptions
  526. * On Windows systems the following system exceptions may be raised if
  527. * the call to _listen_ fails:
  528. * * Errno::ENETDOWN - the network is down
  529. * * Errno::EADDRINUSE - the socket's local address is already in use. This
  530. * usually occurs during the execution of _bind_ but could be delayed
  531. * if the call to _bind_ was to a partially wildcard address (involving
  532. * ADDR_ANY) and if a specific address needs to be committed at the
  533. * time of the call to _listen_
  534. * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
  535. * service provider is still processing a callback function
  536. * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
  537. * * Errno::EISCONN - the +socket+ is already connected
  538. * * Errno::EMFILE - no more socket descriptors are available
  539. * * Errno::ENOBUFS - no buffer space is available
  540. * * Errno::ENOTSOC - +socket+ is not a socket
  541. * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
  542. * the _listen_ method
  543. *
  544. * === See
  545. * * listen manual pages on unix-based systems
  546. * * listen function in Microsoft's Winsock functions reference
  547. */
  548. VALUE
  549. rsock_sock_listen(VALUE sock, VALUE log)
  550. {
  551. rb_io_t *fptr;
  552. int backlog;
  553. backlog = NUM2INT(log);
  554. GetOpenFile(sock, fptr);
  555. if (listen(fptr->fd, backlog) < 0)
  556. rb_sys_fail("listen(2)");
  557. return INT2FIX(0);
  558. }
  559. /*
  560. * call-seq:
  561. * socket.recvfrom(maxlen) => [mesg, sender_addrinfo]
  562. * socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo]
  563. *
  564. * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
  565. * of the +MSG_+ options. The first element of the results, _mesg_, is the data
  566. * received. The second element, _sender_addrinfo_, contains protocol-specific
  567. * address information of the sender.
  568. *
  569. * === Parameters
  570. * * +maxlen+ - the maximum number of bytes to receive from the socket
  571. * * +flags+ - zero or more of the +MSG_+ options
  572. *
  573. * === Example
  574. * # In one file, start this first
  575. * require 'socket'
  576. * include Socket::Constants
  577. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  578. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  579. * socket.bind( sockaddr )
  580. * socket.listen( 5 )
  581. * client, client_addrinfo = socket.accept
  582. * data = client.recvfrom( 20 )[0].chomp
  583. * puts "I only received 20 bytes '#{data}'"
  584. * sleep 1
  585. * socket.close
  586. *
  587. * # In another file, start this second
  588. * require 'socket'
  589. * include Socket::Constants
  590. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  591. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  592. * socket.connect( sockaddr )
  593. * socket.puts "Watch this get cut short!"
  594. * socket.close
  595. *
  596. * === Unix-based Exceptions
  597. * On unix-based based systems the following system exceptions may be raised if the
  598. * call to _recvfrom_ fails:
  599. * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
  600. * data is waiting to be received; or MSG_OOB is set and no out-of-band data
  601. * is available and either the +socket+ file descriptor is marked as
  602. * O_NONBLOCK or the +socket+ does not support blocking to wait for
  603. * out-of-band-data
  604. * * Errno::EWOULDBLOCK - see Errno::EAGAIN
  605. * * Errno::EBADF - the +socket+ is not a valid file descriptor
  606. * * Errno::ECONNRESET - a connection was forcibly closed by a peer
  607. * * Errno::EFAULT - the socket's internal buffer, address or address length
  608. * cannot be accessed or written
  609. * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available
  610. * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
  611. * * Errno::EIO - an i/o error occurred while reading from or writing to the
  612. * filesystem
  613. * * Errno::ENOBUFS - insufficient resources were available in the system to
  614. * perform the operation
  615. * * Errno::ENOMEM - insufficient memory was available to fulfill the request
  616. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  617. * complete the operation
  618. * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
  619. * is not connected
  620. * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
  621. * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
  622. * * Errno::ETIMEDOUT - the connection timed out during connection establishment
  623. * or due to a transmission timeout on an active connection
  624. *
  625. * === Windows Exceptions
  626. * On Windows systems the following system exceptions may be raised if
  627. * the call to _recvfrom_ fails:
  628. * * Errno::ENETDOWN - the network is down
  629. * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
  630. * part of the user address space, or the internal fromlen parameter is
  631. * too small to accommodate the peer address
  632. * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
  633. * the WinSock function WSACancelBlockingCall
  634. * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
  635. * the service provider is still processing a callback function
  636. * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
  637. * unknown flag was specified, or MSG_OOB was specified for a socket with
  638. * SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
  639. * len parameter on +socket+ was zero or negative
  640. * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
  641. * not permitted with a connected socket on a socket that is connection
  642. * oriented or connectionless.
  643. * * Errno::ENETRESET - the connection has been broken due to the keep-alive
  644. * activity detecting a failure while the operation was in progress.
  645. * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
  646. * such as type SOCK_STREAM. OOB data is not supported in the communication
  647. * domain associated with +socket+, or +socket+ is unidirectional and
  648. * supports only send operations
  649. * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
  650. * call _recvfrom_ on a socket after _shutdown_ has been invoked.
  651. * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to
  652. * _recvfrom_ would block.
  653. * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
  654. * and was truncated.
  655. * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
  656. * failure or because the system on the other end went down without
  657. * notice
  658. * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
  659. * executing a hard or abortive close. The application should close the
  660. * socket; it is no longer usable. On a UDP-datagram socket this error
  661. * indicates a previous send operation resulted in an ICMP Port Unreachable
  662. * message.
  663. */
  664. static VALUE
  665. sock_recvfrom(int argc, VALUE *argv, VALUE sock)
  666. {
  667. return rsock_s_recvfrom(sock, argc, argv, RECV_SOCKET);
  668. }
  669. /* :nodoc: */
  670. static VALUE
  671. sock_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, VALUE ex)
  672. {
  673. return rsock_s_recvfrom_nonblock(sock, len, flg, str, ex, RECV_SOCKET);
  674. }
  675. /*
  676. * call-seq:
  677. * socket.accept => [client_socket, client_addrinfo]
  678. *
  679. * Accepts a next connection.
  680. * Returns a new Socket object and Addrinfo object.
  681. *
  682. * serv = Socket.new(:INET, :STREAM, 0)
  683. * serv.listen(5)
  684. * c = Socket.new(:INET, :STREAM, 0)
  685. * c.connect(serv.connect_address)
  686. * p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>]
  687. *
  688. */
  689. static VALUE
  690. sock_accept(VALUE server)
  691. {
  692. union_sockaddr buffer;
  693. socklen_t length = (socklen_t)sizeof(buffer);
  694. VALUE peer = rsock_s_accept(rb_cSocket, server, &buffer.addr, &length);
  695. return rb_assoc_new(peer, rsock_io_socket_addrinfo(peer, &buffer.addr, length));
  696. }
  697. /* :nodoc: */
  698. static VALUE
  699. sock_accept_nonblock(VALUE sock, VALUE ex)
  700. {
  701. rb_io_t *fptr;
  702. VALUE sock2;
  703. union_sockaddr buf;
  704. struct sockaddr *addr = &buf.addr;
  705. socklen_t len = (socklen_t)sizeof buf;
  706. GetOpenFile(sock, fptr);
  707. sock2 = rsock_s_accept_nonblock(rb_cSocket, ex, fptr, addr, &len);
  708. if (SYMBOL_P(sock2)) /* :wait_readable */
  709. return sock2;
  710. return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
  711. }
  712. /*
  713. * call-seq:
  714. * socket.sysaccept => [client_socket_fd, client_addrinfo]
  715. *
  716. * Accepts an incoming connection returning an array containing the (integer)
  717. * file descriptor for the incoming connection, _client_socket_fd_,
  718. * and an Addrinfo, _client_addrinfo_.
  719. *
  720. * === Example
  721. * # In one script, start this first
  722. * require 'socket'
  723. * include Socket::Constants
  724. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  725. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  726. * socket.bind( sockaddr )
  727. * socket.listen( 5 )
  728. * client_fd, client_addrinfo = socket.sysaccept
  729. * client_socket = Socket.for_fd( client_fd )
  730. * puts "The client said, '#{client_socket.readline.chomp}'"
  731. * client_socket.puts "Hello from script one!"
  732. * socket.close
  733. *
  734. * # In another script, start this second
  735. * require 'socket'
  736. * include Socket::Constants
  737. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  738. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  739. * socket.connect( sockaddr )
  740. * socket.puts "Hello from script 2."
  741. * puts "The server said, '#{socket.readline.chomp}'"
  742. * socket.close
  743. *
  744. * Refer to Socket#accept for the exceptions that may be thrown if the call
  745. * to _sysaccept_ fails.
  746. *
  747. * === See
  748. * * Socket#accept
  749. */
  750. static VALUE
  751. sock_sysaccept(VALUE server)
  752. {
  753. union_sockaddr buffer;
  754. socklen_t length = (socklen_t)sizeof(buffer);
  755. VALUE peer = rsock_s_accept(0, server, &buffer.addr, &length);
  756. return rb_assoc_new(peer, rsock_io_socket_addrinfo(peer, &buffer.addr, length));
  757. }
  758. #ifdef HAVE_GETHOSTNAME
  759. /*
  760. * call-seq:
  761. * Socket.gethostname => hostname
  762. *
  763. * Returns the hostname.
  764. *
  765. * p Socket.gethostname #=> "hal"
  766. *
  767. * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc.
  768. * If you need local IP address, use Socket.ip_address_list.
  769. */
  770. static VALUE
  771. sock_gethostname(VALUE obj)
  772. {
  773. #if defined(NI_MAXHOST)
  774. # define RUBY_MAX_HOST_NAME_LEN NI_MAXHOST
  775. #elif defined(HOST_NAME_MAX)
  776. # define RUBY_MAX_HOST_NAME_LEN HOST_NAME_MAX
  777. #else
  778. # define RUBY_MAX_HOST_NAME_LEN 1024
  779. #endif
  780. long len = RUBY_MAX_HOST_NAME_LEN;
  781. VALUE name;
  782. name = rb_str_new(0, len);
  783. while (gethostname(RSTRING_PTR(name), len) < 0) {
  784. int e = errno;
  785. switch (e) {
  786. case ENAMETOOLONG:
  787. #ifdef __linux__
  788. case EINVAL:
  789. /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */
  790. #endif
  791. break;
  792. default:
  793. rb_syserr_fail(e, "gethostname(3)");
  794. }
  795. rb_str_modify_expand(name, len);
  796. len += len;
  797. }
  798. rb_str_resize(name, strlen(RSTRING_PTR(name)));
  799. return name;
  800. }
  801. #else
  802. #ifdef HAVE_UNAME
  803. #include <sys/utsname.h>
  804. static VALUE
  805. sock_gethostname(VALUE obj)
  806. {
  807. struct utsname un;
  808. uname(&un);
  809. return rb_str_new2(un.nodename);
  810. }
  811. #else
  812. #define sock_gethostname rb_f_notimplement
  813. #endif
  814. #endif
  815. static VALUE
  816. make_addrinfo(struct rb_addrinfo *res0, int norevlookup)
  817. {
  818. VALUE base, ary;
  819. struct addrinfo *res;
  820. if (res0 == NULL) {
  821. rb_raise(rb_eSocket, "host not found");
  822. }
  823. base = rb_ary_new();
  824. for (res = res0->ai; res; res = res->ai_next) {
  825. ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup);
  826. if (res->ai_canonname) {
  827. RARRAY_ASET(ary, 2, rb_str_new2(res->ai_canonname));
  828. }
  829. rb_ary_push(ary, INT2FIX(res->ai_family));
  830. rb_ary_push(ary, INT2FIX(res->ai_socktype));
  831. rb_ary_push(ary, INT2FIX(res->ai_protocol));
  832. rb_ary_push(base, ary);
  833. }
  834. return base;
  835. }
  836. static VALUE
  837. sock_sockaddr(struct sockaddr *addr, socklen_t len)
  838. {
  839. char *ptr;
  840. switch (addr->sa_family) {
  841. case AF_INET:
  842. ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr;
  843. len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr);
  844. break;
  845. #ifdef AF_INET6
  846. case AF_INET6:
  847. ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr;
  848. len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr);
  849. break;
  850. #endif
  851. default:
  852. rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family);
  853. break;
  854. }
  855. return rb_str_new(ptr, len);
  856. }
  857. /*
  858. * call-seq:
  859. * Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
  860. *
  861. * Use Addrinfo.getaddrinfo instead.
  862. * This method is deprecated for the following reasons:
  863. *
  864. * - The 3rd element of the result is the address family of the first address.
  865. * The address families of the rest of the addresses are not returned.
  866. * - Uncommon address representation:
  867. * 4/16-bytes binary string to represent IPv4/IPv6 address.
  868. * - gethostbyname() may take a long time and it may block other threads.
  869. * (GVL cannot be released since gethostbyname() is not thread safe.)
  870. * - This method uses gethostbyname() function already removed from POSIX.
  871. *
  872. * This method obtains the host information for _hostname_.
  873. *
  874. * p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"]
  875. *
  876. */
  877. static VALUE
  878. sock_s_gethostbyname(VALUE obj, VALUE host)
  879. {
  880. rb_warn("Socket.gethostbyname is deprecated; use Addrinfo.getaddrinfo instead.");
  881. struct rb_addrinfo *res =
  882. rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME);
  883. return rsock_make_hostent(host, res, sock_sockaddr);
  884. }
  885. /*
  886. * call-seq:
  887. * Socket.gethostbyaddr(address_string [, address_family]) => hostent
  888. *
  889. * Use Addrinfo#getnameinfo instead.
  890. * This method is deprecated for the following reasons:
  891. *
  892. * - Uncommon address representation:
  893. * 4/16-bytes binary string to represent IPv4/IPv6 address.
  894. * - gethostbyaddr() may take a long time and it may block other threads.
  895. * (GVL cannot be released since gethostbyname() is not thread safe.)
  896. * - This method uses gethostbyname() function already removed from POSIX.
  897. *
  898. * This method obtains the host information for _address_.
  899. *
  900. * p Socket.gethostbyaddr([221,186,184,68].pack("CCCC"))
  901. * #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"]
  902. *
  903. * p Socket.gethostbyaddr([127,0,0,1].pack("CCCC"))
  904. * ["localhost", [], 2, "\x7F\x00\x00\x01"]
  905. * p Socket.gethostbyaddr(([0]*15+[1]).pack("C"*16))
  906. * #=> ["localhost", ["ip6-localhost", "ip6-loopback"], 10,
  907. * "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"]
  908. *
  909. */
  910. static VALUE
  911. sock_s_gethostbyaddr(int argc, VALUE *argv, VALUE _)
  912. {
  913. VALUE addr, family;
  914. struct hostent *h;
  915. char **pch;
  916. VALUE ary, names;
  917. int t = AF_INET;
  918. rb_warn("Socket.gethostbyaddr is deprecated; use Addrinfo#getnameinfo instead.");
  919. rb_scan_args(argc, argv, "11", &addr, &family);
  920. StringValue(addr);
  921. if (!NIL_P(family)) {
  922. t = rsock_family_arg(family);
  923. }
  924. #ifdef AF_INET6
  925. else if (RSTRING_LEN(addr) == 16) {
  926. t = AF_INET6;
  927. }
  928. #endif
  929. h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), t);
  930. if (h == NULL) {
  931. #ifdef HAVE_HSTRERROR
  932. extern int h_errno;
  933. rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno));
  934. #else
  935. rb_raise(rb_eSocket, "host not found");
  936. #endif
  937. }
  938. ary = rb_ary_new();
  939. rb_ary_push(ary, rb_str_new2(h->h_name));
  940. names = rb_ary_new();
  941. rb_ary_push(ary, names);
  942. if (h->h_aliases != NULL) {
  943. for (pch = h->h_aliases; *pch; pch++) {
  944. rb_ary_push(names, rb_str_new2(*pch));
  945. }
  946. }
  947. rb_ary_push(ary, INT2NUM(h->h_addrtype));
  948. #ifdef h_addr
  949. for (pch = h->h_addr_list; *pch; pch++) {
  950. rb_ary_push(ary, rb_str_new(*pch, h->h_length));
  951. }
  952. #else
  953. rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length));
  954. #endif
  955. return ary;
  956. }
  957. /*
  958. * call-seq:
  959. * Socket.getservbyname(service_name) => port_number
  960. * Socket.getservbyname(service_name, protocol_name) => port_number
  961. *
  962. * Obtains the port number for _service_name_.
  963. *
  964. * If _protocol_name_ is not given, "tcp" is assumed.
  965. *
  966. * Socket.getservbyname("smtp") #=> 25
  967. * Socket.getservbyname("shell") #=> 514
  968. * Socket.getservbyname("syslog", "udp") #=> 514
  969. */
  970. static VALUE
  971. sock_s_getservbyname(int argc, VALUE *argv, VALUE _)
  972. {
  973. VALUE service, proto;
  974. struct servent *sp;
  975. long port;
  976. const char *servicename, *protoname = "tcp";
  977. rb_scan_args(argc, argv, "11", &service, &proto);
  978. StringValue(service);
  979. if (!NIL_P(proto)) StringValue(proto);
  980. servicename = StringValueCStr(service);
  981. if (!NIL_P(proto)) protoname = StringValueCStr(proto);
  982. sp = getservbyname(servicename, protoname);
  983. if (sp) {
  984. port = ntohs(sp->s_port);
  985. }
  986. else {
  987. char *end;
  988. port = STRTOUL(servicename, &end, 0);
  989. if (*end != '\0') {
  990. rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname);
  991. }
  992. }
  993. return INT2FIX(port);
  994. }
  995. /*
  996. * call-seq:
  997. * Socket.getservbyport(port [, protocol_name]) => service
  998. *
  999. * Obtains the port number for _port_.
  1000. *
  1001. * If _protocol_name_ is not given, "tcp" is assumed.
  1002. *
  1003. * Socket.getservbyport(80) #=> "www"
  1004. * Socket.getservbyport(514, "tcp") #=> "shell"
  1005. * Socket.getservbyport(514, "udp") #=> "syslog"
  1006. *
  1007. */
  1008. static VALUE
  1009. sock_s_getservbyport(int argc, VALUE *argv, VALUE _)
  1010. {
  1011. VALUE port, proto;
  1012. struct servent *sp;
  1013. long portnum;
  1014. const char *protoname = "tcp";
  1015. rb_scan_args(argc, argv, "11", &port, &proto);
  1016. portnum = NUM2LONG(port);
  1017. if (portnum != (uint16_t)portnum) {
  1018. const char *s = portnum > 0 ? "big" : "small";
  1019. rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s);
  1020. }
  1021. if (!NIL_P(proto)) protoname = StringValueCStr(proto);
  1022. sp = getservbyport((int)htons((uint16_t)portnum), protoname);
  1023. if (!sp) {
  1024. rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname);
  1025. }
  1026. return rb_str_new2(sp->s_name);
  1027. }
  1028. /*
  1029. * call-seq:
  1030. * Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array
  1031. *
  1032. * Obtains address information for _nodename_:_servname_.
  1033. *
  1034. * Note that Addrinfo.getaddrinfo provides the same functionality in
  1035. * an object oriented style.
  1036. *
  1037. * _family_ should be an address family such as: :INET, :INET6, etc.
  1038. *
  1039. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  1040. *
  1041. * _protocol_ should be a protocol defined in the family,
  1042. * and defaults to 0 for the family.
  1043. *
  1044. * _flags_ should be bitwise OR of Socket::AI_* constants.
  1045. *
  1046. * Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM)
  1047. * #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP
  1048. *
  1049. * Socket.getaddrinfo("localhost", nil)
  1050. * #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6], # PF_INET/SOCK_STREAM/IPPROTO_TCP
  1051. * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP
  1052. * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]] # PF_INET/SOCK_RAW/IPPROTO_IP
  1053. *
  1054. * _reverse_lookup_ directs the form of the third element, and has to
  1055. * be one of below. If _reverse_lookup_ is omitted, the default value is +nil+.
  1056. *
  1057. * +true+, +:hostname+: hostname is obtained from numeric address using reverse lookup, which may take a time.
  1058. * +false+, +:numeric+: hostname is the same as numeric address.
  1059. * +nil+: obey to the current +do_not_reverse_lookup+ flag.
  1060. *
  1061. * If Addrinfo object is preferred, use Addrinfo.getaddrinfo.
  1062. */
  1063. static VALUE
  1064. sock_s_getaddrinfo(int argc, VALUE *argv, VALUE _)
  1065. {
  1066. VALUE host, port, family, socktype, protocol, flags, ret, revlookup;
  1067. struct addrinfo hints;
  1068. struct rb_addrinfo *res;
  1069. int norevlookup;
  1070. rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup);
  1071. MEMZERO(&hints, struct addrinfo, 1);
  1072. hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
  1073. if (!NIL_P(socktype)) {
  1074. hints.ai_socktype = rsock_socktype_arg(socktype);
  1075. }
  1076. if (!NIL_P(protocol)) {
  1077. hints.ai_protocol = NUM2INT(protocol);
  1078. }
  1079. if (!NIL_P(flags)) {
  1080. hints.ai_flags = NUM2INT(flags);
  1081. }
  1082. if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) {
  1083. norevlookup = rsock_do_not_reverse_lookup;
  1084. }
  1085. res = rsock_getaddrinfo(host, port, &hints, 0);
  1086. ret = make_addrinfo(res, norevlookup);
  1087. rb_freeaddrinfo(res);
  1088. return ret;
  1089. }
  1090. /*
  1091. * call-seq:
  1092. * Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename]
  1093. *
  1094. * Obtains name information for _sockaddr_.
  1095. *
  1096. * _sockaddr_ should be one of follows.
  1097. * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1")
  1098. * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"]
  1099. * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"]
  1100. *
  1101. * _flags_ should be bitwise OR of Socket::NI_* constants.
  1102. *
  1103. * Note:
  1104. * The last form is compatible with IPSocket#addr and IPSocket#peeraddr.
  1105. *
  1106. * Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1")) #=> ["localhost", "www"]
  1107. * Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"]) #=> ["localhost", "www"]
  1108. * Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"]
  1109. *
  1110. * If Addrinfo object is preferred, use Addrinfo#getnameinfo.
  1111. */
  1112. static VALUE
  1113. sock_s_getnameinfo(int argc, VALUE *argv, VALUE _)
  1114. {
  1115. VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
  1116. char hbuf[1024], pbuf[1024];
  1117. int fl;
  1118. struct rb_addrinfo *res = NULL;
  1119. struct addrinfo hints, *r;
  1120. int error, saved_errno;
  1121. union_sockaddr ss;
  1122. struct sockaddr *sap;
  1123. socklen_t salen;
  1124. sa = flags = Qnil;
  1125. rb_scan_args(argc, argv, "11", &sa, &flags);
  1126. fl = 0;
  1127. if (!NIL_P(flags)) {
  1128. fl = NUM2INT(flags);
  1129. }
  1130. tmp = rb_check_sockaddr_string_type(sa);
  1131. if (!NIL_P(tmp)) {
  1132. sa = tmp;
  1133. if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
  1134. rb_raise(rb_eTypeError, "sockaddr length too big");
  1135. }
  1136. memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
  1137. if (!VALIDATE_SOCKLEN(&ss.addr, RSTRING_LEN(sa))) {
  1138. rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
  1139. }
  1140. sap = &ss.addr;
  1141. salen = RSTRING_SOCKLEN(sa);
  1142. goto call_nameinfo;
  1143. }
  1144. tmp = rb_check_array_type(sa);
  1145. if (!NIL_P(tmp)) {
  1146. sa = tmp;
  1147. MEMZERO(&hints, struct addrinfo, 1);
  1148. if (RARRAY_LEN(sa) == 3) {
  1149. af = RARRAY_AREF(sa, 0);
  1150. port = RARRAY_AREF(sa, 1);
  1151. host = RARRAY_AREF(sa, 2);
  1152. }
  1153. else if (RARRAY_LEN(sa) >= 4) {
  1154. af = RARRAY_AREF(sa, 0);
  1155. port = RARRAY_AREF(sa, 1);
  1156. host = RARRAY_AREF(sa, 3);
  1157. if (NIL_P(host)) {
  1158. host = RARRAY_AREF(sa, 2);
  1159. }
  1160. else {
  1161. /*
  1162. * 4th element holds numeric form, don't resolve.
  1163. * see rsock_ipaddr().
  1164. */
  1165. #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
  1166. hints.ai_flags |= AI_NUMERICHOST;
  1167. #endif
  1168. }
  1169. }
  1170. else {
  1171. rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
  1172. RARRAY_LEN(sa));
  1173. }
  1174. hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
  1175. /* af */
  1176. hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af);
  1177. res = rsock_getaddrinfo(host, port, &hints, 0);
  1178. sap = res->ai->ai_addr;
  1179. salen = res->ai->ai_addrlen;
  1180. }
  1181. else {
  1182. rb_raise(rb_eTypeError, "expecting String or Array");
  1183. }
  1184. call_nameinfo:
  1185. error = rb_getnameinfo(sap, salen, hbuf, sizeof(hbuf),
  1186. pbuf, sizeof(pbuf), fl);
  1187. if (error) goto error_exit_name;
  1188. if (res) {
  1189. for (r = res->ai->ai_next; r; r = r->ai_next) {
  1190. char hbuf2[1024], pbuf2[1024];
  1191. sap = r->ai_addr;
  1192. salen = r->ai_addrlen;
  1193. error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2),
  1194. pbuf2, sizeof(pbuf2), fl);
  1195. if (error) goto error_exit_name;
  1196. if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
  1197. rb_freeaddrinfo(res);
  1198. rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
  1199. }
  1200. }
  1201. rb_freeaddrinfo(res);
  1202. }
  1203. return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
  1204. error_exit_name:
  1205. saved_errno = errno;
  1206. if (res) rb_freeaddrinfo(res);
  1207. errno = saved_errno;
  1208. rsock_raise_socket_error("getnameinfo", error);
  1209. UNREACHABLE_RETURN(Qnil);
  1210. }
  1211. /*
  1212. * call-seq:
  1213. * Socket.sockaddr_in(port, host) => sockaddr
  1214. * Socket.pack_sockaddr_in(port, host) => sockaddr
  1215. *
  1216. * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string.
  1217. *
  1218. * Socket.sockaddr_in(80, "127.0.0.1")
  1219. * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  1220. *
  1221. * Socket.sockaddr_in(80, "::1")
  1222. * #=> "\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"
  1223. *
  1224. */
  1225. static VALUE
  1226. sock_s_pack_sockaddr_in(VALUE self, VALUE port, VALUE host)
  1227. {
  1228. struct rb_addrinfo *res = rsock_addrinfo(host, port, AF_UNSPEC, 0, 0);
  1229. VALUE addr = rb_str_new((char*)res->ai->ai_addr, res->ai->ai_addrlen);
  1230. rb_freeaddrinfo(res);
  1231. return addr;
  1232. }
  1233. /*
  1234. * call-seq:
  1235. * Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address]
  1236. *
  1237. * Unpacks _sockaddr_ into port and ip_address.
  1238. *
  1239. * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6.
  1240. *
  1241. * sockaddr = Socket.sockaddr_in(80, "127.0.0.1")
  1242. * p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  1243. * p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"]
  1244. *
  1245. */
  1246. static VALUE
  1247. sock_s_unpack_sockaddr_in(VALUE self, VALUE addr)
  1248. {
  1249. struct sockaddr_in * sockaddr;
  1250. VALUE host;
  1251. sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr);
  1252. if (RSTRING_LEN(addr) <
  1253. (char*)&((struct sockaddr *)sockaddr)->sa_family +
  1254. sizeof(((struct sockaddr *)sockaddr)->sa_family) -
  1255. (char*)sockaddr)
  1256. rb_raise(rb_eArgError, "too short sockaddr");
  1257. if (((struct sockaddr *)sockaddr)->sa_family != AF_INET
  1258. #ifdef INET6
  1259. && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6
  1260. #endif
  1261. ) {
  1262. #ifdef INET6
  1263. rb_raise(rb_eArgError, "not an AF_INET/AF_INET6 sockaddr");
  1264. #else
  1265. rb_raise(rb_eArgError, "not an AF_INET sockaddr");
  1266. #endif
  1267. }
  1268. host = rsock_make_ipaddr((struct sockaddr*)sockaddr, RSTRING_SOCKLEN(addr));
  1269. return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host);
  1270. }
  1271. #ifdef HAVE_SYS_UN_H
  1272. /*
  1273. * call-seq:
  1274. * Socket.sockaddr_un(path) => sockaddr
  1275. * Socket.pack_sockaddr_un(path) => sockaddr
  1276. *
  1277. * Packs _path_ as an AF_UNIX sockaddr string.
  1278. *
  1279. * Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..."
  1280. *
  1281. */
  1282. static VALUE
  1283. sock_s_pack_sockaddr_un(VALUE self, VALUE path)
  1284. {
  1285. struct sockaddr_un sockaddr;
  1286. VALUE addr;
  1287. StringValue(path);
  1288. INIT_SOCKADDR_UN(&sockaddr, sizeof(struct sockaddr_un));
  1289. if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
  1290. rb_raise(rb_eArgError, "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
  1291. (size_t)RSTRING_LEN(path), sizeof(sockaddr.sun_path));
  1292. }
  1293. memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
  1294. addr = rb_str_new((char*)&sockaddr, rsock_unix_sockaddr_len(path));
  1295. return addr;
  1296. }
  1297. /*
  1298. * call-seq:
  1299. * Socket.unpack_sockaddr_un(sockaddr) => path
  1300. *
  1301. * Unpacks _sockaddr_ into path.
  1302. *
  1303. * _sockaddr_ should be a string or an addrinfo for AF_UNIX.
  1304. *
  1305. * sockaddr = Socket.sockaddr_un("/tmp/sock")
  1306. * p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock"
  1307. *
  1308. */
  1309. static VALUE
  1310. sock_s_unpack_sockaddr_un(VALUE self, VALUE addr)
  1311. {
  1312. struct sockaddr_un * sockaddr;
  1313. VALUE path;
  1314. sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr);
  1315. if (RSTRING_LEN(addr) <
  1316. (char*)&((struct sockaddr *)sockaddr)->sa_family +
  1317. sizeof(((struct sockaddr *)sockaddr)->sa_family) -
  1318. (char*)sockaddr)
  1319. rb_raise(rb_eArgError, "too short sockaddr");
  1320. if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) {
  1321. rb_raise(rb_eArgError, "not an AF_UNIX sockaddr");
  1322. }
  1323. if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) {
  1324. rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d",
  1325. RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un));
  1326. }
  1327. path = rsock_unixpath_str(sockaddr, RSTRING_SOCKLEN(addr));
  1328. return path;
  1329. }
  1330. #endif
  1331. #if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32)
  1332. static socklen_t
  1333. sockaddr_len(struct sockaddr *addr)
  1334. {
  1335. if (addr == NULL)
  1336. return 0;
  1337. #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
  1338. if (addr->sa_len != 0)
  1339. return addr->sa_len;
  1340. #endif
  1341. switch (addr->sa_family) {
  1342. case AF_INET:
  1343. return (socklen_t)sizeof(struct sockaddr_in);
  1344. #ifdef AF_INET6
  1345. case AF_INET6:
  1346. return (socklen_t)sizeof(struct sockaddr_in6);
  1347. #endif
  1348. #ifdef HAVE_SYS_UN_H
  1349. case AF_UNIX:
  1350. return (socklen_t)sizeof(struct sockaddr_un);
  1351. #endif
  1352. #ifdef AF_PACKET
  1353. case AF_PACKET:
  1354. return (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + ((struct sockaddr_ll *)addr)->sll_halen);
  1355. #endif
  1356. default:
  1357. return (socklen_t)(offsetof(struct sockaddr, sa_family) + sizeof(addr->sa_family));
  1358. }
  1359. }
  1360. socklen_t
  1361. rsock_sockaddr_len(struct sockaddr *addr)
  1362. {
  1363. return sockaddr_len(addr);
  1364. }
  1365. static VALUE
  1366. sockaddr_obj(struct sockaddr *addr, socklen_t len)
  1367. {
  1368. #if defined(AF_INET6) && defined(__KAME__)
  1369. struct sockaddr_in6 addr6;
  1370. #endif
  1371. if (addr == NULL)
  1372. return Qnil;
  1373. len = sockaddr_len(addr);
  1374. #if defined(__KAME__) && defined(AF_INET6)
  1375. if (addr->sa_family == AF_INET6) {
  1376. /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */
  1377. /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */
  1378. /* convert fe80:1::1 to fe80::1%1 */
  1379. len = (socklen_t)sizeof(struct sockaddr_in6);
  1380. memcpy(&addr6, addr, len);
  1381. addr = (struct sockaddr *)&addr6;
  1382. if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
  1383. addr6.sin6_scope_id == 0 &&
  1384. (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) {
  1385. addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3];
  1386. addr6.sin6_addr.s6_addr[2] = 0;
  1387. addr6.sin6_addr.s6_addr[3] = 0;
  1388. }
  1389. }
  1390. #endif
  1391. return rsock_addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil);
  1392. }
  1393. VALUE
  1394. rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
  1395. {
  1396. return sockaddr_obj(addr, len);
  1397. }
  1398. #endif
  1399. #if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) || defined(_WIN32)
  1400. /*
  1401. * call-seq:
  1402. * Socket.ip_address_list => array
  1403. *
  1404. * Returns local IP addresses as an array.
  1405. *
  1406. * The array contains Addrinfo objects.
  1407. *
  1408. * pp Socket.ip_address_list
  1409. * #=> [#<Addrinfo: 127.0.0.1>,
  1410. * #<Addrinfo: 192…

Large files files are truncated, but you can click here to view the full file