PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 2ms app.codeStats 0ms

/src/org/jruby/ext/socket/RubySocket.java

https://github.com/gilmation/jruby
Java | 786 lines | 650 code | 79 blank | 57 comment | 127 complexity | 10e94e05e55a253274c40e361be0b6ba MD5 | raw file
  1. /***** BEGIN LICENSE BLOCK *****
  2. * Version: CPL 1.0/GPL 2.0/LGPL 2.1
  3. *
  4. * The contents of this file are subject to the Common Public
  5. * License Version 1.0 (the "License"); you may not use this file
  6. * except in compliance with the License. You may obtain a copy of
  7. * the License at http://www.eclipse.org/legal/cpl-v10.html
  8. *
  9. * Software distributed under the License is distributed on an "AS
  10. * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  11. * implied. See the License for the specific language governing
  12. * rights and limitations under the License.
  13. *
  14. * Copyright (C) 2007 Ola Bini <ola@ologix.com>
  15. *
  16. * Alternatively, the contents of this file may be used under the terms of
  17. * either of the GNU General Public License Version 2 or later (the "GPL"),
  18. * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  19. * in which case the provisions of the GPL or the LGPL are applicable instead
  20. * of those above. If you wish to allow use of your version of this file only
  21. * under the terms of either the GPL or the LGPL, and not to allow others to
  22. * use your version of this file under the terms of the CPL, indicate your
  23. * decision by deleting the provisions above and replace them with the notice
  24. * and other provisions required by the GPL or the LGPL. If you do not delete
  25. * the provisions above, a recipient may use your version of this file under
  26. * the terms of any one of the CPL, the GPL or the LGPL.
  27. ***** END LICENSE BLOCK *****/
  28. package org.jruby.ext.socket;
  29. import static com.kenai.constantine.platform.AddressFamily.AF_INET;
  30. import static com.kenai.constantine.platform.AddressFamily.AF_INET6;
  31. import static com.kenai.constantine.platform.IPProto.IPPROTO_TCP;
  32. import static com.kenai.constantine.platform.IPProto.IPPROTO_UDP;
  33. import static com.kenai.constantine.platform.NameInfo.NI_NUMERICHOST;
  34. import static com.kenai.constantine.platform.NameInfo.NI_NUMERICSERV;
  35. import static com.kenai.constantine.platform.ProtocolFamily.PF_INET;
  36. import static com.kenai.constantine.platform.ProtocolFamily.PF_INET6;
  37. import static com.kenai.constantine.platform.Sock.SOCK_DGRAM;
  38. import static com.kenai.constantine.platform.Sock.SOCK_STREAM;
  39. import java.io.ByteArrayOutputStream;
  40. import java.io.DataOutputStream;
  41. import java.io.IOException;
  42. import java.net.DatagramSocket;
  43. import java.net.InetAddress;
  44. import java.net.InetSocketAddress;
  45. import java.net.Socket;
  46. import java.net.SocketException;
  47. import java.net.UnknownHostException;
  48. import java.nio.channels.Channel;
  49. import java.nio.channels.DatagramChannel;
  50. import java.nio.channels.SocketChannel;
  51. import java.util.ArrayList;
  52. import java.util.List;
  53. import java.util.regex.Matcher;
  54. import java.util.regex.Pattern;
  55. import org.jruby.Ruby;
  56. import org.jruby.RubyArray;
  57. import org.jruby.RubyClass;
  58. import org.jruby.RubyFixnum;
  59. import org.jruby.RubyModule;
  60. import org.jruby.RubyNumeric;
  61. import org.jruby.RubyString;
  62. import org.jruby.anno.JRubyClass;
  63. import org.jruby.anno.JRubyMethod;
  64. import org.jruby.anno.JRubyModule;
  65. import org.jruby.exceptions.RaiseException;
  66. import org.jruby.platform.Platform;
  67. import org.jruby.runtime.Arity;
  68. import org.jruby.runtime.ObjectAllocator;
  69. import org.jruby.runtime.ThreadContext;
  70. import org.jruby.runtime.builtin.IRubyObject;
  71. import org.jruby.util.ByteList;
  72. import org.jruby.util.io.ChannelDescriptor;
  73. import org.jruby.util.io.InvalidValueException;
  74. import org.jruby.util.io.ModeFlags;
  75. import com.kenai.constantine.platform.AddressFamily;
  76. import com.kenai.constantine.platform.Sock;
  77. import java.net.Inet6Address;
  78. import java.nio.channels.AlreadyConnectedException;
  79. import java.nio.channels.ClosedChannelException;
  80. import java.nio.channels.ConnectionPendingException;
  81. import java.nio.channels.spi.AbstractSelectableChannel;
  82. /**
  83. * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
  84. */
  85. @JRubyClass(name="Socket", parent="BasicSocket", include="Socket::Constants")
  86. public class RubySocket extends RubyBasicSocket {
  87. @JRubyClass(name="SocketError", parent="StandardError")
  88. public static class SocketError {}
  89. private static ObjectAllocator SOCKET_ALLOCATOR = new ObjectAllocator() {
  90. public IRubyObject allocate(Ruby runtime, RubyClass klass) {
  91. return new RubySocket(runtime, klass);
  92. }
  93. };
  94. public static final int MSG_OOB = 0x1;
  95. public static final int MSG_PEEK = 0x2;
  96. public static final int MSG_DONTROUTE = 0x4;
  97. @JRubyModule(name="Socket::Constants")
  98. public static class Constants {}
  99. static void createSocket(Ruby runtime) {
  100. RubyClass rb_cSocket = runtime.defineClass("Socket", runtime.fastGetClass("BasicSocket"), SOCKET_ALLOCATOR);
  101. RubyModule rb_mConstants = rb_cSocket.defineModuleUnder("Constants");
  102. // we don't have to define any that we don't support; see socket.c
  103. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.Sock.class);
  104. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.SocketOption.class);
  105. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.SocketLevel.class);
  106. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.ProtocolFamily.class);
  107. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.AddressFamily.class);
  108. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.INAddr.class);
  109. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.IPProto.class);
  110. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.Shutdown.class);
  111. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.TCP.class);
  112. runtime.loadConstantSet(rb_mConstants, com.kenai.constantine.platform.NameInfo.class);
  113. // mandatory constants we haven't implemented
  114. rb_mConstants.fastSetConstant("MSG_OOB", runtime.newFixnum(MSG_OOB));
  115. rb_mConstants.fastSetConstant("MSG_PEEK", runtime.newFixnum(MSG_PEEK));
  116. rb_mConstants.fastSetConstant("MSG_DONTROUTE", runtime.newFixnum(MSG_DONTROUTE));
  117. // constants webrick crashes without
  118. rb_mConstants.fastSetConstant("AI_PASSIVE", runtime.newFixnum(1));
  119. // More constants needed by specs
  120. rb_mConstants.fastSetConstant("IP_MULTICAST_TTL", runtime.newFixnum(10));
  121. rb_mConstants.fastSetConstant("IP_MULTICAST_LOOP", runtime.newFixnum(11));
  122. rb_mConstants.fastSetConstant("IP_ADD_MEMBERSHIP", runtime.newFixnum(12));
  123. rb_mConstants.fastSetConstant("IP_MAX_MEMBERSHIPS", runtime.newFixnum(20));
  124. rb_mConstants.fastSetConstant("IP_DEFAULT_MULTICAST_LOOP", runtime.newFixnum(1));
  125. rb_mConstants.fastSetConstant("IP_DEFAULT_MULTICAST_TTL", runtime.newFixnum(1));
  126. rb_cSocket.includeModule(rb_mConstants);
  127. rb_cSocket.defineAnnotatedMethods(RubySocket.class);
  128. }
  129. public RubySocket(Ruby runtime, RubyClass type) {
  130. super(runtime, type);
  131. }
  132. protected int getSoTypeDefault() {
  133. return soType;
  134. }
  135. private int soDomain;
  136. private int soType;
  137. private int soProtocol;
  138. @Deprecated
  139. public static IRubyObject for_fd(IRubyObject socketClass, IRubyObject fd) {
  140. return for_fd(socketClass.getRuntime().getCurrentContext(), socketClass, fd);
  141. }
  142. @JRubyMethod(frame = true, meta = true)
  143. public static IRubyObject for_fd(ThreadContext context, IRubyObject socketClass, IRubyObject fd) {
  144. Ruby ruby = context.getRuntime();
  145. if (fd instanceof RubyFixnum) {
  146. RubySocket socket = (RubySocket)((RubyClass)socketClass).allocate();
  147. // normal file descriptor..try to work with it
  148. ChannelDescriptor descriptor = ChannelDescriptor.getDescriptorByFileno((int)((RubyFixnum)fd).getLongValue());
  149. if (descriptor == null) {
  150. throw ruby.newErrnoEBADFError();
  151. }
  152. Channel mainChannel = descriptor.getChannel();
  153. if (mainChannel instanceof SocketChannel) {
  154. // ok, it's a socket...set values accordingly
  155. // just using AF_INET since we can't tell from SocketChannel...
  156. socket.soDomain = AddressFamily.AF_INET.value();
  157. socket.soType = Sock.SOCK_STREAM.value();
  158. socket.soProtocol = 0;
  159. } else if (mainChannel instanceof DatagramChannel) {
  160. // datagram, set accordingly
  161. // again, AF_INET
  162. socket.soDomain = AddressFamily.AF_INET.value();
  163. socket.soType = Sock.SOCK_DGRAM.value();
  164. socket.soProtocol = 0;
  165. } else {
  166. throw context.getRuntime().newErrnoENOTSOCKError("can't Socket.new/for_fd against a non-socket");
  167. }
  168. socket.initSocket(ruby, descriptor);
  169. return socket;
  170. } else {
  171. throw context.getRuntime().newTypeError(fd, context.getRuntime().getFixnum());
  172. }
  173. }
  174. @JRubyMethod
  175. public IRubyObject initialize(ThreadContext context, IRubyObject domain, IRubyObject type, IRubyObject protocol) {
  176. try {
  177. if(domain instanceof RubyString) {
  178. String domainString = domain.toString();
  179. if(domainString.equals("AF_INET")) {
  180. soDomain = AF_INET.value();
  181. } else if(domainString.equals("PF_INET")) {
  182. soDomain = PF_INET.value();
  183. } else {
  184. throw sockerr(context.getRuntime(), "unknown socket domain " + domainString);
  185. }
  186. } else {
  187. soDomain = RubyNumeric.fix2int(domain);
  188. }
  189. if(type instanceof RubyString) {
  190. String typeString = type.toString();
  191. if(typeString.equals("SOCK_STREAM")) {
  192. soType = SOCK_STREAM.value();
  193. } else if(typeString.equals("SOCK_DGRAM")) {
  194. soType = SOCK_DGRAM.value();
  195. } else {
  196. throw sockerr(context.getRuntime(), "unknown socket type " + typeString);
  197. }
  198. } else {
  199. soType = RubyNumeric.fix2int(type);
  200. }
  201. soProtocol = RubyNumeric.fix2int(protocol);
  202. Channel channel = null;
  203. if(soType == Sock.SOCK_STREAM.value()) {
  204. channel = SocketChannel.open();
  205. } else if(soType == Sock.SOCK_DGRAM.value()) {
  206. channel = DatagramChannel.open();
  207. }
  208. initSocket(context.getRuntime(), new ChannelDescriptor(channel, new ModeFlags(ModeFlags.RDWR)));
  209. } catch (InvalidValueException ex) {
  210. throw context.getRuntime().newErrnoEINVALError();
  211. } catch(IOException e) {
  212. throw sockerr(context.getRuntime(), "initialize: " + e.toString());
  213. }
  214. return this;
  215. }
  216. private static RuntimeException sockerr(Ruby runtime, String msg) {
  217. return new RaiseException(runtime, runtime.fastGetClass("SocketError"), msg, true);
  218. }
  219. @Deprecated
  220. public static IRubyObject gethostname(IRubyObject recv) {
  221. return gethostname(recv.getRuntime().getCurrentContext(), recv);
  222. }
  223. @JRubyMethod(meta = true)
  224. public static IRubyObject gethostname(ThreadContext context, IRubyObject recv) {
  225. try {
  226. return context.getRuntime().newString(InetAddress.getLocalHost().getHostName());
  227. } catch(UnknownHostException e) {
  228. try {
  229. return context.getRuntime().newString(InetAddress.getByAddress(new byte[]{0,0,0,0}).getHostName());
  230. } catch(UnknownHostException e2) {
  231. throw sockerr(context.getRuntime(), "gethostname: name or service not known");
  232. }
  233. }
  234. }
  235. private static InetAddress intoAddress(Ruby runtime, String s) {
  236. try {
  237. byte[] bs = ByteList.plain(s);
  238. return InetAddress.getByAddress(bs);
  239. } catch(Exception e) {
  240. throw sockerr(runtime, "strtoaddr: " + e.toString());
  241. }
  242. }
  243. private static String intoString(Ruby runtime, InetAddress as) {
  244. try {
  245. return new String(ByteList.plain(as.getAddress()));
  246. } catch(Exception e) {
  247. throw sockerr(runtime, "addrtostr: " + e.toString());
  248. }
  249. }
  250. @Deprecated
  251. public static IRubyObject gethostbyaddr(IRubyObject recv, IRubyObject[] args) {
  252. return gethostbyaddr(recv.getRuntime().getCurrentContext(), recv, args);
  253. }
  254. @JRubyMethod(required = 1, rest = true, meta = true)
  255. public static IRubyObject gethostbyaddr(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  256. Ruby runtime = context.getRuntime();
  257. IRubyObject[] ret = new IRubyObject[4];
  258. ret[0] = runtime.newString(intoAddress(runtime,args[0].convertToString().toString()).getCanonicalHostName());
  259. ret[1] = runtime.newArray();
  260. ret[2] = runtime.newFixnum(2); // AF_INET
  261. ret[3] = args[0];
  262. return runtime.newArrayNoCopy(ret);
  263. }
  264. @Deprecated
  265. public static IRubyObject getservbyname(IRubyObject recv, IRubyObject[] args) {
  266. return getservbyname(recv.getRuntime().getCurrentContext(), recv, args);
  267. }
  268. @JRubyMethod(required = 1, optional = 1, meta = true)
  269. public static IRubyObject getservbyname(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  270. Ruby runtime = context.getRuntime();
  271. int argc = Arity.checkArgumentCount(runtime, args, 1, 2);
  272. String name = args[0].convertToString().toString();
  273. String proto = argc == 1 ? "tcp" : args[1].convertToString().toString();
  274. jnr.netdb.Service service = jnr.netdb.Service.getServiceByName(name, proto);
  275. int port;
  276. if (service != null) {
  277. port = service.getPort();
  278. } else {
  279. // MRI behavior: try to convert the name string to port directly
  280. try {
  281. port = Integer.parseInt(name.trim());
  282. } catch (NumberFormatException nfe) {
  283. throw sockerr(runtime, "no such service " + name + "/" + proto);
  284. }
  285. }
  286. return runtime.newFixnum(port);
  287. }
  288. @Deprecated
  289. public static IRubyObject pack_sockaddr_un(IRubyObject recv, IRubyObject filename) {
  290. return pack_sockaddr_un(recv.getRuntime().getCurrentContext(), recv, filename);
  291. }
  292. @JRubyMethod(name = {"pack_sockaddr_un", "sockaddr_un"}, meta = true)
  293. public static IRubyObject pack_sockaddr_un(ThreadContext context, IRubyObject recv, IRubyObject filename) {
  294. StringBuilder sb = new StringBuilder();
  295. sb.append((char)0);
  296. sb.append((char)1);
  297. String str = filename.convertToString().toString();
  298. sb.append(str);
  299. for(int i=str.length();i<104;i++) {
  300. sb.append((char)0);
  301. }
  302. return context.getRuntime().newString(sb.toString());
  303. }
  304. @JRubyMethod(backtrace = true)
  305. public IRubyObject connect_nonblock(ThreadContext context, IRubyObject arg) {
  306. Channel socketChannel = getChannel();
  307. try {
  308. if (socketChannel instanceof AbstractSelectableChannel) {
  309. ((AbstractSelectableChannel) socketChannel).configureBlocking(false);
  310. connect(context, arg);
  311. } else {
  312. throw getRuntime().newErrnoENOPROTOOPTError();
  313. }
  314. } catch(ClosedChannelException e) {
  315. throw context.getRuntime().newErrnoECONNREFUSEDError();
  316. } catch(IOException e) {
  317. e.printStackTrace();
  318. throw sockerr(context.getRuntime(), "connect(2): name or service not known");
  319. } catch (Error e) {
  320. // Workaround for a bug in Sun's JDK 1.5.x, see
  321. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6303753
  322. Throwable cause = e.getCause();
  323. if (cause instanceof SocketException) {
  324. handleSocketException(context.getRuntime(), "connect", (SocketException)cause);
  325. } else {
  326. throw e;
  327. }
  328. }
  329. return RubyFixnum.zero(context.getRuntime());
  330. }
  331. @JRubyMethod(backtrace = true)
  332. public IRubyObject connect(ThreadContext context, IRubyObject arg) {
  333. RubyArray sockaddr = (RubyArray) unpack_sockaddr_in(context, this, arg);
  334. try {
  335. IRubyObject addr = sockaddr.pop(context);
  336. IRubyObject port = sockaddr.pop(context);
  337. InetSocketAddress iaddr = new InetSocketAddress(
  338. addr.convertToString().toString(), RubyNumeric.fix2int(port));
  339. Channel socketChannel = getChannel();
  340. if (socketChannel instanceof SocketChannel) {
  341. if(!((SocketChannel) socketChannel).connect(iaddr)) {
  342. throw context.getRuntime().newErrnoEINPROGRESSError();
  343. }
  344. } else if (socketChannel instanceof DatagramChannel) {
  345. ((DatagramChannel)socketChannel).connect(iaddr);
  346. } else {
  347. throw getRuntime().newErrnoENOPROTOOPTError();
  348. }
  349. } catch(AlreadyConnectedException e) {
  350. throw context.getRuntime().newErrnoEISCONNError();
  351. } catch(ConnectionPendingException e) {
  352. Channel socketChannel = getChannel();
  353. if (socketChannel instanceof SocketChannel) {
  354. try {
  355. if (((SocketChannel) socketChannel).finishConnect()) {
  356. throw context.getRuntime().newErrnoEISCONNError();
  357. }
  358. throw context.getRuntime().newErrnoEINPROGRESSError();
  359. } catch (IOException ex) {
  360. e.printStackTrace();
  361. throw sockerr(context.getRuntime(), "connect(2): name or service not known");
  362. }
  363. }
  364. throw context.getRuntime().newErrnoEINPROGRESSError();
  365. } catch(UnknownHostException e) {
  366. throw sockerr(context.getRuntime(), "connect(2): unknown host");
  367. } catch(SocketException e) {
  368. handleSocketException(context.getRuntime(), "connect", e);
  369. } catch(IOException e) {
  370. e.printStackTrace();
  371. throw sockerr(context.getRuntime(), "connect(2): name or service not known");
  372. } catch (IllegalArgumentException iae) {
  373. throw sockerr(context.getRuntime(), iae.getMessage());
  374. } catch (Error e) {
  375. // Workaround for a bug in Sun's JDK 1.5.x, see
  376. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6303753
  377. Throwable cause = e.getCause();
  378. if (cause instanceof SocketException) {
  379. handleSocketException(context.getRuntime(), "connect", (SocketException)cause);
  380. } else {
  381. throw e;
  382. }
  383. }
  384. return RubyFixnum.zero(context.getRuntime());
  385. }
  386. @JRubyMethod(backtrace = true)
  387. public IRubyObject bind(ThreadContext context, IRubyObject arg) {
  388. RubyArray sockaddr = (RubyArray) unpack_sockaddr_in(context, this, arg);
  389. try {
  390. IRubyObject addr = sockaddr.pop(context);
  391. IRubyObject port = sockaddr.pop(context);
  392. InetSocketAddress iaddr = new InetSocketAddress(
  393. addr.convertToString().toString(), RubyNumeric.fix2int(port));
  394. Channel socketChannel = getChannel();
  395. if (socketChannel instanceof SocketChannel) {
  396. Socket socket = ((SocketChannel)socketChannel).socket();
  397. socket.bind(iaddr);
  398. } else if (socketChannel instanceof DatagramChannel) {
  399. DatagramSocket socket = ((DatagramChannel)socketChannel).socket();
  400. socket.bind(iaddr);
  401. } else {
  402. throw getRuntime().newErrnoENOPROTOOPTError();
  403. }
  404. } catch(UnknownHostException e) {
  405. throw sockerr(context.getRuntime(), "bind(2): unknown host");
  406. } catch(SocketException e) {
  407. handleSocketException(context.getRuntime(), "bind", e);
  408. } catch(IOException e) {
  409. e.printStackTrace();
  410. throw sockerr(context.getRuntime(), "bind(2): name or service not known");
  411. } catch (IllegalArgumentException iae) {
  412. throw sockerr(context.getRuntime(), iae.getMessage());
  413. } catch (Error e) {
  414. // Workaround for a bug in Sun's JDK 1.5.x, see
  415. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6303753
  416. Throwable cause = e.getCause();
  417. if (cause instanceof SocketException) {
  418. handleSocketException(context.getRuntime(), "bind", (SocketException)cause);
  419. } else {
  420. throw e;
  421. }
  422. }
  423. return RubyFixnum.zero(context.getRuntime());
  424. }
  425. private void handleSocketException(Ruby runtime, String caller, SocketException e) {
  426. // e.printStackTrace();
  427. String msg = formatMessage(e, "bind");
  428. // This is ugly, but what can we do, Java provides the same exception type
  429. // for different situations, so we differentiate the errors
  430. // based on the exception's message.
  431. if (ALREADY_BOUND_PATTERN.matcher(msg).find()) {
  432. throw runtime.newErrnoEINVALError(msg);
  433. } else if (ADDR_NOT_AVAIL_PATTERN.matcher(msg).find()) {
  434. throw runtime.newErrnoEADDRNOTAVAILError(msg);
  435. } else if (PERM_DENIED_PATTERN.matcher(msg).find()) {
  436. throw runtime.newErrnoEACCESError(msg);
  437. } else {
  438. throw runtime.newErrnoEADDRINUSEError(msg);
  439. }
  440. }
  441. private static String formatMessage(Throwable e, String defaultMsg) {
  442. String msg = e.getMessage();
  443. if (msg == null) {
  444. msg = defaultMsg;
  445. } else {
  446. msg = defaultMsg + " - " + msg;
  447. }
  448. return msg;
  449. }
  450. @Deprecated
  451. public static IRubyObject pack_sockaddr_in(IRubyObject recv, IRubyObject port, IRubyObject host) {
  452. return pack_sockaddr_in(recv.getRuntime().getCurrentContext(), recv, port, host);
  453. }
  454. @JRubyMethod(name = {"pack_sockaddr_in", "sockaddr_in"}, meta = true)
  455. public static IRubyObject pack_sockaddr_in(ThreadContext context, IRubyObject recv, IRubyObject port, IRubyObject host) {
  456. return pack_sockaddr_in(context, recv,
  457. RubyNumeric.fix2int(port),
  458. host.isNil() ? null : host.convertToString().toString());
  459. }
  460. public static IRubyObject pack_sockaddr_in(ThreadContext context, IRubyObject recv, int iport, String host) {
  461. ByteArrayOutputStream bufS = new ByteArrayOutputStream();
  462. try {
  463. DataOutputStream ds = new DataOutputStream(bufS);
  464. if(Platform.IS_BSD) {
  465. ds.write(16);
  466. ds.write(2);
  467. } else {
  468. ds.write(2);
  469. ds.write(0);
  470. }
  471. ds.write(iport >> 8);
  472. ds.write(iport);
  473. try {
  474. if(host != null && "".equals(host)) {
  475. ds.writeInt(0);
  476. } else {
  477. InetAddress[] addrs = InetAddress.getAllByName(host);
  478. byte[] addr = addrs[0].getAddress();
  479. ds.write(addr, 0, addr.length);
  480. }
  481. } catch (UnknownHostException e) {
  482. throw sockerr(context.getRuntime(), "getaddrinfo: No address associated with nodename");
  483. }
  484. ds.writeInt(0);
  485. ds.writeInt(0);
  486. } catch (IOException e) {
  487. throw sockerr(context.getRuntime(), "pack_sockaddr_in: internal error");
  488. }
  489. return context.getRuntime().newString(new ByteList(bufS.toByteArray(),
  490. false));
  491. }
  492. @Deprecated
  493. public static IRubyObject unpack_sockaddr_in(IRubyObject recv, IRubyObject addr) {
  494. return unpack_sockaddr_in(recv.getRuntime().getCurrentContext(), recv, addr);
  495. }
  496. @JRubyMethod(meta = true)
  497. public static IRubyObject unpack_sockaddr_in(ThreadContext context, IRubyObject recv, IRubyObject addr) {
  498. String val = addr.convertToString().toString();
  499. if((Platform.IS_BSD && val.charAt(0) != 16 && val.charAt(1) != 2) || (!Platform.IS_BSD && val.charAt(0) != 2)) {
  500. throw context.getRuntime().newArgumentError("can't resolve socket address of wrong type");
  501. }
  502. int port = (val.charAt(2) << 8) + (val.charAt(3));
  503. StringBuilder sb = new StringBuilder();
  504. sb.append((int)val.charAt(4));
  505. sb.append(".");
  506. sb.append((int)val.charAt(5));
  507. sb.append(".");
  508. sb.append((int)val.charAt(6));
  509. sb.append(".");
  510. sb.append((int)val.charAt(7));
  511. IRubyObject[] result = new IRubyObject[]{
  512. context.getRuntime().newFixnum(port),
  513. context.getRuntime().newString(sb.toString())};
  514. return context.getRuntime().newArrayNoCopy(result);
  515. }
  516. private static final ByteList BROADCAST = new ByteList("<broadcast>".getBytes());
  517. private static final byte[] INADDR_BROADCAST = new byte[] {-1,-1,-1,-1}; // 255.255.255.255
  518. private static final ByteList ANY = new ByteList("<any>".getBytes());
  519. private static final byte[] INADDR_ANY = new byte[] {0,0,0,0}; // 0.0.0.0
  520. public static InetAddress getRubyInetAddress(ByteList address) throws UnknownHostException {
  521. if (address.equal(BROADCAST)) {
  522. return InetAddress.getByAddress(INADDR_BROADCAST);
  523. } else if (address.equal(ANY)) {
  524. return InetAddress.getByAddress(INADDR_ANY);
  525. } else {
  526. return InetAddress.getByName(address.toString());
  527. }
  528. }
  529. @Deprecated
  530. public static IRubyObject gethostbyname(IRubyObject recv, IRubyObject hostname) {
  531. return gethostbyname(recv.getRuntime().getCurrentContext(), recv, hostname);
  532. }
  533. @JRubyMethod(meta = true)
  534. public static IRubyObject gethostbyname(ThreadContext context, IRubyObject recv, IRubyObject hostname) {
  535. try {
  536. InetAddress addr = getRubyInetAddress(hostname.convertToString().getByteList());
  537. Ruby runtime = context.getRuntime();
  538. IRubyObject[] ret = new IRubyObject[4];
  539. ret[0] = runtime.newString(addr.getHostAddress());
  540. ret[1] = runtime.newArray();
  541. ret[2] = runtime.newFixnum(2); // AF_INET
  542. ret[3] = runtime.newString(new ByteList(addr.getAddress()));
  543. return runtime.newArrayNoCopy(ret);
  544. } catch(UnknownHostException e) {
  545. throw sockerr(context.getRuntime(), "gethostbyname: name or service not known");
  546. }
  547. }
  548. @Deprecated
  549. public static IRubyObject getaddrinfo(IRubyObject recv, IRubyObject[] args) {
  550. return getaddrinfo(recv.getRuntime().getCurrentContext(), recv, args);
  551. }
  552. //def self.getaddrinfo(host, port, family = nil, socktype = nil, protocol = nil, flags = nil)
  553. @JRubyMethod(required = 2, optional = 4, meta = true)
  554. public static IRubyObject getaddrinfo(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  555. args = Arity.scanArgs(context.getRuntime(),args,2,4);
  556. try {
  557. Ruby r = context.getRuntime();
  558. IRubyObject host = args[0];
  559. IRubyObject port = args[1];
  560. boolean emptyHost = host.isNil() || host.convertToString().isEmpty();
  561. if(port instanceof RubyString) {
  562. port = getservbyname(context, recv, new IRubyObject[]{port});
  563. }
  564. IRubyObject family = args[2];
  565. IRubyObject socktype = args[3];
  566. //IRubyObject protocol = args[4];
  567. IRubyObject flags = args[5];
  568. boolean is_ipv6 = (! family.isNil()) && (RubyNumeric.fix2int(family) & AF_INET6.value()) == AF_INET6.value();
  569. boolean sock_stream = true;
  570. boolean sock_dgram = true;
  571. if(!socktype.isNil()) {
  572. int val = RubyNumeric.fix2int(socktype);
  573. if(val == SOCK_STREAM.value()) {
  574. sock_dgram = false;
  575. } else if(val == SOCK_DGRAM.value()) {
  576. sock_stream = false;
  577. }
  578. }
  579. // When Socket::AI_PASSIVE and host is nil, return 'any' address.
  580. InetAddress[] addrs = null;
  581. if(!flags.isNil() && RubyFixnum.fix2int(flags) > 0) {
  582. // The value of 1 is for Socket::AI_PASSIVE.
  583. int flag = RubyNumeric.fix2int(flags);
  584. if ((flag == 1) && emptyHost ) {
  585. // use RFC 2732 style string to ensure that we get Inet6Address
  586. addrs = InetAddress.getAllByName(is_ipv6 ? "[::]" : "0.0.0.0");
  587. }
  588. }
  589. if (addrs == null)
  590. addrs = InetAddress.getAllByName(emptyHost ? (is_ipv6 ? "[::1]" : null) : host.convertToString().toString());
  591. List<IRubyObject> l = new ArrayList<IRubyObject>();
  592. for(int i = 0; i < addrs.length; i++) {
  593. IRubyObject[] c;
  594. if(sock_dgram) {
  595. c = new IRubyObject[7];
  596. c[0] = r.newString(is_ipv6 ? "AF_INET6" : "AF_INET");
  597. c[1] = port;
  598. c[2] = r.newString(getHostAddress(recv, addrs[i]));
  599. c[3] = r.newString(addrs[i].getHostAddress());
  600. c[4] = r.newFixnum(is_ipv6 ? PF_INET6 : PF_INET);
  601. c[5] = r.newFixnum(SOCK_DGRAM);
  602. c[6] = r.newFixnum(IPPROTO_UDP);
  603. l.add(r.newArrayNoCopy(c));
  604. }
  605. if(sock_stream) {
  606. c = new IRubyObject[7];
  607. c[0] = r.newString(is_ipv6 ? "AF_INET6" : "AF_INET");
  608. c[1] = port;
  609. c[2] = r.newString(getHostAddress(recv, addrs[i]));
  610. c[3] = r.newString(addrs[i].getHostAddress());
  611. c[4] = r.newFixnum(is_ipv6 ? PF_INET6 : PF_INET);
  612. c[5] = r.newFixnum(SOCK_STREAM);
  613. c[6] = r.newFixnum(IPPROTO_TCP);
  614. l.add(r.newArrayNoCopy(c));
  615. }
  616. }
  617. return r.newArray(l);
  618. } catch(UnknownHostException e) {
  619. throw sockerr(context.getRuntime(), "getaddrinfo: name or service not known");
  620. }
  621. }
  622. @Deprecated
  623. public static IRubyObject getnameinfo(IRubyObject recv, IRubyObject[] args) {
  624. return getnameinfo(recv.getRuntime().getCurrentContext(), recv, args);
  625. }
  626. @JRubyMethod(required = 1, optional = 1, meta = true)
  627. public static IRubyObject getnameinfo(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  628. Ruby runtime = context.getRuntime();
  629. int argc = Arity.checkArgumentCount(runtime, args, 1, 2);
  630. int flags = argc == 2 ? RubyNumeric.num2int(args[1]) : 0;
  631. IRubyObject arg0 = args[0];
  632. String host, port;
  633. if (arg0 instanceof RubyArray) {
  634. List list = ((RubyArray)arg0).getList();
  635. int len = list.size();
  636. if (len < 3 || len > 4) {
  637. throw runtime.newArgumentError("array size should be 3 or 4, "+len+" given");
  638. }
  639. // if array has 4 elements, third element is ignored
  640. host = list.size() == 3 ? list.get(2).toString() : list.get(3).toString();
  641. port = list.get(1).toString();
  642. } else if (arg0 instanceof RubyString) {
  643. String arg = ((RubyString)arg0).toString();
  644. Matcher m = STRING_IPV4_ADDRESS_PATTERN.matcher(arg);
  645. if (!m.matches()) {
  646. IRubyObject obj = unpack_sockaddr_in(context, recv, arg0);
  647. if (obj instanceof RubyArray) {
  648. List list = ((RubyArray)obj).getList();
  649. int len = list.size();
  650. if (len != 2) {
  651. throw runtime.newArgumentError("invalid address representation");
  652. }
  653. host = list.get(1).toString();
  654. port = list.get(0).toString();
  655. }
  656. else {
  657. throw runtime.newArgumentError("invalid address string");
  658. }
  659. } else if ((host = m.group(IPV4_HOST_GROUP)) == null || host.length() == 0 ||
  660. (port = m.group(IPV4_PORT_GROUP)) == null || port.length() == 0) {
  661. throw runtime.newArgumentError("invalid address string");
  662. } else {
  663. // Try IPv6
  664. try {
  665. InetAddress ipv6_addr = InetAddress.getByName(host);
  666. if (ipv6_addr instanceof Inet6Address) {
  667. host = ipv6_addr.getHostAddress();
  668. }
  669. } catch (UnknownHostException uhe) {
  670. throw runtime.newArgumentError("invalid address string");
  671. }
  672. }
  673. } else {
  674. throw runtime.newArgumentError("invalid args");
  675. }
  676. InetAddress addr;
  677. try {
  678. addr = InetAddress.getByName(host);
  679. } catch (UnknownHostException e) {
  680. throw sockerr(runtime, "unknown host: "+ host);
  681. }
  682. if ((flags & NI_NUMERICHOST.value()) == 0) {
  683. host = addr.getCanonicalHostName();
  684. } else {
  685. host = addr.getHostAddress();
  686. }
  687. jnr.netdb.Service serv = jnr.netdb.Service.getServiceByPort(Integer.parseInt(port), null);
  688. if (serv != null) {
  689. if ((flags & NI_NUMERICSERV.value()) == 0) {
  690. port = serv.getName();
  691. } else {
  692. port = Integer.toString(serv.getPort());
  693. }
  694. }
  695. return runtime.newArray(runtime.newString(host), runtime.newString(port));
  696. }
  697. private static String getHostAddress(IRubyObject recv, InetAddress addr) {
  698. return do_not_reverse_lookup(recv).isTrue() ? addr.getHostAddress() : addr.getCanonicalHostName();
  699. }
  700. private static final Pattern STRING_IPV4_ADDRESS_PATTERN =
  701. Pattern.compile("((.*)\\/)?([\\.0-9]+)(:([0-9]+))?");
  702. private final static Pattern ALREADY_BOUND_PATTERN = Pattern.compile("[Aa]lready.*bound");
  703. private final static Pattern ADDR_NOT_AVAIL_PATTERN = Pattern.compile("assign.*address");
  704. private final static Pattern PERM_DENIED_PATTERN = Pattern.compile("[Pp]ermission.*denied");
  705. private static final int IPV4_HOST_GROUP = 3;
  706. private static final int IPV4_PORT_GROUP = 5;
  707. }// RubySocket