RubyServerSocket.java

  1. /***** BEGIN LICENSE BLOCK *****
  2.  * Version: EPL 1.0/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Eclipse 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/epl-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 EPL, 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 EPL, the GPL or the LGPL.
  27.  ***** END LICENSE BLOCK *****/
  28. package org.jruby.ext.socket;

  29. import jnr.constants.platform.Sock;
  30. import org.jruby.Ruby;
  31. import org.jruby.RubyArray;
  32. import org.jruby.RubyClass;
  33. import org.jruby.RubyFixnum;
  34. import org.jruby.anno.JRubyClass;
  35. import org.jruby.anno.JRubyMethod;
  36. import org.jruby.common.IRubyWarnings;
  37. import org.jruby.runtime.ObjectAllocator;
  38. import org.jruby.runtime.ThreadContext;
  39. import org.jruby.runtime.builtin.IRubyObject;
  40. import org.jruby.util.io.ChannelFD;
  41. import org.jruby.util.io.ModeFlags;
  42. import org.jruby.util.io.Sockaddr;

  43. import java.io.IOException;
  44. import java.net.InetSocketAddress;
  45. import java.net.ServerSocket;
  46. import java.net.SocketException;
  47. import java.net.UnknownHostException;
  48. import java.nio.channels.Channel;
  49. import java.nio.channels.IllegalBlockingModeException;
  50. import java.nio.channels.SelectableChannel;
  51. import java.nio.channels.ServerSocketChannel;
  52. import java.nio.channels.SocketChannel;

  53. /**
  54.  * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
  55.  */
  56. @JRubyClass(name="Socket", parent="BasicSocket", include="Socket::Constants")
  57. public class RubyServerSocket extends RubySocket {
  58.     static void createServerSocket(Ruby runtime) {
  59.         RubyClass rb_cSocket = runtime.defineClass("ServerSocket", runtime.getClass("Socket"), SERVER_SOCKET_ALLOCATOR);

  60.         rb_cSocket.defineAnnotatedMethods(RubyServerSocket.class);
  61.     }

  62.     private static ObjectAllocator SERVER_SOCKET_ALLOCATOR = new ObjectAllocator() {
  63.         public IRubyObject allocate(Ruby runtime, RubyClass klass) {
  64.             return new RubyServerSocket(runtime, klass);
  65.         }
  66.     };

  67.     public RubyServerSocket(Ruby runtime, RubyClass type) {
  68.         super(runtime, type);
  69.     }

  70.     @JRubyMethod(name = "listen")
  71.     public IRubyObject listen(ThreadContext context, IRubyObject backlog) {
  72.         context.runtime.getWarnings().warnOnce(
  73.                 IRubyWarnings.ID.LISTEN_SERVER_SOCKET,
  74.                 "pass backlog to #bind instead of #listen (http://wiki.jruby.org/ServerSocket)");

  75.         return context.runtime.newFixnum(0);
  76.     }

  77.     @JRubyMethod(notImplemented = true)
  78.     public IRubyObject connect_nonblock(ThreadContext context, IRubyObject arg) {
  79.         throw SocketUtils.sockerr(context.runtime, "server socket cannot connect");
  80.     }

  81.     @JRubyMethod(notImplemented = true)
  82.     public IRubyObject connect(ThreadContext context, IRubyObject arg) {
  83.         throw SocketUtils.sockerr(context.runtime, "server socket cannot connect");
  84.     }

  85.     @JRubyMethod()
  86.     public IRubyObject bind(ThreadContext context, IRubyObject addr) {
  87.         InetSocketAddress iaddr = null;

  88.         if (addr instanceof Addrinfo) {
  89.             Addrinfo addrInfo = (Addrinfo) addr;
  90.             iaddr = new InetSocketAddress(addrInfo.getInetAddress().getHostAddress(), addrInfo.getPort());
  91.         } else {
  92.             iaddr = Sockaddr.addressFromSockaddr_in(context, addr);
  93.         }

  94.         doBind(context, getChannel(), iaddr, 0);
  95.         return RubyFixnum.zero(context.runtime);
  96.     }

  97.     @JRubyMethod()
  98.     public IRubyObject bind(ThreadContext context, IRubyObject addr, IRubyObject backlog) {
  99.         InetSocketAddress iaddr = null;

  100.         if (addr instanceof Addrinfo) {
  101.             Addrinfo addrInfo = (Addrinfo) addr;
  102.             iaddr = new InetSocketAddress(addrInfo.getInetAddress().getHostAddress(), addrInfo.getPort());
  103.         } else {
  104.             iaddr = Sockaddr.addressFromSockaddr_in(context, addr);
  105.         }
  106.         doBind(context, getChannel(), iaddr, RubyFixnum.fix2int(backlog));

  107.         return RubyFixnum.zero(context.runtime);
  108.     }

  109.     @JRubyMethod()
  110.     public IRubyObject accept(ThreadContext context) {
  111.         return doAccept(context, getChannel());
  112.     }

  113.     @JRubyMethod()
  114.     public IRubyObject accept_nonblock(ThreadContext context) {
  115.         return doAcceptNonblock(context, getChannel());
  116.     }

  117.     protected ChannelFD initChannelFD(Ruby runtime) {
  118.         Channel channel;

  119.         try {
  120.             if(soType == Sock.SOCK_STREAM) {
  121.                 channel = ServerSocketChannel.open();

  122.             } else {
  123.                 throw runtime.newArgumentError("unsupported server socket type `" + soType + "'");

  124.             }

  125.             return newChannelFD(runtime, channel);

  126.         } catch (IOException e) {
  127.             throw SocketUtils.sockerr(runtime, "initialize: " + e.toString());

  128.         }
  129.     }

  130.     private RubyArray doAcceptNonblock(ThreadContext context, Channel channel) {
  131.         try {
  132.             if (channel instanceof SelectableChannel) {
  133.                 SelectableChannel selectable = (SelectableChannel)channel;

  134.                 synchronized (selectable.blockingLock()) {
  135.                     boolean oldBlocking = selectable.isBlocking();

  136.                     try {
  137.                         selectable.configureBlocking(false);

  138.                         RubySocket socket = doAccept(context, channel);
  139.                         SocketChannel socketChannel = (SocketChannel)socket.getChannel();
  140.                         InetSocketAddress addr = (InetSocketAddress)socketChannel.socket().getRemoteSocketAddress();

  141.                         return context.runtime.newArray(
  142.                                 socket,
  143.                                 Sockaddr.packSockaddrFromAddress(context, addr));
  144.                     } finally {
  145.                         selectable.configureBlocking(oldBlocking);
  146.                     }
  147.                 }
  148.             } else {
  149.                 throw getRuntime().newErrnoENOPROTOOPTError();

  150.             }

  151.         } catch (IOException e) {
  152.             throw SocketUtils.sockerr(context.runtime, e.getLocalizedMessage());

  153.         }
  154.     }

  155.     private RubySocket doAccept(ThreadContext context, Channel channel) {
  156.         Ruby runtime = context.runtime;

  157.         try {
  158.             if (channel instanceof ServerSocketChannel) {
  159.                 ServerSocketChannel serverChannel = (ServerSocketChannel)getChannel();

  160.                 SocketChannel socket = serverChannel.accept();

  161.                 if (socket == null) {
  162.                     // This appears to be undocumented in JDK; null as a sentinel value
  163.                     // for a nonblocking accept with nothing available. We raise for Ruby.
  164.                     // indicates that no connection is available in non-blocking mode
  165.                     throw runtime.newErrnoEAGAINReadableError("accept(2) would block");
  166.                 }

  167.                 RubySocket rubySocket = new RubySocket(runtime, runtime.getClass("Socket"));
  168.                 rubySocket.initFromServer(runtime, this, socket);

  169.                 return rubySocket;

  170.             } else {
  171.                 throw runtime.newErrnoENOPROTOOPTError();
  172.             }

  173.         } catch (IllegalBlockingModeException ibme) {
  174.             // indicates that no connection is available in non-blocking mode
  175.             throw runtime.newErrnoEAGAINReadableError("accept(2) would block");

  176.         } catch (IOException e) {
  177.             throw SocketUtils.sockerr(runtime, e.getLocalizedMessage());

  178.         }
  179.     }

  180.     private void doBind(ThreadContext context, Channel channel, InetSocketAddress iaddr, int backlog) {
  181.         Ruby runtime = context.runtime;

  182.         try {
  183.             if (channel instanceof ServerSocketChannel) {
  184.                 ServerSocket socket = ((ServerSocketChannel)channel).socket();
  185.                 socket.bind(iaddr, backlog);

  186.             } else {
  187.                 throw runtime.newErrnoENOPROTOOPTError();
  188.             }

  189.         } catch (UnknownHostException e) {
  190.             throw SocketUtils.sockerr(runtime, "bind(2): unknown host");

  191.         } catch (SocketException e) {
  192.             handleSocketException(runtime, "bind", e);

  193.         } catch (IOException e) {
  194.             throw SocketUtils.sockerr(runtime, "bind(2): name or service not known");

  195.         } catch (IllegalArgumentException iae) {
  196.             throw SocketUtils.sockerr(runtime, iae.getMessage());

  197.         }
  198.     }
  199. }// RubySocket