PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/rkh/jruby
Java | 323 lines | 252 code | 33 blank | 38 comment | 35 complexity | cbf8cf1230b4baae80f5598708954984 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 Damian Steer <pldms@mac.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 java.io.IOException;
  30. import java.net.ConnectException;
  31. import java.net.InetAddress;
  32. import java.net.InetSocketAddress;
  33. import java.net.PortUnreachableException;
  34. import java.net.SocketException;
  35. import java.net.MulticastSocket;
  36. import java.net.UnknownHostException;
  37. import java.net.DatagramPacket;
  38. import java.nio.ByteBuffer;
  39. import java.nio.channels.DatagramChannel;
  40. import java.nio.channels.SelectionKey;
  41. import org.jruby.Ruby;
  42. import org.jruby.RubyClass;
  43. import org.jruby.RubyFixnum;
  44. import org.jruby.RubyModule;
  45. import org.jruby.RubyNumeric;
  46. import org.jruby.RubyString;
  47. import org.jruby.anno.JRubyClass;
  48. import org.jruby.anno.JRubyMethod;
  49. import org.jruby.runtime.Block;
  50. import org.jruby.runtime.ObjectAllocator;
  51. import org.jruby.runtime.ThreadContext;
  52. import org.jruby.runtime.Visibility;
  53. import org.jruby.runtime.builtin.IRubyObject;
  54. import org.jruby.util.ByteList;
  55. import org.jruby.util.io.ModeFlags;
  56. import org.jruby.util.io.ChannelDescriptor;
  57. /**
  58. * @author <a href="mailto:pldms@mac.com">Damian Steer</a>
  59. */
  60. @JRubyClass(name="UDPSocket", parent="IPSocket")
  61. public class RubyUDPSocket extends RubyIPSocket {
  62. static void createUDPSocket(Ruby runtime) {
  63. RubyClass rb_cUDPSocket = runtime.defineClass("UDPSocket", runtime.getClass("IPSocket"), UDPSOCKET_ALLOCATOR);
  64. rb_cUDPSocket.includeModule(runtime.getClass("Socket").getConstant("Constants"));
  65. rb_cUDPSocket.defineAnnotatedMethods(RubyUDPSocket.class);
  66. runtime.getObject().setConstant("UDPsocket", rb_cUDPSocket);
  67. }
  68. private static ObjectAllocator UDPSOCKET_ALLOCATOR = new ObjectAllocator() {
  69. public IRubyObject allocate(Ruby runtime, RubyClass klass) {
  70. return new RubyUDPSocket(runtime, klass);
  71. }
  72. };
  73. public RubyUDPSocket(Ruby runtime, RubyClass type) {
  74. super(runtime, type);
  75. }
  76. @JRubyMethod(visibility = Visibility.PRIVATE)
  77. public IRubyObject initialize(ThreadContext context) {
  78. try {
  79. DatagramChannel channel = DatagramChannel.open();
  80. initSocket(context.getRuntime(), new ChannelDescriptor(channel, new ModeFlags(ModeFlags.RDWR)));
  81. } catch (org.jruby.util.io.InvalidValueException ex) {
  82. throw context.getRuntime().newErrnoEINVALError();
  83. } catch (ConnectException e) {
  84. throw context.getRuntime().newErrnoECONNREFUSEDError();
  85. } catch (UnknownHostException e) {
  86. throw sockerr(context.getRuntime(), "initialize: name or service not known");
  87. } catch (IOException e) {
  88. throw sockerr(context.getRuntime(), "initialize: name or service not known");
  89. }
  90. return this;
  91. }
  92. @JRubyMethod(visibility = Visibility.PRIVATE)
  93. public IRubyObject initialize(ThreadContext context, IRubyObject protocol) {
  94. // we basically ignore protocol. let someone report it...
  95. return initialize(context);
  96. }
  97. @Deprecated
  98. public IRubyObject bind(IRubyObject host, IRubyObject port) {
  99. return bind(getRuntime().getCurrentContext(), host, port);
  100. }
  101. @JRubyMethod
  102. public IRubyObject bind(ThreadContext context, IRubyObject host, IRubyObject port) {
  103. InetSocketAddress addr = null;
  104. try {
  105. if (host.isNil()
  106. || ((host instanceof RubyString)
  107. && ((RubyString) host).isEmpty())) {
  108. // host is nil or the empty string, bind to INADDR_ANY
  109. addr = new InetSocketAddress(RubyNumeric.fix2int(port));
  110. } else if (host instanceof RubyFixnum) {
  111. // passing in something like INADDR_ANY
  112. int intAddr = RubyNumeric.fix2int(host);
  113. RubyModule socketMod = context.getRuntime().getModule("Socket");
  114. if (intAddr == RubyNumeric.fix2int(socketMod.getConstant("INADDR_ANY"))) {
  115. addr = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), RubyNumeric.fix2int(port));
  116. }
  117. } else {
  118. // passing in something like INADDR_ANY
  119. addr = new InetSocketAddress(InetAddress.getByName(host.convertToString().toString()), RubyNumeric.fix2int(port));
  120. }
  121. if (this.multicastStateManager == null) {
  122. ((DatagramChannel) this.getChannel()).socket().bind(addr);
  123. } else {
  124. this.multicastStateManager.rebindToPort(RubyNumeric.fix2int(port));
  125. }
  126. return RubyFixnum.zero(context.getRuntime());
  127. } catch (UnknownHostException e) {
  128. throw sockerr(context.getRuntime(), "bind: name or service not known");
  129. } catch (SocketException e) {
  130. throw sockerr(context.getRuntime(), "bind: name or service not known");
  131. } catch (IOException e) {
  132. throw sockerr(context.getRuntime(), "bind: name or service not known");
  133. } catch (Error e) {
  134. // Workaround for a bug in Sun's JDK 1.5.x, see
  135. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6303753
  136. if (e.getCause() instanceof SocketException) {
  137. throw sockerr(context.getRuntime(), "bind: name or service not known");
  138. } else {
  139. throw e;
  140. }
  141. }
  142. }
  143. @Deprecated
  144. public IRubyObject connect(IRubyObject host, IRubyObject port) {
  145. return connect(getRuntime().getCurrentContext(), host, port);
  146. }
  147. @JRubyMethod
  148. public IRubyObject connect(ThreadContext context, IRubyObject host, IRubyObject port) {
  149. try {
  150. InetSocketAddress addr;
  151. addr = new InetSocketAddress(InetAddress.getByName(host.convertToString().toString()), RubyNumeric.fix2int(port));
  152. ((DatagramChannel) this.getChannel()).connect(addr);
  153. return RubyFixnum.zero(context.getRuntime());
  154. } catch (UnknownHostException e) {
  155. throw sockerr(context.getRuntime(), "connect: name or service not known");
  156. } catch (IOException e) {
  157. throw sockerr(context.getRuntime(), "connect: name or service not known");
  158. }
  159. }
  160. @Deprecated
  161. public IRubyObject recvfrom(IRubyObject[] args) {
  162. return recvfrom(getRuntime().getCurrentContext(), args);
  163. }
  164. @JRubyMethod(required = 1, rest = true)
  165. public IRubyObject recvfrom(ThreadContext context, IRubyObject[] args) {
  166. try {
  167. InetSocketAddress sender = null;
  168. int length = RubyNumeric.fix2int(args[0]);
  169. ByteBuffer buf = ByteBuffer.allocate(length);
  170. byte[] buf2 = new byte[length];
  171. DatagramPacket recv = new DatagramPacket(buf2, buf2.length);
  172. if (this.multicastStateManager == null) {
  173. ((DatagramChannel) this.getChannel()).configureBlocking(false);
  174. context.getThread().select(this, SelectionKey.OP_READ);
  175. sender = (InetSocketAddress) ((DatagramChannel) this.getChannel()).receive(buf);
  176. } else {
  177. MulticastSocket ms = this.multicastStateManager.getMulticastSocket();
  178. ms.receive(recv);
  179. sender = (InetSocketAddress) recv.getSocketAddress();
  180. }
  181. // see JRUBY-4678
  182. if (sender == null) {
  183. throw context.getRuntime().newErrnoECONNRESETError();
  184. }
  185. IRubyObject addressArray = context.getRuntime().newArray(new IRubyObject[]{
  186. context.getRuntime().newString("AF_INET"),
  187. context.getRuntime().newFixnum(sender.getPort()),
  188. context.getRuntime().newString(sender.getHostName()),
  189. context.getRuntime().newString(sender.getAddress().getHostAddress())
  190. });
  191. IRubyObject result = null;
  192. if (this.multicastStateManager == null) {
  193. result = context.getRuntime().newString(new ByteList(buf.array(), 0, buf.position()));
  194. } else {
  195. result = context.getRuntime().newString(new ByteList(recv.getData(), 0, recv.getLength()));
  196. }
  197. return context.getRuntime().newArray(new IRubyObject[]{result, addressArray});
  198. } catch (UnknownHostException e) {
  199. throw sockerr(context.getRuntime(), "recvfrom: name or service not known");
  200. } catch (PortUnreachableException e) {
  201. throw context.getRuntime().newErrnoECONNREFUSEDError();
  202. } catch (IOException e) {
  203. throw sockerr(context.getRuntime(), "recvfrom: name or service not known");
  204. }
  205. }
  206. @Override
  207. public IRubyObject recv(ThreadContext context, IRubyObject[] args) {
  208. try {
  209. int length = RubyNumeric.fix2int(args[0]);
  210. ByteBuffer buf = ByteBuffer.allocate(length);
  211. ((DatagramChannel) this.getChannel()).configureBlocking(false);
  212. context.getThread().select(this, SelectionKey.OP_READ);
  213. InetSocketAddress sender = (InetSocketAddress) ((DatagramChannel) this.getChannel()).receive(buf);
  214. // see JRUBY-4678
  215. if (sender == null) {
  216. throw context.getRuntime().newErrnoECONNRESETError();
  217. }
  218. return context.getRuntime().newString(new ByteList(buf.array(), 0, buf.position()));
  219. } catch (IOException e) {
  220. throw sockerr(context.getRuntime(), "recv: name or service not known");
  221. }
  222. }
  223. @Deprecated
  224. public IRubyObject send(IRubyObject[] args) {
  225. return send(getRuntime().getCurrentContext(), args);
  226. }
  227. @JRubyMethod(required = 1, rest = true)
  228. public IRubyObject send(ThreadContext context, IRubyObject[] args) {
  229. try {
  230. int written;
  231. if (args.length >= 3) { // host and port given
  232. RubyString nameStr = args[2].convertToString();
  233. RubyString data = args[0].convertToString();
  234. ByteBuffer buf = ByteBuffer.wrap(data.getBytes());
  235. byte [] buf2 = data.getBytes();
  236. DatagramPacket sendDP = null;
  237. int port;
  238. if (args[3] instanceof RubyString) {
  239. jnr.netdb.Service service = jnr.netdb.Service.getServiceByName(args[3].asJavaString(), "udp");
  240. if (service != null) {
  241. port = service.getPort();
  242. } else {
  243. port = (int)args[3].convertToInteger("to_i").getLongValue();
  244. }
  245. } else {
  246. port = (int)args[3].convertToInteger().getLongValue();
  247. }
  248. InetAddress address = RubySocket.getRubyInetAddress(nameStr.getByteList());
  249. InetSocketAddress addr =
  250. new InetSocketAddress(address, port);
  251. if (this.multicastStateManager == null) {
  252. written = ((DatagramChannel) this.getChannel()).send(buf, addr);
  253. }
  254. else {
  255. sendDP = new DatagramPacket(buf2, buf2.length, address, port);
  256. MulticastSocket ms = this.multicastStateManager.getMulticastSocket();
  257. ms.send(sendDP);
  258. written = sendDP.getLength();
  259. }
  260. } else {
  261. RubyString data = args[0].convertToString();
  262. ByteBuffer buf = ByteBuffer.wrap(data.getBytes());
  263. written = ((DatagramChannel) this.getChannel()).write(buf);
  264. }
  265. return context.getRuntime().newFixnum(written);
  266. } catch (UnknownHostException e) {
  267. throw sockerr(context.getRuntime(), "send: name or service not known");
  268. } catch (IOException e) {
  269. throw sockerr(context.getRuntime(), "send: name or service not known");
  270. }
  271. }
  272. @Deprecated
  273. public static IRubyObject open(IRubyObject recv, IRubyObject[] args, Block block) {
  274. return open(recv.getRuntime().getCurrentContext(), recv, args, block);
  275. }
  276. @JRubyMethod(rest = true, meta = true)
  277. public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
  278. RubyUDPSocket sock = (RubyUDPSocket) recv.callMethod(context, "new", args);
  279. if (!block.isGiven()) {
  280. return sock;
  281. }
  282. try {
  283. return block.yield(context, sock);
  284. } finally {
  285. if (sock.openFile.isOpen()) {
  286. sock.close();
  287. }
  288. }
  289. }
  290. }// RubyUDPSocket