PageRenderTime 85ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/ext/socket/socket.c

http://github.com/MacRuby/MacRuby
C | 6607 lines | 3911 code | 575 blank | 2121 comment | 708 complexity | 3e0615e38a3c23a30f1ec0a06234c95d MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1
  1. /************************************************
  2. socket.c -
  3. $Author: akr $
  4. created at: Thu Mar 31 12:21:29 JST 1994
  5. Copyright (C) 1993-2007 Yukihiro Matsumoto
  6. ************************************************/
  7. #include "macruby_internal.h"
  8. #include "ruby/io.h"
  9. #include "ruby/signal.h"
  10. #include "ruby/util.h"
  11. #include <stdio.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #ifdef HAVE_UNISTD_H
  15. #include <unistd.h>
  16. #endif
  17. #ifdef HAVE_SYS_UIO_H
  18. #include <sys/uio.h>
  19. #endif
  20. #ifdef HAVE_XTI_H
  21. #include <xti.h>
  22. #endif
  23. #ifndef _WIN32
  24. #if defined(__BEOS__)
  25. # include <net/socket.h>
  26. #else
  27. # include <sys/socket.h>
  28. #endif
  29. #include <netinet/in.h>
  30. #ifdef HAVE_NETINET_IN_SYSTM_H
  31. # include <netinet/in_systm.h>
  32. #endif
  33. #ifdef HAVE_NETINET_TCP_H
  34. # include <netinet/tcp.h>
  35. #endif
  36. #ifdef HAVE_NETINET_UDP_H
  37. # include <netinet/udp.h>
  38. #endif
  39. #ifdef HAVE_ARPA_INET_H
  40. # include <arpa/inet.h>
  41. #endif
  42. #include <netdb.h>
  43. #endif
  44. #include <errno.h>
  45. #ifdef HAVE_SYS_UN_H
  46. #include <sys/un.h>
  47. #endif
  48. #if defined(HAVE_FCNTL)
  49. #ifdef HAVE_SYS_SELECT_H
  50. #include <sys/select.h>
  51. #endif
  52. #ifdef HAVE_SYS_TYPES_H
  53. #include <sys/types.h>
  54. #endif
  55. #ifdef HAVE_SYS_TIME_H
  56. #include <sys/time.h>
  57. #endif
  58. #ifdef HAVE_FCNTL_H
  59. #include <fcntl.h>
  60. #endif
  61. #endif
  62. #ifdef HAVE_IFADDRS_H
  63. #include <ifaddrs.h>
  64. #endif
  65. #ifdef HAVE_SYS_IOCTL_H
  66. #include <sys/ioctl.h>
  67. #endif
  68. #ifdef HAVE_SYS_SOCKIO_H
  69. #include <sys/sockio.h>
  70. #endif
  71. #ifdef HAVE_NET_IF_H
  72. #include <net/if.h>
  73. #endif
  74. #ifdef HAVE_SYS_PARAM_H
  75. #include <sys/param.h>
  76. #endif
  77. #ifdef HAVE_SYS_UCRED_H
  78. #include <sys/ucred.h>
  79. #endif
  80. #ifdef HAVE_UCRED_H
  81. #include <ucred.h>
  82. #endif
  83. #ifndef EWOULDBLOCK
  84. #define EWOULDBLOCK EAGAIN
  85. #endif
  86. #ifndef HAVE_GETADDRINFO
  87. # include "addrinfo.h"
  88. #endif
  89. #include "sockport.h"
  90. static int do_not_reverse_lookup = 1;
  91. #define FMODE_NOREVLOOKUP 0x100
  92. VALUE rb_cBasicSocket;
  93. VALUE rb_cIPSocket;
  94. VALUE rb_cTCPSocket;
  95. VALUE rb_cTCPServer;
  96. VALUE rb_cUDPSocket;
  97. #ifdef AF_UNIX
  98. VALUE rb_cUNIXSocket;
  99. VALUE rb_cUNIXServer;
  100. #endif
  101. VALUE rb_cSocket;
  102. static VALUE rb_cAddrinfo;
  103. static VALUE rb_eSocket;
  104. #define INET_CLIENT 0
  105. #define INET_SERVER 1
  106. #define INET_SOCKS 2
  107. #ifndef NI_MAXHOST
  108. # define NI_MAXHOST 1025
  109. #endif
  110. #ifndef NI_MAXSERV
  111. # define NI_MAXSERV 32
  112. #endif
  113. #ifdef AF_INET6
  114. # define IS_IP_FAMILY(af) ((af) == AF_INET || (af) == AF_INET6)
  115. #else
  116. # define IS_IP_FAMILY(af) ((af) == AF_INET)
  117. #endif
  118. #ifndef HAVE_SOCKADDR_STORAGE
  119. /*
  120. * RFC 2553: protocol-independent placeholder for socket addresses
  121. */
  122. #define _SS_MAXSIZE 128
  123. #define _SS_ALIGNSIZE (sizeof(double))
  124. #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) * 2)
  125. #define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) * 2 - \
  126. _SS_PAD1SIZE - _SS_ALIGNSIZE)
  127. struct sockaddr_storage {
  128. #ifdef HAVE_SA_LEN
  129. unsigned char ss_len; /* address length */
  130. unsigned char ss_family; /* address family */
  131. #else
  132. unsigned short ss_family;
  133. #endif
  134. char __ss_pad1[_SS_PAD1SIZE];
  135. double __ss_align; /* force desired structure storage alignment */
  136. char __ss_pad2[_SS_PAD2SIZE];
  137. };
  138. #endif
  139. static void sock_define_const(char *name, int value);
  140. static void sock_define_uconst(const char *name, unsigned int value);
  141. #include "constants.h"
  142. static int str_is_number(const char *);
  143. /* fix [ruby-core:29427] */
  144. static int
  145. ruby_getaddrinfo__darwin(const char *nodename, const char *servname,
  146. struct addrinfo *hints, struct addrinfo **res)
  147. {
  148. const char *tmp_servname;
  149. struct addrinfo tmp_hints;
  150. tmp_servname = servname;
  151. MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
  152. if (nodename && servname) {
  153. if (str_is_number(tmp_servname) && atoi(servname) == 0) {
  154. tmp_servname = NULL;
  155. #ifdef AI_NUMERICSERV
  156. if (tmp_hints.ai_flags) tmp_hints.ai_flags &= ~AI_NUMERICSERV;
  157. #endif
  158. }
  159. }
  160. int error = getaddrinfo(nodename, tmp_servname, &tmp_hints, res);
  161. return error;
  162. }
  163. #undef getaddrinfo
  164. #define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__darwin((node),(serv),(hints),(res))
  165. #if defined(INET6) && (defined(LOOKUP_ORDER_HACK_INET) || defined(LOOKUP_ORDER_HACK_INET6))
  166. #define LOOKUP_ORDERS 3
  167. static int lookup_order_table[LOOKUP_ORDERS] = {
  168. #if defined(LOOKUP_ORDER_HACK_INET)
  169. PF_INET, PF_INET6, PF_UNSPEC,
  170. #elif defined(LOOKUP_ORDER_HACK_INET6)
  171. PF_INET6, PF_INET, PF_UNSPEC,
  172. #else
  173. /* should not happen */
  174. #endif
  175. };
  176. static int
  177. ruby_getaddrinfo(char *nodename, char *servname,
  178. struct addrinfo *hints, struct addrinfo **res)
  179. {
  180. struct addrinfo tmp_hints;
  181. int i, af, error;
  182. if (hints->ai_family != PF_UNSPEC) {
  183. return getaddrinfo(nodename, servname, hints, res);
  184. }
  185. for (i = 0; i < LOOKUP_ORDERS; i++) {
  186. af = lookup_order_table[i];
  187. MEMCPY(&tmp_hints, hints, struct addrinfo, 1);
  188. tmp_hints.ai_family = af;
  189. error = getaddrinfo(nodename, servname, &tmp_hints, res);
  190. if (error) {
  191. if (tmp_hints.ai_family == PF_UNSPEC) {
  192. break;
  193. }
  194. }
  195. else {
  196. break;
  197. }
  198. }
  199. return error;
  200. }
  201. #define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res))
  202. #endif
  203. #if defined(_AIX)
  204. static int
  205. ruby_getaddrinfo__aix(char *nodename, char *servname,
  206. struct addrinfo *hints, struct addrinfo **res)
  207. {
  208. int error = getaddrinfo(nodename, servname, hints, res);
  209. struct addrinfo *r;
  210. if (error)
  211. return error;
  212. for (r = *res; r != NULL; r = r->ai_next) {
  213. if (r->ai_addr->sa_family == 0)
  214. r->ai_addr->sa_family = r->ai_family;
  215. if (r->ai_addr->sa_len == 0)
  216. r->ai_addr->sa_len = r->ai_addrlen;
  217. }
  218. return 0;
  219. }
  220. #undef getaddrinfo
  221. #define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res))
  222. static int
  223. ruby_getnameinfo__aix(const struct sockaddr *sa, size_t salen,
  224. char *host, size_t hostlen,
  225. char *serv, size_t servlen, int flags)
  226. {
  227. struct sockaddr_in6 *sa6;
  228. u_int32_t *a6;
  229. if (sa->sa_family == AF_INET6) {
  230. sa6 = (struct sockaddr_in6 *)sa;
  231. a6 = sa6->sin6_addr.u6_addr.u6_addr32;
  232. if (a6[0] == 0 && a6[1] == 0 && a6[2] == 0 && a6[3] == 0) {
  233. strncpy(host, "::", hostlen);
  234. snprintf(serv, servlen, "%d", sa6->sin6_port);
  235. return 0;
  236. }
  237. }
  238. return getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
  239. }
  240. #undef getnameinfo
  241. #define getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) \
  242. ruby_getnameinfo__aix((sa), (salen), (host), (hostlen), (serv), (servlen), (flags))
  243. #ifndef CMSG_SPACE
  244. # define CMSG_SPACE(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + _CMSG_ALIGN(len))
  245. #endif
  246. #ifndef CMSG_LEN
  247. # define CMSG_LEN(len) (_CMSG_ALIGN(sizeof(struct cmsghdr)) + (len))
  248. #endif
  249. #endif
  250. #ifdef __BEOS__
  251. #undef close
  252. #define close closesocket
  253. #endif
  254. #define MakeOpenFile(obj, fp) \
  255. do { \
  256. fp = ALLOC(rb_io_t); \
  257. GC_WB(&RFILE(obj)->fptr, fp); \
  258. fp->fd = fp->read_fd = fp->write_fd = -1; \
  259. fp->pid = -1; \
  260. } \
  261. while (0)
  262. static int
  263. constant_arg(VALUE arg, int (*str_to_int)(char*, int, int*), const char *errmsg)
  264. {
  265. VALUE tmp;
  266. char *ptr;
  267. int ret;
  268. if (SYMBOL_P(arg)) {
  269. arg = rb_sym_to_s(arg);
  270. goto str;
  271. }
  272. else if (!NIL_P(tmp = rb_check_string_type(arg))) {
  273. arg = tmp;
  274. str:
  275. rb_check_safe_obj(arg);
  276. ptr = RSTRING_PTR(arg);
  277. if (str_to_int(ptr, RSTRING_LEN(arg), &ret) == -1)
  278. rb_raise(rb_eSocket, "%s: %s", errmsg, ptr);
  279. }
  280. else {
  281. ret = NUM2INT(arg);
  282. }
  283. return ret;
  284. }
  285. static int
  286. family_arg(VALUE domain)
  287. {
  288. /* convert AF_INET, etc. */
  289. return constant_arg(domain, family_to_int, "unknown socket domain");
  290. }
  291. static int
  292. socktype_arg(VALUE type)
  293. {
  294. /* convert SOCK_STREAM, etc. */
  295. return constant_arg(type, socktype_to_int, "unknown socket type");
  296. }
  297. static int
  298. level_arg(VALUE level)
  299. {
  300. /* convert SOL_SOCKET, IPPROTO_TCP, etc. */
  301. return constant_arg(level, level_to_int, "unknown protocol level");
  302. }
  303. static int
  304. optname_arg(int level, VALUE optname)
  305. {
  306. switch (level) {
  307. case SOL_SOCKET:
  308. return constant_arg(optname, so_optname_to_int, "unknown socket level option name");
  309. case IPPROTO_IP:
  310. return constant_arg(optname, ip_optname_to_int, "unknown IP level option name");
  311. #ifdef IPPROTO_IPV6
  312. case IPPROTO_IPV6:
  313. return constant_arg(optname, ipv6_optname_to_int, "unknown IPv6 level option name");
  314. #endif
  315. case IPPROTO_TCP:
  316. return constant_arg(optname, tcp_optname_to_int, "unknown TCP level option name");
  317. case IPPROTO_UDP:
  318. return constant_arg(optname, udp_optname_to_int, "unknown UDP level option name");
  319. default:
  320. return NUM2INT(optname);
  321. }
  322. }
  323. static int
  324. shutdown_how_arg(VALUE how)
  325. {
  326. /* convert SHUT_RD, SHUT_WR, SHUT_RDWR. */
  327. return constant_arg(how, shutdown_how_to_int, "unknown shutdown argument");
  328. }
  329. static VALUE
  330. init_sock(VALUE sock, int fd)
  331. {
  332. rb_io_t *fp;
  333. #ifdef S_ISSOCK
  334. struct stat sbuf;
  335. if (fstat(fd, &sbuf) < 0) {
  336. rb_sys_fail(0);
  337. }
  338. if (!S_ISSOCK(sbuf.st_mode)) {
  339. rb_raise(rb_eArgError, "not a socket file descriptor");
  340. }
  341. #endif
  342. MakeOpenFile(sock, fp);
  343. fp->fd = fp->read_fd = fp->write_fd = fd;
  344. fp->mode = FMODE_READWRITE|FMODE_DUPLEX;
  345. rb_io_ascii8bit_binmode(sock);
  346. if (do_not_reverse_lookup) {
  347. fp->mode |= FMODE_NOREVLOOKUP;
  348. }
  349. fp->mode |= FMODE_SYNC;
  350. return sock;
  351. }
  352. /*
  353. * call-seq:
  354. * BasicSocket.for_fd(fd) => basicsocket
  355. *
  356. * Returns a socket object which contains the file descriptor, _fd_.
  357. *
  358. * # If invoked by inetd, STDIN/STDOUT/STDERR is a socket.
  359. * STDIN_SOCK = Socket.for_fd(STDIN.fileno)
  360. * p STDIN_SOCK.remote_address
  361. *
  362. */
  363. static VALUE
  364. bsock_s_for_fd(VALUE klass, SEL sel, VALUE fd)
  365. {
  366. rb_io_t *fptr;
  367. VALUE sock = init_sock(rb_obj_alloc(klass), NUM2INT(fd));
  368. GetOpenFile(sock, fptr);
  369. return sock;
  370. }
  371. /*
  372. * call-seq:
  373. * basicsocket.shutdown([how]) => 0
  374. *
  375. * Calls shutdown(2) system call.
  376. *
  377. * s.shutdown(Socket::SHUT_RD) disallows further read.
  378. *
  379. * s.shutdown(Socket::SHUT_WR) disallows further write.
  380. *
  381. * s.shutdown(Socket::SHUT_RDWR) disallows further read and write.
  382. *
  383. * _how_ can be symbol or string:
  384. * - :RD, :SHUT_RD, "RD" and "SHUT_RD" are accepted as Socket::SHUT_RD.
  385. * - :WR, :SHUT_WR, "WR" and "SHUT_WR" are accepted as Socket::SHUT_WR.
  386. * - :RDWR, :SHUT_RDWR, "RDWR" and "SHUT_RDWR" are accepted as Socket::SHUT_RDWR.
  387. *
  388. * UNIXSocket.pair {|s1, s2|
  389. * s1.puts "ping"
  390. * s1.shutdown(:WR)
  391. * p s2.read #=> "ping\n"
  392. * s2.puts "pong"
  393. * s2.close
  394. * p s1.read #=> "pong\n"
  395. * }
  396. *
  397. */
  398. static VALUE
  399. bsock_shutdown(VALUE sock, SEL sel, int argc, VALUE *argv)
  400. {
  401. VALUE howto;
  402. int how;
  403. rb_io_t *fptr;
  404. if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
  405. rb_raise(rb_eSecurityError, "Insecure: can't shutdown socket");
  406. }
  407. rb_scan_args(argc, argv, "01", &howto);
  408. if (howto == Qnil)
  409. how = SHUT_RDWR;
  410. else {
  411. how = shutdown_how_arg(howto);
  412. if (how != SHUT_WR && how != SHUT_RD && how != SHUT_RDWR) {
  413. rb_raise(rb_eArgError, "`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR");
  414. }
  415. }
  416. GetOpenFile(sock, fptr);
  417. if (shutdown(fptr->fd, how) == -1)
  418. rb_sys_fail(0);
  419. return INT2FIX(0);
  420. }
  421. /*
  422. * call-seq:
  423. * basicsocket.close_read => nil
  424. *
  425. * Disallows further read using shutdown system call.
  426. *
  427. * s1, s2 = UNIXSocket.pair
  428. * s1.close_read
  429. * s2.puts #=> Broken pipe (Errno::EPIPE)
  430. */
  431. static VALUE
  432. bsock_close_read(VALUE sock, SEL sel)
  433. {
  434. rb_io_t *fptr;
  435. if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
  436. rb_raise(rb_eSecurityError, "Insecure: can't close socket");
  437. }
  438. GetOpenFile(sock, fptr);
  439. shutdown(fptr->fd, 0);
  440. if (!(fptr->mode & FMODE_WRITABLE)) {
  441. return rb_io_close(sock);
  442. }
  443. fptr->mode &= ~FMODE_READABLE;
  444. fptr->read_fd = -1;
  445. return Qnil;
  446. }
  447. /*
  448. * call-seq:
  449. * basicsocket.close_write => nil
  450. *
  451. * Disallows further write using shutdown system call.
  452. *
  453. * UNIXSocket.pair {|s1, s2|
  454. * s1.print "ping"
  455. * s1.close_write
  456. * p s2.read #=> "ping"
  457. * s2.print "pong"
  458. * s2.close
  459. * p s1.read #=> "pong"
  460. * }
  461. */
  462. static VALUE
  463. bsock_close_write(VALUE sock, SEL sel)
  464. {
  465. rb_io_t *fptr;
  466. if (rb_safe_level() >= 4 && !OBJ_TAINTED(sock)) {
  467. rb_raise(rb_eSecurityError, "Insecure: can't close socket");
  468. }
  469. GetOpenFile(sock, fptr);
  470. if (!(fptr->mode & FMODE_READABLE)) {
  471. return rb_io_close(sock);
  472. }
  473. shutdown(fptr->fd, 1);
  474. fptr->mode &= ~FMODE_WRITABLE;
  475. fptr->write_fd = -1;
  476. return Qnil;
  477. }
  478. /*
  479. * Document-method: setsockopt
  480. * call-seq:
  481. * setsockopt(level, optname, optval)
  482. * setsockopt(socketoption)
  483. *
  484. * Sets a socket option. These are protocol and system specific, see your
  485. * local system documentation for details.
  486. *
  487. * === Parameters
  488. * * +level+ is an integer, usually one of the SOL_ constants such as
  489. * Socket::SOL_SOCKET, or a protocol level.
  490. * A string or symbol of the name, possibly without prefix, is also
  491. * accepted.
  492. * * +optname+ is an integer, usually one of the SO_ constants, such
  493. * as Socket::SO_REUSEADDR.
  494. * A string or symbol of the name, possibly without prefix, is also
  495. * accepted.
  496. * * +optval+ is the value of the option, it is passed to the underlying
  497. * setsockopt() as a pointer to a certain number of bytes. How this is
  498. * done depends on the type:
  499. * - Fixnum: value is assigned to an int, and a pointer to the int is
  500. * passed, with length of sizeof(int).
  501. * - true or false: 1 or 0 (respectively) is assigned to an int, and the
  502. * int is passed as for a Fixnum. Note that +false+ must be passed,
  503. * not +nil+.
  504. * - String: the string's data and length is passed to the socket.
  505. * * +socketoption+ is an instance of Socket::Option
  506. *
  507. * === Examples
  508. *
  509. * Some socket options are integers with boolean values, in this case
  510. * #setsockopt could be called like this:
  511. * sock.setsockopt(:SOCKET, :REUSEADDR, true)
  512. * sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
  513. * sock.setsockopt(Socket::Option.bool(:INET, :SOCKET, :REUSEADDR, true))
  514. *
  515. * Some socket options are integers with numeric values, in this case
  516. * #setsockopt could be called like this:
  517. * sock.setsockopt(:IP, :TTL, 255)
  518. * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255)
  519. * sock.setsockopt(Socket::Option.int(:INET, :IP, :TTL, 255))
  520. *
  521. * Option values may be structs. Passing them can be complex as it involves
  522. * examining your system headers to determine the correct definition. An
  523. * example is an +ip_mreq+, which may be defined in your system headers as:
  524. * struct ip_mreq {
  525. * struct in_addr imr_multiaddr;
  526. * struct in_addr imr_interface;
  527. * };
  528. *
  529. * In this case #setsockopt could be called like this:
  530. * optval = IPAddr.new("224.0.0.251").hton +
  531. * IPAddr.new(Socket::INADDR_ANY, Socket::AF_INET).hton
  532. * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval)
  533. *
  534. */
  535. static VALUE
  536. bsock_setsockopt(VALUE sock, SEL sel, VALUE lev, VALUE optname, VALUE val)
  537. {
  538. int level, option;
  539. rb_io_t *fptr;
  540. int i;
  541. const char *v;
  542. int vlen;
  543. rb_secure(2);
  544. level = level_arg(lev);
  545. option = optname_arg(level, optname);
  546. switch (TYPE(val)) {
  547. case T_FIXNUM:
  548. i = FIX2INT(val);
  549. goto numval;
  550. case T_FALSE:
  551. i = 0;
  552. goto numval;
  553. case T_TRUE:
  554. i = 1;
  555. numval:
  556. v = (char*)&i; vlen = (int)sizeof(i);
  557. break;
  558. default:
  559. StringValue(val);
  560. v = RSTRING_PTR(val);
  561. vlen = RSTRING_LENINT(val);
  562. break;
  563. }
  564. #define rb_sys_fail_path(path) rb_sys_fail(path == 0 ? NULL : RSTRING_PTR(path));
  565. GetOpenFile(sock, fptr);
  566. if (setsockopt(fptr->fd, level, option, v, vlen) < 0)
  567. rb_sys_fail_path(fptr->path);
  568. return INT2FIX(0);
  569. }
  570. /*
  571. * Document-method: getsockopt
  572. * call-seq:
  573. * getsockopt(level, optname) => socketoption
  574. *
  575. * Gets a socket option. These are protocol and system specific, see your
  576. * local system documentation for details. The option is returned as
  577. * a Socket::Option object.
  578. *
  579. * === Parameters
  580. * * +level+ is an integer, usually one of the SOL_ constants such as
  581. * Socket::SOL_SOCKET, or a protocol level.
  582. * A string or symbol of the name, possibly without prefix, is also
  583. * accepted.
  584. * * +optname+ is an integer, usually one of the SO_ constants, such
  585. * as Socket::SO_REUSEADDR.
  586. * A string or symbol of the name, possibly without prefix, is also
  587. * accepted.
  588. *
  589. * === Examples
  590. *
  591. * Some socket options are integers with boolean values, in this case
  592. * #getsockopt could be called like this:
  593. *
  594. * reuseaddr = sock.getsockopt(:SOCKET, :REUSEADDR).bool
  595. *
  596. * optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
  597. * optval = optval.unpack "i"
  598. * reuseaddr = optval[0] == 0 ? false : true
  599. *
  600. * Some socket options are integers with numeric values, in this case
  601. * #getsockopt could be called like this:
  602. *
  603. * ipttl = sock.getsockopt(:IP, :TTL).int
  604. *
  605. * optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL)
  606. * ipttl = optval.unpack("i")[0]
  607. *
  608. * Option values may be structs. Decoding them can be complex as it involves
  609. * examining your system headers to determine the correct definition. An
  610. * example is a +struct linger+, which may be defined in your system headers
  611. * as:
  612. * struct linger {
  613. * int l_onoff;
  614. * int l_linger;
  615. * };
  616. *
  617. * In this case #getsockopt could be called like this:
  618. *
  619. * # Socket::Option knows linger structure.
  620. * onoff, linger = sock.getsockopt(:SOCKET, :LINGER).linger
  621. *
  622. * optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
  623. * onoff, linger = optval.unpack "ii"
  624. * onoff = onoff == 0 ? false : true
  625. */
  626. static VALUE
  627. bsock_getsockopt(VALUE sock, SEL sel, VALUE lev, VALUE optname)
  628. {
  629. #if !defined(__BEOS__)
  630. int level, option;
  631. socklen_t len;
  632. char *buf;
  633. rb_io_t *fptr;
  634. level = level_arg(lev);
  635. option = optname_arg(level, optname);
  636. len = 256;
  637. buf = ALLOCA_N(char,len);
  638. GetOpenFile(sock, fptr);
  639. if (getsockopt(fptr->fd, level, option, buf, &len) < 0)
  640. rb_sys_fail_path(fptr->path);
  641. return rb_str_new(buf, len);
  642. #else
  643. rb_notimplement();
  644. #endif
  645. }
  646. /*
  647. * call-seq:
  648. * basicsocket.getsockname => sockaddr
  649. *
  650. * Returns the local address of the socket as a sockaddr string.
  651. *
  652. * TCPServer.open("127.0.0.1", 15120) {|serv|
  653. * p serv.getsockname #=> "\x02\x00;\x10\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  654. * }
  655. *
  656. * If Addrinfo object is preferred over the binary string,
  657. * use BasicSocket#local_address.
  658. */
  659. static VALUE
  660. bsock_getsockname(VALUE sock, SEL sel)
  661. {
  662. struct sockaddr_storage buf;
  663. socklen_t len = (socklen_t)sizeof buf;
  664. rb_io_t *fptr;
  665. GetOpenFile(sock, fptr);
  666. if (getsockname(fptr->fd, (struct sockaddr*)&buf, &len) < 0)
  667. rb_sys_fail("getsockname(2)");
  668. return rb_str_new((char*)&buf, len);
  669. }
  670. /*
  671. * call-seq:
  672. * basicsocket.getpeername => sockaddr
  673. *
  674. * Returns the remote address of the socket as a sockaddr string.
  675. *
  676. * TCPServer.open("127.0.0.1", 1440) {|serv|
  677. * c = TCPSocket.new("127.0.0.1", 1440)
  678. * s = serv.accept
  679. * p s.getpeername #=> "\x02\x00\x82u\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  680. * }
  681. *
  682. * If Addrinfo object is preferred over the binary string,
  683. * use BasicSocket#remote_address.
  684. *
  685. */
  686. static VALUE
  687. bsock_getpeername(VALUE sock, SEL sel)
  688. {
  689. struct sockaddr_storage buf;
  690. socklen_t len = (socklen_t)sizeof buf;
  691. rb_io_t *fptr;
  692. GetOpenFile(sock, fptr);
  693. if (getpeername(fptr->fd, (struct sockaddr*)&buf, &len) < 0)
  694. rb_sys_fail("getpeername(2)");
  695. return rb_str_new((char*)&buf, len);
  696. }
  697. #if defined(HAVE_GETPEEREID) || defined(SO_PEERCRED) || defined(HAVE_GETPEERUCRED)
  698. /*
  699. * call-seq:
  700. * basicsocket.getpeereid => [euid, egid]
  701. *
  702. * Returns the user and group on the peer of the UNIX socket.
  703. * The result is a two element array which contains the effective uid and the effective gid.
  704. *
  705. * Socket.unix_server_loop("/tmp/sock") {|s|
  706. * begin
  707. * euid, egid = s.getpeereid
  708. *
  709. * # Check the connected client is myself or not.
  710. * next if euid != Process.uid
  711. *
  712. * # do something about my resource.
  713. *
  714. * ensure
  715. * s.close
  716. * end
  717. * }
  718. *
  719. */
  720. static VALUE
  721. bsock_getpeereid(VALUE self, SEL sel)
  722. {
  723. #if defined(HAVE_GETPEEREID)
  724. rb_io_t *fptr;
  725. uid_t euid;
  726. gid_t egid;
  727. GetOpenFile(self, fptr);
  728. if (getpeereid(fptr->fd, &euid, &egid) == -1)
  729. rb_sys_fail("getpeereid");
  730. return rb_assoc_new(UIDT2NUM(euid), GIDT2NUM(egid));
  731. #elif defined(SO_PEERCRED) /* GNU/Linux */
  732. rb_io_t *fptr;
  733. struct ucred cred;
  734. socklen_t len = sizeof(cred);
  735. GetOpenFile(self, fptr);
  736. if (getsockopt(fptr->fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) == -1)
  737. rb_sys_fail("getsockopt(SO_PEERCRED)");
  738. return rb_assoc_new(UIDT2NUM(cred.uid), GIDT2NUM(cred.gid));
  739. #elif defined(HAVE_GETPEERUCRED) /* Solaris */
  740. rb_io_t *fptr;
  741. ucred_t *uc = NULL;
  742. VALUE ret;
  743. GetOpenFile(self, fptr);
  744. if (getpeerucred(fptr->fd, &uc) == -1)
  745. rb_sys_fail("getpeerucred");
  746. ret = rb_assoc_new(UIDT2NUM(ucred_geteuid(uc)), GIDT2NUM(ucred_getegid(uc)));
  747. ucred_free(uc);
  748. return ret;
  749. #endif
  750. }
  751. #else
  752. #define bsock_getpeereid rb_f_notimplement
  753. #endif
  754. static VALUE addrinfo_new(struct sockaddr *addr, socklen_t len, int family, int socktype, int protocol, VALUE canonname, VALUE inspectname);
  755. static VALUE fd_socket_addrinfo(int fd, struct sockaddr *addr, socklen_t len);
  756. static VALUE io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len);
  757. /*
  758. * call-seq:
  759. * bsock.local_address => addrinfo
  760. *
  761. * Returns an Addrinfo object for local address obtained by getsockname.
  762. *
  763. * Note that addrinfo.protocol is filled by 0.
  764. *
  765. * TCPSocket.open("www.ruby-lang.org", 80) {|s|
  766. * p s.local_address #=> #<Addrinfo: 192.168.0.129:36873 TCP>
  767. * }
  768. *
  769. * TCPServer.open("127.0.0.1", 1512) {|serv|
  770. * p serv.local_address #=> #<Addrinfo: 127.0.0.1:1512 TCP>
  771. * }
  772. *
  773. */
  774. static VALUE
  775. bsock_local_address(VALUE sock, SEL sel)
  776. {
  777. struct sockaddr_storage buf;
  778. socklen_t len = (socklen_t)sizeof buf;
  779. rb_io_t *fptr;
  780. GetOpenFile(sock, fptr);
  781. if (getsockname(fptr->fd, (struct sockaddr*)&buf, &len) < 0)
  782. rb_sys_fail("getsockname(2)");
  783. return fd_socket_addrinfo(fptr->fd, (struct sockaddr *)&buf, len);
  784. }
  785. /*
  786. * call-seq:
  787. * bsock.remote_address => addrinfo
  788. *
  789. * Returns an Addrinfo object for remote address obtained by getpeername.
  790. *
  791. * Note that addrinfo.protocol is filled by 0.
  792. *
  793. * TCPSocket.open("www.ruby-lang.org", 80) {|s|
  794. * p s.remote_address #=> #<Addrinfo: 221.186.184.68:80 TCP>
  795. * }
  796. *
  797. * TCPServer.open("127.0.0.1", 1728) {|serv|
  798. * c = TCPSocket.new("127.0.0.1", 1728)
  799. * s = serv.accept
  800. * p s.remote_address #=> #<Addrinfo: 127.0.0.1:36504 TCP>
  801. * }
  802. *
  803. */
  804. static VALUE
  805. bsock_remote_address(VALUE sock, SEL sel)
  806. {
  807. struct sockaddr_storage buf;
  808. socklen_t len = (socklen_t)sizeof buf;
  809. rb_io_t *fptr;
  810. GetOpenFile(sock, fptr);
  811. if (getpeername(fptr->fd, (struct sockaddr*)&buf, &len) < 0)
  812. rb_sys_fail("getpeername(2)");
  813. return fd_socket_addrinfo(fptr->fd, (struct sockaddr *)&buf, len);
  814. }
  815. #define SockAddrStringValue(v) sockaddr_string_value(&(v))
  816. #define SockAddrStringValuePtr(v) sockaddr_string_value_ptr(&(v))
  817. static VALUE sockaddr_string_value(volatile VALUE *);
  818. static char *sockaddr_string_value_ptr(volatile VALUE *);
  819. /*
  820. * call-seq:
  821. * basicsocket.send(mesg, flags [, dest_sockaddr]) => numbytes_sent
  822. *
  823. * send _mesg_ via _basicsocket_.
  824. *
  825. * _mesg_ should be a string.
  826. *
  827. * _flags_ should be a bitwise OR of Socket::MSG_* constants.
  828. *
  829. * _dest_sockaddr_ should be a packed sockaddr string or an addrinfo.
  830. *
  831. * TCPSocket.open("localhost", 80) {|s|
  832. * s.send "GET / HTTP/1.0\r\n\r\n", 0
  833. * p s.read
  834. * }
  835. */
  836. static VALUE
  837. bsock_send(VALUE sock, SEL sel, int argc, VALUE *argv)
  838. {
  839. VALUE mesg, to;
  840. VALUE flags;
  841. rb_io_t *fptr;
  842. int fd, n;
  843. rb_secure(4);
  844. rb_scan_args(argc, argv, "21", &mesg, &flags, &to);
  845. StringValue(mesg);
  846. if (!NIL_P(to)) SockAddrStringValue(to);
  847. GetOpenFile(sock, fptr);
  848. fd = fptr->fd;
  849. retry:
  850. rb_thread_fd_writable(fd);
  851. if (!NIL_P(to)) {
  852. n = sendto(fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), NUM2INT(flags),
  853. (struct sockaddr*)RSTRING_PTR(to), RSTRING_LEN(to));
  854. }
  855. else {
  856. n = send(fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), NUM2INT(flags));
  857. }
  858. if (n < 0) {
  859. if (rb_io_wait_writable(fd)) {
  860. goto retry;
  861. }
  862. rb_sys_fail("send(2)");
  863. }
  864. return INT2FIX(n);
  865. }
  866. /*
  867. * call-seq:
  868. * basicsocket.do_not_reverse_lookup => true or false
  869. *
  870. * Gets the do_not_reverse_lookup flag of _basicsocket_.
  871. *
  872. * TCPSocket.open("www.ruby-lang.org", 80) {|sock|
  873. * p sock.do_not_reverse_lookup #=> false
  874. * p sock.peeraddr #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
  875. * sock.do_not_reverse_lookup = true
  876. * p sock.peeraddr #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
  877. * }
  878. */
  879. static VALUE
  880. bsock_do_not_reverse_lookup(VALUE sock, SEL sel)
  881. {
  882. rb_io_t *fptr;
  883. GetOpenFile(sock, fptr);
  884. return (fptr->mode & FMODE_NOREVLOOKUP) ? Qtrue : Qfalse;
  885. }
  886. /*
  887. * call-seq:
  888. * basicsocket.do_not_reverse_lookup = bool
  889. *
  890. * Sets the do_not_reverse_lookup flag of _basicsocket_.
  891. *
  892. * BasicSocket.do_not_reverse_lookup = false
  893. * p TCPSocket.new("127.0.0.1", 80).do_not_reverse_lookup #=> false
  894. * BasicSocket.do_not_reverse_lookup = true
  895. * p TCPSocket.new("127.0.0.1", 80).do_not_reverse_lookup #=> true
  896. *
  897. */
  898. static VALUE
  899. bsock_do_not_reverse_lookup_set(VALUE sock, SEL sel, VALUE state)
  900. {
  901. rb_io_t *fptr;
  902. rb_secure(4);
  903. GetOpenFile(sock, fptr);
  904. if (RTEST(state)) {
  905. fptr->mode |= FMODE_NOREVLOOKUP;
  906. }
  907. else {
  908. fptr->mode &= ~FMODE_NOREVLOOKUP;
  909. }
  910. return sock;
  911. }
  912. static VALUE ipaddr(struct sockaddr*, int);
  913. #ifdef HAVE_SYS_UN_H
  914. static VALUE unixaddr(struct sockaddr_un*, socklen_t);
  915. #endif
  916. enum sock_recv_type {
  917. RECV_RECV, /* BasicSocket#recv(no from) */
  918. RECV_IP, /* IPSocket#recvfrom */
  919. RECV_UNIX, /* UNIXSocket#recvfrom */
  920. RECV_SOCKET /* Socket#recvfrom */
  921. };
  922. static VALUE
  923. s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
  924. {
  925. rb_io_t *fptr;
  926. VALUE str;
  927. struct sockaddr_storage buf;
  928. socklen_t alen = (socklen_t)sizeof buf;
  929. VALUE len, flg;
  930. long buflen;
  931. long slen;
  932. int fd, flags;
  933. rb_scan_args(argc, argv, "11", &len, &flg);
  934. if (flg == Qnil) flags = 0;
  935. else flags = NUM2INT(flg);
  936. buflen = NUM2INT(len);
  937. GetOpenFile(sock, fptr);
  938. if (rb_io_read_pending(fptr)) {
  939. rb_raise(rb_eIOError, "recv for buffered IO");
  940. }
  941. fd = fptr->fd;
  942. str = rb_bstr_new();
  943. rb_bstr_resize(str, buflen);
  944. retry:
  945. rb_thread_wait_fd(fd);
  946. rb_io_check_closed(fptr);
  947. if (rb_bstr_length(str) != buflen) {
  948. rb_raise(rb_eRuntimeError, "buffer string modified");
  949. }
  950. slen = recvfrom(fd, rb_bstr_bytes(str), buflen, flags,
  951. (struct sockaddr *)&buf, &alen);
  952. if (slen < 0) {
  953. if (rb_io_wait_readable(fd)) {
  954. goto retry;
  955. }
  956. rb_sys_fail("recvfrom(2)");
  957. }
  958. if (slen < rb_bstr_length(str)) {
  959. rb_bstr_resize(str, slen);
  960. }
  961. rb_obj_taint(str);
  962. switch (from) {
  963. case RECV_RECV:
  964. return (VALUE)str;
  965. case RECV_IP:
  966. #if 0
  967. if (alen != sizeof(struct sockaddr_in)) {
  968. rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
  969. }
  970. #endif
  971. if (alen && alen != sizeof(buf)) /* OSX doesn't return a from result for connection-oriented sockets */
  972. return rb_assoc_new(str, ipaddr((struct sockaddr*)&buf, fptr->mode & FMODE_NOREVLOOKUP));
  973. else
  974. return rb_assoc_new(str, Qnil);
  975. #ifdef HAVE_SYS_UN_H
  976. case RECV_UNIX:
  977. return rb_assoc_new(str, unixaddr((struct sockaddr_un*)&buf, alen));
  978. #endif
  979. case RECV_SOCKET:
  980. return rb_assoc_new(str, io_socket_addrinfo(sock, (struct sockaddr*)&buf, alen));
  981. default:
  982. rb_bug("s_recvfrom called with bad value");
  983. }
  984. }
  985. static VALUE
  986. s_recvfrom_nonblock(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
  987. {
  988. rb_io_t *fptr;
  989. VALUE str;
  990. struct sockaddr_storage buf;
  991. socklen_t alen = (socklen_t)sizeof buf;
  992. VALUE len, flg;
  993. long buflen;
  994. long slen;
  995. int fd, flags;
  996. VALUE addr = Qnil;
  997. rb_scan_args(argc, argv, "11", &len, &flg);
  998. if (flg == Qnil) flags = 0;
  999. else flags = NUM2INT(flg);
  1000. buflen = NUM2INT(len);
  1001. #ifdef MSG_DONTWAIT
  1002. /* MSG_DONTWAIT avoids the race condition between fcntl and recvfrom.
  1003. It is not portable, though. */
  1004. flags |= MSG_DONTWAIT;
  1005. #endif
  1006. GetOpenFile(sock, fptr);
  1007. if (rb_io_read_pending(fptr)) {
  1008. rb_raise(rb_eIOError, "recvfrom for buffered IO");
  1009. }
  1010. fd = fptr->fd;
  1011. str = rb_bstr_new();
  1012. rb_bstr_resize(str, buflen);
  1013. rb_io_check_closed(fptr);
  1014. rb_io_set_nonblock(fptr);
  1015. slen = recvfrom(fd, rb_bstr_bytes(str), buflen, flags,
  1016. (struct sockaddr *)&buf, &alen);
  1017. if (slen < 0) {
  1018. switch (errno) {
  1019. case EAGAIN:
  1020. #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
  1021. case EWOULDBLOCK:
  1022. #endif
  1023. rb_mod_sys_fail(rb_mWaitReadable, "recvfrom(2) would block");
  1024. }
  1025. rb_sys_fail("recvfrom(2)");
  1026. }
  1027. if (slen < rb_bstr_length(str)) {
  1028. rb_bstr_resize(str, slen);
  1029. }
  1030. rb_obj_taint(str);
  1031. switch (from) {
  1032. case RECV_RECV:
  1033. return str;
  1034. case RECV_IP:
  1035. if (alen && alen != sizeof(buf)) /* connection-oriented socket may not return a from result */
  1036. addr = ipaddr((struct sockaddr*)&buf, fptr->mode & FMODE_NOREVLOOKUP);
  1037. break;
  1038. case RECV_SOCKET:
  1039. addr = io_socket_addrinfo(sock, (struct sockaddr*)&buf, alen);
  1040. break;
  1041. default:
  1042. rb_bug("s_recvfrom_nonblock called with bad value");
  1043. }
  1044. return rb_assoc_new(str, addr);
  1045. }
  1046. /*
  1047. * call-seq:
  1048. * basicsocket.recv(maxlen) => mesg
  1049. * basicsocket.recv(maxlen, flags) => mesg
  1050. *
  1051. * Receives a message.
  1052. *
  1053. * _maxlen_ is the maximum number of bytes to receive.
  1054. *
  1055. * _flags_ should be a bitwise OR of Socket::MSG_* constants.
  1056. *
  1057. * UNIXSocket.pair {|s1, s2|
  1058. * s1.puts "Hello World"
  1059. * p s2.recv(4) #=> "Hell"
  1060. * p s2.recv(4, Socket::MSG_PEEK) #=> "o Wo"
  1061. * p s2.recv(4) #=> "o Wo"
  1062. * p s2.recv(10) #=> "rld\n"
  1063. * }
  1064. */
  1065. static VALUE
  1066. bsock_recv(VALUE sock, SEL sel, int argc, VALUE *argv)
  1067. {
  1068. return s_recvfrom(sock, argc, argv, RECV_RECV);
  1069. }
  1070. /*
  1071. * call-seq:
  1072. * basicsocket.recv_nonblock(maxlen) => mesg
  1073. * basicsocket.recv_nonblock(maxlen, flags) => mesg
  1074. *
  1075. * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
  1076. * O_NONBLOCK is set for the underlying file descriptor.
  1077. * _flags_ is zero or more of the +MSG_+ options.
  1078. * The result, _mesg_, is the data received.
  1079. *
  1080. * When recvfrom(2) returns 0, Socket#recv_nonblock returns
  1081. * an empty string as data.
  1082. * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
  1083. *
  1084. * === Parameters
  1085. * * +maxlen+ - the number of bytes to receive from the socket
  1086. * * +flags+ - zero or more of the +MSG_+ options
  1087. *
  1088. * === Example
  1089. * serv = TCPServer.new("127.0.0.1", 0)
  1090. * af, port, host, addr = serv.addr
  1091. * c = TCPSocket.new(addr, port)
  1092. * s = serv.accept
  1093. * c.send "aaa", 0
  1094. * begin # emulate blocking recv.
  1095. * p s.recv_nonblock(10) #=> "aaa"
  1096. * rescue IO::WaitReadable
  1097. * IO.select([s])
  1098. * retry
  1099. * end
  1100. *
  1101. * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  1102. * to _recv_nonblock_ fails.
  1103. *
  1104. * BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure,
  1105. * including Errno::EWOULDBLOCK.
  1106. *
  1107. * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
  1108. * it is extended by IO::WaitReadable.
  1109. * So IO::WaitReadable can be used to rescue the exceptions for retrying recv_nonblock.
  1110. *
  1111. * === See
  1112. * * Socket#recvfrom
  1113. */
  1114. static VALUE
  1115. bsock_recv_nonblock(VALUE sock, SEL sel, int argc, VALUE *argv)
  1116. {
  1117. return s_recvfrom_nonblock(sock, argc, argv, RECV_RECV);
  1118. }
  1119. /*
  1120. * call-seq:
  1121. * BasicSocket.do_not_reverse_lookup => true or false
  1122. *
  1123. * Gets the global do_not_reverse_lookup flag.
  1124. *
  1125. * BasicSocket.do_not_reverse_lookup #=> false
  1126. */
  1127. static VALUE
  1128. bsock_do_not_rev_lookup(VALUE self, SEL sel)
  1129. {
  1130. return do_not_reverse_lookup ? Qtrue : Qfalse;
  1131. }
  1132. /*
  1133. * call-seq:
  1134. * BasicSocket.do_not_reverse_lookup = bool
  1135. *
  1136. * Sets the global do_not_reverse_lookup flag.
  1137. *
  1138. * The flag is used for initial value of do_not_reverse_lookup for each socket.
  1139. *
  1140. * s1 = TCPSocket.new("localhost", 80)
  1141. * p s1.do_not_reverse_lookup #=> true
  1142. * BasicSocket.do_not_reverse_lookup = false
  1143. * s2 = TCPSocket.new("localhost", 80)
  1144. * p s2.do_not_reverse_lookup #=> false
  1145. * p s1.do_not_reverse_lookup #=> true
  1146. *
  1147. */
  1148. static VALUE
  1149. bsock_do_not_rev_lookup_set(VALUE self, SEL sel, VALUE val)
  1150. {
  1151. rb_secure(4);
  1152. do_not_reverse_lookup = RTEST(val);
  1153. return val;
  1154. }
  1155. NORETURN(static void raise_socket_error(char *, int));
  1156. static void
  1157. raise_socket_error(char *reason, int error)
  1158. {
  1159. #ifdef EAI_SYSTEM
  1160. if (error == EAI_SYSTEM) rb_sys_fail(reason);
  1161. #endif
  1162. rb_raise(rb_eSocket, "%s: %s", reason, gai_strerror(error));
  1163. }
  1164. static void
  1165. make_ipaddr0(struct sockaddr *addr, char *buf, size_t len)
  1166. {
  1167. int error;
  1168. error = getnameinfo(addr, SA_LEN(addr), buf, len, NULL, 0, NI_NUMERICHOST);
  1169. if (error) {
  1170. raise_socket_error("getnameinfo", error);
  1171. }
  1172. }
  1173. static VALUE
  1174. make_ipaddr(struct sockaddr *addr)
  1175. {
  1176. char hbuf[1024];
  1177. make_ipaddr0(addr, hbuf, sizeof(hbuf));
  1178. return rb_str_new2(hbuf);
  1179. }
  1180. static void
  1181. make_inetaddr(long host, char *buf, size_t len)
  1182. {
  1183. struct sockaddr_in sin;
  1184. MEMZERO(&sin, struct sockaddr_in, 1);
  1185. sin.sin_family = AF_INET;
  1186. SET_SIN_LEN(&sin, sizeof(sin));
  1187. sin.sin_addr.s_addr = host;
  1188. make_ipaddr0((struct sockaddr*)&sin, buf, len);
  1189. }
  1190. static int
  1191. str_is_number(const char *p)
  1192. {
  1193. char *ep;
  1194. if (!p || *p == '\0')
  1195. return 0;
  1196. ep = NULL;
  1197. (void)STRTOUL(p, &ep, 10);
  1198. if (ep && *ep == '\0')
  1199. return 1;
  1200. else
  1201. return 0;
  1202. }
  1203. static char*
  1204. host_str(VALUE host, char *hbuf, size_t len, int *flags_ptr)
  1205. {
  1206. if (NIL_P(host)) {
  1207. return NULL;
  1208. }
  1209. else if (rb_obj_is_kind_of(host, rb_cInteger)) {
  1210. unsigned int i = NUM2UINT(host);
  1211. make_inetaddr(htonl(i), hbuf, len);
  1212. if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
  1213. return hbuf;
  1214. }
  1215. else {
  1216. const char *name;
  1217. SafeStringValue(host);
  1218. name = RSTRING_PTR(host);
  1219. if (!name || *name == 0 || (name[0] == '<' && strcmp(name, "<any>") == 0)) {
  1220. make_inetaddr(INADDR_ANY, hbuf, len);
  1221. if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
  1222. }
  1223. else if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  1224. make_inetaddr(INADDR_BROADCAST, hbuf, len);
  1225. if (flags_ptr) *flags_ptr |= AI_NUMERICHOST;
  1226. }
  1227. else if (strlen(name) >= len) {
  1228. rb_raise(rb_eArgError, "hostname too long (%ld)", strlen(name));
  1229. }
  1230. else {
  1231. strcpy(hbuf, name);
  1232. }
  1233. return hbuf;
  1234. }
  1235. }
  1236. static char*
  1237. port_str(VALUE port, char *pbuf, size_t len, int *flags_ptr)
  1238. {
  1239. if (NIL_P(port)) {
  1240. return 0;
  1241. }
  1242. else if (FIXNUM_P(port)) {
  1243. snprintf(pbuf, len, "%ld", FIX2LONG(port));
  1244. #ifdef AI_NUMERICSERV
  1245. if (flags_ptr) *flags_ptr |= AI_NUMERICSERV;
  1246. #endif
  1247. return pbuf;
  1248. }
  1249. else {
  1250. const char *serv;
  1251. SafeStringValue(port);
  1252. serv = RSTRING_PTR(port);
  1253. if (strlen(serv) >= len) {
  1254. rb_raise(rb_eArgError, "service name too long (%ld)", strlen(serv));
  1255. }
  1256. strcpy(pbuf, serv);
  1257. return pbuf;
  1258. }
  1259. }
  1260. static struct addrinfo*
  1261. sock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack)
  1262. {
  1263. struct addrinfo* res = NULL;
  1264. char *hostp, *portp;
  1265. int error;
  1266. char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
  1267. int additional_flags = 0;
  1268. hostp = host_str(host, hbuf, sizeof(hbuf), &additional_flags);
  1269. portp = port_str(port, pbuf, sizeof(pbuf), &additional_flags);
  1270. if (socktype_hack && hints->ai_socktype == 0 && str_is_number(portp)) {
  1271. hints->ai_socktype = SOCK_DGRAM;
  1272. }
  1273. hints->ai_flags |= additional_flags;
  1274. error = getaddrinfo(hostp, portp, hints, &res);
  1275. if (error) {
  1276. if (hostp && hostp[strlen(hostp)-1] == '\n') {
  1277. rb_raise(rb_eSocket, "newline at the end of hostname");
  1278. }
  1279. raise_socket_error("getaddrinfo", error);
  1280. }
  1281. #if defined(__APPLE__) && defined(__MACH__)
  1282. {
  1283. struct addrinfo *r;
  1284. r = res;
  1285. while (r) {
  1286. if (! r->ai_socktype) r->ai_socktype = hints->ai_socktype;
  1287. if (! r->ai_protocol) {
  1288. if (r->ai_socktype == SOCK_DGRAM) {
  1289. r->ai_protocol = IPPROTO_UDP;
  1290. }
  1291. else if (r->ai_socktype == SOCK_STREAM) {
  1292. r->ai_protocol = IPPROTO_TCP;
  1293. }
  1294. }
  1295. r = r->ai_next;
  1296. }
  1297. }
  1298. #endif
  1299. return res;
  1300. }
  1301. static struct addrinfo*
  1302. sock_addrinfo(VALUE host, VALUE port, int socktype, int flags)
  1303. {
  1304. struct addrinfo hints;
  1305. MEMZERO(&hints, struct addrinfo, 1);
  1306. hints.ai_family = AF_UNSPEC;
  1307. hints.ai_socktype = socktype;
  1308. hints.ai_flags = flags;
  1309. return sock_getaddrinfo(host, port, &hints, 1);
  1310. }
  1311. static VALUE
  1312. ipaddr(struct sockaddr *sockaddr, int norevlookup)
  1313. {
  1314. VALUE family, port, addr1, addr2;
  1315. VALUE ary;
  1316. int error;
  1317. char hbuf[1024], pbuf[1024];
  1318. ID id;
  1319. id = intern_family(sockaddr->sa_family);
  1320. if (id) {
  1321. family = rb_str_dup(rb_id2str(id));
  1322. }
  1323. else {
  1324. sprintf(pbuf, "unknown:%d", sockaddr->sa_family);
  1325. family = rb_str_new2(pbuf);
  1326. }
  1327. addr1 = Qnil;
  1328. if (!norevlookup) {
  1329. error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
  1330. NULL, 0, 0);
  1331. if (! error) {
  1332. addr1 = rb_str_new2(hbuf);
  1333. }
  1334. }
  1335. error = getnameinfo(sockaddr, SA_LEN(sockaddr), hbuf, sizeof(hbuf),
  1336. pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV);
  1337. if (error) {
  1338. raise_socket_error("getnameinfo", error);
  1339. }
  1340. addr2 = rb_str_new2(hbuf);
  1341. if (addr1 == Qnil) {
  1342. addr1 = addr2;
  1343. }
  1344. port = INT2FIX(atoi(pbuf));
  1345. ary = rb_ary_new3(4, family, port, addr1, addr2);
  1346. return ary;
  1347. }
  1348. static int
  1349. ruby_socket(int domain, int type, int proto)
  1350. {
  1351. int fd;
  1352. fd = socket(domain, type, proto);
  1353. if (fd < 0) {
  1354. if (errno == EMFILE || errno == ENFILE) {
  1355. rb_gc();
  1356. fd = socket(domain, type, proto);
  1357. }
  1358. }
  1359. return fd;
  1360. }
  1361. static int
  1362. wait_connectable0(int fd, rb_fdset_t *fds_w, rb_fdset_t *fds_e)
  1363. {
  1364. int sockerr;
  1365. socklen_t sockerrlen;
  1366. for (;;) {
  1367. rb_fd_zero(fds_w);
  1368. rb_fd_zero(fds_e);
  1369. rb_fd_set(fd, fds_w);
  1370. rb_fd_set(fd, fds_e);
  1371. rb_thread_select(fd+1, 0, rb_fd_ptr(fds_w), rb_fd_ptr(fds_e), 0);
  1372. if (rb_fd_isset(fd, fds_w)) {
  1373. return 0;
  1374. }
  1375. else if (rb_fd_isset(fd, fds_e)) {
  1376. sockerrlen = (socklen_t)sizeof(sockerr);
  1377. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr,
  1378. &sockerrlen) == 0) {
  1379. if (sockerr == 0)
  1380. continue; /* workaround for winsock */
  1381. errno = sockerr;
  1382. }
  1383. return -1;
  1384. }
  1385. }
  1386. }
  1387. struct wait_connectable_arg {
  1388. int fd;
  1389. rb_fdset_t *fds_w;
  1390. rb_fdset_t *fds_e;
  1391. };
  1392. #ifdef HAVE_RB_FD_INIT
  1393. static VALUE
  1394. try_wait_connectable(VALUE arg)
  1395. {
  1396. struct wait_connectable_arg *p = (struct wait_connectable_arg *)arg;
  1397. return (VALUE)wait_connectable0(p->fd, p->fds_w, p->fds_e);
  1398. }
  1399. static VALUE
  1400. wait_connectable_ensure(VALUE arg)
  1401. {
  1402. struct wait_connectable_arg *p = (struct wait_connectable_arg *)arg;
  1403. rb_fd_term(p->fds_w);
  1404. rb_fd_term(p->fds_e);
  1405. return Qnil;
  1406. }
  1407. #endif
  1408. static int
  1409. wait_connectable(int fd)
  1410. {
  1411. struct wait_connectable_arg *arg;
  1412. arg = (void *)xmalloc(sizeof(struct wait_connectable_arg));
  1413. GC_WB(&arg->fds_w, xmalloc(sizeof(rb_fdset_t)));
  1414. GC_WB(&arg->fds_e, xmalloc(sizeof(rb_fdset_t)));
  1415. rb_fd_init(arg->fds_w);
  1416. rb_fd_init(arg->fds_e);
  1417. #ifdef HAVE_RB_FD_INIT
  1418. arg->fd = fd;
  1419. return (int)rb_ensure(try_wait_connectable, (VALUE)arg,
  1420. wait_connectable_ensure,(VALUE)arg);
  1421. #else
  1422. return wait_connectable0(fd, arg->fds_w, arg->fds_e);
  1423. #endif
  1424. }
  1425. #ifdef __CYGWIN__
  1426. #define WAIT_IN_PROGRESS 10
  1427. #endif
  1428. #ifdef __APPLE__
  1429. #define WAIT_IN_PROGRESS 10
  1430. #endif
  1431. #ifdef __linux__
  1432. /* returns correct error */
  1433. #define WAIT_IN_PROGRESS 0
  1434. #endif
  1435. #ifndef WAIT_IN_PROGRESS
  1436. /* BSD origin code apparently has a problem */
  1437. #define WAIT_IN_PROGRESS 1
  1438. #endif
  1439. static int
  1440. ruby_connect(int fd, struct sockaddr *sockaddr, int len, int socks)
  1441. {
  1442. int status;
  1443. #if WAIT_IN_PROGRESS > 0
  1444. int wait_in_progress = -1;
  1445. int sockerr;
  1446. socklen_t sockerrlen;
  1447. #endif
  1448. for (;;) {
  1449. status = connect(fd, sockaddr, len);
  1450. if (status < 0) {
  1451. switch (errno) {
  1452. case EINTR:
  1453. #if defined(ERESTART)
  1454. case ERESTART:
  1455. #endif
  1456. continue;
  1457. case EAGAIN:
  1458. #ifdef EINPROGRESS
  1459. case EINPROGRESS:
  1460. #endif
  1461. #if WAIT_IN_PROGRESS > 0
  1462. sockerrlen = (socklen_t)sizeof(sockerr);
  1463. status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen);
  1464. if (status) break;
  1465. if (sockerr) {
  1466. status = -1;
  1467. errno = sockerr;
  1468. break;
  1469. }
  1470. #endif
  1471. #ifdef EALREADY
  1472. case EALREADY:
  1473. #endif
  1474. #if WAIT_IN_PROGRESS > 0
  1475. wait_in_progress = WAIT_IN_PROGRESS;
  1476. #endif
  1477. status = wait_connectable(fd);
  1478. if (status) {
  1479. break;
  1480. }
  1481. errno = 0;
  1482. continue;
  1483. #if WAIT_IN_PROGRESS > 0
  1484. case EINVAL:
  1485. if (wait_in_progress-- > 0) {
  1486. /*
  1487. * connect() after EINPROGRESS returns EINVAL on
  1488. * some platforms, need to check true error
  1489. * status.
  1490. */
  1491. sockerrlen = (socklen_t)sizeof(sockerr);
  1492. status = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &sockerrlen);
  1493. if (!status && !sockerr) {
  1494. struct timeval tv = {0, 100000};
  1495. rb_thread_wait_for(tv);
  1496. continue;
  1497. }
  1498. status = -1;
  1499. errno = sockerr;
  1500. }
  1501. break;
  1502. #endif
  1503. #ifdef EISCONN
  1504. case EISCONN:
  1505. status = 0;
  1506. errno = 0;
  1507. break;
  1508. #endif
  1509. default:
  1510. break;
  1511. }
  1512. }
  1513. return status;
  1514. }
  1515. }
  1516. struct inetsock_arg
  1517. {
  1518. VALUE sock;
  1519. struct {
  1520. VALUE host, serv;
  1521. struct addrinfo *res;
  1522. } remote, local;
  1523. int type;
  1524. int fd;
  1525. };
  1526. static VALUE
  1527. inetsock_cleanup(struct inetsock_arg *arg)
  1528. {
  1529. if (arg->remote.res) {
  1530. freeaddrinfo(arg->remote.res);
  1531. arg->remote.res = 0;
  1532. }
  1533. if (arg->local.res) {
  1534. freeaddrinfo(arg->local.res);
  1535. arg->local.res = 0;
  1536. }
  1537. if (arg->fd >= 0) {
  1538. close(arg->fd);
  1539. }
  1540. return Qnil;
  1541. }
  1542. static VALUE
  1543. init_inetsock_internal(struct inetsock_arg *arg)
  1544. {
  1545. int type = arg->type;
  1546. struct addrinfo *res;
  1547. int fd, status = 0;
  1548. char *syscall = NULL;
  1549. arg->remote.res = sock_addrinfo(arg->remote.host, arg->remote.serv, SOCK_STREAM,
  1550. (type == INET_SERVER) ? AI_PASSIVE : 0);
  1551. /*
  1552. * Maybe also accept a local address
  1553. */
  1554. if (type != INET_SERVER && (!NIL_P(arg->local.host) || !NIL_P(arg->local.serv))) {
  1555. arg->local.res = sock_addrinfo(arg->local.host, arg->local.serv, SOCK_STREAM, 0);
  1556. }
  1557. arg->fd = fd = -1;
  1558. for (res = arg->remote.res; res; res = res->ai_next) {
  1559. #if !defined(INET6) && defined(AF_INET6)
  1560. if (res->ai_family == AF_INET6)
  1561. continue;
  1562. #endif
  1563. status = ruby_socket(res->ai_family,res->ai_socktype,res->ai_protocol);
  1564. syscall = "socket(2)";
  1565. fd = status;
  1566. if (fd < 0) {
  1567. continue;
  1568. }
  1569. arg->fd = fd;
  1570. if (type == INET_SERVER) {
  1571. #if !defined(_WIN32) && !defined(__CYGWIN__)
  1572. status = 1;
  1573. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
  1574. (char*)&status, sizeof(status));
  1575. #endif
  1576. status = bind(fd, res->ai_addr, res->ai_addrlen);
  1577. syscall = "bind(2)";
  1578. }
  1579. else {
  1580. if (arg->local.res) {
  1581. status = bind(fd, arg->local.res->ai_addr, arg->local.res->ai_addrlen);
  1582. syscall = "bind(2)";
  1583. }
  1584. if (status >= 0) {
  1585. status = ruby_connect(fd, res->ai_addr, res->ai_addrlen,
  1586. (type == INET_SOCKS));
  1587. syscall = "connect(2)";
  1588. }
  1589. }
  1590. if (status < 0) {
  1591. close(fd);
  1592. arg->fd = fd = -1;
  1593. continue;
  1594. } else
  1595. break;
  1596. }
  1597. if (status < 0) {
  1598. rb_sys_fail(syscall);
  1599. }
  1600. arg->fd = -1;
  1601. if (type == INET_SERVER) {
  1602. status = listen(fd, 5);
  1603. if (status < 0) {
  1604. close(fd);
  1605. syscall = "listen(2)";
  1606. }
  1607. }
  1608. /* create new instance */
  1609. return init_sock(arg->sock, fd);
  1610. }
  1611. static VALUE
  1612. init_inetsock(VALUE sock, VALUE remote_host, VALUE remote_serv,
  1613. VALUE local_host, VALUE local_serv, int type)
  1614. {
  1615. struct inetsock_arg arg;
  1616. arg.sock = sock;
  1617. arg.remote.host = remote_host;
  1618. arg.remote.serv = remote_serv;
  1619. arg.remote.res = 0;
  1620. arg.local.host = local_host;
  1621. arg.local.serv = local_serv;
  1622. arg.local.res = 0;
  1623. arg.type = type;
  1624. arg.fd = -1;
  1625. return rb_ensure(init_inetsock_internal, (VALUE)&arg,
  1626. inetsock_cleanup, (VALUE)&arg);
  1627. }
  1628. /*
  1629. * call-seq:
  1630. * TCPSocket.new(remote_host, remote_port, local_host=nil, local_port=nil)
  1631. *
  1632. * Opens a TCP connection to +remote_host+ on +remote_port+. If +local_host+
  1633. * and +local_port+ are specified, then those parameters are used on the local
  1634. * end to establish the connection.
  1635. */
  1636. static VALUE
  1637. tcp_init(VALUE sock, SEL sel, int argc, VALUE *argv)
  1638. {
  1639. VALUE remote_host, remote_serv;
  1640. VALUE local_host, local_serv;
  1641. rb_scan_args(argc, argv, "22", &remote_host, &remote_serv,
  1642. &local_host, &local_serv);
  1643. return init_inetsock(sock, remote_host, remote_serv,
  1644. local_host, local_serv, INET_CLIENT);
  1645. }
  1646. struct hostent_arg {
  1647. VALUE host;
  1648. struct addrinfo* addr;
  1649. VALUE (*ipaddr)(struct sockaddr*, size_t);
  1650. };
  1651. static VALUE
  1652. make_hostent_internal(struct hostent_arg *arg)
  1653. {
  1654. VALUE host = arg->host;
  1655. struct addrinfo* addr = arg->addr;
  1656. VALUE (*ipaddr)(struct sockaddr*, size_t) = arg->ipaddr;
  1657. struct addrinfo *ai;
  1658. struct hostent *h;
  1659. VALUE ary, names;
  1660. char **pch;
  1661. const char* hostp;
  1662. char hbuf[NI_MAXHOST];
  1663. ary = rb_ary_new();
  1664. if (addr->ai_canonname) {
  1665. hostp = addr->ai_canonname;
  1666. }
  1667. else {
  1668. hostp = host_str(host, hbuf, sizeof(hbuf), NULL);
  1669. }
  1670. rb_ary_push(ary, rb_str_new2(hostp));
  1671. if (addr->ai_canonname && (h = gethostbyname(addr->ai_canonname))) {
  1672. names = rb_ary_new();
  1673. if (h->h_aliases != NULL) {
  1674. for (pch = h->h_aliases; *pch; pch++) {
  1675. rb_ary_push(names, rb_str_new2(*pch));
  1676. }
  1677. }
  1678. }
  1679. else {
  1680. names = rb_ary_new2(0);
  1681. }
  1682. rb_ary_push(ary, names);
  1683. rb_ary_push(ary, INT2NUM(addr->ai_family));
  1684. for (ai = addr; ai; ai = ai->ai_next) {
  1685. rb_ary_push(ary, (*ipaddr)(ai->ai_addr, ai->ai_addrlen));
  1686. }
  1687. return ary;
  1688. }
  1689. static VALUE
  1690. make_hostent(VALUE host, struct addrinfo *addr, VALUE (*ipaddr)(struct sockaddr *, size_t))
  1691. {
  1692. struct hostent_arg arg;
  1693. arg.host = host;
  1694. arg.addr = addr;
  1695. arg.ipaddr = ipaddr;
  1696. return rb_ensure(make_hostent_internal, (VALUE)&arg,
  1697. RUBY_METHOD_FUNC(freeaddrinfo), (VALUE)addr);
  1698. }
  1699. static VALUE
  1700. tcp_sockaddr(struct sockaddr *addr, size_t len)
  1701. {
  1702. return make_ipaddr(addr);
  1703. }
  1704. /*
  1705. * call-seq:
  1706. * TCPSocket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
  1707. *
  1708. * Lookups host information by _hostname_.
  1709. *
  1710. * TCPSocket.gethostbyname("localhost")
  1711. * #=> ["localhost", ["hal"], 2, "127.0.0.1"]
  1712. *
  1713. */
  1714. static VALUE
  1715. tcp_s_gethostbyname(VALUE obj, SEL sel, VALUE host)
  1716. {
  1717. rb_secure(3);
  1718. return make_hostent(host, sock_addrinfo(host, Qnil, SOCK_STREAM,
  1719. AI_CANONNAME), tcp_sockaddr);
  1720. }
  1721. /*
  1722. * call-seq:
  1723. * TCPServer.new([hostname,] port) => tcpserver
  1724. *
  1725. * Creates a new server socket bound to _port_.
  1726. *
  1727. * If _hostname_ is given, the socket is bound to it.
  1728. *
  1729. * serv = TCPServer.new("127.0.0.1", 28561)
  1730. * s = serv.accept
  1731. * s.puts Time.now
  1732. * s.close
  1733. */
  1734. static VALUE
  1735. tcp_svr_init(VALUE sock, SEL sel, int argc, VALUE *argv)
  1736. {
  1737. VALUE arg1, arg2;
  1738. if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2)
  1739. return init_inetsock(sock, arg1, arg2, Qnil, Qnil, INET_SERVER);
  1740. else
  1741. return init_inetsock(sock, Qnil, arg1, Qnil, Qnil, INET_SERVER);
  1742. }
  1743. static void
  1744. make_fd_nonblock(int fd)
  1745. {
  1746. int flags;
  1747. #ifdef F_GETFL
  1748. flags = fcntl(fd, F_GETFL);
  1749. if (flags == -1) {
  1750. rb_sys_fail(0);
  1751. }
  1752. #else
  1753. flags = 0;
  1754. #endif
  1755. flags |= O_NONBLOCK;
  1756. if (fcntl(fd, F_SETFL, flags) == -1) {
  1757. rb_sys_fail(0);
  1758. }
  1759. }
  1760. static VALUE
  1761. s_accept_nonblock(VALUE klass, rb_io_t *fptr, struct sockaddr *sockaddr, socklen_t *len)
  1762. {
  1763. int fd2;
  1764. rb_secure(3);
  1765. rb_io_set_nonblock(fptr);
  1766. fd2 = accept(fptr->fd, (struct sockaddr*)sockaddr, len);
  1767. if (fd2 < 0) {
  1768. switch (errno) {
  1769. case EAGAIN:
  1770. #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
  1771. case EWOULDBLOCK:
  1772. #endif
  1773. case ECONNABORTED:
  1774. #if defined EPROTO
  1775. case EPROTO:
  1776. #endif
  1777. rb_mod_sys_fail(rb_mWaitReadable, "accept(2) would block");
  1778. }
  1779. rb_sys_fail("accept(2)");
  1780. }
  1781. make_fd_nonblock(fd2);
  1782. return init_sock(rb_obj_alloc(klass), fd2);
  1783. }
  1784. static VALUE
  1785. s_accept(VALUE klass, int fd, struct sockaddr *sockaddr, socklen_t *len)
  1786. {
  1787. int fd2;
  1788. int retry = 0;
  1789. rb_secure(3);
  1790. retry:
  1791. rb_thread_wait_fd(fd);
  1792. #if defined(_nec_ews)
  1793. fd2 = accept(fd, sockaddr, len);
  1794. #else
  1795. fd2 = accept(fd, sockaddr, len);
  1796. #endif
  1797. if (fd2 < 0) {
  1798. switch (errno) {
  1799. case EMFILE:
  1800. case ENFILE:
  1801. if (retry) break;
  1802. rb_gc();
  1803. retry = 1;
  1804. goto retry;
  1805. default:
  1806. if (!rb_io_wait_readable(fd)) break;
  1807. retry = 0;
  1808. goto retry;
  1809. }
  1810. rb_sys_fail(0);
  1811. }
  1812. if (!klass) return INT2NUM(fd2);
  1813. return init_sock(rb_obj_alloc(klass), fd2);
  1814. }
  1815. /*
  1816. * call-seq:
  1817. * tcpserver.accept => tcpsocket
  1818. *
  1819. * TCPServer.open("127.0.0.1", 14641) {|serv|
  1820. * s = serv.accept
  1821. * s.puts Time.now
  1822. * s.close
  1823. * }
  1824. *
  1825. */
  1826. static VALUE
  1827. tcp_accept(VALUE sock, SEL sel)
  1828. {
  1829. rb_io_t *fptr;
  1830. struct sockaddr_storage from;
  1831. socklen_t fromlen;
  1832. GetOpenFile(sock, fptr);
  1833. fromlen = (socklen_t)sizeof(from);
  1834. return s_accept(rb_cTCPSocket, fptr->fd,
  1835. (struct sockaddr*)&from, &fromlen);
  1836. }
  1837. /*
  1838. * call-seq:
  1839. * tcpserver.accept_nonblock => tcpsocket
  1840. *
  1841. * Accepts an incoming connection using accept(2) after
  1842. * O_NONBLOCK is set for the underlying file descriptor.
  1843. * It returns an accepted TCPSocket for the incoming connection.
  1844. *
  1845. * === Example
  1846. * require 'socket'
  1847. * serv = TCPServer.new(2202)
  1848. * begin # emulate blocking accept
  1849. * sock = serv.accept_nonblock
  1850. * rescue IO::WaitReadable, Errno::EINTR
  1851. * IO.select([serv])
  1852. * retry
  1853. * end
  1854. * # sock is an accepted socket.
  1855. *
  1856. * Refer to Socket#accept for the exceptions that may be thrown if the call
  1857. * to TCPServer#accept_nonblock fails.
  1858. *
  1859. * TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure,
  1860. * including Errno::EWOULDBLOCK.
  1861. *
  1862. * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED, Errno::EPROTO,
  1863. * it is extended by IO::WaitReadable.
  1864. * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  1865. *
  1866. * === See
  1867. * * TCPServer#accept
  1868. * * Socket#accept
  1869. */
  1870. static VALUE
  1871. tcp_accept_nonblock(VALUE sock, SEL sel)
  1872. {
  1873. rb_io_t *fptr;
  1874. struct sockaddr_storage from;
  1875. socklen_t fromlen;
  1876. GetOpenFile(sock, fptr);
  1877. fromlen = (socklen_t)sizeof(from);
  1878. return s_accept_nonblock(rb_cTCPSocket, fptr,
  1879. (struct sockaddr *)&from, &fromlen);
  1880. }
  1881. /*
  1882. * call-seq:
  1883. * tcpserver.sysaccept => file_descriptor
  1884. *
  1885. * Returns a file descriptor of a accepted connection.
  1886. *
  1887. * TCPServer.open("127.0.0.1", 28561) {|serv|
  1888. * fd = serv.sysaccept
  1889. * s = IO.for_fd(fd)
  1890. * s.puts Time.now
  1891. * s.close
  1892. * }
  1893. *
  1894. */
  1895. static VALUE
  1896. tcp_sysaccept(VALUE sock, SEL sel)
  1897. {
  1898. rb_io_t *fptr;
  1899. struct sockaddr_storage from;
  1900. socklen_t fromlen;
  1901. GetOpenFile(sock, fptr);
  1902. fromlen = (socklen_t)sizeof(from);
  1903. return s_accept(0, fptr->fd, (struct sockaddr*)&from, &fromlen);
  1904. }
  1905. #ifdef HAVE_SYS_UN_H
  1906. struct unixsock_arg {
  1907. struct sockaddr_un *sockaddr;
  1908. int fd;
  1909. };
  1910. static VALUE
  1911. unixsock_connect_internal(struct unixsock_arg *arg)
  1912. {
  1913. return (VALUE)ruby_connect(arg->fd, (struct sockaddr*)arg->sockaddr,
  1914. (socklen_t)sizeof(*arg->sockaddr), 0);
  1915. }
  1916. static VALUE
  1917. init_unixsock(VALUE sock, VALUE path, int server)
  1918. {
  1919. struct sockaddr_un sockaddr;
  1920. int fd, status;
  1921. rb_io_t *fptr;
  1922. SafeStringValue(path);
  1923. fd = ruby_socket(AF_UNIX, SOCK_STREAM, 0);
  1924. if (fd < 0) {
  1925. rb_sys_fail("socket(2)");
  1926. }
  1927. MEMZERO(&sockaddr, struct sockaddr_un, 1);
  1928. sockaddr.sun_family = AF_UNIX;
  1929. if (sizeof(sockaddr.sun_path) <= (size_t)RSTRING_LEN(path)) {
  1930. rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)",
  1931. (int)sizeof(sockaddr.sun_path)-1);
  1932. }
  1933. memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
  1934. if (server) {
  1935. status = bind(fd, (struct sockaddr*)&sockaddr, (socklen_t)sizeof(sockaddr));
  1936. }
  1937. else {
  1938. int prot;
  1939. struct unixsock_arg arg;
  1940. arg.sockaddr = &sockaddr;
  1941. arg.fd = fd;
  1942. status = (int)rb_protect((VALUE(*)(VALUE))unixsock_connect_internal, (VALUE)&arg, &prot);
  1943. if (prot) {
  1944. close(fd);
  1945. rb_jump_tag(prot);
  1946. }
  1947. }
  1948. if (status < 0) {
  1949. close(fd);
  1950. rb_sys_fail(sockaddr.sun_path);
  1951. }
  1952. if (server) {
  1953. if (listen(fd, 5) < 0) {
  1954. close(fd);
  1955. rb_sys_fail("listen(2)");
  1956. }
  1957. }
  1958. init_sock(sock, fd);
  1959. if (server) {
  1960. GetOpenFile(sock, fptr);
  1961. GC_WB(&fptr->path, rb_str_dup(path));
  1962. }
  1963. return sock;
  1964. }
  1965. #endif
  1966. static ID id_numeric, id_hostname;
  1967. int
  1968. revlookup_flag(VALUE revlookup, int *norevlookup)
  1969. {
  1970. #define return_norevlookup(x) {*norevlookup = x; return 1;}
  1971. ID id;
  1972. switch (revlookup) {
  1973. case Qtrue: return_norevlookup(0);
  1974. case Qfalse: return_norevlookup(1);
  1975. case Qnil: break;
  1976. default:
  1977. Check_Type(revlookup, T_SYMBOL);
  1978. id = SYM2ID(revlookup);
  1979. if (id == id_numeric) return_norevlookup(1);
  1980. if (id == id_hostname) return_norevlookup(0);
  1981. rb_raise(rb_eArgError, "invalid reverse_lookup flag: :%s", rb_id2name(id));
  1982. }
  1983. return 0;
  1984. #undef return_norevlookup
  1985. }
  1986. /*
  1987. * call-seq:
  1988. * ipsocket.addr([reverse_lookup]) => [address_family, port, hostname, numeric_address]
  1989. *
  1990. * Returns the local address as an array which contains
  1991. * address_family, port, hostname and numeric_address.
  1992. *
  1993. * If +reverse_lookup+ is +true+ or +:hostname+,
  1994. * hostname is obtained from numeric_address using reverse lookup.
  1995. * Or if it is +false+, or +:numeric+,
  1996. * hostname is same as numeric_address.
  1997. * Or if it is +nil+ or ommitted, obeys to +ipsocket.do_not_reverse_lookup+.
  1998. * See +Socket.getaddrinfo+ also.
  1999. *
  2000. * TCPSocket.open("www.ruby-lang.org", 80) {|sock|
  2001. * p sock.addr #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
  2002. * p sock.addr(true) #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
  2003. * p sock.addr(false) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"]
  2004. * p sock.addr(:hostname) #=> ["AF_INET", 49429, "hal", "192.168.0.128"]
  2005. * p sock.addr(:numeric) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"]
  2006. * }
  2007. *
  2008. */
  2009. static VALUE
  2010. ip_addr(VALUE sock, SEL sel, int argc, VALUE *argv)
  2011. {
  2012. rb_io_t *fptr;
  2013. struct sockaddr_storage addr;
  2014. socklen_t len = (socklen_t)sizeof addr;
  2015. int norevlookup;
  2016. GetOpenFile(sock, fptr);
  2017. if (argc < 1 || !revlookup_flag(argv[0], &norevlookup))
  2018. norevlookup = fptr->mode & FMODE_NOREVLOOKUP;
  2019. if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
  2020. rb_sys_fail("getsockname(2)");
  2021. return ipaddr((struct sockaddr*)&addr, norevlookup);
  2022. }
  2023. /*
  2024. * call-seq:
  2025. * ipsocket.peeraddr([reverse_lookup]) => [address_family, port, hostname, numeric_address]
  2026. *
  2027. * Returns the remote address as an array which contains
  2028. * address_family, port, hostname and numeric_address.
  2029. * It is defined for connection oriented socket such as TCPSocket.
  2030. *
  2031. * If +reverse_lookup+ is +true+ or +:hostname+,
  2032. * hostname is obtained from numeric_address using reverse lookup.
  2033. * Or if it is +false+, or +:numeric+,
  2034. * hostname is same as numeric_address.
  2035. * Or if it is +nil+ or ommitted, obeys to +ipsocket.do_not_reverse_lookup+.
  2036. * See +Socket.getaddrinfo+ also.
  2037. *
  2038. * TCPSocket.open("www.ruby-lang.org", 80) {|sock|
  2039. * p sock.peeraddr #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
  2040. * p sock.peeraddr(true) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
  2041. * p sock.peeraddr(false) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
  2042. * p sock.peeraddr(:hostname) #=> ["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68"]
  2043. * p sock.peeraddr(:numeric) #=> ["AF_INET", 80, "221.186.184.68", "221.186.184.68"]
  2044. * }
  2045. *
  2046. */
  2047. static VALUE
  2048. ip_peeraddr(VALUE sock, SEL sel, int argc, VALUE *argv)
  2049. {
  2050. rb_io_t *fptr;
  2051. struct sockaddr_storage addr;
  2052. socklen_t len = (socklen_t)sizeof addr;
  2053. int norevlookup;
  2054. GetOpenFile(sock, fptr);
  2055. if (argc < 1 || !revlookup_flag(argv[0], &norevlookup))
  2056. norevlookup = fptr->mode & FMODE_NOREVLOOKUP;
  2057. if (getpeername(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
  2058. rb_sys_fail("getpeername(2)");
  2059. return ipaddr((struct sockaddr*)&addr, norevlookup);
  2060. }
  2061. /*
  2062. * call-seq:
  2063. * ipsocket.recvfrom(maxlen) => [mesg, ipaddr]
  2064. * ipsocket.recvfrom(maxlen, flags) => [mesg, ipaddr]
  2065. *
  2066. * Receives a message and return the message as a string and
  2067. * an address which the message come from.
  2068. *
  2069. * _maxlen_ is the maximum number of bytes to receive.
  2070. *
  2071. * _flags_ should be a bitwise OR of Socket::MSG_* constants.
  2072. *
  2073. * ipaddr is same as IPSocket#{peeraddr,addr}.
  2074. *
  2075. * u1 = UDPSocket.new
  2076. * u1.bind("127.0.0.1", 4913)
  2077. * u2 = UDPSocket.new
  2078. * u2.send "uuuu", 0, "127.0.0.1", 4913
  2079. * p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]]
  2080. *
  2081. */
  2082. static VALUE
  2083. ip_recvfrom(VALUE sock, SEL sel, int argc, VALUE *argv)
  2084. {
  2085. return s_recvfrom(sock, argc, argv, RECV_IP);
  2086. }
  2087. /*
  2088. * call-seq:
  2089. * IPSocket.getaddress(host) => ipaddress
  2090. *
  2091. * Lookups the IP address of _host_.
  2092. *
  2093. * IPSocket.getaddress("localhost") #=> "127.0.0.1"
  2094. * IPSocket.getaddress("ip6-localhost") #=> "::1"
  2095. *
  2096. */
  2097. static VALUE
  2098. ip_s_getaddress(VALUE obj, SEL sel, VALUE host)
  2099. {
  2100. struct sockaddr_storage addr;
  2101. struct addrinfo *res = sock_addrinfo(host, Qnil, SOCK_STREAM, 0);
  2102. /* just take the first one */
  2103. memcpy(&addr, res->ai_addr, res->ai_addrlen);
  2104. freeaddrinfo(res);
  2105. return make_ipaddr((struct sockaddr*)&addr);
  2106. }
  2107. /*
  2108. * call-seq:
  2109. * UDPSocket.new([address_family]) => socket
  2110. *
  2111. * Creates a new UDPSocket object.
  2112. *
  2113. * _address_family_ should be an integer, a string or a symbol:
  2114. * Socket::AF_INET, "AF_INET", :INET, etc.
  2115. *
  2116. * UDPSocket.new #=> #<UDPSocket:fd 3>
  2117. * UDPSocket.new(Socket::AF_INET6) #=> #<UDPSocket:fd 4>
  2118. *
  2119. */
  2120. static VALUE
  2121. udp_init(VALUE sock, SEL sel, int argc, VALUE *argv)
  2122. {
  2123. VALUE arg;
  2124. int family = AF_INET;
  2125. int fd;
  2126. rb_secure(3);
  2127. if (rb_scan_args(argc, argv, "01", &arg) == 1) {
  2128. family = family_arg(arg);
  2129. }
  2130. fd = ruby_socket(family, SOCK_DGRAM, 0);
  2131. if (fd < 0) {
  2132. rb_sys_fail("socket(2) - udp");
  2133. }
  2134. return init_sock(sock, fd);
  2135. }
  2136. struct udp_arg
  2137. {
  2138. struct addrinfo *res;
  2139. int fd;
  2140. };
  2141. static VALUE
  2142. udp_connect_internal(struct udp_arg *arg)
  2143. {
  2144. int fd = arg->fd;
  2145. struct addrinfo *res;
  2146. for (res = arg->res; res; res = res->ai_next) {
  2147. if (ruby_connect(fd, res->ai_addr, res->ai_addrlen, 0) >= 0) {
  2148. return Qtrue;
  2149. }
  2150. }
  2151. return Qfalse;
  2152. }
  2153. /*
  2154. * call-seq:
  2155. * udpsocket.connect(host, port) => 0
  2156. *
  2157. * Connects _udpsocket_ to _host_:_port_.
  2158. *
  2159. * This makes possible to send without destination address.
  2160. *
  2161. * u1 = UDPSocket.new
  2162. * u1.bind("127.0.0.1", 4913)
  2163. * u2 = UDPSocket.new
  2164. * u2.connect("127.0.0.1", 4913)
  2165. * u2.send "uuuu", 0
  2166. * p u1.recvfrom(10) #=> ["uuuu", ["AF_INET", 33230, "localhost", "127.0.0.1"]]
  2167. *
  2168. */
  2169. static VALUE
  2170. udp_connect(VALUE sock, SEL sel, VALUE host, VALUE port)
  2171. {
  2172. rb_io_t *fptr;
  2173. struct udp_arg arg;
  2174. VALUE ret;
  2175. rb_secure(3);
  2176. arg.res = sock_addrinfo(host, port, SOCK_DGRAM, 0);
  2177. GetOpenFile(sock, fptr);
  2178. arg.fd = fptr->fd;
  2179. ret = rb_ensure(udp_connect_internal, (VALUE)&arg,
  2180. RUBY_METHOD_FUNC(freeaddrinfo), (VALUE)arg.res);
  2181. if (!ret) rb_sys_fail("connect(2)");
  2182. return INT2FIX(0);
  2183. }
  2184. /*
  2185. * call-seq:
  2186. * udpsocket.bind(host, port) #=> 0
  2187. *
  2188. * Binds _udpsocket_ to _host_:_port_.
  2189. *
  2190. * u1 = UDPSocket.new
  2191. * u1.bind("127.0.0.1", 4913)
  2192. * u1.send "message-to-self", 0, "127.0.0.1", 4913
  2193. * p u1.recvfrom(10) #=> ["message-to", ["AF_INET", 4913, "localhost", "127.0.0.1"]]
  2194. *
  2195. */
  2196. static VALUE
  2197. udp_bind(VALUE sock, SEL sel, VALUE host, VALUE port)
  2198. {
  2199. rb_io_t *fptr;
  2200. struct addrinfo *res0, *res;
  2201. rb_secure(3);
  2202. res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
  2203. GetOpenFile(sock, fptr);
  2204. for (res = res0; res; res = res->ai_next) {
  2205. if (bind(fptr->fd, res->ai_addr, res->ai_addrlen) < 0) {
  2206. continue;
  2207. }
  2208. freeaddrinfo(res0);
  2209. return INT2FIX(0);
  2210. }
  2211. freeaddrinfo(res0);
  2212. rb_sys_fail("bind(2)");
  2213. return INT2FIX(0);
  2214. }
  2215. /*
  2216. * call-seq:
  2217. * udpsocket.send(mesg, flags, host, port) => numbytes_sent
  2218. * udpsocket.send(mesg, flags, sockaddr_to) => numbytes_sent
  2219. * udpsocket.send(mesg, flags) => numbytes_sent
  2220. *
  2221. * Sends _mesg_ via _udpsocket_.
  2222. *
  2223. * _flags_ should be a bitwise OR of Socket::MSG_* constants.
  2224. *
  2225. * u1 = UDPSocket.new
  2226. * u1.bind("127.0.0.1", 4913)
  2227. *
  2228. * u2 = UDPSocket.new
  2229. * u2.send "hi", 0, "127.0.0.1", 4913
  2230. *
  2231. * mesg, addr = u1.recvfrom(10)
  2232. * u1.send mesg, 0, addr[3], addr[1]
  2233. *
  2234. * p u2.recv(100) #=> "hi"
  2235. *
  2236. */
  2237. static VALUE
  2238. udp_send(VALUE sock, SEL sel, int argc, VALUE *argv)
  2239. {
  2240. VALUE mesg, flags, host, port;
  2241. rb_io_t *fptr;
  2242. int n;
  2243. struct addrinfo *res0, *res;
  2244. if (argc == 2 || argc == 3) {
  2245. return bsock_send(sock, 0, argc, argv);
  2246. }
  2247. rb_secure(4);
  2248. rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port);
  2249. StringValue(mesg);
  2250. res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
  2251. GetOpenFile(sock, fptr);
  2252. for (res = res0; res; res = res->ai_next) {
  2253. retry:
  2254. rb_thread_fd_writable(fptr->fd);
  2255. n = sendto(fptr->fd, RSTRING_PTR(mesg), RSTRING_LEN(mesg), NUM2INT(flags),
  2256. res->ai_addr, res->ai_addrlen);
  2257. if (n >= 0) {
  2258. freeaddrinfo(res0);
  2259. return INT2FIX(n);
  2260. }
  2261. if (rb_io_wait_writable(fptr->fd)) {
  2262. goto retry;
  2263. }
  2264. }
  2265. freeaddrinfo(res0);
  2266. rb_sys_fail("sendto(2)");
  2267. return INT2FIX(n);
  2268. }
  2269. /*
  2270. * call-seq:
  2271. * udpsocket.recvfrom_nonblock(maxlen) => [mesg, sender_inet_addr]
  2272. * udpsocket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_inet_addr]
  2273. *
  2274. * Receives up to _maxlen_ bytes from +udpsocket+ using recvfrom(2) after
  2275. * O_NONBLOCK is set for the underlying file descriptor.
  2276. * If _maxlen_ is omitted, its default value is 65536.
  2277. * _flags_ is zero or more of the +MSG_+ options.
  2278. * The first element of the results, _mesg_, is the data received.
  2279. * The second element, _sender_inet_addr_, is an array to represent the sender address.
  2280. *
  2281. * When recvfrom(2) returns 0,
  2282. * Socket#recvfrom_nonblock returns an empty string as data.
  2283. * It means an empty packet.
  2284. *
  2285. * === Parameters
  2286. * * +maxlen+ - the number of bytes to receive from the socket
  2287. * * +flags+ - zero or more of the +MSG_+ options
  2288. *
  2289. * === Example
  2290. * require 'socket'
  2291. * s1 = UDPSocket.new
  2292. * s1.bind("127.0.0.1", 0)
  2293. * s2 = UDPSocket.new
  2294. * s2.bind("127.0.0.1", 0)
  2295. * s2.connect(*s1.addr.values_at(3,1))
  2296. * s1.connect(*s2.addr.values_at(3,1))
  2297. * s1.send "aaa", 0
  2298. * begin # emulate blocking recvfrom
  2299. * p s2.recvfrom_nonblock(10) #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]]
  2300. * rescue IO::WaitReadable
  2301. * IO.select([s2])
  2302. * retry
  2303. * end
  2304. *
  2305. * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  2306. * to _recvfrom_nonblock_ fails.
  2307. *
  2308. * UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
  2309. * including Errno::EWOULDBLOCK.
  2310. *
  2311. * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
  2312. * it is extended by IO::WaitReadable.
  2313. * So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock.
  2314. *
  2315. * === See
  2316. * * Socket#recvfrom
  2317. */
  2318. static VALUE
  2319. udp_recvfrom_nonblock(VALUE sock, SEL sel, int argc, VALUE *argv)
  2320. {
  2321. return s_recvfrom_nonblock(sock, argc, argv, RECV_IP);
  2322. }
  2323. #ifdef HAVE_SYS_UN_H
  2324. /*
  2325. * call-seq:
  2326. * UNIXSocket.new(path) => unixsocket
  2327. *
  2328. * Creates a new UNIX client socket connected to _path_.
  2329. *
  2330. * s = UNIXSocket.new("/tmp/sock")
  2331. * s.send "hello", 0
  2332. *
  2333. */
  2334. static VALUE
  2335. unix_init(VALUE sock, SEL sel, VALUE path)
  2336. {
  2337. return init_unixsock(sock, path, 0);
  2338. }
  2339. static char*
  2340. unixpath(struct sockaddr_un *sockaddr, socklen_t len)
  2341. {
  2342. if (sockaddr->sun_path < (char*)sockaddr + len)
  2343. return sockaddr->sun_path;
  2344. else
  2345. return "";
  2346. }
  2347. /*
  2348. * call-seq:
  2349. * unixsocket.path => path
  2350. *
  2351. * Returns the path of the local address of unixsocket.
  2352. *
  2353. * s = UNIXServer.new("/tmp/sock")
  2354. * p s.path #=> "/tmp/sock"
  2355. *
  2356. */
  2357. static VALUE
  2358. unix_path(VALUE sock, SEL sel)
  2359. {
  2360. rb_io_t *fptr;
  2361. GetOpenFile(sock, fptr);
  2362. if (fptr->path == 0) {
  2363. struct sockaddr_un addr;
  2364. socklen_t len = (socklen_t)sizeof(addr);
  2365. if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0) {
  2366. rb_sys_fail(0);
  2367. }
  2368. GC_WB(&fptr->path, rb_str_new2(unixpath(&addr, len)));
  2369. }
  2370. return rb_str_dup(fptr->path);
  2371. }
  2372. /*
  2373. * call-seq:
  2374. * UNIXServer.new(path) => unixserver
  2375. *
  2376. * Creates a new UNIX server socket bound to _path_.
  2377. *
  2378. * serv = UNIXServer.new("/tmp/sock")
  2379. * s = serv.accept
  2380. * p s.read
  2381. */
  2382. static VALUE
  2383. unix_svr_init(VALUE sock, SEL sel, VALUE path)
  2384. {
  2385. return init_unixsock(sock, path, 1);
  2386. }
  2387. /*
  2388. * call-seq:
  2389. * unixsocket.recvfrom(maxlen [, flags]) => [mesg, unixaddress]
  2390. *
  2391. * Receives a message via _unixsocket_.
  2392. *
  2393. * _maxlen_ is the maximum number of bytes to receive.
  2394. *
  2395. * _flags_ should be a bitwise OR of Socket::MSG_* constants.
  2396. *
  2397. * s1 = Socket.new(:UNIX, :DGRAM, 0)
  2398. * s1_ai = Addrinfo.unix("/tmp/sock1")
  2399. * s1.bind(s1_ai)
  2400. *
  2401. * s2 = Socket.new(:UNIX, :DGRAM, 0)
  2402. * s2_ai = Addrinfo.unix("/tmp/sock2")
  2403. * s2.bind(s2_ai)
  2404. * s3 = UNIXSocket.for_fd(s2.fileno)
  2405. *
  2406. * s1.send "a", 0, s2_ai
  2407. * p s3.recvfrom(10) #=> ["a", ["AF_UNIX", "/tmp/sock1"]]
  2408. *
  2409. */
  2410. static VALUE
  2411. unix_recvfrom(VALUE sock, SEL sel, int argc, VALUE *argv)
  2412. {
  2413. return s_recvfrom(sock, argc, argv, RECV_UNIX);
  2414. }
  2415. #if defined(HAVE_ST_MSG_CONTROL) && defined(SCM_RIGHTS)
  2416. #define FD_PASSING_BY_MSG_CONTROL 1
  2417. #else
  2418. #define FD_PASSING_BY_MSG_CONTROL 0
  2419. #endif
  2420. #if defined(HAVE_ST_MSG_ACCRIGHTS)
  2421. #define FD_PASSING_BY_MSG_ACCRIGHTS 1
  2422. #else
  2423. #define FD_PASSING_BY_MSG_ACCRIGHTS 0
  2424. #endif
  2425. /*
  2426. * call-seq:
  2427. * unixsocket.send_io(io) => nil
  2428. *
  2429. * Sends _io_ as file descriptor passing.
  2430. *
  2431. * s1, s2 = UNIXSocket.pair
  2432. *
  2433. * s1.send_io STDOUT
  2434. * stdout = s2.recv_io
  2435. *
  2436. * p STDOUT.fileno #=> 1
  2437. * p stdout.fileno #=> 6
  2438. *
  2439. * stdout.puts "hello" # outputs "hello\n" to standard output.
  2440. */
  2441. static VALUE
  2442. unix_send_io(VALUE sock, SEL sel, VALUE val)
  2443. {
  2444. #if defined(HAVE_SENDMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS)
  2445. int fd;
  2446. rb_io_t *fptr;
  2447. struct msghdr msg;
  2448. struct iovec vec[1];
  2449. char buf[1];
  2450. #if FD_PASSING_BY_MSG_CONTROL
  2451. struct {
  2452. struct cmsghdr hdr;
  2453. char pad[8+sizeof(int)+8];
  2454. } cmsg;
  2455. #endif
  2456. if (rb_obj_is_kind_of(val, rb_cIO)) {
  2457. rb_io_t *valfptr;
  2458. GetOpenFile(val, valfptr);
  2459. fd = valfptr->fd;
  2460. }
  2461. else if (FIXNUM_P(val)) {
  2462. fd = FIX2INT(val);
  2463. }
  2464. else {
  2465. rb_raise(rb_eTypeError, "neither IO nor file descriptor");
  2466. }
  2467. GetOpenFile(sock, fptr);
  2468. msg.msg_name = NULL;
  2469. msg.msg_namelen = 0;
  2470. /* Linux and Solaris doesn't work if msg_iov is NULL. */
  2471. buf[0] = '\0';
  2472. vec[0].iov_base = buf;
  2473. vec[0].iov_len = 1;
  2474. msg.msg_iov = vec;
  2475. msg.msg_iovlen = 1;
  2476. #if FD_PASSING_BY_MSG_CONTROL
  2477. msg.msg_control = (caddr_t)&cmsg;
  2478. msg.msg_controllen = (socklen_t)CMSG_LEN(sizeof(int));
  2479. msg.msg_flags = 0;
  2480. MEMZERO((char*)&cmsg, char, sizeof(cmsg));
  2481. cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int));
  2482. cmsg.hdr.cmsg_level = SOL_SOCKET;
  2483. cmsg.hdr.cmsg_type = SCM_RIGHTS;
  2484. *(int *)CMSG_DATA(&cmsg.hdr) = fd;
  2485. #else
  2486. msg.msg_accrights = (caddr_t)&fd;
  2487. msg.msg_accrightslen = sizeof(fd);
  2488. #endif
  2489. while (sendmsg(fptr->fd, &msg, 0) == -1) {
  2490. if (!rb_io_wait_readable(fptr->fd)) {
  2491. rb_sys_fail("sendmsg(2)");
  2492. }
  2493. }
  2494. return Qnil;
  2495. #else
  2496. rb_notimplement();
  2497. return Qnil; /* not reached */
  2498. #endif
  2499. }
  2500. /*
  2501. * call-seq:
  2502. * unixsocket.recv_io([klass [, mode]]) => io
  2503. *
  2504. * UNIXServer.open("/tmp/sock") {|serv|
  2505. * UNIXSocket.open("/tmp/sock") {|c|
  2506. * s = serv.accept
  2507. *
  2508. * c.send_io STDOUT
  2509. * stdout = s.recv_io
  2510. *
  2511. * p STDOUT.fileno #=> 1
  2512. * p stdout.fileno #=> 7
  2513. *
  2514. * stdout.puts "hello" # outputs "hello\n" to standard output.
  2515. * }
  2516. * }
  2517. *
  2518. */
  2519. static VALUE
  2520. unix_recv_io(VALUE sock, SEL sel, int argc, VALUE *argv)
  2521. {
  2522. #if defined(HAVE_RECVMSG) && (FD_PASSING_BY_MSG_CONTROL || FD_PASSING_BY_MSG_ACCRIGHTS)
  2523. VALUE klass, mode;
  2524. rb_io_t *fptr;
  2525. struct msghdr msg;
  2526. struct iovec vec[2];
  2527. char buf[1];
  2528. int fd;
  2529. #if FD_PASSING_BY_MSG_CONTROL
  2530. struct {
  2531. struct cmsghdr hdr;
  2532. char pad[8+sizeof(int)+8];
  2533. } cmsg;
  2534. #endif
  2535. rb_scan_args(argc, argv, "02", &klass, &mode);
  2536. if (argc == 0)
  2537. klass = rb_cIO;
  2538. if (argc <= 1)
  2539. mode = Qnil;
  2540. GetOpenFile(sock, fptr);
  2541. rb_io_wait_readable(fptr->fd);
  2542. msg.msg_name = NULL;
  2543. msg.msg_namelen = 0;
  2544. vec[0].iov_base = buf;
  2545. vec[0].iov_len = sizeof(buf);
  2546. msg.msg_iov = vec;
  2547. msg.msg_iovlen = 1;
  2548. #if FD_PASSING_BY_MSG_CONTROL
  2549. msg.msg_control = (caddr_t)&cmsg;
  2550. msg.msg_controllen = (socklen_t)CMSG_SPACE(sizeof(int));
  2551. msg.msg_flags = 0;
  2552. cmsg.hdr.cmsg_len = (socklen_t)CMSG_LEN(sizeof(int));
  2553. cmsg.hdr.cmsg_level = SOL_SOCKET;
  2554. cmsg.hdr.cmsg_type = SCM_RIGHTS;
  2555. *(int *)CMSG_DATA(&cmsg.hdr) = -1;
  2556. #else
  2557. msg.msg_accrights = (caddr_t)&fd;
  2558. msg.msg_accrightslen = sizeof(fd);
  2559. fd = -1;
  2560. #endif
  2561. while (recvmsg(fptr->fd, &msg, 0) == -1) {
  2562. if (!rb_io_wait_readable(fptr->fd)) {
  2563. rb_sys_fail("recvmsg(2)");
  2564. }
  2565. }
  2566. #if FD_PASSING_BY_MSG_CONTROL
  2567. if (msg.msg_controllen != CMSG_SPACE(sizeof(int))) {
  2568. rb_raise(rb_eSocket,
  2569. "file descriptor was not passed (msg_controllen=%d, %ld expected)",
  2570. msg.msg_controllen, CMSG_SPACE(sizeof(int)));
  2571. }
  2572. if (cmsg.hdr.cmsg_len != CMSG_LEN(sizeof(int))) {
  2573. rb_raise(rb_eSocket,
  2574. "file descriptor was not passed (cmsg_len=%d, %ld expected)",
  2575. cmsg.hdr.cmsg_len, CMSG_LEN(sizeof(int)));
  2576. }
  2577. if (cmsg.hdr.cmsg_level != SOL_SOCKET) {
  2578. rb_raise(rb_eSocket,
  2579. "file descriptor was not passed (cmsg_level=%d, %d expected)",
  2580. cmsg.hdr.cmsg_level, SOL_SOCKET);
  2581. }
  2582. if (cmsg.hdr.cmsg_type != SCM_RIGHTS) {
  2583. rb_raise(rb_eSocket,
  2584. "file descriptor was not passed (cmsg_type=%d, %d expected)",
  2585. cmsg.hdr.cmsg_type, SCM_RIGHTS);
  2586. }
  2587. #else
  2588. if (msg.msg_accrightslen != sizeof(fd)) {
  2589. rb_raise(rb_eSocket,
  2590. "file descriptor was not passed (accrightslen) : %d != %ld",
  2591. msg.msg_accrightslen, sizeof(fd));
  2592. }
  2593. #endif
  2594. #if FD_PASSING_BY_MSG_CONTROL
  2595. fd = *(int *)CMSG_DATA(&cmsg.hdr);
  2596. #endif
  2597. if (klass == Qnil)
  2598. return INT2FIX(fd);
  2599. else {
  2600. static ID for_fd = 0;
  2601. int ff_argc;
  2602. VALUE ff_argv[2];
  2603. if (!for_fd)
  2604. for_fd = rb_intern("for_fd");
  2605. ff_argc = mode == Qnil ? 1 : 2;
  2606. ff_argv[0] = INT2FIX(fd);
  2607. ff_argv[1] = mode;
  2608. return rb_funcall2(klass, for_fd, ff_argc, ff_argv);
  2609. }
  2610. #else
  2611. rb_notimplement();
  2612. return Qnil; /* not reached */
  2613. #endif
  2614. }
  2615. /*
  2616. * call-seq:
  2617. * unixserver.accept => unixsocket
  2618. *
  2619. * Accepts a new connection.
  2620. * It returns new UNIXSocket object.
  2621. *
  2622. * UNIXServer.open("/tmp/sock") {|serv|
  2623. * UNIXSocket.open("/tmp/sock") {|c|
  2624. * s = serv.accept
  2625. * s.puts "hi"
  2626. * s.close
  2627. * p c.read #=> "hi\n"
  2628. * }
  2629. * }
  2630. *
  2631. */
  2632. static VALUE
  2633. unix_accept(VALUE sock, SEL sel)
  2634. {
  2635. rb_io_t *fptr;
  2636. struct sockaddr_un from;
  2637. socklen_t fromlen;
  2638. GetOpenFile(sock, fptr);
  2639. fromlen = (socklen_t)sizeof(struct sockaddr_un);
  2640. return s_accept(rb_cUNIXSocket, fptr->fd,
  2641. (struct sockaddr*)&from, &fromlen);
  2642. }
  2643. /*
  2644. * call-seq:
  2645. * unixserver.accept_nonblock => unixsocket
  2646. *
  2647. * Accepts an incoming connection using accept(2) after
  2648. * O_NONBLOCK is set for the underlying file descriptor.
  2649. * It returns an accepted UNIXSocket for the incoming connection.
  2650. *
  2651. * === Example
  2652. * require 'socket'
  2653. * serv = UNIXServer.new("/tmp/sock")
  2654. * begin # emulate blocking accept
  2655. * sock = serv.accept_nonblock
  2656. * rescue IO::WaitReadable, Errno::EINTR
  2657. * IO.select([serv])
  2658. * retry
  2659. * end
  2660. * # sock is an accepted socket.
  2661. *
  2662. * Refer to Socket#accept for the exceptions that may be thrown if the call
  2663. * to UNIXServer#accept_nonblock fails.
  2664. *
  2665. * UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure,
  2666. * including Errno::EWOULDBLOCK.
  2667. *
  2668. * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED or Errno::EPROTO,
  2669. * it is extended by IO::WaitReadable.
  2670. * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  2671. *
  2672. * === See
  2673. * * UNIXServer#accept
  2674. * * Socket#accept
  2675. */
  2676. static VALUE
  2677. unix_accept_nonblock(VALUE sock, SEL sel)
  2678. {
  2679. rb_io_t *fptr;
  2680. struct sockaddr_un from;
  2681. socklen_t fromlen;
  2682. GetOpenFile(sock, fptr);
  2683. fromlen = (socklen_t)sizeof(from);
  2684. return s_accept_nonblock(rb_cUNIXSocket, fptr,
  2685. (struct sockaddr *)&from, &fromlen);
  2686. }
  2687. /*
  2688. * call-seq:
  2689. * unixserver.sysaccept => file_descriptor
  2690. *
  2691. * Accepts a new connection.
  2692. * It returns the new file descriptor which is an integer.
  2693. *
  2694. * UNIXServer.open("/tmp/sock") {|serv|
  2695. * UNIXSocket.open("/tmp/sock") {|c|
  2696. * fd = serv.sysaccept
  2697. * s = IO.new(fd)
  2698. * s.puts "hi"
  2699. * s.close
  2700. * p c.read #=> "hi\n"
  2701. * }
  2702. * }
  2703. *
  2704. */
  2705. static VALUE
  2706. unix_sysaccept(VALUE sock, SEL sel)
  2707. {
  2708. rb_io_t *fptr;
  2709. struct sockaddr_un from;
  2710. socklen_t fromlen;
  2711. GetOpenFile(sock, fptr);
  2712. fromlen = (socklen_t)sizeof(struct sockaddr_un);
  2713. return s_accept(0, fptr->fd, (struct sockaddr*)&from, &fromlen);
  2714. }
  2715. #ifdef HAVE_SYS_UN_H
  2716. static VALUE
  2717. unixaddr(struct sockaddr_un *sockaddr, socklen_t len)
  2718. {
  2719. return rb_assoc_new(rb_str_new2("AF_UNIX"),
  2720. rb_str_new2(unixpath(sockaddr, len)));
  2721. }
  2722. #endif
  2723. /*
  2724. * call-seq:
  2725. * unixsocket.addr => [address_family, unix_path]
  2726. *
  2727. * Returns the local address as an array which contains
  2728. * address_family and unix_path.
  2729. *
  2730. * Example
  2731. * serv = UNIXServer.new("/tmp/sock")
  2732. * p serv.addr #=> ["AF_UNIX", "/tmp/sock"]
  2733. */
  2734. static VALUE
  2735. unix_addr(VALUE sock, SEL sel)
  2736. {
  2737. rb_io_t *fptr;
  2738. struct sockaddr_un addr;
  2739. socklen_t len = (socklen_t)sizeof addr;
  2740. GetOpenFile(sock, fptr);
  2741. if (getsockname(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
  2742. rb_sys_fail("getsockname(2)");
  2743. return unixaddr(&addr, len);
  2744. }
  2745. /*
  2746. * call-seq:
  2747. * unixsocket.peeraddr => [address_family, unix_path]
  2748. *
  2749. * Returns the remote address as an array which contains
  2750. * address_family and unix_path.
  2751. *
  2752. * Example
  2753. * serv = UNIXServer.new("/tmp/sock")
  2754. * c = UNIXSocket.new("/tmp/sock")
  2755. * p c.peeraddr #=> ["AF_UNIX", "/tmp/sock"]
  2756. */
  2757. static VALUE
  2758. unix_peeraddr(VALUE sock, SEL sel)
  2759. {
  2760. rb_io_t *fptr;
  2761. struct sockaddr_un addr;
  2762. socklen_t len = (socklen_t)sizeof addr;
  2763. GetOpenFile(sock, fptr);
  2764. if (getpeername(fptr->fd, (struct sockaddr*)&addr, &len) < 0)
  2765. rb_sys_fail("getpeername(2)");
  2766. return unixaddr(&addr, len);
  2767. }
  2768. #endif
  2769. static void
  2770. setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
  2771. {
  2772. *dv = family_arg(domain);
  2773. *tv = socktype_arg(type);
  2774. }
  2775. /*
  2776. * call-seq:
  2777. * Socket.new(domain, socktype [, protocol]) => socket
  2778. *
  2779. * Creates a new socket object.
  2780. *
  2781. * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
  2782. *
  2783. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  2784. *
  2785. * _protocol_ should be a protocol defined in the domain.
  2786. * This is optional.
  2787. * If it is not given, 0 is used internally.
  2788. *
  2789. * Socket.new(:INET, :STREAM) # TCP socket
  2790. * Socket.new(:INET, :DGRAM) # UDP socket
  2791. * Socket.new(:UNIX, :STREAM) # UNIX stream socket
  2792. * Socket.new(:UNIX, :DGRAM) # UNIX datagram socket
  2793. */
  2794. static VALUE
  2795. sock_initialize(VALUE sock, SEL sel, int argc, VALUE *argv)
  2796. {
  2797. VALUE domain, type, protocol;
  2798. int fd;
  2799. int d, t;
  2800. rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
  2801. if (NIL_P(protocol))
  2802. protocol = INT2FIX(0);
  2803. rb_secure(3);
  2804. setup_domain_and_type(domain, &d, type, &t);
  2805. fd = ruby_socket(d, t, NUM2INT(protocol));
  2806. if (fd < 0) rb_sys_fail("socket(2)");
  2807. return init_sock(sock, fd);
  2808. }
  2809. #if defined HAVE_SOCKETPAIR
  2810. static VALUE
  2811. io_call_close(VALUE io)
  2812. {
  2813. return rb_funcall(io, rb_intern("close"), 0, 0);
  2814. }
  2815. static VALUE
  2816. io_close(VALUE io)
  2817. {
  2818. return rb_rescue(io_call_close, io, 0, 0);
  2819. }
  2820. static VALUE
  2821. pair_yield(VALUE pair)
  2822. {
  2823. return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1));
  2824. }
  2825. #endif
  2826. /*
  2827. * call-seq:
  2828. * Socket.pair(domain, type, protocol) => [socket1, socket2]
  2829. * Socket.socketpair(domain, type, protocol) => [socket1, socket2]
  2830. *
  2831. * Creates a pair of sockets connected each other.
  2832. *
  2833. * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
  2834. *
  2835. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  2836. *
  2837. * _protocol_ should be a protocol defined in the domain.
  2838. * 0 is default protocol for the domain.
  2839. *
  2840. * s1, s2 = Socket.pair(:UNIX, :DGRAM, 0)
  2841. * s1.send "a", 0
  2842. * s1.send "b", 0
  2843. * p s2.recv(10) #=> "a"
  2844. * p s2.recv(10) #=> "b"
  2845. *
  2846. */
  2847. static VALUE
  2848. sock_s_socketpair(VALUE klass, SEL sel, int argc, VALUE *argv)
  2849. {
  2850. #if defined HAVE_SOCKETPAIR
  2851. VALUE domain, type, protocol;
  2852. int d, t, p, sp[2];
  2853. int ret;
  2854. VALUE s1, s2, r;
  2855. rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
  2856. if (NIL_P(protocol))
  2857. protocol = INT2FIX(0);
  2858. setup_domain_and_type(domain, &d, type, &t);
  2859. p = NUM2INT(protocol);
  2860. ret = socketpair(d, t, p, sp);
  2861. if (ret < 0 && (errno == EMFILE || errno == ENFILE)) {
  2862. rb_gc();
  2863. ret = socketpair(d, t, p, sp);
  2864. }
  2865. if (ret < 0) {
  2866. rb_sys_fail("socketpair(2)");
  2867. }
  2868. s1 = init_sock(rb_obj_alloc(klass), sp[0]);
  2869. s2 = init_sock(rb_obj_alloc(klass), sp[1]);
  2870. r = rb_assoc_new(s1, s2);
  2871. if (rb_block_given_p()) {
  2872. return rb_ensure(pair_yield, r, io_close, s1);
  2873. }
  2874. return r;
  2875. #else
  2876. rb_notimplement();
  2877. #endif
  2878. }
  2879. #ifdef HAVE_SYS_UN_H
  2880. /*
  2881. * call-seq:
  2882. * UNIXSocket.pair([type [, protocol]]) => [unixsocket1, unixsocket2]
  2883. * UNIXSocket.socketpair([type [, protocol]]) => [unixsocket1, unixsocket2]
  2884. *
  2885. * Creates a pair of sockets connected each other.
  2886. *
  2887. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  2888. *
  2889. * _protocol_ should be a protocol defined in the domain.
  2890. * 0 is default protocol for the domain.
  2891. *
  2892. * s1, s2 = UNIXSocket.pair
  2893. * s1.send "a", 0
  2894. * s1.send "b", 0
  2895. * p s2.recv(10) #=> "ab"
  2896. *
  2897. */
  2898. static VALUE
  2899. unix_s_socketpair(VALUE klass, SEL sel, int argc, VALUE *argv)
  2900. {
  2901. VALUE domain, type, protocol;
  2902. VALUE args[3];
  2903. domain = INT2FIX(PF_UNIX);
  2904. rb_scan_args(argc, argv, "02", &type, &protocol);
  2905. if (argc == 0)
  2906. type = INT2FIX(SOCK_STREAM);
  2907. if (argc <= 1)
  2908. protocol = INT2FIX(0);
  2909. args[0] = domain;
  2910. args[1] = type;
  2911. args[2] = protocol;
  2912. return sock_s_socketpair(klass, 0, 3, args);
  2913. }
  2914. #endif
  2915. /*
  2916. * call-seq:
  2917. * socket.connect(remote_sockaddr) => 0
  2918. *
  2919. * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if
  2920. * successful, otherwise an exception is raised.
  2921. *
  2922. * === Parameter
  2923. * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
  2924. *
  2925. * === Example:
  2926. * # Pull down Google's web page
  2927. * require 'socket'
  2928. * include Socket::Constants
  2929. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  2930. * sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
  2931. * socket.connect( sockaddr )
  2932. * socket.write( "GET / HTTP/1.0\r\n\r\n" )
  2933. * results = socket.read
  2934. *
  2935. * === Unix-based Exceptions
  2936. * On unix-based systems the following system exceptions may be raised if
  2937. * the call to _connect_ fails:
  2938. * * Errno::EACCES - search permission is denied for a component of the prefix
  2939. * path or write access to the +socket+ is denied
  2940. * * Errno::EADDRINUSE - the _sockaddr_ is already in use
  2941. * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
  2942. * local machine
  2943. * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
  2944. * the address family of the specified +socket+
  2945. * * Errno::EALREADY - a connection is already in progress for the specified
  2946. * socket
  2947. * * Errno::EBADF - the +socket+ is not a valid file descriptor
  2948. * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
  2949. * refused the connection request
  2950. * * Errno::ECONNRESET - the remote host reset the connection request
  2951. * * Errno::EFAULT - the _sockaddr_ cannot be accessed
  2952. * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
  2953. * because the host is down or a remote router cannot reach it)
  2954. * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
  2955. * connection cannot be immediately established; the connection will be
  2956. * established asynchronously
  2957. * * Errno::EINTR - the attempt to establish the connection was interrupted by
  2958. * delivery of a signal that was caught; the connection will be established
  2959. * asynchronously
  2960. * * Errno::EISCONN - the specified +socket+ is already connected
  2961. * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
  2962. * length for the address family or there is an invalid family in _sockaddr_
  2963. * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
  2964. * PATH_MAX
  2965. * * Errno::ENETDOWN - the local interface used to reach the destination is down
  2966. * * Errno::ENETUNREACH - no route to the network is present
  2967. * * Errno::ENOBUFS - no buffer space is available
  2968. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  2969. * complete the operation
  2970. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  2971. * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
  2972. * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
  2973. * bound to the specified peer address
  2974. * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
  2975. * was made.
  2976. *
  2977. * On unix-based systems if the address family of the calling +socket+ is
  2978. * AF_UNIX the follow exceptions may be raised if the call to _connect_
  2979. * fails:
  2980. * * Errno::EIO - an i/o error occurred while reading from or writing to the
  2981. * file system
  2982. * * Errno::ELOOP - too many symbolic links were encountered in translating
  2983. * the pathname in _sockaddr_
  2984. * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
  2985. * characters, or an entire pathname exceeded PATH_MAX characters
  2986. * * Errno::ENOENT - a component of the pathname does not name an existing file
  2987. * or the pathname is an empty string
  2988. * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
  2989. * is not a directory
  2990. *
  2991. * === Windows Exceptions
  2992. * On Windows systems the following system exceptions may be raised if
  2993. * the call to _connect_ fails:
  2994. * * Errno::ENETDOWN - the network is down
  2995. * * Errno::EADDRINUSE - the socket's local address is already in use
  2996. * * Errno::EINTR - the socket was cancelled
  2997. * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
  2998. * is still processing a callback function. Or a nonblocking connect call is
  2999. * in progress on the +socket+.
  3000. * * Errno::EALREADY - see Errno::EINVAL
  3001. * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
  3002. * ADDR_ANY TODO check ADDRANY TO INADDR_ANY
  3003. * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
  3004. * with this +socket+
  3005. * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
  3006. * refused the connection request
  3007. * * Errno::EFAULT - the socket's internal address or address length parameter
  3008. * is too small or is not a valid part of the user space address
  3009. * * Errno::EINVAL - the +socket+ is a listening socket
  3010. * * Errno::EISCONN - the +socket+ is already connected
  3011. * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
  3012. * * Errno::EHOSTUNREACH - no route to the network is present
  3013. * * Errno::ENOBUFS - no buffer space is available
  3014. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  3015. * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
  3016. * was made.
  3017. * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
  3018. * connection cannot be completed immediately
  3019. * * Errno::EACCES - the attempt to connect the datagram socket to the
  3020. * broadcast address failed
  3021. *
  3022. * === See
  3023. * * connect manual pages on unix-based systems
  3024. * * connect function in Microsoft's Winsock functions reference
  3025. */
  3026. static VALUE
  3027. sock_connect(VALUE sock, SEL sel, VALUE addr)
  3028. {
  3029. rb_io_t *fptr;
  3030. int fd, n;
  3031. SockAddrStringValue(addr);
  3032. addr = rb_str_new4(addr);
  3033. GetOpenFile(sock, fptr);
  3034. fd = fptr->fd;
  3035. n = ruby_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr), 0);
  3036. if (n < 0) {
  3037. rb_sys_fail("connect(2)");
  3038. }
  3039. return INT2FIX(n);
  3040. }
  3041. /*
  3042. * call-seq:
  3043. * socket.connect_nonblock(remote_sockaddr) => 0
  3044. *
  3045. * Requests a connection to be made on the given +remote_sockaddr+ after
  3046. * O_NONBLOCK is set for the underlying file descriptor.
  3047. * Returns 0 if successful, otherwise an exception is raised.
  3048. *
  3049. * === Parameter
  3050. * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
  3051. *
  3052. * === Example:
  3053. * # Pull down Google's web page
  3054. * require 'socket'
  3055. * include Socket::Constants
  3056. * socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  3057. * sockaddr = Socket.sockaddr_in(80, 'www.google.com')
  3058. * begin # emulate blocking connect
  3059. * socket.connect_nonblock(sockaddr)
  3060. * rescue IO::WaitWritable
  3061. * IO.select(nil, [socket]) # wait 3-way handshake completion
  3062. * begin
  3063. * socket.connect_nonblock(sockaddr) # check connection failure
  3064. * rescue Errno::EISCONN
  3065. * end
  3066. * end
  3067. * socket.write("GET / HTTP/1.0\r\n\r\n")
  3068. * results = socket.read
  3069. *
  3070. * Refer to Socket#connect for the exceptions that may be thrown if the call
  3071. * to _connect_nonblock_ fails.
  3072. *
  3073. * Socket#connect_nonblock may raise any error corresponding to connect(2) failure,
  3074. * including Errno::EINPROGRESS.
  3075. *
  3076. * If the exception is Errno::EINPROGRESS,
  3077. * it is extended by IO::WaitWritable.
  3078. * So IO::WaitWritable can be used to rescue the exceptions for retrying connect_nonblock.
  3079. *
  3080. * === See
  3081. * * Socket#connect
  3082. */
  3083. static VALUE
  3084. sock_connect_nonblock(VALUE sock, SEL sel, VALUE addr)
  3085. {
  3086. rb_io_t *fptr;
  3087. int n;
  3088. SockAddrStringValue(addr);
  3089. addr = rb_str_new4(addr);
  3090. GetOpenFile(sock, fptr);
  3091. rb_io_set_nonblock(fptr);
  3092. n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr));
  3093. if (n < 0) {
  3094. if (errno == EINPROGRESS) {
  3095. rb_mod_sys_fail(rb_mWaitWritable, "connect(2) would block");
  3096. }
  3097. rb_sys_fail("connect(2)");
  3098. }
  3099. return INT2FIX(n);
  3100. }
  3101. /*
  3102. * call-seq:
  3103. * socket.bind(local_sockaddr) => 0
  3104. *
  3105. * Binds to the given local address.
  3106. *
  3107. * === Parameter
  3108. * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object
  3109. *
  3110. * === Example
  3111. * require 'socket'
  3112. *
  3113. * # use Addrinfo
  3114. * socket = Socket.new(:INET, :STREAM, 0)
  3115. * socket.bind(Addrinfo.tcp("127.0.0.1", 2222))
  3116. * p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>
  3117. *
  3118. * # use struct sockaddr
  3119. * include Socket::Constants
  3120. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3121. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3122. * socket.bind( sockaddr )
  3123. *
  3124. * === Unix-based Exceptions
  3125. * On unix-based based systems the following system exceptions may be raised if
  3126. * the call to _bind_ fails:
  3127. * * Errno::EACCES - the specified _sockaddr_ is protected and the current
  3128. * user does not have permission to bind to it
  3129. * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
  3130. * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
  3131. * local machine
  3132. * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
  3133. * the family of the calling +socket+
  3134. * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
  3135. * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
  3136. * * Errno::EINVAL - the +socket+ is already bound to an address, and the
  3137. * protocol does not support binding to the new _sockaddr_ or the +socket+
  3138. * has been shut down.
  3139. * * Errno::EINVAL - the address length is not a valid length for the address
  3140. * family
  3141. * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
  3142. * PATH_MAX
  3143. * * Errno::ENOBUFS - no buffer space is available
  3144. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  3145. * complete the operation
  3146. * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
  3147. * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
  3148. * binding to an address
  3149. *
  3150. * On unix-based based systems if the address family of the calling +socket+ is
  3151. * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
  3152. * fails:
  3153. * * Errno::EACCES - search permission is denied for a component of the prefix
  3154. * path or write access to the +socket+ is denied
  3155. * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
  3156. * * Errno::EISDIR - same as Errno::EDESTADDRREQ
  3157. * * Errno::EIO - an i/o error occurred
  3158. * * Errno::ELOOP - too many symbolic links were encountered in translating
  3159. * the pathname in _sockaddr_
  3160. * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
  3161. * characters, or an entire pathname exceeded PATH_MAX characters
  3162. * * Errno::ENOENT - a component of the pathname does not name an existing file
  3163. * or the pathname is an empty string
  3164. * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
  3165. * is not a directory
  3166. * * Errno::EROFS - the name would reside on a read only filesystem
  3167. *
  3168. * === Windows Exceptions
  3169. * On Windows systems the following system exceptions may be raised if
  3170. * the call to _bind_ fails:
  3171. * * Errno::ENETDOWN-- the network is down
  3172. * * Errno::EACCES - the attempt to connect the datagram socket to the
  3173. * broadcast address failed
  3174. * * Errno::EADDRINUSE - the socket's local address is already in use
  3175. * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
  3176. * computer
  3177. * * Errno::EFAULT - the socket's internal address or address length parameter
  3178. * is too small or is not a valid part of the user space addressed
  3179. * * Errno::EINVAL - the +socket+ is already bound to an address
  3180. * * Errno::ENOBUFS - no buffer space is available
  3181. * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
  3182. *
  3183. * === See
  3184. * * bind manual pages on unix-based systems
  3185. * * bind function in Microsoft's Winsock functions reference
  3186. */
  3187. static VALUE
  3188. sock_bind(VALUE sock, SEL sel, VALUE addr)
  3189. {
  3190. rb_io_t *fptr;
  3191. SockAddrStringValue(addr);
  3192. GetOpenFile(sock, fptr);
  3193. if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_LENINT(addr)) < 0)
  3194. rb_sys_fail("bind(2)");
  3195. return INT2FIX(0);
  3196. }
  3197. /*
  3198. * call-seq:
  3199. * socket.listen( int ) => 0
  3200. *
  3201. * Listens for connections, using the specified +int+ as the backlog. A call
  3202. * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
  3203. * SOCK_SEQPACKET.
  3204. *
  3205. * === Parameter
  3206. * * +backlog+ - the maximum length of the queue for pending connections.
  3207. *
  3208. * === Example 1
  3209. * require 'socket'
  3210. * include Socket::Constants
  3211. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3212. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3213. * socket.bind( sockaddr )
  3214. * socket.listen( 5 )
  3215. *
  3216. * === Example 2 (listening on an arbitrary port, unix-based systems only):
  3217. * require 'socket'
  3218. * include Socket::Constants
  3219. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3220. * socket.listen( 1 )
  3221. *
  3222. * === Unix-based Exceptions
  3223. * On unix based systems the above will work because a new +sockaddr+ struct
  3224. * is created on the address ADDR_ANY, for an arbitrary port number as handed
  3225. * off by the kernel. It will not work on Windows, because Windows requires that
  3226. * the +socket+ is bound by calling _bind_ before it can _listen_.
  3227. *
  3228. * If the _backlog_ amount exceeds the implementation-dependent maximum
  3229. * queue length, the implementation's maximum queue length will be used.
  3230. *
  3231. * On unix-based based systems the following system exceptions may be raised if the
  3232. * call to _listen_ fails:
  3233. * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
  3234. * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
  3235. * the protocol does not support listening on an unbound socket
  3236. * * Errno::EINVAL - the _socket_ is already connected
  3237. * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
  3238. * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
  3239. * * Errno::EACCES - the calling process does not have appropriate privileges
  3240. * * Errno::EINVAL - the _socket_ has been shut down
  3241. * * Errno::ENOBUFS - insufficient resources are available in the system to
  3242. * complete the call
  3243. *
  3244. * === Windows Exceptions
  3245. * On Windows systems the following system exceptions may be raised if
  3246. * the call to _listen_ fails:
  3247. * * Errno::ENETDOWN - the network is down
  3248. * * Errno::EADDRINUSE - the socket's local address is already in use. This
  3249. * usually occurs during the execution of _bind_ but could be delayed
  3250. * if the call to _bind_ was to a partially wildcard address (involving
  3251. * ADDR_ANY) and if a specific address needs to be committed at the
  3252. * time of the call to _listen_
  3253. * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
  3254. * service provider is still processing a callback function
  3255. * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
  3256. * * Errno::EISCONN - the +socket+ is already connected
  3257. * * Errno::EMFILE - no more socket descriptors are available
  3258. * * Errno::ENOBUFS - no buffer space is available
  3259. * * Errno::ENOTSOC - +socket+ is not a socket
  3260. * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
  3261. * the _listen_ method
  3262. *
  3263. * === See
  3264. * * listen manual pages on unix-based systems
  3265. * * listen function in Microsoft's Winsock functions reference
  3266. */
  3267. static VALUE
  3268. sock_listen(VALUE sock, SEL sel, VALUE log)
  3269. {
  3270. rb_io_t *fptr;
  3271. int backlog;
  3272. rb_secure(4);
  3273. backlog = NUM2INT(log);
  3274. GetOpenFile(sock, fptr);
  3275. if (listen(fptr->fd, backlog) < 0)
  3276. rb_sys_fail("listen(2)");
  3277. return INT2FIX(0);
  3278. }
  3279. /*
  3280. * call-seq:
  3281. * socket.recvfrom(maxlen) => [mesg, sender_addrinfo]
  3282. * socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo]
  3283. *
  3284. * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
  3285. * of the +MSG_+ options. The first element of the results, _mesg_, is the data
  3286. * received. The second element, _sender_addrinfo_, contains protocol-specific
  3287. * address information of the sender.
  3288. *
  3289. * === Parameters
  3290. * * +maxlen+ - the maximum number of bytes to receive from the socket
  3291. * * +flags+ - zero or more of the +MSG_+ options
  3292. *
  3293. * === Example
  3294. * # In one file, start this first
  3295. * require 'socket'
  3296. * include Socket::Constants
  3297. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3298. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3299. * socket.bind( sockaddr )
  3300. * socket.listen( 5 )
  3301. * client, client_addrinfo = socket.accept
  3302. * data = client.recvfrom( 20 )[0].chomp
  3303. * puts "I only received 20 bytes '#{data}'"
  3304. * sleep 1
  3305. * socket.close
  3306. *
  3307. * # In another file, start this second
  3308. * require 'socket'
  3309. * include Socket::Constants
  3310. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3311. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3312. * socket.connect( sockaddr )
  3313. * socket.puts "Watch this get cut short!"
  3314. * socket.close
  3315. *
  3316. * === Unix-based Exceptions
  3317. * On unix-based based systems the following system exceptions may be raised if the
  3318. * call to _recvfrom_ fails:
  3319. * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
  3320. * data is waiting to be received; or MSG_OOB is set and no out-of-band data
  3321. * is available and either the +socket+ file descriptor is marked as
  3322. * O_NONBLOCK or the +socket+ does not support blocking to wait for
  3323. * out-of-band-data
  3324. * * Errno::EWOULDBLOCK - see Errno::EAGAIN
  3325. * * Errno::EBADF - the +socket+ is not a valid file descriptor
  3326. * * Errno::ECONNRESET - a connection was forcibly closed by a peer
  3327. * * Errno::EFAULT - the socket's internal buffer, address or address length
  3328. * cannot be accessed or written
  3329. * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available
  3330. * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
  3331. * * Errno::EIO - an i/o error occurred while reading from or writing to the
  3332. * filesystem
  3333. * * Errno::ENOBUFS - insufficient resources were available in the system to
  3334. * perform the operation
  3335. * * Errno::ENOMEM - insufficient memory was available to fulfill the request
  3336. * * Errno::ENOSR - there were insufficient STREAMS resources available to
  3337. * complete the operation
  3338. * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
  3339. * is not connected
  3340. * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
  3341. * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
  3342. * * Errno::ETIMEDOUT - the connection timed out during connection establishment
  3343. * or due to a transmission timeout on an active connection
  3344. *
  3345. * === Windows Exceptions
  3346. * On Windows systems the following system exceptions may be raised if
  3347. * the call to _recvfrom_ fails:
  3348. * * Errno::ENETDOWN - the network is down
  3349. * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
  3350. * part of the user address space, or the internal fromlen parameter is
  3351. * too small to accommodate the peer address
  3352. * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
  3353. * the WinSock function WSACancelBlockingCall
  3354. * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
  3355. * the service provider is still processing a callback function
  3356. * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
  3357. * unknown flag was specified, or MSG_OOB was specified for a socket with
  3358. * SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
  3359. * len parameter on +socket+ was zero or negative
  3360. * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
  3361. * not permitted with a connected socket on a socket that is connection
  3362. * oriented or connectionless.
  3363. * * Errno::ENETRESET - the connection has been broken due to the keep-alive
  3364. * activity detecting a failure while the operation was in progress.
  3365. * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
  3366. * such as type SOCK_STREAM. OOB data is not supported in the communication
  3367. * domain associated with +socket+, or +socket+ is unidirectional and
  3368. * supports only send operations
  3369. * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
  3370. * call _recvfrom_ on a socket after _shutdown_ has been invoked.
  3371. * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to
  3372. * _recvfrom_ would block.
  3373. * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
  3374. * and was truncated.
  3375. * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
  3376. * failure or because the system on the other end went down without
  3377. * notice
  3378. * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
  3379. * executing a hard or abortive close. The application should close the
  3380. * socket; it is no longer usable. On a UDP-datagram socket this error
  3381. * indicates a previous send operation resulted in an ICMP Port Unreachable
  3382. * message.
  3383. */
  3384. static VALUE
  3385. sock_recvfrom(VALUE sock, SEL sel, int argc, VALUE *argv)
  3386. {
  3387. return s_recvfrom(sock, argc, argv, RECV_SOCKET);
  3388. }
  3389. /*
  3390. * call-seq:
  3391. * socket.recvfrom_nonblock(maxlen) => [mesg, sender_addrinfo]
  3392. * socket.recvfrom_nonblock(maxlen, flags) => [mesg, sender_addrinfo]
  3393. *
  3394. * Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
  3395. * O_NONBLOCK is set for the underlying file descriptor.
  3396. * _flags_ is zero or more of the +MSG_+ options.
  3397. * The first element of the results, _mesg_, is the data received.
  3398. * The second element, _sender_addrinfo_, contains protocol-specific address
  3399. * information of the sender.
  3400. *
  3401. * When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns
  3402. * an empty string as data.
  3403. * The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
  3404. *
  3405. * === Parameters
  3406. * * +maxlen+ - the maximum number of bytes to receive from the socket
  3407. * * +flags+ - zero or more of the +MSG_+ options
  3408. *
  3409. * === Example
  3410. * # In one file, start this first
  3411. * require 'socket'
  3412. * include Socket::Constants
  3413. * socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  3414. * sockaddr = Socket.sockaddr_in(2200, 'localhost')
  3415. * socket.bind(sockaddr)
  3416. * socket.listen(5)
  3417. * client, client_addrinfo = socket.accept
  3418. * begin # emulate blocking recvfrom
  3419. * pair = client.recvfrom_nonblock(20)
  3420. * rescue IO::WaitReadable
  3421. * IO.select([client])
  3422. * retry
  3423. * end
  3424. * data = pair[0].chomp
  3425. * puts "I only received 20 bytes '#{data}'"
  3426. * sleep 1
  3427. * socket.close
  3428. *
  3429. * # In another file, start this second
  3430. * require 'socket'
  3431. * include Socket::Constants
  3432. * socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  3433. * sockaddr = Socket.sockaddr_in(2200, 'localhost')
  3434. * socket.connect(sockaddr)
  3435. * socket.puts "Watch this get cut short!"
  3436. * socket.close
  3437. *
  3438. * Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  3439. * to _recvfrom_nonblock_ fails.
  3440. *
  3441. * Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
  3442. * including Errno::EWOULDBLOCK.
  3443. *
  3444. * If the exception is Errno::EWOULDBLOCK or Errno::AGAIN,
  3445. * it is extended by IO::WaitReadable.
  3446. * So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock.
  3447. *
  3448. * === See
  3449. * * Socket#recvfrom
  3450. */
  3451. static VALUE
  3452. sock_recvfrom_nonblock(VALUE sock, SEL sel, int argc, VALUE *argv)
  3453. {
  3454. return s_recvfrom_nonblock(sock, argc, argv, RECV_SOCKET);
  3455. }
  3456. /*
  3457. * call-seq:
  3458. * socket.accept => [client_socket, client_addrinfo]
  3459. *
  3460. * Accepts a next connection.
  3461. * Returns a new Socket object and Addrinfo object.
  3462. *
  3463. * serv = Socket.new(:INET, :STREAM, 0)
  3464. * serv.listen(5)
  3465. * c = Socket.new(:INET, :STREAM, 0)
  3466. * c.connect(serv.connect_address)
  3467. * p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>]
  3468. *
  3469. */
  3470. static VALUE
  3471. sock_accept(VALUE sock, SEL sel)
  3472. {
  3473. rb_io_t *fptr;
  3474. VALUE sock2;
  3475. struct sockaddr_storage buf;
  3476. socklen_t len = (socklen_t)sizeof buf;
  3477. GetOpenFile(sock, fptr);
  3478. sock2 = s_accept(rb_cSocket,fptr->fd,(struct sockaddr*)&buf,&len);
  3479. return rb_assoc_new(sock2, io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len));
  3480. }
  3481. /*
  3482. * call-seq:
  3483. * socket.accept_nonblock => [client_socket, client_addrinfo]
  3484. *
  3485. * Accepts an incoming connection using accept(2) after
  3486. * O_NONBLOCK is set for the underlying file descriptor.
  3487. * It returns an array containing the accepted socket
  3488. * for the incoming connection, _client_socket_,
  3489. * and an Addrinfo, _client_addrinfo_.
  3490. *
  3491. * === Example
  3492. * # In one script, start this first
  3493. * require 'socket'
  3494. * include Socket::Constants
  3495. * socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  3496. * sockaddr = Socket.sockaddr_in(2200, 'localhost')
  3497. * socket.bind(sockaddr)
  3498. * socket.listen(5)
  3499. * begin # emulate blocking accept
  3500. * client_socket, client_addrinfo = socket.accept_nonblock
  3501. * rescue IO::WaitReadable, Errno::EINTR
  3502. * IO.select([socket])
  3503. * retry
  3504. * end
  3505. * puts "The client said, '#{client_socket.readline.chomp}'"
  3506. * client_socket.puts "Hello from script one!"
  3507. * socket.close
  3508. *
  3509. * # In another script, start this second
  3510. * require 'socket'
  3511. * include Socket::Constants
  3512. * socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  3513. * sockaddr = Socket.sockaddr_in(2200, 'localhost')
  3514. * socket.connect(sockaddr)
  3515. * socket.puts "Hello from script 2."
  3516. * puts "The server said, '#{socket.readline.chomp}'"
  3517. * socket.close
  3518. *
  3519. * Refer to Socket#accept for the exceptions that may be thrown if the call
  3520. * to _accept_nonblock_ fails.
  3521. *
  3522. * Socket#accept_nonblock may raise any error corresponding to accept(2) failure,
  3523. * including Errno::EWOULDBLOCK.
  3524. *
  3525. * If the exception is Errno::EWOULDBLOCK, Errno::AGAIN, Errno::ECONNABORTED or Errno::EPROTO,
  3526. * it is extended by IO::WaitReadable.
  3527. * So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  3528. *
  3529. * === See
  3530. * * Socket#accept
  3531. */
  3532. static VALUE
  3533. sock_accept_nonblock(VALUE sock, SEL sel)
  3534. {
  3535. rb_io_t *fptr;
  3536. VALUE sock2;
  3537. struct sockaddr_storage buf;
  3538. socklen_t len = (socklen_t)sizeof buf;
  3539. GetOpenFile(sock, fptr);
  3540. sock2 = s_accept_nonblock(rb_cSocket, fptr, (struct sockaddr *)&buf, &len);
  3541. return rb_assoc_new(sock2, io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len));
  3542. }
  3543. /*
  3544. * call-seq:
  3545. * socket.sysaccept => [client_socket_fd, client_addrinfo]
  3546. *
  3547. * Accepts an incoming connection returning an array containing the (integer)
  3548. * file descriptor for the incoming connection, _client_socket_fd_,
  3549. * and an Addrinfo, _client_addrinfo_.
  3550. *
  3551. * === Example
  3552. * # In one script, start this first
  3553. * require 'socket'
  3554. * include Socket::Constants
  3555. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3556. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3557. * socket.bind( sockaddr )
  3558. * socket.listen( 5 )
  3559. * client_fd, client_addrinfo = socket.sysaccept
  3560. * client_socket = Socket.for_fd( client_fd )
  3561. * puts "The client said, '#{client_socket.readline.chomp}'"
  3562. * client_socket.puts "Hello from script one!"
  3563. * socket.close
  3564. *
  3565. * # In another script, start this second
  3566. * require 'socket'
  3567. * include Socket::Constants
  3568. * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
  3569. * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
  3570. * socket.connect( sockaddr )
  3571. * socket.puts "Hello from script 2."
  3572. * puts "The server said, '#{socket.readline.chomp}'"
  3573. * socket.close
  3574. *
  3575. * Refer to Socket#accept for the exceptions that may be thrown if the call
  3576. * to _sysaccept_ fails.
  3577. *
  3578. * === See
  3579. * * Socket#accept
  3580. */
  3581. static VALUE
  3582. sock_sysaccept(VALUE sock, SEL sel)
  3583. {
  3584. rb_io_t *fptr;
  3585. VALUE sock2;
  3586. struct sockaddr_storage buf;
  3587. socklen_t len = (socklen_t)sizeof buf;
  3588. GetOpenFile(sock, fptr);
  3589. sock2 = s_accept(0,fptr->fd,(struct sockaddr*)&buf,&len);
  3590. return rb_assoc_new(sock2, io_socket_addrinfo(sock2, (struct sockaddr*)&buf, len));
  3591. }
  3592. static inline VALUE
  3593. rb_io_check_io(VALUE io)
  3594. {
  3595. return rb_check_convert_type(io, T_FILE, "IO", "to_io");
  3596. }
  3597. VALUE rb_f_open(VALUE io, SEL sel, int argc, VALUE *argv);
  3598. /*
  3599. * call-seq:
  3600. * socket.sendfile(dest, offset, len) => integer
  3601. *
  3602. * Uses the sendfile(2) system call to send the file specified by <code>dest</code>
  3603. * to <code>socket</code>. <code>dest</code> must either be a readable IO object or
  3604. * a String representing a path on the file system. The <code>offset</code>
  3605. * and <code>len</code> parameters determine the offset and length of the sent file.
  3606. * Returns the number of bytes set. May throw a SystemCallError if the underlying call fails.
  3607. */
  3608. static VALUE
  3609. socket_sendfile(VALUE self, SEL sel, VALUE file, VALUE offset, VALUE len)
  3610. {
  3611. bool needs_to_close = false;
  3612. off_t to_offset = NUM2OFFT(offset);
  3613. off_t to_write = NUM2OFFT(len);
  3614. rb_io_t *socket;
  3615. if (to_offset < 0 || to_write < 0) {
  3616. rb_raise(rb_eArgError, "negative argument");
  3617. }
  3618. GetOpenFile(self, socket);
  3619. VALUE io = rb_io_check_io(file);
  3620. if (NIL_P(io)) {
  3621. io = rb_f_open(rb_cIO, 0, 1, &file);
  3622. needs_to_close = true;
  3623. }
  3624. rb_io_t *source = ExtractIOStruct(io);
  3625. rb_io_check_closed(source);
  3626. if (sendfile(source->fd, socket->fd, to_offset, &to_write, NULL, 0) == -1) {
  3627. if (needs_to_close) {
  3628. rb_io_close(io);
  3629. }
  3630. rb_sys_fail("sendfile(2) failed.");
  3631. }
  3632. if (needs_to_close) {
  3633. rb_io_close(io);
  3634. }
  3635. return OFFT2NUM(to_write);
  3636. }
  3637. #ifdef HAVE_GETHOSTNAME
  3638. /*
  3639. * call-seq:
  3640. * Socket.gethostname => hostname
  3641. *
  3642. * Returns the hostname.
  3643. *
  3644. * p Socket.gethostname #=> "hal"
  3645. *
  3646. * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc.
  3647. * If you need local IP address, use Socket.ip_address_list.
  3648. */
  3649. static VALUE
  3650. sock_gethostname(VALUE obj, SEL sel)
  3651. {
  3652. #ifndef HOST_NAME_MAX
  3653. # define HOST_NAME_MAX 1024
  3654. #endif
  3655. char buf[HOST_NAME_MAX+1];
  3656. rb_secure(3);
  3657. if (gethostname(buf, (int)sizeof buf - 1) < 0)
  3658. rb_sys_fail("gethostname");
  3659. buf[sizeof buf - 1] = '\0';
  3660. return rb_str_new2(buf);
  3661. }
  3662. #else
  3663. #ifdef HAVE_UNAME
  3664. #include <sys/utsname.h>
  3665. static VALUE
  3666. sock_gethostname(VALUE obj, SEL sel)
  3667. {
  3668. struct utsname un;
  3669. rb_secure(3);
  3670. uname(&un);
  3671. return rb_str_new2(un.nodename);
  3672. }
  3673. #else
  3674. static VALUE
  3675. sock_gethostname(VALUE obj, SEL sel)
  3676. {
  3677. rb_notimplement();
  3678. }
  3679. #endif
  3680. #endif
  3681. static VALUE
  3682. make_addrinfo(struct addrinfo *res0, int norevlookup)
  3683. {
  3684. VALUE base, ary;
  3685. struct addrinfo *res;
  3686. if (res0 == NULL) {
  3687. rb_raise(rb_eSocket, "host not found");
  3688. }
  3689. base = rb_ary_new();
  3690. for (res = res0; res; res = res->ai_next) {
  3691. ary = ipaddr(res->ai_addr, norevlookup);
  3692. if (res->ai_canonname) {
  3693. rb_ary_store(ary, 2, rb_str_new2(res->ai_canonname));
  3694. }
  3695. rb_ary_push(ary, INT2FIX(res->ai_family));
  3696. rb_ary_push(ary, INT2FIX(res->ai_socktype));
  3697. rb_ary_push(ary, INT2FIX(res->ai_protocol));
  3698. rb_ary_push(base, ary);
  3699. }
  3700. return base;
  3701. }
  3702. static VALUE
  3703. sock_sockaddr(struct sockaddr *addr, size_t len)
  3704. {
  3705. char *ptr;
  3706. switch (addr->sa_family) {
  3707. case AF_INET:
  3708. ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr;
  3709. len = sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr);
  3710. break;
  3711. #ifdef INET6
  3712. case AF_INET6:
  3713. ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr;
  3714. len = sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr);
  3715. break;
  3716. #endif
  3717. default:
  3718. rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family);
  3719. break;
  3720. }
  3721. return rb_str_new(ptr, len);
  3722. }
  3723. /*
  3724. * call-seq:
  3725. * Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
  3726. *
  3727. * Obtains the host information for _hostname_.
  3728. *
  3729. * p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"]
  3730. *
  3731. */
  3732. static VALUE
  3733. sock_s_gethostbyname(VALUE obj, SEL sel, VALUE host)
  3734. {
  3735. rb_secure(3);
  3736. return make_hostent(host, sock_addrinfo(host, Qnil, SOCK_STREAM, AI_CANONNAME), sock_sockaddr);
  3737. }
  3738. /*
  3739. * call-seq:
  3740. * Socket.gethostbyaddr(address_string [, address_family]) => hostent
  3741. *
  3742. * Obtains the host information for _address_.
  3743. *
  3744. * p Socket.gethostbyaddr([221,186,184,68].pack("CCCC"))
  3745. * #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"]
  3746. */
  3747. static VALUE
  3748. sock_s_gethostbyaddr(VALUE self, SEL sel, int argc, VALUE *argv)
  3749. {
  3750. VALUE addr, family;
  3751. struct hostent *h;
  3752. struct sockaddr *sa;
  3753. char **pch;
  3754. VALUE ary, names;
  3755. int t = AF_INET;
  3756. rb_scan_args(argc, argv, "11", &addr, &family);
  3757. sa = (struct sockaddr*)StringValuePtr(addr);
  3758. if (!NIL_P(family)) {
  3759. t = family_arg(family);
  3760. }
  3761. #ifdef INET6
  3762. else if (RSTRING_LEN(addr) == 16) {
  3763. t = AF_INET6;
  3764. }
  3765. #endif
  3766. h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_LENINT(addr), t);
  3767. if (h == NULL) {
  3768. #ifdef HAVE_HSTRERROR
  3769. extern int h_errno;
  3770. rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno));
  3771. #else
  3772. rb_raise(rb_eSocket, "host not found");
  3773. #endif
  3774. }
  3775. ary = rb_ary_new();
  3776. rb_ary_push(ary, rb_str_new2(h->h_name));
  3777. names = rb_ary_new();
  3778. rb_ary_push(ary, names);
  3779. if (h->h_aliases != NULL) {
  3780. for (pch = h->h_aliases; *pch; pch++) {
  3781. rb_ary_push(names, rb_str_new2(*pch));
  3782. }
  3783. }
  3784. rb_ary_push(ary, INT2NUM(h->h_addrtype));
  3785. #ifdef h_addr
  3786. for (pch = h->h_addr_list; *pch; pch++) {
  3787. rb_ary_push(ary, rb_str_new(*pch, h->h_length));
  3788. }
  3789. #else
  3790. rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length));
  3791. #endif
  3792. return ary;
  3793. }
  3794. /*
  3795. * call-seq:
  3796. * Socket.getservbyname(service_name) => port_number
  3797. * Socket.getservbyname(service_name, protocol_name) => port_number
  3798. *
  3799. * Obtains the port number for _service_name_.
  3800. *
  3801. * If _protocol_name_ is not given, "tcp" is assumed.
  3802. *
  3803. * Socket.getservbyname("smtp") #=> 25
  3804. * Socket.getservbyname("shell") #=> 514
  3805. * Socket.getservbyname("syslog", "udp") #=> 514
  3806. */
  3807. static VALUE
  3808. sock_s_getservbyname(VALUE self, SEL sel, int argc, VALUE *argv)
  3809. {
  3810. VALUE service, proto;
  3811. struct servent *sp;
  3812. int port;
  3813. rb_scan_args(argc, argv, "11", &service, &proto);
  3814. if (NIL_P(proto)) proto = rb_str_new2("tcp");
  3815. StringValue(service);
  3816. StringValue(proto);
  3817. sp = getservbyname(StringValueCStr(service), StringValueCStr(proto));
  3818. if (sp) {
  3819. port = ntohs(sp->s_port);
  3820. }
  3821. else {
  3822. const char *s = RSTRING_PTR(service);
  3823. char *end;
  3824. port = STRTOUL(s, &end, 0);
  3825. if (*end != '\0') {
  3826. rb_raise(rb_eSocket, "no such service %s/%s", s, RSTRING_PTR(proto));
  3827. }
  3828. }
  3829. return INT2FIX(port);
  3830. }
  3831. /*
  3832. * call-seq:
  3833. * Socket.getservbyport(port [, protocol_name]) => service
  3834. *
  3835. * Obtains the port number for _port_.
  3836. *
  3837. * If _protocol_name_ is not given, "tcp" is assumed.
  3838. *
  3839. * Socket.getservbyport(80) #=> "www"
  3840. * Socket.getservbyport(514, "tcp") #=> "shell"
  3841. * Socket.getservbyport(514, "udp") #=> "syslog"
  3842. *
  3843. */
  3844. static VALUE
  3845. sock_s_getservbyport(VALUE self, SEL sel, int argc, VALUE *argv)
  3846. {
  3847. VALUE port, proto;
  3848. struct servent *sp;
  3849. long portnum;
  3850. rb_scan_args(argc, argv, "11", &port, &proto);
  3851. portnum = NUM2LONG(port);
  3852. if (portnum != (uint16_t)portnum) {
  3853. const char *s = portnum > 0 ? "big" : "small";
  3854. rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s);
  3855. }
  3856. if (NIL_P(proto)) proto = rb_str_new2("tcp");
  3857. StringValue(proto);
  3858. sp = getservbyport((int)htons((uint16_t)portnum), StringValueCStr(proto));
  3859. if (!sp) {
  3860. rb_raise(rb_eSocket, "no such service for port %ld/%s", NUM2LONG(port),
  3861. RSTRING_PTR(proto));
  3862. }
  3863. return rb_tainted_str_new2(sp->s_name);
  3864. }
  3865. /*
  3866. * call-seq:
  3867. * Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array
  3868. *
  3869. * Obtains address information for _nodename_:_servname_.
  3870. *
  3871. * _family_ should be an address family such as: :INET, :INET6, :UNIX, etc.
  3872. *
  3873. * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
  3874. *
  3875. * _protocol_ should be a protocol defined in the family.
  3876. * 0 is default protocol for the family.
  3877. *
  3878. * _flags_ should be bitwise OR of Socket::AI_* constants.
  3879. *
  3880. * Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM)
  3881. * #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP
  3882. *
  3883. * Socket.getaddrinfo("localhost", nil)
  3884. * #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6], # PF_INET/SOCK_STREAM/IPPROTO_TCP
  3885. * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP
  3886. * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]] # PF_INET/SOCK_RAW/IPPROTO_IP
  3887. *
  3888. * _reverse_lookup_ directs the form of the third element, and has to
  3889. * be one of below.
  3890. * If it is ommitted, the default value is +nil+.
  3891. *
  3892. * +true+, +:hostname+: hostname is obtained from numeric address using reverse lookup, which may take a time.
  3893. * +false+, +:numeric+: hostname is same as numeric address.
  3894. * +nil+: obey to the current +do_not_reverse_lookup+ flag.
  3895. *
  3896. * If Addrinfo object is preferred, use Addrinfo.getaddrinfo.
  3897. */
  3898. static VALUE
  3899. sock_s_getaddrinfo(VALUE self, SEL sel, int argc, VALUE *argv)
  3900. {
  3901. VALUE host, port, family, socktype, protocol, flags, ret, revlookup;
  3902. char hbuf[1024], pbuf[1024];
  3903. char *hptr, *pptr;
  3904. struct addrinfo hints, *res;
  3905. int error;
  3906. int norevlookup;
  3907. rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup);
  3908. if (NIL_P(host)) {
  3909. hptr = NULL;
  3910. }
  3911. else {
  3912. strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
  3913. hbuf[sizeof(hbuf) - 1] = '\0';
  3914. hptr = hbuf;
  3915. }
  3916. if (NIL_P(port)) {
  3917. pptr = NULL;
  3918. }
  3919. else if (FIXNUM_P(port)) {
  3920. snprintf(pbuf, sizeof(pbuf), "%ld", FIX2LONG(port));
  3921. pptr = pbuf;
  3922. }
  3923. else {
  3924. strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
  3925. pbuf[sizeof(pbuf) - 1] = '\0';
  3926. pptr = pbuf;
  3927. }
  3928. MEMZERO(&hints, struct addrinfo, 1);
  3929. hints.ai_family = NIL_P(family) ? PF_UNSPEC : family_arg(family);
  3930. if (!NIL_P(socktype)) {
  3931. hints.ai_socktype = socktype_arg(socktype);
  3932. }
  3933. if (!NIL_P(protocol)) {
  3934. hints.ai_protocol = NUM2INT(protocol);
  3935. }
  3936. if (!NIL_P(flags)) {
  3937. hints.ai_flags = NUM2INT(flags);
  3938. }
  3939. if (NIL_P(revlookup) || !revlookup_flag(revlookup, &norevlookup)) {
  3940. norevlookup = do_not_reverse_lookup;
  3941. }
  3942. error = getaddrinfo(hptr, pptr, &hints, &res);
  3943. if (error) {
  3944. raise_socket_error("getaddrinfo", error);
  3945. }
  3946. ret = make_addrinfo(res, norevlookup);
  3947. freeaddrinfo(res);
  3948. return ret;
  3949. }
  3950. /*
  3951. * call-seq:
  3952. * Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename]
  3953. *
  3954. * Obtains name information for _sockaddr_.
  3955. *
  3956. * _sockaddr_ should be one of follows.
  3957. * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1")
  3958. * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"]
  3959. * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"]
  3960. *
  3961. * _flags_ should be bitwise OR of Socket::NI_* constants.
  3962. *
  3963. * Note that the last form is compatible with IPSocket#{addr,peeraddr}.
  3964. *
  3965. * Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1")) #=> ["localhost", "www"]
  3966. * Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"]) #=> ["localhost", "www"]
  3967. * Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"]
  3968. *
  3969. * If Addrinfo object is preferred, use Addrinfo#getnameinfo.
  3970. */
  3971. static VALUE
  3972. sock_s_getnameinfo(VALUE self, SEL sel, int argc, VALUE *argv)
  3973. {
  3974. VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
  3975. char *hptr, *pptr;
  3976. char hbuf[1024], pbuf[1024];
  3977. int fl;
  3978. struct addrinfo hints, *res = NULL, *r;
  3979. int error;
  3980. struct sockaddr_storage ss;
  3981. struct sockaddr *sap;
  3982. sa = flags = Qnil;
  3983. rb_scan_args(argc, argv, "11", &sa, &flags);
  3984. fl = 0;
  3985. if (!NIL_P(flags)) {
  3986. fl = NUM2INT(flags);
  3987. }
  3988. tmp = rb_check_string_type(sa);
  3989. if (!NIL_P(tmp)) {
  3990. sa = tmp;
  3991. if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
  3992. rb_raise(rb_eTypeError, "sockaddr length too big");
  3993. }
  3994. memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
  3995. if ((size_t)RSTRING_LEN(sa) != SS_LEN(&ss)) {
  3996. rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
  3997. }
  3998. sap = (struct sockaddr*)&ss;
  3999. goto call_nameinfo;
  4000. }
  4001. tmp = rb_check_array_type(sa);
  4002. if (!NIL_P(tmp)) {
  4003. sa = tmp;
  4004. MEMZERO(&hints, struct addrinfo, 1);
  4005. if (RARRAY_LEN(sa) == 3) {
  4006. af = RARRAY_AT(sa, 0);
  4007. port = RARRAY_AT(sa, 1);
  4008. host = RARRAY_AT(sa, 2);
  4009. }
  4010. else if (RARRAY_LEN(sa) >= 4) {
  4011. af = RARRAY_AT(sa, 0);
  4012. port = RARRAY_AT(sa, 1);
  4013. host = RARRAY_AT(sa, 3);
  4014. if (NIL_P(host)) {
  4015. host = RARRAY_AT(sa, 2);
  4016. }
  4017. else {
  4018. /*
  4019. * 4th element holds numeric form, don't resolve.
  4020. * see ipaddr().
  4021. */
  4022. #ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
  4023. hints.ai_flags |= AI_NUMERICHOST;
  4024. #endif
  4025. }
  4026. }
  4027. else {
  4028. rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
  4029. RARRAY_LEN(sa));
  4030. }
  4031. /* host */
  4032. if (NIL_P(host)) {
  4033. hptr = NULL;
  4034. }
  4035. else {
  4036. strncpy(hbuf, StringValuePtr(host), sizeof(hbuf));
  4037. hbuf[sizeof(hbuf) - 1] = '\0';
  4038. hptr = hbuf;
  4039. }
  4040. /* port */
  4041. if (NIL_P(port)) {
  4042. strcpy(pbuf, "0");
  4043. pptr = NULL;
  4044. }
  4045. else if (FIXNUM_P(port)) {
  4046. snprintf(pbuf, sizeof(pbuf), "%ld", NUM2LONG(port));
  4047. pptr = pbuf;
  4048. }
  4049. else {
  4050. strncpy(pbuf, StringValuePtr(port), sizeof(pbuf));
  4051. pbuf[sizeof(pbuf) - 1] = '\0';
  4052. pptr = pbuf;
  4053. }
  4054. hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
  4055. /* af */
  4056. hints.ai_family = NIL_P(af) ? PF_UNSPEC : family_arg(af);
  4057. error = getaddrinfo(hptr, pptr, &hints, &res);
  4058. if (error) goto error_exit_addr;
  4059. sap = res->ai_addr;
  4060. }
  4061. else {
  4062. rb_raise(rb_eTypeError, "expecting String or Array");
  4063. }
  4064. call_nameinfo:
  4065. error = getnameinfo(sap, SA_LEN(sap), hbuf, sizeof(hbuf),
  4066. pbuf, sizeof(pbuf), fl);
  4067. if (error) goto error_exit_name;
  4068. if (res) {
  4069. for (r = res->ai_next; r; r = r->ai_next) {
  4070. char hbuf2[1024], pbuf2[1024];
  4071. sap = r->ai_addr;
  4072. error = getnameinfo(sap, SA_LEN(sap), hbuf2, sizeof(hbuf2),
  4073. pbuf2, sizeof(pbuf2), fl);
  4074. if (error) goto error_exit_name;
  4075. if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
  4076. freeaddrinfo(res);
  4077. rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
  4078. }
  4079. }
  4080. freeaddrinfo(res);
  4081. }
  4082. return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
  4083. error_exit_addr:
  4084. if (res) freeaddrinfo(res);
  4085. raise_socket_error("getaddrinfo", error);
  4086. error_exit_name:
  4087. if (res) freeaddrinfo(res);
  4088. raise_socket_error("getnameinfo", error);
  4089. }
  4090. /*
  4091. * call-seq:
  4092. * Socket.sockaddr_in(port, host) => sockaddr
  4093. * Socket.pack_sockaddr_in(port, host) => sockaddr
  4094. *
  4095. * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string.
  4096. *
  4097. * Socket.sockaddr_in(80, "127.0.0.1")
  4098. * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  4099. *
  4100. * Socket.sockaddr_in(80, "::1")
  4101. * #=> "\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"
  4102. *
  4103. */
  4104. static VALUE
  4105. sock_s_pack_sockaddr_in(VALUE self, SEL sel, VALUE port, VALUE host)
  4106. {
  4107. struct addrinfo *res = sock_addrinfo(host, port, 0, 0);
  4108. VALUE addr = rb_str_new((char*)res->ai_addr, res->ai_addrlen);
  4109. freeaddrinfo(res);
  4110. OBJ_INFECT(addr, port);
  4111. OBJ_INFECT(addr, host);
  4112. return addr;
  4113. }
  4114. /*
  4115. * call-seq:
  4116. * Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address]
  4117. *
  4118. * Unpacks _sockaddr_ into port and ip_address.
  4119. *
  4120. * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6.
  4121. *
  4122. * sockaddr = Socket.sockaddr_in(80, "127.0.0.1")
  4123. * p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  4124. * p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"]
  4125. *
  4126. */
  4127. static VALUE
  4128. sock_s_unpack_sockaddr_in(VALUE self, SEL sel, VALUE addr)
  4129. {
  4130. struct sockaddr_in * sockaddr;
  4131. VALUE host;
  4132. sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr);
  4133. if (RSTRING_LEN(addr) <
  4134. (char*)&((struct sockaddr *)sockaddr)->sa_family +
  4135. sizeof(((struct sockaddr *)sockaddr)->sa_family) -
  4136. (char*)sockaddr)
  4137. rb_raise(rb_eArgError, "too short sockaddr");
  4138. if (((struct sockaddr *)sockaddr)->sa_family != AF_INET
  4139. #ifdef INET6
  4140. && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6
  4141. #endif
  4142. ) {
  4143. #ifdef INET6
  4144. rb_raise(rb_eArgError, "not an AF_INET/AF_INET6 sockaddr");
  4145. #else
  4146. rb_raise(rb_eArgError, "not an AF_INET sockaddr");
  4147. #endif
  4148. }
  4149. host = make_ipaddr((struct sockaddr*)sockaddr);
  4150. OBJ_INFECT(host, addr);
  4151. return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host);
  4152. }
  4153. #ifdef HAVE_SYS_UN_H
  4154. /*
  4155. * call-seq:
  4156. * Socket.sockaddr_un(path) => sockaddr
  4157. * Socket.pack_sockaddr_un(path) => sockaddr
  4158. *
  4159. * Packs _path_ as an AF_UNIX sockaddr string.
  4160. *
  4161. * Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..."
  4162. *
  4163. */
  4164. static VALUE
  4165. sock_s_pack_sockaddr_un(VALUE self, SEL sel, VALUE path)
  4166. {
  4167. struct sockaddr_un sockaddr;
  4168. char *sun_path;
  4169. VALUE addr;
  4170. MEMZERO(&sockaddr, struct sockaddr_un, 1);
  4171. sockaddr.sun_family = AF_UNIX;
  4172. sun_path = StringValueCStr(path);
  4173. if (sizeof(sockaddr.sun_path) <= strlen(sun_path)) {
  4174. rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)",
  4175. (int)sizeof(sockaddr.sun_path)-1);
  4176. }
  4177. strncpy(sockaddr.sun_path, sun_path, sizeof(sockaddr.sun_path)-1);
  4178. addr = rb_str_new((char*)&sockaddr, sizeof(sockaddr));
  4179. OBJ_INFECT(addr, path);
  4180. return addr;
  4181. }
  4182. /*
  4183. * call-seq:
  4184. * Socket.unpack_sockaddr_un(sockaddr) => path
  4185. *
  4186. * Unpacks _sockaddr_ into path.
  4187. *
  4188. * _sockaddr_ should be a string or an addrinfo for AF_UNIX.
  4189. *
  4190. * sockaddr = Socket.sockaddr_un("/tmp/sock")
  4191. * p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock"
  4192. *
  4193. */
  4194. static VALUE
  4195. sock_s_unpack_sockaddr_un(VALUE self, SEL sel, VALUE addr)
  4196. {
  4197. struct sockaddr_un * sockaddr;
  4198. char *sun_path;
  4199. VALUE path;
  4200. sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr);
  4201. if (RSTRING_LEN(addr) <
  4202. (char*)&((struct sockaddr *)sockaddr)->sa_family +
  4203. sizeof(((struct sockaddr *)sockaddr)->sa_family) -
  4204. (char*)sockaddr)
  4205. rb_raise(rb_eArgError, "too short sockaddr");
  4206. if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) {
  4207. rb_raise(rb_eArgError, "not an AF_UNIX sockaddr");
  4208. }
  4209. if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) {
  4210. rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %ld",
  4211. RSTRING_LEN(addr), sizeof(struct sockaddr_un));
  4212. }
  4213. sun_path = unixpath(sockaddr, RSTRING_LENINT(addr));
  4214. if (sizeof(struct sockaddr_un) == RSTRING_LEN(addr) &&
  4215. sun_path == sockaddr->sun_path &&
  4216. sun_path + strlen(sun_path) == RSTRING_PTR(addr) + RSTRING_LEN(addr)) {
  4217. rb_raise(rb_eArgError, "sockaddr_un.sun_path not NUL terminated");
  4218. }
  4219. path = rb_str_new2(sun_path);
  4220. OBJ_INFECT(path, addr);
  4221. return path;
  4222. }
  4223. #endif
  4224. #if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32)
  4225. static VALUE
  4226. sockaddr_obj(struct sockaddr *addr)
  4227. {
  4228. socklen_t len;
  4229. #if defined(AF_INET6) && defined(__KAME__)
  4230. struct sockaddr_in6 addr6;
  4231. #endif
  4232. if (addr == NULL)
  4233. return Qnil;
  4234. switch (addr->sa_family) {
  4235. case AF_INET:
  4236. len = (socklen_t)sizeof(struct sockaddr_in);
  4237. break;
  4238. #ifdef AF_INET6
  4239. case AF_INET6:
  4240. len = (socklen_t)sizeof(struct sockaddr_in6);
  4241. # ifdef __KAME__
  4242. /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */
  4243. /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */
  4244. /* convert fe80:1::1 to fe80::1%1 */
  4245. memcpy(&addr6, addr, len);
  4246. addr = (struct sockaddr *)&addr6;
  4247. if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
  4248. addr6.sin6_scope_id == 0 &&
  4249. (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) {
  4250. addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3];
  4251. addr6.sin6_addr.s6_addr[2] = 0;
  4252. addr6.sin6_addr.s6_addr[3] = 0;
  4253. }
  4254. # endif
  4255. break;
  4256. #endif
  4257. #ifdef HAVE_SYS_UN_H
  4258. case AF_UNIX:
  4259. len = (socklen_t)sizeof(struct sockaddr_un);
  4260. break;
  4261. #endif
  4262. default:
  4263. len = (socklen_t)sizeof(struct sockaddr_in);
  4264. break;
  4265. }
  4266. #ifdef SA_LEN
  4267. if (len < (socklen_t)SA_LEN(addr))
  4268. len = (socklen_t)SA_LEN(addr);
  4269. #endif
  4270. return addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil);
  4271. }
  4272. #endif
  4273. #if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) || defined(_WIN32)
  4274. /*
  4275. * call-seq:
  4276. * Socket.ip_address_list => array
  4277. *
  4278. * Returns local IP addresses as an array.
  4279. *
  4280. * The array contains Addrinfo objects.
  4281. *
  4282. * pp Socket.ip_address_list
  4283. * #=> [#<Addrinfo: 127.0.0.1>,
  4284. * #<Addrinfo: 192.168.0.128>,
  4285. * #<Addrinfo: ::1>,
  4286. * ...]
  4287. *
  4288. */
  4289. static VALUE
  4290. socket_s_ip_address_list(VALUE self, SEL sel)
  4291. {
  4292. #if defined(HAVE_GETIFADDRS)
  4293. struct ifaddrs *ifp = NULL;
  4294. struct ifaddrs *p;
  4295. int ret;
  4296. VALUE list;
  4297. ret = getifaddrs(&ifp);
  4298. if (ret == -1) {
  4299. rb_sys_fail("getifaddrs");
  4300. }
  4301. list = rb_ary_new();
  4302. for (p = ifp; p; p = p->ifa_next) {
  4303. if (p->ifa_addr != NULL && IS_IP_FAMILY(p->ifa_addr->sa_family)) {
  4304. rb_ary_push(list, sockaddr_obj(p->ifa_addr));
  4305. }
  4306. }
  4307. freeifaddrs(ifp);
  4308. return list;
  4309. #elif defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)
  4310. /* Solaris if_tcp(7P) */
  4311. /* HP-UX has SIOCGLIFCONF too. But it uses different struct */
  4312. int fd = -1;
  4313. int ret;
  4314. struct lifnum ln;
  4315. struct lifconf lc;
  4316. char *reason = NULL;
  4317. int save_errno;
  4318. int i;
  4319. VALUE list = Qnil;
  4320. lc.lifc_buf = NULL;
  4321. fd = socket(AF_INET, SOCK_DGRAM, 0);
  4322. if (fd == -1)
  4323. rb_sys_fail("socket");
  4324. memset(&ln, 0, sizeof(ln));
  4325. ln.lifn_family = AF_UNSPEC;
  4326. ret = ioctl(fd, SIOCGLIFNUM, &ln);
  4327. if (ret == -1) {
  4328. reason = "SIOCGLIFNUM";
  4329. goto finish;
  4330. }
  4331. memset(&lc, 0, sizeof(lc));
  4332. lc.lifc_family = AF_UNSPEC;
  4333. lc.lifc_flags = 0;
  4334. lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count;
  4335. lc.lifc_req = xmalloc(lc.lifc_len);
  4336. ret = ioctl(fd, SIOCGLIFCONF, &lc);
  4337. if (ret == -1) {
  4338. reason = "SIOCGLIFCONF";
  4339. goto finish;
  4340. }
  4341. list = rb_ary_new();
  4342. for (i = 0; i < ln.lifn_count; i++) {
  4343. struct lifreq *req = &lc.lifc_req[i];
  4344. if (IS_IP_FAMILY(req->lifr_addr.ss_family)) {
  4345. if (req->lifr_addr.ss_family == AF_INET6 &&
  4346. IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) &&
  4347. ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id == 0) {
  4348. struct lifreq req2;
  4349. memcpy(req2.lifr_name, req->lifr_name, LIFNAMSIZ);
  4350. ret = ioctl(fd, SIOCGLIFINDEX, &req2);
  4351. if (ret == -1) {
  4352. reason = "SIOCGLIFINDEX";
  4353. goto finish;
  4354. }
  4355. ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id = req2.lifr_index;
  4356. }
  4357. rb_ary_push(list, sockaddr_obj((struct sockaddr *)&req->lifr_addr));
  4358. }
  4359. }
  4360. finish:
  4361. save_errno = errno;
  4362. if (lc.lifc_buf != NULL)
  4363. xfree(lc.lifc_req);
  4364. if (fd != -1)
  4365. close(fd);
  4366. errno = save_errno;
  4367. if (reason)
  4368. rb_sys_fail(reason);
  4369. return list;
  4370. #elif defined(SIOCGIFCONF)
  4371. int fd = -1;
  4372. int ret;
  4373. #define EXTRA_SPACE (sizeof(struct ifconf) + sizeof(struct sockaddr_storage))
  4374. char initbuf[4096+EXTRA_SPACE];
  4375. char *buf = initbuf;
  4376. int bufsize;
  4377. struct ifconf conf;
  4378. struct ifreq *req;
  4379. VALUE list = Qnil;
  4380. const char *reason = NULL;
  4381. int save_errno;
  4382. fd = socket(AF_INET, SOCK_DGRAM, 0);
  4383. if (fd == -1)
  4384. rb_sys_fail("socket");
  4385. bufsize = sizeof(initbuf);
  4386. buf = initbuf;
  4387. retry:
  4388. conf.ifc_len = bufsize;
  4389. conf.ifc_req = (struct ifreq *)buf;
  4390. /* fprintf(stderr, "bufsize: %d\n", bufsize); */
  4391. ret = ioctl(fd, SIOCGIFCONF, &conf);
  4392. if (ret == -1) {
  4393. reason = "SIOCGIFCONF";
  4394. goto finish;
  4395. }
  4396. /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */
  4397. if (bufsize - EXTRA_SPACE < conf.ifc_len) {
  4398. if (bufsize < conf.ifc_len) {
  4399. /* NetBSD returns required size for all interfaces. */
  4400. bufsize = conf.ifc_len + EXTRA_SPACE;
  4401. }
  4402. else {
  4403. bufsize = bufsize << 1;
  4404. }
  4405. if (buf == initbuf)
  4406. buf = NULL;
  4407. buf = xrealloc(buf, bufsize);
  4408. goto retry;
  4409. }
  4410. close(fd);
  4411. fd = -1;
  4412. list = rb_ary_new();
  4413. req = conf.ifc_req;
  4414. while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) {
  4415. struct sockaddr *addr = &req->ifr_addr;
  4416. if (IS_IP_FAMILY(addr->sa_family)) {
  4417. rb_ary_push(list, sockaddr_obj(addr));
  4418. }
  4419. #ifdef HAVE_SA_LEN
  4420. # ifndef _SIZEOF_ADDR_IFREQ
  4421. # define _SIZEOF_ADDR_IFREQ(r) \
  4422. (sizeof(struct ifreq) + \
  4423. (sizeof(struct sockaddr) < (r).ifr_addr.sa_len ? \
  4424. (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \
  4425. 0))
  4426. # endif
  4427. req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req));
  4428. #else
  4429. req = (struct ifreq *)((char*)req + sizeof(struct ifreq));
  4430. #endif
  4431. }
  4432. finish:
  4433. save_errno = errno;
  4434. if (buf != initbuf)
  4435. xfree(buf);
  4436. if (fd != -1)
  4437. close(fd);
  4438. errno = save_errno;
  4439. if (reason)
  4440. rb_sys_fail(reason);
  4441. return list;
  4442. #undef EXTRA_SPACE
  4443. #elif defined(_WIN32)
  4444. typedef struct ip_adapter_unicast_address_st {
  4445. unsigned LONG_LONG dummy0;
  4446. struct ip_adapter_unicast_address_st *Next;
  4447. struct {
  4448. struct sockaddr *lpSockaddr;
  4449. int iSockaddrLength;
  4450. } Address;
  4451. int dummy1;
  4452. int dummy2;
  4453. int dummy3;
  4454. long dummy4;
  4455. long dummy5;
  4456. long dummy6;
  4457. } ip_adapter_unicast_address_t;
  4458. typedef struct ip_adapter_anycast_address_st {
  4459. unsigned LONG_LONG dummy0;
  4460. struct ip_adapter_anycast_address_st *Next;
  4461. struct {
  4462. struct sockaddr *lpSockaddr;
  4463. int iSockaddrLength;
  4464. } Address;
  4465. } ip_adapter_anycast_address_t;
  4466. typedef struct ip_adapter_addresses_st {
  4467. unsigned LONG_LONG dummy0;
  4468. struct ip_adapter_addresses_st *Next;
  4469. void *dummy1;
  4470. ip_adapter_unicast_address_t *FirstUnicastAddress;
  4471. ip_adapter_anycast_address_t *FirstAnycastAddress;
  4472. void *dummy2;
  4473. void *dummy3;
  4474. void *dummy4;
  4475. void *dummy5;
  4476. void *dummy6;
  4477. BYTE dummy7[8];
  4478. DWORD dummy8;
  4479. DWORD dummy9;
  4480. DWORD dummy10;
  4481. DWORD IfType;
  4482. int OperStatus;
  4483. DWORD dummy12;
  4484. DWORD dummy13[16];
  4485. void *dummy14;
  4486. } ip_adapter_addresses_t;
  4487. typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG);
  4488. HMODULE h;
  4489. GetAdaptersAddresses_t pGetAdaptersAddresses;
  4490. ULONG len;
  4491. DWORD ret;
  4492. ip_adapter_addresses_t *adapters;
  4493. VALUE list;
  4494. h = LoadLibrary("iphlpapi.dll");
  4495. if (!h)
  4496. rb_notimplement();
  4497. pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses");
  4498. if (!pGetAdaptersAddresses) {
  4499. FreeLibrary(h);
  4500. rb_notimplement();
  4501. }
  4502. ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len);
  4503. if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) {
  4504. errno = rb_w32_map_errno(ret);
  4505. FreeLibrary(h);
  4506. rb_sys_fail("GetAdaptersAddresses");
  4507. }
  4508. adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len);
  4509. ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len);
  4510. if (ret != ERROR_SUCCESS) {
  4511. errno = rb_w32_map_errno(ret);
  4512. FreeLibrary(h);
  4513. rb_sys_fail("GetAdaptersAddresses");
  4514. }
  4515. list = rb_ary_new();
  4516. for (; adapters; adapters = adapters->Next) {
  4517. ip_adapter_unicast_address_t *uni;
  4518. ip_adapter_anycast_address_t *any;
  4519. if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */
  4520. continue;
  4521. for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) {
  4522. #ifndef INET6
  4523. if (uni->Address.lpSockaddr->sa_family == AF_INET)
  4524. #else
  4525. if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family))
  4526. #endif
  4527. rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr));
  4528. }
  4529. for (any = adapters->FirstAnycastAddress; any; any = any->Next) {
  4530. #ifndef INET6
  4531. if (any->Address.lpSockaddr->sa_family == AF_INET)
  4532. #else
  4533. if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family))
  4534. #endif
  4535. rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr));
  4536. }
  4537. }
  4538. FreeLibrary(h);
  4539. return list;
  4540. #endif
  4541. }
  4542. #else
  4543. #define socket_s_ip_address_list rb_f_notimplement
  4544. #endif
  4545. typedef struct {
  4546. VALUE inspectname;
  4547. VALUE canonname;
  4548. int pfamily;
  4549. int socktype;
  4550. int protocol;
  4551. socklen_t sockaddr_len;
  4552. struct sockaddr_storage addr;
  4553. } rb_addrinfo_t;
  4554. static void
  4555. addrinfo_mark(void *ptr)
  4556. {
  4557. rb_addrinfo_t *rai = ptr;
  4558. if (rai) {
  4559. //rb_gc_mark(rai->inspectname);
  4560. //rb_gc_mark(rai->canonname);
  4561. }
  4562. }
  4563. static void
  4564. addrinfo_free(rb_addrinfo_t *rai)
  4565. {
  4566. xfree(rai);
  4567. }
  4568. static VALUE
  4569. addrinfo_s_allocate(VALUE klass, SEL sel)
  4570. {
  4571. return Data_Wrap_Struct(klass, addrinfo_mark, addrinfo_free, 0);
  4572. }
  4573. #define IS_ADDRINFO(obj) (RDATA(obj)->dmark == (RUBY_DATA_FUNC)addrinfo_mark)
  4574. static rb_addrinfo_t *
  4575. check_addrinfo(VALUE self)
  4576. {
  4577. Check_Type(self, RUBY_T_DATA);
  4578. if (!IS_ADDRINFO(self)) {
  4579. rb_raise(rb_eTypeError, "wrong argument type %s (expected Addrinfo)",
  4580. rb_class2name(CLASS_OF(self)));
  4581. }
  4582. return DATA_PTR(self);
  4583. }
  4584. static rb_addrinfo_t *
  4585. get_addrinfo(VALUE self)
  4586. {
  4587. rb_addrinfo_t *rai = check_addrinfo(self);
  4588. if (!rai) {
  4589. rb_raise(rb_eTypeError, "uninitialized socket address");
  4590. }
  4591. return rai;
  4592. }
  4593. static rb_addrinfo_t *
  4594. alloc_addrinfo()
  4595. {
  4596. rb_addrinfo_t *rai = ALLOC(rb_addrinfo_t);
  4597. memset(rai, 0, sizeof(rb_addrinfo_t));
  4598. rai->inspectname = Qnil;
  4599. rai->canonname = Qnil;
  4600. return rai;
  4601. }
  4602. static void
  4603. init_addrinfo(rb_addrinfo_t *rai, struct sockaddr *sa, socklen_t len,
  4604. int pfamily, int socktype, int protocol,
  4605. VALUE canonname, VALUE inspectname)
  4606. {
  4607. if (sizeof(rai->addr) < len)
  4608. rb_raise(rb_eArgError, "sockaddr string too big");
  4609. memcpy((void *)&rai->addr, (void *)sa, len);
  4610. rai->sockaddr_len = len;
  4611. rai->pfamily = pfamily;
  4612. rai->socktype = socktype;
  4613. rai->protocol = protocol;
  4614. GC_WB(&rai->canonname, canonname);
  4615. GC_WB(&rai->inspectname, inspectname);
  4616. }
  4617. static VALUE
  4618. addrinfo_new(struct sockaddr *addr, socklen_t len,
  4619. int family, int socktype, int protocol,
  4620. VALUE canonname, VALUE inspectname)
  4621. {
  4622. VALUE a;
  4623. rb_addrinfo_t *rai;
  4624. a = addrinfo_s_allocate(rb_cAddrinfo, 0);
  4625. rai = alloc_addrinfo();
  4626. GC_WB(&(DATA_PTR(a)), rai);
  4627. init_addrinfo(rai, addr, len, family, socktype, protocol, canonname, inspectname);
  4628. return a;
  4629. }
  4630. static struct addrinfo *
  4631. call_getaddrinfo(VALUE node, VALUE service,
  4632. VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
  4633. int socktype_hack)
  4634. {
  4635. struct addrinfo hints, *res;
  4636. MEMZERO(&hints, struct addrinfo, 1);
  4637. hints.ai_family = NIL_P(family) ? PF_UNSPEC : family_arg(family);
  4638. if (!NIL_P(socktype)) {
  4639. hints.ai_socktype = socktype_arg(socktype);
  4640. }
  4641. if (!NIL_P(protocol)) {
  4642. hints.ai_protocol = NUM2INT(protocol);
  4643. }
  4644. if (!NIL_P(flags)) {
  4645. hints.ai_flags = NUM2INT(flags);
  4646. }
  4647. res = sock_getaddrinfo(node, service, &hints, socktype_hack);
  4648. if (res == NULL)
  4649. rb_raise(rb_eSocket, "host not found");
  4650. return res;
  4651. }
  4652. static VALUE make_inspectname(VALUE node, VALUE service, struct addrinfo *res);
  4653. static void
  4654. init_addrinfo_getaddrinfo(rb_addrinfo_t *rai, VALUE node, VALUE service,
  4655. VALUE family, VALUE socktype, VALUE protocol, VALUE flags,
  4656. VALUE inspectnode, VALUE inspectservice)
  4657. {
  4658. struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 1);
  4659. VALUE canonname;
  4660. VALUE inspectname = rb_str_equal(node, inspectnode) ? Qnil : make_inspectname(inspectnode, inspectservice, res);
  4661. canonname = Qnil;
  4662. if (res->ai_canonname) {
  4663. canonname = rb_tainted_str_new_cstr(res->ai_canonname);
  4664. OBJ_FREEZE(canonname);
  4665. }
  4666. init_addrinfo(rai, res->ai_addr, res->ai_addrlen,
  4667. NUM2INT(family), NUM2INT(socktype), NUM2INT(protocol),
  4668. canonname, inspectname);
  4669. freeaddrinfo(res);
  4670. }
  4671. static VALUE
  4672. make_inspectname(VALUE node, VALUE service, struct addrinfo *res)
  4673. {
  4674. VALUE inspectname = Qnil;
  4675. if (res) {
  4676. char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
  4677. int ret;
  4678. ret = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
  4679. sizeof(hbuf), pbuf, sizeof(pbuf),
  4680. NI_NUMERICHOST|NI_NUMERICSERV);
  4681. if (ret == 0) {
  4682. if (TYPE(node) == T_STRING && strcmp(hbuf, RSTRING_PTR(node)) == 0)
  4683. node = Qnil;
  4684. if (TYPE(service) == T_STRING && strcmp(pbuf, RSTRING_PTR(service)) == 0)
  4685. service = Qnil;
  4686. else if (TYPE(service) == T_FIXNUM && atoi(pbuf) == FIX2INT(service))
  4687. service = Qnil;
  4688. }
  4689. }
  4690. if (TYPE(node) == T_STRING) {
  4691. inspectname = rb_str_dup(node);
  4692. }
  4693. if (TYPE(service) == T_STRING) {
  4694. if (NIL_P(inspectname))
  4695. inspectname = rb_sprintf(":%s", StringValueCStr(service));
  4696. else
  4697. rb_str_catf(inspectname, ":%s", StringValueCStr(service));
  4698. }
  4699. else if (TYPE(service) == T_FIXNUM && FIX2INT(service) != 0)
  4700. {
  4701. if (NIL_P(inspectname))
  4702. inspectname = rb_sprintf(":%d", (int)FIX2INT(service));
  4703. else
  4704. rb_str_catf(inspectname, ":%d", (int)FIX2INT(service));
  4705. }
  4706. if (!NIL_P(inspectname)) {
  4707. OBJ_INFECT(inspectname, node);
  4708. OBJ_INFECT(inspectname, service);
  4709. OBJ_FREEZE(inspectname);
  4710. }
  4711. return inspectname;
  4712. }
  4713. static VALUE
  4714. addrinfo_firstonly_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
  4715. {
  4716. VALUE ret;
  4717. VALUE canonname;
  4718. VALUE inspectname;
  4719. struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
  4720. inspectname = make_inspectname(node, service, res);
  4721. canonname = Qnil;
  4722. if (res->ai_canonname) {
  4723. canonname = rb_tainted_str_new_cstr(res->ai_canonname);
  4724. OBJ_FREEZE(canonname);
  4725. }
  4726. ret = addrinfo_new(res->ai_addr, res->ai_addrlen,
  4727. res->ai_family, res->ai_socktype, res->ai_protocol,
  4728. canonname, inspectname);
  4729. freeaddrinfo(res);
  4730. return ret;
  4731. }
  4732. static VALUE
  4733. addrinfo_list_new(VALUE node, VALUE service, VALUE family, VALUE socktype, VALUE protocol, VALUE flags)
  4734. {
  4735. VALUE ret;
  4736. struct addrinfo *r;
  4737. VALUE inspectname;
  4738. struct addrinfo *res = call_getaddrinfo(node, service, family, socktype, protocol, flags, 0);
  4739. inspectname = make_inspectname(node, service, res);
  4740. ret = rb_ary_new();
  4741. for (r = res; r; r = r->ai_next) {
  4742. VALUE addr;
  4743. VALUE canonname = Qnil;
  4744. if (r->ai_canonname) {
  4745. canonname = rb_tainted_str_new_cstr(r->ai_canonname);
  4746. OBJ_FREEZE(canonname);
  4747. }
  4748. addr = addrinfo_new(r->ai_addr, r->ai_addrlen,
  4749. r->ai_family, r->ai_socktype, r->ai_protocol,
  4750. canonname, inspectname);
  4751. rb_ary_push(ret, addr);
  4752. }
  4753. freeaddrinfo(res);
  4754. return ret;
  4755. }
  4756. #ifdef HAVE_SYS_UN_H
  4757. static void
  4758. init_unix_addrinfo(rb_addrinfo_t *rai, VALUE path, int socktype)
  4759. {
  4760. struct sockaddr_un un;
  4761. StringValue(path);
  4762. if (sizeof(un.sun_path) <= (size_t)RSTRING_LEN(path))
  4763. rb_raise(rb_eArgError, "too long unix socket path (max: %dbytes)",
  4764. (int)sizeof(un.sun_path)-1);
  4765. MEMZERO(&un, struct sockaddr_un, 1);
  4766. un.sun_family = AF_UNIX;
  4767. memcpy((void*)&un.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
  4768. init_addrinfo(rai, (struct sockaddr *)&un, (socklen_t)sizeof(un),
  4769. PF_UNIX, socktype, 0, Qnil, Qnil);
  4770. }
  4771. #endif
  4772. /*
  4773. * call-seq:
  4774. * Addrinfo.new(sockaddr) => addrinfo
  4775. * Addrinfo.new(sockaddr, family) => addrinfo
  4776. * Addrinfo.new(sockaddr, family, socktype) => addrinfo
  4777. * Addrinfo.new(sockaddr, family, socktype, protocol) => addrinfo
  4778. *
  4779. * returns a new instance of Addrinfo.
  4780. * The instance contains sockaddr, family, socktype, protocol.
  4781. * sockaddr means struct sockaddr which can be used for connect(2), etc.
  4782. * family, socktype and protocol are integers which is used for arguments of socket(2).
  4783. *
  4784. * sockaddr is specified as an array or a string.
  4785. * The array should be compatible to the value of IPSocket#addr or UNIXSocket#addr.
  4786. * The string should be struct sockaddr as generated by
  4787. * Socket.sockaddr_in or Socket.unpack_sockaddr_un.
  4788. *
  4789. * sockaddr examples:
  4790. * - ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"]
  4791. * - ["AF_INET6", 42304, "ip6-localhost", "::1"]
  4792. * - ["AF_UNIX", "/tmp/sock"]
  4793. * - Socket.sockaddr_in("smtp", "2001:DB8::1")
  4794. * - Socket.sockaddr_in(80, "172.18.22.42")
  4795. * - Socket.sockaddr_in(80, "www.ruby-lang.org")
  4796. * - Socket.sockaddr_un("/tmp/sock")
  4797. *
  4798. * In an AF_INET/AF_INET6 sockaddr array, the 4th element,
  4799. * numeric IP address, is used to construct socket address in the Addrinfo instance.
  4800. * If the 3rd element, textual host name, is non-nil, it is also recorded but used only for Addrinfo#inspect.
  4801. *
  4802. * family is specified as an integer to specify the protocol family such as Socket::PF_INET.
  4803. * It can be a symbol or a string which is the constant name
  4804. * with or without PF_ prefix such as :INET, :INET6, :UNIX, "PF_INET", etc.
  4805. * If omitted, PF_UNSPEC is assumed.
  4806. *
  4807. * socktype is specified as an integer to specify the socket type such as Socket::SOCK_STREAM.
  4808. * It can be a symbol or a string which is the constant name
  4809. * with or without SOCK_ prefix such as :STREAM, :DGRAM, :RAW, "SOCK_STREAM", etc.
  4810. * If omitted, 0 is assumed.
  4811. *
  4812. * protocol is specified as an integer to specify the protocol such as Socket::IPPROTO_TCP.
  4813. * It must be an integer, unlike family and socktype.
  4814. * If omitted, 0 is assumed.
  4815. * Note that 0 is reasonable value for most protocols, except raw socket.
  4816. *
  4817. */
  4818. static VALUE
  4819. addrinfo_initialize(VALUE self, SEL sel, int argc, VALUE *argv)
  4820. {
  4821. rb_addrinfo_t *rai;
  4822. VALUE sockaddr_arg, sockaddr_ary, pfamily, socktype, protocol;
  4823. int i_pfamily, i_socktype, i_protocol;
  4824. struct sockaddr *sockaddr_ptr;
  4825. socklen_t sockaddr_len;
  4826. VALUE canonname = Qnil, inspectname = Qnil;
  4827. if (check_addrinfo(self))
  4828. rb_raise(rb_eTypeError, "already initialized socket address");
  4829. rai = alloc_addrinfo();
  4830. GC_WB(&(DATA_PTR(self)), rai);
  4831. rb_scan_args(argc, argv, "13", &sockaddr_arg, &pfamily, &socktype, &protocol);
  4832. i_pfamily = NIL_P(pfamily) ? PF_UNSPEC : family_arg(pfamily);
  4833. i_socktype = NIL_P(socktype) ? 0 : socktype_arg(socktype);
  4834. i_protocol = NIL_P(protocol) ? 0 : NUM2INT(protocol);
  4835. sockaddr_ary = rb_check_array_type(sockaddr_arg);
  4836. if (!NIL_P(sockaddr_ary)) {
  4837. VALUE afamily = rb_ary_entry(sockaddr_ary, 0);
  4838. int af;
  4839. StringValue(afamily);
  4840. if (family_to_int(RSTRING_PTR(afamily), RSTRING_LENINT(afamily), &af) == -1)
  4841. rb_raise(rb_eSocket, "unknown address family: %s", StringValueCStr(afamily));
  4842. switch (af) {
  4843. case AF_INET: /* ["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"] */
  4844. #ifdef INET6
  4845. case AF_INET6: /* ["AF_INET6", 42304, "ip6-localhost", "::1"] */
  4846. #endif
  4847. {
  4848. VALUE service = rb_ary_entry(sockaddr_ary, 1);
  4849. VALUE nodename = rb_ary_entry(sockaddr_ary, 2);
  4850. VALUE numericnode = rb_ary_entry(sockaddr_ary, 3);
  4851. int flags;
  4852. service = INT2NUM(NUM2INT(service));
  4853. if (!NIL_P(nodename))
  4854. StringValue(nodename);
  4855. StringValue(numericnode);
  4856. flags = AI_NUMERICHOST;
  4857. #ifdef AI_NUMERICSERV
  4858. flags |= AI_NUMERICSERV;
  4859. #endif
  4860. init_addrinfo_getaddrinfo(rai, numericnode, service,
  4861. INT2NUM(i_pfamily ? i_pfamily : af), INT2NUM(i_socktype), INT2NUM(i_protocol),
  4862. INT2NUM(flags),
  4863. nodename, service);
  4864. break;
  4865. }
  4866. #ifdef HAVE_SYS_UN_H
  4867. case AF_UNIX: /* ["AF_UNIX", "/tmp/sock"] */
  4868. {
  4869. VALUE path = rb_ary_entry(sockaddr_ary, 1);
  4870. StringValue(path);
  4871. init_unix_addrinfo(rai, path, SOCK_STREAM);
  4872. break;
  4873. }
  4874. #endif
  4875. default:
  4876. rb_raise(rb_eSocket, "unexpected address family");
  4877. }
  4878. }
  4879. else {
  4880. StringValue(sockaddr_arg);
  4881. sockaddr_ptr = (struct sockaddr *)RSTRING_PTR(sockaddr_arg);
  4882. sockaddr_len = RSTRING_LENINT(sockaddr_arg);
  4883. init_addrinfo(rai, sockaddr_ptr, sockaddr_len,
  4884. i_pfamily, i_socktype, i_protocol,
  4885. canonname, inspectname);
  4886. }
  4887. return self;
  4888. }
  4889. static int
  4890. get_afamily(struct sockaddr *addr, socklen_t len)
  4891. {
  4892. if ((char*)&addr->sa_family + sizeof(addr->sa_family) - (char*)addr <= len)
  4893. return addr->sa_family;
  4894. else
  4895. return AF_UNSPEC;
  4896. }
  4897. static int
  4898. ai_get_afamily(rb_addrinfo_t *rai)
  4899. {
  4900. return get_afamily((struct sockaddr *)&rai->addr, rai->sockaddr_len);
  4901. }
  4902. static VALUE
  4903. inspect_sockaddr(VALUE addrinfo, VALUE ret)
  4904. {
  4905. rb_addrinfo_t *rai = get_addrinfo(addrinfo);
  4906. if (rai->sockaddr_len == 0) {
  4907. rb_str_cat2(ret, "empty-sockaddr");
  4908. }
  4909. else if ((long)rai->sockaddr_len < ((char*)&rai->addr.ss_family + sizeof(rai->addr.ss_family)) - (char*)&rai->addr)
  4910. rb_str_cat2(ret, "too-short-sockaddr");
  4911. else {
  4912. switch (rai->addr.ss_family) {
  4913. case AF_INET:
  4914. {
  4915. struct sockaddr_in *addr;
  4916. int port;
  4917. if (rai->sockaddr_len < sizeof(struct sockaddr_in)) {
  4918. rb_str_cat2(ret, "too-short-AF_INET-sockaddr");
  4919. }
  4920. else {
  4921. addr = (struct sockaddr_in *)&rai->addr;
  4922. rb_str_catf(ret, "%d.%d.%d.%d",
  4923. ((unsigned char*)&addr->sin_addr)[0],
  4924. ((unsigned char*)&addr->sin_addr)[1],
  4925. ((unsigned char*)&addr->sin_addr)[2],
  4926. ((unsigned char*)&addr->sin_addr)[3]);
  4927. port = ntohs(addr->sin_port);
  4928. if (port)
  4929. rb_str_catf(ret, ":%d", port);
  4930. if (sizeof(struct sockaddr_in) < rai->sockaddr_len)
  4931. rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(rai->sockaddr_len - sizeof(struct sockaddr_in)));
  4932. }
  4933. break;
  4934. }
  4935. #ifdef AF_INET6
  4936. case AF_INET6:
  4937. {
  4938. struct sockaddr_in6 *addr;
  4939. char hbuf[1024];
  4940. int port;
  4941. int error;
  4942. if (rai->sockaddr_len < sizeof(struct sockaddr_in6)) {
  4943. rb_str_cat2(ret, "too-short-AF_INET6-sockaddr");
  4944. }
  4945. else {
  4946. addr = (struct sockaddr_in6 *)&rai->addr;
  4947. /* use getnameinfo for scope_id.
  4948. * RFC 4007: IPv6 Scoped Address Architecture
  4949. * draft-ietf-ipv6-scope-api-00.txt: Scoped Address Extensions to the IPv6 Basic Socket API
  4950. */
  4951. error = getnameinfo((struct sockaddr *)&rai->addr, rai->sockaddr_len,
  4952. hbuf, (socklen_t)sizeof(hbuf), NULL, 0,
  4953. NI_NUMERICHOST|NI_NUMERICSERV);
  4954. if (error) {
  4955. raise_socket_error("getnameinfo", error);
  4956. }
  4957. if (addr->sin6_port == 0) {
  4958. rb_str_cat2(ret, hbuf);
  4959. }
  4960. else {
  4961. port = ntohs(addr->sin6_port);
  4962. rb_str_catf(ret, "[%s]:%d", hbuf, port);
  4963. }
  4964. if (sizeof(struct sockaddr_in6) < rai->sockaddr_len)
  4965. rb_str_catf(ret, "(sockaddr %d bytes too long)", (int)(rai->sockaddr_len - sizeof(struct sockaddr_in6)));
  4966. }
  4967. break;
  4968. }
  4969. #endif
  4970. #ifdef HAVE_SYS_UN_H
  4971. case AF_UNIX:
  4972. {
  4973. struct sockaddr_un *addr = (struct sockaddr_un *)&rai->addr;
  4974. char *p, *s, *t, *e;
  4975. s = addr->sun_path;
  4976. e = (char*)addr + rai->sockaddr_len;
  4977. if (e < s)
  4978. rb_str_cat2(ret, "too-short-AF_UNIX-sockaddr");
  4979. else if (s == e)
  4980. rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr");
  4981. else {
  4982. int printable_only = 1;
  4983. p = s;
  4984. while (p < e && *p != '\0') {
  4985. printable_only = printable_only && ISPRINT(*p) && !ISSPACE(*p);
  4986. p++;
  4987. }
  4988. t = p;
  4989. while (p < e && *p == '\0')
  4990. p++;
  4991. if (printable_only && /* only printable, no space */
  4992. t < e && /* NUL terminated */
  4993. p == e) { /* no data after NUL */
  4994. if (s == t)
  4995. rb_str_cat2(ret, "empty-path-AF_UNIX-sockaddr");
  4996. else if (s[0] == '/') /* absolute path */
  4997. rb_str_cat2(ret, s);
  4998. else
  4999. rb_str_catf(ret, "AF_UNIX %s", s);
  5000. }
  5001. else {
  5002. rb_str_cat2(ret, "AF_UNIX");
  5003. e = (char *)addr->sun_path + sizeof(addr->sun_path);
  5004. while (s < e && *(e-1) == '\0')
  5005. e--;
  5006. while (s < e)
  5007. rb_str_catf(ret, ":%02x", (unsigned char)*s++);
  5008. }
  5009. if (addr->sun_path + sizeof(addr->sun_path) < (char*)&rai->addr + rai->sockaddr_len)
  5010. rb_str_catf(ret, "(sockaddr %d bytes too long)",
  5011. (int)(rai->sockaddr_len - (addr->sun_path + sizeof(addr->sun_path) - (char*)&rai->addr)));
  5012. }
  5013. break;
  5014. }
  5015. #endif
  5016. default:
  5017. {
  5018. ID id = intern_family(rai->addr.ss_family);
  5019. if (id == 0)
  5020. rb_str_catf(ret, "unknown address family %d", rai->addr.ss_family);
  5021. else
  5022. rb_str_catf(ret, "%s address format unknown", rb_id2name(id));
  5023. break;
  5024. }
  5025. }
  5026. }
  5027. return ret;
  5028. }
  5029. /*
  5030. * call-seq:
  5031. * addrinfo.inspect => string
  5032. *
  5033. * returns a string which shows addrinfo in human-readable form.
  5034. *
  5035. * Addrinfo.tcp("localhost", 80).inspect #=> "#<Addrinfo: 127.0.0.1:80 TCP (localhost:80)>"
  5036. * Addrinfo.unix("/tmp/sock").inspect #=> "#<Addrinfo: /tmp/sock SOCK_STREAM>"
  5037. *
  5038. */
  5039. static VALUE
  5040. addrinfo_inspect(VALUE self, SEL sel)
  5041. {
  5042. rb_addrinfo_t *rai = get_addrinfo(self);
  5043. int internet_p;
  5044. VALUE ret;
  5045. ret = rb_sprintf("#<%s: ", rb_obj_classname(self));
  5046. inspect_sockaddr(self, ret);
  5047. if (rai->pfamily && ai_get_afamily(rai) != rai->pfamily) {
  5048. ID id = intern_protocol_family(rai->pfamily);
  5049. if (id)
  5050. rb_str_catf(ret, " %s", rb_id2name(id));
  5051. else
  5052. rb_str_catf(ret, " PF_\?\?\?(%d)", rai->pfamily);
  5053. }
  5054. internet_p = rai->pfamily == PF_INET;
  5055. #ifdef INET6
  5056. internet_p = internet_p || rai->pfamily == PF_INET6;
  5057. #endif
  5058. if (internet_p && rai->socktype == SOCK_STREAM &&
  5059. (rai->protocol == 0 || rai->protocol == IPPROTO_TCP)) {
  5060. rb_str_cat2(ret, " TCP");
  5061. }
  5062. else if (internet_p && rai->socktype == SOCK_DGRAM &&
  5063. (rai->protocol == 0 || rai->protocol == IPPROTO_UDP)) {
  5064. rb_str_cat2(ret, " UDP");
  5065. }
  5066. else {
  5067. if (rai->socktype) {
  5068. ID id = intern_socktype(rai->socktype);
  5069. if (id)
  5070. rb_str_catf(ret, " %s", rb_id2name(id));
  5071. else
  5072. rb_str_catf(ret, " SOCK_\?\?\?(%d)", rai->socktype);
  5073. }
  5074. if (rai->protocol) {
  5075. if (internet_p) {
  5076. ID id = intern_ipproto(rai->protocol);
  5077. if (id)
  5078. rb_str_catf(ret, " %s", rb_id2name(id));
  5079. else
  5080. goto unknown_protocol;
  5081. }
  5082. else {
  5083. unknown_protocol:
  5084. rb_str_catf(ret, " UNKNOWN_PROTOCOL(%d)", rai->protocol);
  5085. }
  5086. }
  5087. }
  5088. if (!NIL_P(rai->canonname)) {
  5089. VALUE name = rai->canonname;
  5090. rb_str_catf(ret, " %s", StringValueCStr(name));
  5091. }
  5092. if (!NIL_P(rai->inspectname)) {
  5093. VALUE name = rai->inspectname;
  5094. rb_str_catf(ret, " (%s)", StringValueCStr(name));
  5095. }
  5096. rb_str_buf_cat2(ret, ">");
  5097. return ret;
  5098. }
  5099. /*
  5100. * call-seq:
  5101. * addrinfo.inspect_sockaddr => string
  5102. *
  5103. * returns a string which shows the sockaddr in _addrinfo_ with human-readable form.
  5104. *
  5105. * Addrinfo.tcp("localhost", 80).inspect_sockaddr #=> "127.0.0.1:80"
  5106. * Addrinfo.tcp("ip6-localhost", 80).inspect_sockaddr #=> "[::1]:80"
  5107. * Addrinfo.unix("/tmp/sock").inspect_sockaddr #=> "/tmp/sock"
  5108. *
  5109. */
  5110. static VALUE
  5111. addrinfo_inspect_sockaddr(VALUE self, SEL sel)
  5112. {
  5113. return inspect_sockaddr(self, rb_str_new("", 0));
  5114. }
  5115. /*
  5116. * call-seq:
  5117. * addrinfo.afamily => integer
  5118. *
  5119. * returns the address family as an integer.
  5120. *
  5121. * Addrinfo.tcp("localhost", 80).afamily == Socket::AF_INET #=> true
  5122. *
  5123. */
  5124. static VALUE
  5125. addrinfo_afamily(VALUE self, SEL sel)
  5126. {
  5127. rb_addrinfo_t *rai = get_addrinfo(self);
  5128. return INT2NUM(ai_get_afamily(rai));
  5129. }
  5130. /*
  5131. * call-seq:
  5132. * addrinfo.pfamily => integer
  5133. *
  5134. * returns the protocol family as an integer.
  5135. *
  5136. * Addrinfo.tcp("localhost", 80).pfamily == Socket::PF_INET #=> true
  5137. *
  5138. */
  5139. static VALUE
  5140. addrinfo_pfamily(VALUE self, SEL sel)
  5141. {
  5142. rb_addrinfo_t *rai = get_addrinfo(self);
  5143. return INT2NUM(rai->pfamily);
  5144. }
  5145. /*
  5146. * call-seq:
  5147. * addrinfo.socktype => integer
  5148. *
  5149. * returns the socket type as an integer.
  5150. *
  5151. * Addrinfo.tcp("localhost", 80).socktype == Socket::SOCK_STREAM #=> true
  5152. *
  5153. */
  5154. static VALUE
  5155. addrinfo_socktype(VALUE self, SEL sel)
  5156. {
  5157. rb_addrinfo_t *rai = get_addrinfo(self);
  5158. return INT2NUM(rai->socktype);
  5159. }
  5160. /*
  5161. * call-seq:
  5162. * addrinfo.protocol => integer
  5163. *
  5164. * returns the socket type as an integer.
  5165. *
  5166. * Addrinfo.tcp("localhost", 80).protocol == Socket::IPPROTO_TCP #=> true
  5167. *
  5168. */
  5169. static VALUE
  5170. addrinfo_protocol(VALUE self, SEL sel)
  5171. {
  5172. rb_addrinfo_t *rai = get_addrinfo(self);
  5173. return INT2NUM(rai->protocol);
  5174. }
  5175. /*
  5176. * call-seq:
  5177. * addrinfo.to_sockaddr => string
  5178. *
  5179. * returns the socket address as packed struct sockaddr string.
  5180. *
  5181. * Addrinfo.tcp("localhost", 80).to_sockaddr
  5182. * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
  5183. *
  5184. */
  5185. static VALUE
  5186. addrinfo_to_sockaddr(VALUE self, SEL sel)
  5187. {
  5188. rb_addrinfo_t *rai = get_addrinfo(self);
  5189. VALUE ret;
  5190. ret = rb_str_new((char*)&rai->addr, rai->sockaddr_len);
  5191. OBJ_INFECT(ret, self);
  5192. return ret;
  5193. }
  5194. /*
  5195. * call-seq:
  5196. * addrinfo.canonname => string or nil
  5197. *
  5198. * returns the canonical name as an string.
  5199. *
  5200. * nil is returned if no canonical name.
  5201. *
  5202. * The canonical name is set by Addrinfo.getaddrinfo when AI_CANONNAME is specified.
  5203. *
  5204. * list = Addrinfo.getaddrinfo("www.ruby-lang.org", 80, :INET, :STREAM, nil, Socket::AI_CANONNAME)
  5205. * p list[0] #=> #<Addrinfo: 221.186.184.68:80 TCP carbon.ruby-lang.org (www.ruby-lang.org:80)>
  5206. * p list[0].canonname #=> "carbon.ruby-lang.org"
  5207. *
  5208. */
  5209. static VALUE
  5210. addrinfo_canonname(VALUE self, SEL sel)
  5211. {
  5212. rb_addrinfo_t *rai = get_addrinfo(self);
  5213. return rai->canonname;
  5214. }
  5215. /*
  5216. * call-seq:
  5217. * addrinfo.ip? => true or false
  5218. *
  5219. * returns true if addrinfo is internet (IPv4/IPv6) address.
  5220. * returns false otherwise.
  5221. *
  5222. * Addrinfo.tcp("127.0.0.1", 80).ip? #=> true
  5223. * Addrinfo.tcp("::1", 80).ip? #=> true
  5224. * Addrinfo.unix("/tmp/sock").ip? #=> false
  5225. *
  5226. */
  5227. static VALUE
  5228. addrinfo_ip_p(VALUE self, SEL sel)
  5229. {
  5230. rb_addrinfo_t *rai = get_addrinfo(self);
  5231. int family = ai_get_afamily(rai);
  5232. return IS_IP_FAMILY(family) ? Qtrue : Qfalse;
  5233. }
  5234. /*
  5235. * call-seq:
  5236. * addrinfo.ipv4? => true or false
  5237. *
  5238. * returns true if addrinfo is IPv4 address.
  5239. * returns false otherwise.
  5240. *
  5241. * Addrinfo.tcp("127.0.0.1", 80).ipv4? #=> true
  5242. * Addrinfo.tcp("::1", 80).ipv4? #=> false
  5243. * Addrinfo.unix("/tmp/sock").ipv4? #=> false
  5244. *
  5245. */
  5246. static VALUE
  5247. addrinfo_ipv4_p(VALUE self, SEL sel)
  5248. {
  5249. rb_addrinfo_t *rai = get_addrinfo(self);
  5250. return ai_get_afamily(rai) == AF_INET ? Qtrue : Qfalse;
  5251. }
  5252. /*
  5253. * call-seq:
  5254. * addrinfo.ipv6? => true or false
  5255. *
  5256. * returns true if addrinfo is IPv6 address.
  5257. * returns false otherwise.
  5258. *
  5259. * Addrinfo.tcp("127.0.0.1", 80).ipv6? #=> false
  5260. * Addrinfo.tcp("::1", 80).ipv6? #=> true
  5261. * Addrinfo.unix("/tmp/sock").ipv6? #=> false
  5262. *
  5263. */
  5264. static VALUE
  5265. addrinfo_ipv6_p(VALUE self, SEL sel)
  5266. {
  5267. #ifdef AF_INET6
  5268. rb_addrinfo_t *rai = get_addrinfo(self);
  5269. return ai_get_afamily(rai) == AF_INET6 ? Qtrue : Qfalse;
  5270. #else
  5271. return Qfalse;
  5272. #endif
  5273. }
  5274. /*
  5275. * call-seq:
  5276. * addrinfo.unix? => true or false
  5277. *
  5278. * returns true if addrinfo is UNIX address.
  5279. * returns false otherwise.
  5280. *
  5281. * Addrinfo.tcp("127.0.0.1", 80).unix? #=> false
  5282. * Addrinfo.tcp("::1", 80).unix? #=> false
  5283. * Addrinfo.unix("/tmp/sock").unix? #=> true
  5284. *
  5285. */
  5286. static VALUE
  5287. addrinfo_unix_p(VALUE self, SEL sel)
  5288. {
  5289. rb_addrinfo_t *rai = get_addrinfo(self);
  5290. #ifdef AF_UNIX
  5291. return ai_get_afamily(rai) == AF_UNIX ? Qtrue : Qfalse;
  5292. #else
  5293. return Qfalse;
  5294. #endif
  5295. }
  5296. /*
  5297. * call-seq:
  5298. * addrinfo.getnameinfo => [nodename, service]
  5299. * addrinfo.getnameinfo(flags) => [nodename, service]
  5300. *
  5301. * returns nodename and service as a pair of strings.
  5302. * This converts struct sockaddr in addrinfo to textual representation.
  5303. *
  5304. * flags should be bitwise OR of Socket::NI_??? constants.
  5305. *
  5306. * Addrinfo.tcp("127.0.0.1", 80).getnameinfo #=> ["localhost", "www"]
  5307. *
  5308. * Addrinfo.tcp("127.0.0.1", 80).getnameinfo(Socket::NI_NUMERICSERV)
  5309. * #=> ["localhost", "80"]
  5310. */
  5311. static VALUE
  5312. addrinfo_getnameinfo(VALUE self, SEL sel, int argc, VALUE *argv)
  5313. {
  5314. rb_addrinfo_t *rai = get_addrinfo(self);
  5315. VALUE vflags;
  5316. char hbuf[1024], pbuf[1024];
  5317. int flags, error;
  5318. rb_scan_args(argc, argv, "01", &vflags);
  5319. flags = NIL_P(vflags) ? 0 : NUM2INT(vflags);
  5320. if (rai->socktype == SOCK_DGRAM)
  5321. flags |= NI_DGRAM;
  5322. error = getnameinfo((struct sockaddr *)&rai->addr, rai->sockaddr_len,
  5323. hbuf, (socklen_t)sizeof(hbuf), pbuf, (socklen_t)sizeof(pbuf),
  5324. flags);
  5325. if (error) {
  5326. raise_socket_error("getnameinfo", error);
  5327. }
  5328. return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
  5329. }
  5330. /*
  5331. * call-seq:
  5332. * addrinfo.ip_unpack => [addr, port]
  5333. *
  5334. * Returns the IP address and port number as 2-element array.
  5335. *
  5336. * Addrinfo.tcp("127.0.0.1", 80).ip_unpack #=> ["127.0.0.1", 80]
  5337. * Addrinfo.tcp("::1", 80).ip_unpack #=> ["::1", 80]
  5338. */
  5339. static VALUE
  5340. addrinfo_ip_unpack(VALUE self, SEL sel)
  5341. {
  5342. rb_addrinfo_t *rai = get_addrinfo(self);
  5343. int family = ai_get_afamily(rai);
  5344. VALUE vflags;
  5345. VALUE ret, portstr;
  5346. if (!IS_IP_FAMILY(family))
  5347. rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
  5348. vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV);
  5349. ret = addrinfo_getnameinfo(self, 0, 1, &vflags);
  5350. portstr = rb_ary_entry(ret, 1);
  5351. rb_ary_store(ret, 1, INT2NUM(atoi(StringValueCStr(portstr))));
  5352. return ret;
  5353. }
  5354. /*
  5355. * call-seq:
  5356. * addrinfo.ip_address => string
  5357. *
  5358. * Returns the IP address as a string.
  5359. *
  5360. * Addrinfo.tcp("127.0.0.1", 80).ip_address #=> "127.0.0.1"
  5361. * Addrinfo.tcp("::1", 80).ip_address #=> "::1"
  5362. */
  5363. static VALUE
  5364. addrinfo_ip_address(VALUE self, SEL sel)
  5365. {
  5366. rb_addrinfo_t *rai = get_addrinfo(self);
  5367. int family = ai_get_afamily(rai);
  5368. VALUE vflags;
  5369. VALUE ret;
  5370. if (!IS_IP_FAMILY(family))
  5371. rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
  5372. vflags = INT2NUM(NI_NUMERICHOST|NI_NUMERICSERV);
  5373. ret = addrinfo_getnameinfo(self, 0, 1, &vflags);
  5374. return rb_ary_entry(ret, 0);
  5375. }
  5376. /*
  5377. * call-seq:
  5378. * addrinfo.ip_port => port
  5379. *
  5380. * Returns the port number as an integer.
  5381. *
  5382. * Addrinfo.tcp("127.0.0.1", 80).ip_port #=> 80
  5383. * Addrinfo.tcp("::1", 80).ip_port #=> 80
  5384. */
  5385. static VALUE
  5386. addrinfo_ip_port(VALUE self, SEL sel)
  5387. {
  5388. rb_addrinfo_t *rai = get_addrinfo(self);
  5389. int family = ai_get_afamily(rai);
  5390. int port;
  5391. if (!IS_IP_FAMILY(family)) {
  5392. bad_family:
  5393. #ifdef AF_INET6
  5394. rb_raise(rb_eSocket, "need IPv4 or IPv6 address");
  5395. #else
  5396. rb_raise(rb_eSocket, "need IPv4 address");
  5397. #endif
  5398. }
  5399. switch (family) {
  5400. case AF_INET:
  5401. if (rai->sockaddr_len != sizeof(struct sockaddr_in))
  5402. rb_raise(rb_eSocket, "unexpected sockaddr size for IPv4");
  5403. port = ntohs(((struct sockaddr_in *)&rai->addr)->sin_port);
  5404. break;
  5405. #ifdef AF_INET6
  5406. case AF_INET6:
  5407. if (rai->sockaddr_len != sizeof(struct sockaddr_in6))
  5408. rb_raise(rb_eSocket, "unexpected sockaddr size for IPv6");
  5409. port = ntohs(((struct sockaddr_in6 *)&rai->addr)->sin6_port);
  5410. break;
  5411. #endif
  5412. default:
  5413. goto bad_family;
  5414. }
  5415. return INT2NUM(port);
  5416. }
  5417. static int
  5418. extract_in_addr(VALUE self, uint32_t *addrp)
  5419. {
  5420. rb_addrinfo_t *rai = get_addrinfo(self);
  5421. int family = ai_get_afamily(rai);
  5422. if (family != AF_INET) return 0;
  5423. *addrp = ntohl(((struct sockaddr_in *)&rai->addr)->sin_addr.s_addr);
  5424. return 1;
  5425. }
  5426. /*
  5427. * Returns true for IPv4 private address (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).
  5428. * It returns false otherwise.
  5429. */
  5430. static VALUE
  5431. addrinfo_ipv4_private_p(VALUE self, SEL sel)
  5432. {
  5433. uint32_t a;
  5434. if (!extract_in_addr(self, &a)) return Qfalse;
  5435. if ((a & 0xff000000) == 0x0a000000 || /* 10.0.0.0/8 */
  5436. (a & 0xfff00000) == 0xac100000 || /* 172.16.0.0/12 */
  5437. (a & 0xffff0000) == 0xc0a80000) /* 192.168.0.0/16 */
  5438. return Qtrue;
  5439. return Qfalse;
  5440. }
  5441. /*
  5442. * Returns true for IPv4 loopback address (127.0.0.0/8).
  5443. * It returns false otherwise.
  5444. */
  5445. static VALUE
  5446. addrinfo_ipv4_loopback_p(VALUE self, SEL sel)
  5447. {
  5448. uint32_t a;
  5449. if (!extract_in_addr(self, &a)) return Qfalse;
  5450. if ((a & 0xff000000) == 0x7f000000) /* 127.0.0.0/8 */
  5451. return Qtrue;
  5452. return Qfalse;
  5453. }
  5454. /*
  5455. * Returns true for IPv4 multicast address (224.0.0.0/4).
  5456. * It returns false otherwise.
  5457. */
  5458. static VALUE
  5459. addrinfo_ipv4_multicast_p(VALUE self, SEL sel)
  5460. {
  5461. uint32_t a;
  5462. if (!extract_in_addr(self, &a)) return Qfalse;
  5463. if ((a & 0xf0000000) == 0xe0000000) /* 224.0.0.0/4 */
  5464. return Qtrue;
  5465. return Qfalse;
  5466. }
  5467. #ifdef INET6
  5468. static struct in6_addr *
  5469. extract_in6_addr(VALUE self)
  5470. {
  5471. rb_addrinfo_t *rai = get_addrinfo(self);
  5472. int family = ai_get_afamily(rai);
  5473. if (family != AF_INET6) return NULL;
  5474. return &((struct sockaddr_in6 *)&rai->addr)->sin6_addr;
  5475. }
  5476. /*
  5477. * Returns true for IPv6 unspecified address (::).
  5478. * It returns false otherwise.
  5479. */
  5480. static VALUE
  5481. addrinfo_ipv6_unspecified_p(VALUE self, SEL sel)
  5482. {
  5483. struct in6_addr *addr = extract_in6_addr(self);
  5484. if (addr && IN6_IS_ADDR_UNSPECIFIED(addr)) return Qtrue;
  5485. return Qfalse;
  5486. }
  5487. /*
  5488. * Returns true for IPv6 loopback address (::1).
  5489. * It returns false otherwise.
  5490. */
  5491. static VALUE
  5492. addrinfo_ipv6_loopback_p(VALUE self, SEL sel)
  5493. {
  5494. struct in6_addr *addr = extract_in6_addr(self);
  5495. if (addr && IN6_IS_ADDR_LOOPBACK(addr)) return Qtrue;
  5496. return Qfalse;
  5497. }
  5498. /*
  5499. * Returns true for IPv6 multicast address (ff00::/8).
  5500. * It returns false otherwise.
  5501. */
  5502. static VALUE
  5503. addrinfo_ipv6_multicast_p(VALUE self, SEL sel)
  5504. {
  5505. struct in6_addr *addr = extract_in6_addr(self);
  5506. if (addr && IN6_IS_ADDR_MULTICAST(addr)) return Qtrue;
  5507. return Qfalse;
  5508. }
  5509. /*
  5510. * Returns true for IPv6 link local address (ff80::/10).
  5511. * It returns false otherwise.
  5512. */
  5513. static VALUE
  5514. addrinfo_ipv6_linklocal_p(VALUE self, SEL sel)
  5515. {
  5516. struct in6_addr *addr = extract_in6_addr(self);
  5517. if (addr && IN6_IS_ADDR_LINKLOCAL(addr)) return Qtrue;
  5518. return Qfalse;
  5519. }
  5520. /*
  5521. * Returns true for IPv6 site local address (ffc0::/10).
  5522. * It returns false otherwise.
  5523. */
  5524. static VALUE
  5525. addrinfo_ipv6_sitelocal_p(VALUE self, SEL sel)
  5526. {
  5527. struct in6_addr *addr = extract_in6_addr(self);
  5528. if (addr && IN6_IS_ADDR_SITELOCAL(addr)) return Qtrue;
  5529. return Qfalse;
  5530. }
  5531. /*
  5532. * Returns true for IPv4-mapped IPv6 address (::ffff:0:0/80).
  5533. * It returns false otherwise.
  5534. */
  5535. static VALUE
  5536. addrinfo_ipv6_v4mapped_p(VALUE self, SEL sel)
  5537. {
  5538. struct in6_addr *addr = extract_in6_addr(self);
  5539. if (addr && IN6_IS_ADDR_V4MAPPED(addr)) return Qtrue;
  5540. return Qfalse;
  5541. }
  5542. /*
  5543. * Returns true for IPv4-compatible IPv6 address (::/80).
  5544. * It returns false otherwise.
  5545. */
  5546. static VALUE
  5547. addrinfo_ipv6_v4compat_p(VALUE self, SEL sel)
  5548. {
  5549. struct in6_addr *addr = extract_in6_addr(self);
  5550. if (addr && IN6_IS_ADDR_V4COMPAT(addr)) return Qtrue;
  5551. return Qfalse;
  5552. }
  5553. /*
  5554. * Returns true for IPv6 multicast node-local scope address.
  5555. * It returns false otherwise.
  5556. */
  5557. static VALUE
  5558. addrinfo_ipv6_mc_nodelocal_p(VALUE self, SEL sel)
  5559. {
  5560. struct in6_addr *addr = extract_in6_addr(self);
  5561. if (addr && IN6_IS_ADDR_MC_NODELOCAL(addr)) return Qtrue;
  5562. return Qfalse;
  5563. }
  5564. /*
  5565. * Returns true for IPv6 multicast link-local scope address.
  5566. * It returns false otherwise.
  5567. */
  5568. static VALUE
  5569. addrinfo_ipv6_mc_linklocal_p(VALUE self, SEL sel)
  5570. {
  5571. struct in6_addr *addr = extract_in6_addr(self);
  5572. if (addr && IN6_IS_ADDR_MC_LINKLOCAL(addr)) return Qtrue;
  5573. return Qfalse;
  5574. }
  5575. /*
  5576. * Returns true for IPv6 multicast site-local scope address.
  5577. * It returns false otherwise.
  5578. */
  5579. static VALUE
  5580. addrinfo_ipv6_mc_sitelocal_p(VALUE self, SEL sel)
  5581. {
  5582. struct in6_addr *addr = extract_in6_addr(self);
  5583. if (addr && IN6_IS_ADDR_MC_SITELOCAL(addr)) return Qtrue;
  5584. return Qfalse;
  5585. }
  5586. /*
  5587. * Returns true for IPv6 multicast organization-local scope address.
  5588. * It returns false otherwise.
  5589. */
  5590. static VALUE
  5591. addrinfo_ipv6_mc_orglocal_p(VALUE self, SEL sel)
  5592. {
  5593. struct in6_addr *addr = extract_in6_addr(self);
  5594. if (addr && IN6_IS_ADDR_MC_ORGLOCAL(addr)) return Qtrue;
  5595. return Qfalse;
  5596. }
  5597. /*
  5598. * Returns true for IPv6 multicast global scope address.
  5599. * It returns false otherwise.
  5600. */
  5601. static VALUE
  5602. addrinfo_ipv6_mc_global_p(VALUE self, SEL sel)
  5603. {
  5604. struct in6_addr *addr = extract_in6_addr(self);
  5605. if (addr && IN6_IS_ADDR_MC_GLOBAL(addr)) return Qtrue;
  5606. return Qfalse;
  5607. }
  5608. /*
  5609. * Returns IPv4 address of IPv4 mapped/compatible IPv6 address.
  5610. * It returns nil if +self+ is not IPv4 mapped/compatible IPv6 address.
  5611. *
  5612. * Addrinfo.ip("::192.0.2.3").ipv6_to_ipv4 #=> #<Addrinfo: 192.0.2.3>
  5613. * Addrinfo.ip("::ffff:192.0.2.3").ipv6_to_ipv4 #=> #<Addrinfo: 192.0.2.3>
  5614. * Addrinfo.ip("::1").ipv6_to_ipv4 #=> nil
  5615. * Addrinfo.ip("192.0.2.3").ipv6_to_ipv4 #=> nil
  5616. * Addrinfo.unix("/tmp/sock").ipv6_to_ipv4 #=> nil
  5617. */
  5618. static VALUE
  5619. addrinfo_ipv6_to_ipv4(VALUE self, SEL sel)
  5620. {
  5621. rb_addrinfo_t *rai = get_addrinfo(self);
  5622. struct in6_addr *addr;
  5623. int family = ai_get_afamily(rai);
  5624. if (family != AF_INET6) return Qnil;
  5625. addr = &((struct sockaddr_in6 *)&rai->addr)->sin6_addr;
  5626. if (IN6_IS_ADDR_V4MAPPED(addr) || IN6_IS_ADDR_V4COMPAT(addr)) {
  5627. struct sockaddr_in sin4;
  5628. MEMZERO(&sin4, struct sockaddr_in, 1);
  5629. sin4.sin_family = AF_INET;
  5630. SET_SIN_LEN(&sin4, sizeof(sin4));
  5631. memcpy(&sin4.sin_addr, (char*)addr + sizeof(*addr) - sizeof(sin4.sin_addr), sizeof(sin4.sin_addr));
  5632. return addrinfo_new((struct sockaddr *)&sin4, (socklen_t)sizeof(sin4),
  5633. PF_INET, rai->socktype, rai->protocol,
  5634. rai->canonname, rai->inspectname);
  5635. }
  5636. else {
  5637. return Qnil;
  5638. }
  5639. }
  5640. #endif
  5641. #ifdef HAVE_SYS_UN_H
  5642. /*
  5643. * call-seq:
  5644. * addrinfo.unix_path => path
  5645. *
  5646. * Returns the socket path as a string.
  5647. *
  5648. * Addrinfo.unix("/tmp/sock").unix_path #=> "/tmp/sock"
  5649. */
  5650. static VALUE
  5651. addrinfo_unix_path(VALUE self, SEL sel)
  5652. {
  5653. rb_addrinfo_t *rai = get_addrinfo(self);
  5654. int family = ai_get_afamily(rai);
  5655. struct sockaddr_un *addr;
  5656. char *s, *e;
  5657. if (family != AF_UNIX)
  5658. rb_raise(rb_eSocket, "need AF_UNIX address");
  5659. addr = (struct sockaddr_un *)&rai->addr;
  5660. s = addr->sun_path;
  5661. e = (char*)addr + rai->sockaddr_len;
  5662. if (e < s)
  5663. rb_raise(rb_eSocket, "too short AF_UNIX address");
  5664. if (addr->sun_path + sizeof(addr->sun_path) < e)
  5665. rb_raise(rb_eSocket, "too long AF_UNIX address");
  5666. while (s < e && *(e-1) == '\0')
  5667. e--;
  5668. return rb_str_new(s, e-s);
  5669. }
  5670. #endif
  5671. /*
  5672. * call-seq:
  5673. * Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags) => [addrinfo, ...]
  5674. * Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol) => [addrinfo, ...]
  5675. * Addrinfo.getaddrinfo(nodename, service, family, socktype) => [addrinfo, ...]
  5676. * Addrinfo.getaddrinfo(nodename, service, family) => [addrinfo, ...]
  5677. * Addrinfo.getaddrinfo(nodename, service) => [addrinfo, ...]
  5678. *
  5679. * returns a list of addrinfo objects as an array.
  5680. *
  5681. * This method converts nodename (hostname) and service (port) to addrinfo.
  5682. * Since the conversion is not unique, the result is a list of addrinfo objects.
  5683. *
  5684. * nodename or service can be nil if no conversion intended.
  5685. *
  5686. * family, socktype and protocol are hint for preferred protocol.
  5687. * If the result will be used for a socket with SOCK_STREAM,
  5688. * SOCK_STREAM should be specified as socktype.
  5689. * If so, Addrinfo.getaddrinfo returns addrinfo list appropriate for SOCK_STREAM.
  5690. * If they are omitted or nil is given, the result is not restricted.
  5691. *
  5692. * Similarly, PF_INET6 as family restricts for IPv6.
  5693. *
  5694. * flags should be bitwise OR of Socket::AI_??? constants.
  5695. *
  5696. * Note that socktype should be specified whenever application knows the usage of the address.
  5697. * Some platform causes an error when socktype is omitted and servname is specified as an integer
  5698. * because some port numbers, 512 for example, are ambiguous without socktype.
  5699. *
  5700. * Addrinfo.getaddrinfo("www.kame.net", 80, nil, :STREAM)
  5701. * #=> [#<Addrinfo: 203.178.141.194:80 TCP (www.kame.net:80)>,
  5702. * # #<Addrinfo: [2001:200:0:8002:203:47ff:fea5:3085]:80 TCP (www.kame.net:80)>]
  5703. *
  5704. */
  5705. static VALUE
  5706. addrinfo_s_getaddrinfo(VALUE self, SEL sel, int argc, VALUE *argv)
  5707. {
  5708. VALUE node, service, family, socktype, protocol, flags;
  5709. rb_scan_args(argc, argv, "24", &node, &service, &family, &socktype, &protocol, &flags);
  5710. return addrinfo_list_new(node, service, family, socktype, protocol, flags);
  5711. }
  5712. /*
  5713. * call-seq:
  5714. * Addrinfo.ip(host) => addrinfo
  5715. *
  5716. * returns an addrinfo object for IP address.
  5717. *
  5718. * The port, socktype, protocol of the result is filled by zero.
  5719. * So, it is not appropriate to create a socket.
  5720. *
  5721. * Addrinfo.ip("localhost") #=> #<Addrinfo: 127.0.0.1 (localhost)>
  5722. */
  5723. static VALUE
  5724. addrinfo_s_ip(VALUE self, SEL sel, VALUE host)
  5725. {
  5726. VALUE ret;
  5727. rb_addrinfo_t *rai;
  5728. ret = addrinfo_firstonly_new(host, Qnil,
  5729. INT2NUM(PF_UNSPEC), INT2FIX(0), INT2FIX(0), INT2FIX(0));
  5730. rai = get_addrinfo(ret);
  5731. rai->socktype = 0;
  5732. rai->protocol = 0;
  5733. return ret;
  5734. }
  5735. /*
  5736. * call-seq:
  5737. * Addrinfo.tcp(host, port) => addrinfo
  5738. *
  5739. * returns an addrinfo object for TCP address.
  5740. *
  5741. * Addrinfo.tcp("localhost", "smtp") #=> #<Addrinfo: 127.0.0.1:25 TCP (localhost:smtp)>
  5742. */
  5743. static VALUE
  5744. addrinfo_s_tcp(VALUE self, SEL sel, VALUE host, VALUE port)
  5745. {
  5746. return addrinfo_firstonly_new(host, port,
  5747. INT2NUM(PF_UNSPEC), INT2NUM(SOCK_STREAM), INT2NUM(IPPROTO_TCP), INT2FIX(0));
  5748. }
  5749. /*
  5750. * call-seq:
  5751. * Addrinfo.udp(host, port) => addrinfo
  5752. *
  5753. * returns an addrinfo object for UDP address.
  5754. *
  5755. * Addrinfo.udp("localhost", "daytime") #=> #<Addrinfo: 127.0.0.1:13 UDP (localhost:daytime)>
  5756. */
  5757. static VALUE
  5758. addrinfo_s_udp(VALUE self, SEL sel, VALUE host, VALUE port)
  5759. {
  5760. return addrinfo_firstonly_new(host, port,
  5761. INT2NUM(PF_UNSPEC), INT2NUM(SOCK_DGRAM), INT2NUM(IPPROTO_UDP), INT2FIX(0));
  5762. }
  5763. #ifdef HAVE_SYS_UN_H
  5764. /*
  5765. * call-seq:
  5766. * Addrinfo.unix(path [, socktype]) => addrinfo
  5767. *
  5768. * returns an addrinfo object for UNIX socket address.
  5769. *
  5770. * _socktype_ specifies the socket type.
  5771. * If it is omitted, :STREAM is used.
  5772. *
  5773. * Addrinfo.unix("/tmp/sock") #=> #<Addrinfo: /tmp/sock SOCK_STREAM>
  5774. * Addrinfo.unix("/tmp/sock", :DGRAM) #=> #<Addrinfo: /tmp/sock SOCK_DGRAM>
  5775. */
  5776. static VALUE
  5777. addrinfo_s_unix(VALUE self, SEL sel, int argc, VALUE *argv)
  5778. {
  5779. VALUE path, vsocktype, addr;
  5780. int socktype;
  5781. rb_addrinfo_t *rai;
  5782. rb_scan_args(argc, argv, "11", &path, &vsocktype);
  5783. if (NIL_P(vsocktype))
  5784. socktype = SOCK_STREAM;
  5785. else
  5786. socktype = socktype_arg(vsocktype);
  5787. addr = addrinfo_s_allocate(rb_cAddrinfo, 0);
  5788. rai = alloc_addrinfo();
  5789. GC_WB(&(DATA_PTR(addr)), rai);
  5790. init_unix_addrinfo(rai, path, socktype);
  5791. OBJ_INFECT(addr, path);
  5792. return addr;
  5793. }
  5794. #endif
  5795. static VALUE
  5796. sockaddr_string_value(volatile VALUE *v)
  5797. {
  5798. VALUE val = *v;
  5799. if (TYPE(val) == RUBY_T_DATA && IS_ADDRINFO(val)) {
  5800. *v = addrinfo_to_sockaddr(val, 0);
  5801. }
  5802. StringValue(*v);
  5803. return *v;
  5804. }
  5805. static char *
  5806. sockaddr_string_value_ptr(volatile VALUE *v)
  5807. {
  5808. sockaddr_string_value(v);
  5809. return RSTRING_PTR(*v);
  5810. }
  5811. static VALUE
  5812. fd_socket_addrinfo(int fd, struct sockaddr *addr, socklen_t len)
  5813. {
  5814. int family;
  5815. int socktype;
  5816. int ret;
  5817. socklen_t optlen = (socklen_t)sizeof(socktype);
  5818. /* assumes protocol family and address family are identical */
  5819. family = get_afamily(addr, len);
  5820. ret = getsockopt(fd, SOL_SOCKET, SO_TYPE, (void*)&socktype, &optlen);
  5821. if (ret == -1) {
  5822. rb_sys_fail("getsockopt(SO_TYPE)");
  5823. }
  5824. return addrinfo_new(addr, len, family, socktype, 0, Qnil, Qnil);
  5825. }
  5826. static VALUE
  5827. io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len)
  5828. {
  5829. rb_io_t *fptr;
  5830. switch (TYPE(io)) {
  5831. case T_FIXNUM:
  5832. return fd_socket_addrinfo(FIX2INT(io), addr, len);
  5833. case T_BIGNUM:
  5834. return fd_socket_addrinfo(NUM2INT(io), addr, len);
  5835. case T_FILE:
  5836. GetOpenFile(io, fptr);
  5837. return fd_socket_addrinfo(fptr->fd, addr, len);
  5838. default:
  5839. rb_raise(rb_eTypeError, "neither IO nor file descriptor");
  5840. }
  5841. }
  5842. static VALUE mConst;
  5843. static void
  5844. sock_define_const(char *name, int value)
  5845. {
  5846. rb_define_const(rb_cSocket, name, INT2FIX(value));
  5847. rb_define_const(mConst, name, INT2FIX(value));
  5848. }
  5849. static void
  5850. sock_define_uconst(const char *name, unsigned int value)
  5851. {
  5852. rb_define_const(rb_cSocket, name, UINT2NUM(value));
  5853. rb_define_const(mConst, name, UINT2NUM(value));
  5854. }
  5855. /*
  5856. * Class +Socket+ provides access to the underlying operating system
  5857. * socket implementations. It can be used to provide more operating system
  5858. * specific functionality than the protocol-specific socket classes but at the
  5859. * expense of greater complexity. In particular, the class handles addresses
  5860. * using +struct+ sockaddr structures packed into Ruby strings, which can be
  5861. * a joy to manipulate.
  5862. *
  5863. * === Exception Handling
  5864. * Ruby's implementation of +Socket+ causes an exception to be raised
  5865. * based on the error generated by the system dependent implementation.
  5866. * This is why the methods are documented in a way that isolate
  5867. * Unix-based system exceptions from Windows based exceptions. If more
  5868. * information on particular exception is needed please refer to the
  5869. * Unix manual pages or the Windows WinSock reference.
  5870. *
  5871. *
  5872. * === Documentation by
  5873. * * Zach Dennis
  5874. * * Sam Roberts
  5875. * * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
  5876. *
  5877. * Much material in this documentation is taken with permission from
  5878. * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
  5879. */
  5880. void
  5881. Init_socket()
  5882. {
  5883. rb_eSocket = rb_define_class("SocketError", rb_eStandardError);
  5884. rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO);
  5885. rb_undef_method(rb_cBasicSocket, "initialize");
  5886. rb_objc_define_method(*(VALUE *)rb_cBasicSocket, "do_not_reverse_lookup",
  5887. bsock_do_not_rev_lookup, 0);
  5888. rb_objc_define_method(*(VALUE *)rb_cBasicSocket, "do_not_reverse_lookup=",
  5889. bsock_do_not_rev_lookup_set, 1);
  5890. rb_objc_define_method(*(VALUE *)rb_cBasicSocket, "for_fd",
  5891. bsock_s_for_fd, 1);
  5892. rb_objc_define_method(rb_cBasicSocket, "close_read", bsock_close_read, 0);
  5893. rb_objc_define_method(rb_cBasicSocket, "close_write", bsock_close_write, 0);
  5894. rb_objc_define_method(rb_cBasicSocket, "shutdown", bsock_shutdown, -1);
  5895. rb_objc_define_method(rb_cBasicSocket, "setsockopt", bsock_setsockopt, 3);
  5896. rb_objc_define_method(rb_cBasicSocket, "getsockopt", bsock_getsockopt, 2);
  5897. rb_objc_define_method(rb_cBasicSocket, "getsockname", bsock_getsockname, 0);
  5898. rb_objc_define_method(rb_cBasicSocket, "getpeername", bsock_getpeername, 0);
  5899. rb_objc_define_method(rb_cBasicSocket, "getpeereid", bsock_getpeereid, 0);
  5900. rb_objc_define_method(rb_cBasicSocket, "local_address", bsock_local_address, 0);
  5901. rb_objc_define_method(rb_cBasicSocket, "remote_address", bsock_remote_address, 0);
  5902. rb_objc_define_method(rb_cBasicSocket, "send", bsock_send, -1);
  5903. rb_objc_define_method(rb_cBasicSocket, "recv", bsock_recv, -1);
  5904. rb_objc_define_method(rb_cBasicSocket, "recv_nonblock", bsock_recv_nonblock, -1);
  5905. rb_objc_define_method(rb_cBasicSocket, "do_not_reverse_lookup", bsock_do_not_reverse_lookup, 0);
  5906. rb_objc_define_method(rb_cBasicSocket, "do_not_reverse_lookup=", bsock_do_not_reverse_lookup_set, 1);
  5907. rb_objc_define_method(rb_cBasicSocket, "sendfile", socket_sendfile, 3);
  5908. rb_cIPSocket = rb_define_class("IPSocket", rb_cBasicSocket);
  5909. rb_objc_define_method(rb_cIPSocket, "addr", ip_addr, -1);
  5910. rb_objc_define_method(rb_cIPSocket, "peeraddr", ip_peeraddr, -1);
  5911. rb_objc_define_method(rb_cIPSocket, "recvfrom", ip_recvfrom, -1);
  5912. rb_objc_define_method(*(VALUE *)rb_cIPSocket, "getaddress", ip_s_getaddress, 1);
  5913. id_numeric = rb_intern_const("numeric");
  5914. id_hostname = rb_intern_const("hostname");
  5915. rb_cTCPSocket = rb_define_class("TCPSocket", rb_cIPSocket);
  5916. rb_objc_define_method(*(VALUE *)rb_cTCPSocket, "gethostbyname", tcp_s_gethostbyname, 1);
  5917. rb_objc_define_method(rb_cTCPSocket, "initialize", tcp_init, -1);
  5918. rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket);
  5919. rb_objc_define_method(rb_cTCPServer, "accept", tcp_accept, 0);
  5920. rb_objc_define_method(rb_cTCPServer, "accept_nonblock", tcp_accept_nonblock, 0);
  5921. rb_objc_define_method(rb_cTCPServer, "sysaccept", tcp_sysaccept, 0);
  5922. rb_objc_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1);
  5923. rb_objc_define_method(rb_cTCPServer, "listen", sock_listen, 1);
  5924. rb_cUDPSocket = rb_define_class("UDPSocket", rb_cIPSocket);
  5925. rb_objc_define_method(rb_cUDPSocket, "initialize", udp_init, -1);
  5926. rb_objc_define_method(rb_cUDPSocket, "connect", udp_connect, 2);
  5927. rb_objc_define_method(rb_cUDPSocket, "bind", udp_bind, 2);
  5928. rb_objc_define_method(rb_cUDPSocket, "send", udp_send, -1);
  5929. rb_objc_define_method(rb_cUDPSocket, "recvfrom_nonblock", udp_recvfrom_nonblock, -1);
  5930. #ifdef HAVE_SYS_UN_H
  5931. rb_cUNIXSocket = rb_define_class("UNIXSocket", rb_cBasicSocket);
  5932. rb_objc_define_method(rb_cUNIXSocket, "initialize", unix_init, 1);
  5933. rb_objc_define_method(rb_cUNIXSocket, "path", unix_path, 0);
  5934. rb_objc_define_method(rb_cUNIXSocket, "addr", unix_addr, 0);
  5935. rb_objc_define_method(rb_cUNIXSocket, "peeraddr", unix_peeraddr, 0);
  5936. rb_objc_define_method(rb_cUNIXSocket, "recvfrom", unix_recvfrom, -1);
  5937. rb_objc_define_method(rb_cUNIXSocket, "send_io", unix_send_io, 1);
  5938. rb_objc_define_method(rb_cUNIXSocket, "recv_io", unix_recv_io, -1);
  5939. rb_objc_define_method(*(VALUE *)rb_cUNIXSocket, "socketpair", unix_s_socketpair, -1);
  5940. rb_objc_define_method(*(VALUE *)rb_cUNIXSocket, "pair", unix_s_socketpair, -1);
  5941. rb_cUNIXServer = rb_define_class("UNIXServer", rb_cUNIXSocket);
  5942. rb_objc_define_method(rb_cUNIXServer, "initialize", unix_svr_init, 1);
  5943. rb_objc_define_method(rb_cUNIXServer, "accept", unix_accept, 0);
  5944. rb_objc_define_method(rb_cUNIXServer, "accept_nonblock", unix_accept_nonblock, 0);
  5945. rb_objc_define_method(rb_cUNIXServer, "sysaccept", unix_sysaccept, 0);
  5946. rb_objc_define_method(rb_cUNIXServer, "listen", sock_listen, 1);
  5947. #endif
  5948. rb_cSocket = rb_define_class("Socket", rb_cBasicSocket);
  5949. rb_objc_define_method(rb_cSocket, "initialize", sock_initialize, -1);
  5950. rb_objc_define_method(rb_cSocket, "connect", sock_connect, 1);
  5951. rb_objc_define_method(rb_cSocket, "connect_nonblock", sock_connect_nonblock, 1);
  5952. rb_objc_define_method(rb_cSocket, "bind", sock_bind, 1);
  5953. rb_objc_define_method(rb_cSocket, "listen", sock_listen, 1);
  5954. rb_objc_define_method(rb_cSocket, "accept", sock_accept, 0);
  5955. rb_objc_define_method(rb_cSocket, "accept_nonblock", sock_accept_nonblock, 0);
  5956. rb_objc_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0);
  5957. rb_objc_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1);
  5958. rb_objc_define_method(rb_cSocket, "recvfrom_nonblock", sock_recvfrom_nonblock, -1);
  5959. rb_objc_define_method(*(VALUE *)rb_cSocket, "socketpair", sock_s_socketpair, -1);
  5960. rb_objc_define_method(*(VALUE *)rb_cSocket, "pair", sock_s_socketpair, -1);
  5961. rb_objc_define_method(*(VALUE *)rb_cSocket, "gethostname", sock_gethostname, 0);
  5962. rb_objc_define_method(*(VALUE *)rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1);
  5963. rb_objc_define_method(*(VALUE *)rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1);
  5964. rb_objc_define_method(*(VALUE *)rb_cSocket, "getservbyname", sock_s_getservbyname, -1);
  5965. rb_objc_define_method(*(VALUE *)rb_cSocket, "getservbyport", sock_s_getservbyport, -1);
  5966. rb_objc_define_method(*(VALUE *)rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1);
  5967. rb_objc_define_method(*(VALUE *)rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1);
  5968. rb_objc_define_method(*(VALUE *)rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2);
  5969. rb_objc_define_method(*(VALUE *)rb_cSocket, "pack_sockaddr_in", sock_s_pack_sockaddr_in, 2);
  5970. rb_objc_define_method(*(VALUE *)rb_cSocket, "unpack_sockaddr_in", sock_s_unpack_sockaddr_in, 1);
  5971. #ifdef HAVE_SYS_UN_H
  5972. rb_objc_define_method(*(VALUE *)rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1);
  5973. rb_objc_define_method(*(VALUE *)rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1);
  5974. rb_objc_define_method(*(VALUE *)rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1);
  5975. #endif
  5976. rb_objc_define_method(*(VALUE *)rb_cSocket, "ip_address_list", socket_s_ip_address_list, 0);
  5977. rb_cAddrinfo = rb_define_class("Addrinfo", rb_cData);
  5978. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "alloc", addrinfo_s_allocate, 0);
  5979. rb_objc_define_method(rb_cAddrinfo, "initialize", addrinfo_initialize, -1);
  5980. rb_objc_define_method(rb_cAddrinfo, "inspect", addrinfo_inspect, 0);
  5981. rb_objc_define_method(rb_cAddrinfo, "inspect_sockaddr", addrinfo_inspect_sockaddr, 0);
  5982. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "getaddrinfo", addrinfo_s_getaddrinfo, -1);
  5983. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "ip", addrinfo_s_ip, 1);
  5984. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "tcp", addrinfo_s_tcp, 2);
  5985. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "udp", addrinfo_s_udp, 2);
  5986. #ifdef HAVE_SYS_UN_H
  5987. rb_objc_define_method(*(VALUE *)rb_cAddrinfo, "unix", addrinfo_s_unix, -1);
  5988. #endif
  5989. rb_objc_define_method(rb_cAddrinfo, "afamily", addrinfo_afamily, 0);
  5990. rb_objc_define_method(rb_cAddrinfo, "pfamily", addrinfo_pfamily, 0);
  5991. rb_objc_define_method(rb_cAddrinfo, "socktype", addrinfo_socktype, 0);
  5992. rb_objc_define_method(rb_cAddrinfo, "protocol", addrinfo_protocol, 0);
  5993. rb_objc_define_method(rb_cAddrinfo, "canonname", addrinfo_canonname, 0);
  5994. rb_objc_define_method(rb_cAddrinfo, "ipv4?", addrinfo_ipv4_p, 0);
  5995. rb_objc_define_method(rb_cAddrinfo, "ipv6?", addrinfo_ipv6_p, 0);
  5996. rb_objc_define_method(rb_cAddrinfo, "unix?", addrinfo_unix_p, 0);
  5997. rb_objc_define_method(rb_cAddrinfo, "ip?", addrinfo_ip_p, 0);
  5998. rb_objc_define_method(rb_cAddrinfo, "ip_unpack", addrinfo_ip_unpack, 0);
  5999. rb_objc_define_method(rb_cAddrinfo, "ip_address", addrinfo_ip_address, 0);
  6000. rb_objc_define_method(rb_cAddrinfo, "ip_port", addrinfo_ip_port, 0);
  6001. rb_objc_define_method(rb_cAddrinfo, "ipv4_private?", addrinfo_ipv4_private_p, 0);
  6002. rb_objc_define_method(rb_cAddrinfo, "ipv4_loopback?", addrinfo_ipv4_loopback_p, 0);
  6003. rb_objc_define_method(rb_cAddrinfo, "ipv4_multicast?", addrinfo_ipv4_multicast_p, 0);
  6004. #ifdef INET6
  6005. rb_objc_define_method(rb_cAddrinfo, "ipv6_unspecified?", addrinfo_ipv6_unspecified_p, 0);
  6006. rb_objc_define_method(rb_cAddrinfo, "ipv6_loopback?", addrinfo_ipv6_loopback_p, 0);
  6007. rb_objc_define_method(rb_cAddrinfo, "ipv6_multicast?", addrinfo_ipv6_multicast_p, 0);
  6008. rb_objc_define_method(rb_cAddrinfo, "ipv6_linklocal?", addrinfo_ipv6_linklocal_p, 0);
  6009. rb_objc_define_method(rb_cAddrinfo, "ipv6_sitelocal?", addrinfo_ipv6_sitelocal_p, 0);
  6010. rb_objc_define_method(rb_cAddrinfo, "ipv6_v4mapped?", addrinfo_ipv6_v4mapped_p, 0);
  6011. rb_objc_define_method(rb_cAddrinfo, "ipv6_v4compat?", addrinfo_ipv6_v4compat_p, 0);
  6012. rb_objc_define_method(rb_cAddrinfo, "ipv6_mc_nodelocal?", addrinfo_ipv6_mc_nodelocal_p, 0);
  6013. rb_objc_define_method(rb_cAddrinfo, "ipv6_mc_linklocal?", addrinfo_ipv6_mc_linklocal_p, 0);
  6014. rb_objc_define_method(rb_cAddrinfo, "ipv6_mc_sitelocal?", addrinfo_ipv6_mc_sitelocal_p, 0);
  6015. rb_objc_define_method(rb_cAddrinfo, "ipv6_mc_orglocal?", addrinfo_ipv6_mc_orglocal_p, 0);
  6016. rb_objc_define_method(rb_cAddrinfo, "ipv6_mc_global?", addrinfo_ipv6_mc_global_p, 0);
  6017. rb_define_method(rb_cAddrinfo, "ipv6_to_ipv4", addrinfo_ipv6_to_ipv4, 0);
  6018. #endif
  6019. #ifdef HAVE_SYS_UN_H
  6020. rb_objc_define_method(rb_cAddrinfo, "unix_path", addrinfo_unix_path, 0);
  6021. #endif
  6022. rb_objc_define_method(rb_cAddrinfo, "to_sockaddr", addrinfo_to_sockaddr, 0);
  6023. rb_objc_define_method(rb_cAddrinfo, "to_s", addrinfo_to_sockaddr, 0); /* compatibility for ruby before 1.9.2 */
  6024. rb_objc_define_method(rb_cAddrinfo, "getnameinfo", addrinfo_getnameinfo, -1);
  6025. /* constants */
  6026. mConst = rb_define_module_under(rb_cSocket, "Constants");
  6027. init_constants(mConst);
  6028. }