PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/jruby/jruby
Java | 671 lines | 507 code | 116 blank | 48 comment | 77 complexity | a7c556b64fce30146026138aed61f833 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, GPL-2.0, JSON, LGPL-2.1
  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 java.io.IOException;
  30. import java.net.DatagramSocket;
  31. import java.net.InetSocketAddress;
  32. import java.net.InterfaceAddress;
  33. import java.net.NetworkInterface;
  34. import java.net.Socket;
  35. import java.net.SocketAddress;
  36. import java.net.SocketException;
  37. import java.net.UnknownHostException;
  38. import java.nio.channels.AlreadyConnectedException;
  39. import java.nio.channels.Channel;
  40. import java.nio.channels.ClosedChannelException;
  41. import java.nio.channels.ConnectionPendingException;
  42. import java.nio.channels.DatagramChannel;
  43. import java.nio.channels.SelectableChannel;
  44. import java.nio.channels.SocketChannel;
  45. import java.util.Enumeration;
  46. import java.util.regex.Pattern;
  47. import jnr.constants.platform.AddressFamily;
  48. import jnr.constants.platform.INAddr;
  49. import jnr.constants.platform.IPProto;
  50. import jnr.constants.platform.NameInfo;
  51. import jnr.constants.platform.ProtocolFamily;
  52. import jnr.constants.platform.Shutdown;
  53. import jnr.constants.platform.Sock;
  54. import jnr.constants.platform.SocketLevel;
  55. import jnr.constants.platform.SocketOption;
  56. import jnr.constants.platform.TCP;
  57. import jnr.netdb.Protocol;
  58. import jnr.unixsocket.UnixSocketAddress;
  59. import jnr.unixsocket.UnixSocketChannel;
  60. import org.jruby.Ruby;
  61. import org.jruby.RubyArray;
  62. import org.jruby.RubyClass;
  63. import org.jruby.RubyFixnum;
  64. import org.jruby.RubyModule;
  65. import org.jruby.anno.JRubyClass;
  66. import org.jruby.anno.JRubyMethod;
  67. import org.jruby.ast.util.ArgsUtil;
  68. import org.jruby.exceptions.RaiseException;
  69. import org.jruby.runtime.ObjectAllocator;
  70. import org.jruby.runtime.ThreadContext;
  71. import org.jruby.runtime.Visibility;
  72. import org.jruby.runtime.builtin.IRubyObject;
  73. import org.jruby.util.io.ChannelFD;
  74. import org.jruby.util.io.Sockaddr;
  75. import static org.jruby.runtime.Helpers.arrayOf;
  76. /**
  77. * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
  78. */
  79. @JRubyClass(name="Socket", parent="BasicSocket", include="Socket::Constants")
  80. public class RubySocket extends RubyBasicSocket {
  81. static void createSocket(Ruby runtime) {
  82. RubyClass rb_cSocket = runtime.defineClass("Socket", runtime.getClass("BasicSocket"), SOCKET_ALLOCATOR);
  83. RubyModule rb_mConstants = rb_cSocket.defineModuleUnder("Constants");
  84. // we don't have to define any that we don't support; see socket.c
  85. runtime.loadConstantSet(rb_mConstants, Sock.class);
  86. runtime.loadConstantSet(rb_mConstants, SocketOption.class);
  87. runtime.loadConstantSet(rb_mConstants, SocketLevel.class);
  88. runtime.loadConstantSet(rb_mConstants, ProtocolFamily.class);
  89. runtime.loadConstantSet(rb_mConstants, AddressFamily.class);
  90. runtime.loadConstantSet(rb_mConstants, INAddr.class);
  91. runtime.loadConstantSet(rb_mConstants, IPProto.class);
  92. runtime.loadConstantSet(rb_mConstants, Shutdown.class);
  93. runtime.loadConstantSet(rb_mConstants, TCP.class);
  94. runtime.loadConstantSet(rb_mConstants, NameInfo.class);
  95. // this value seems to be hardcoded in MRI to 5 when not defined, but
  96. // it is 128 on OS X. We use 128 for now until we can get it added to
  97. // jnr-constants.
  98. rb_mConstants.setConstant("SOMAXCONN", RubyFixnum.newFixnum(runtime, 128));
  99. // mandatory constants we haven't implemented
  100. rb_mConstants.setConstant("MSG_OOB", runtime.newFixnum(MSG_OOB));
  101. rb_mConstants.setConstant("MSG_PEEK", runtime.newFixnum(MSG_PEEK));
  102. rb_mConstants.setConstant("MSG_DONTROUTE", runtime.newFixnum(MSG_DONTROUTE));
  103. rb_mConstants.setConstant("MSG_WAITALL", runtime.newFixnum(MSG_WAITALL));
  104. // constants webrick crashes without
  105. rb_mConstants.setConstant("AI_PASSIVE", runtime.newFixnum(1));
  106. // More constants needed by specs
  107. rb_mConstants.setConstant("IP_MULTICAST_TTL", runtime.newFixnum(10));
  108. rb_mConstants.setConstant("IP_MULTICAST_LOOP", runtime.newFixnum(11));
  109. rb_mConstants.setConstant("IP_ADD_MEMBERSHIP", runtime.newFixnum(12));
  110. rb_mConstants.setConstant("IP_MAX_MEMBERSHIPS", runtime.newFixnum(20));
  111. rb_mConstants.setConstant("IP_DEFAULT_MULTICAST_LOOP", runtime.newFixnum(1));
  112. rb_mConstants.setConstant("IP_DEFAULT_MULTICAST_TTL", runtime.newFixnum(1));
  113. rb_cSocket.includeModule(rb_mConstants);
  114. rb_cSocket.defineAnnotatedMethods(RubySocket.class);
  115. }
  116. private static ObjectAllocator SOCKET_ALLOCATOR = new ObjectAllocator() {
  117. @Override
  118. public IRubyObject allocate(Ruby runtime, RubyClass klass) {
  119. return new RubySocket(runtime, klass);
  120. }
  121. };
  122. public RubySocket(Ruby runtime, RubyClass type) {
  123. super(runtime, type);
  124. }
  125. @JRubyMethod(meta = true)
  126. public static IRubyObject for_fd(ThreadContext context, IRubyObject socketClass, IRubyObject _fd) {
  127. Ruby runtime = context.runtime;
  128. if (_fd instanceof RubyFixnum) {
  129. int intFD = (int)((RubyFixnum)_fd).getLongValue();
  130. ChannelFD fd = runtime.getFilenoUtil().getWrapperFromFileno(intFD);
  131. if (fd == null) {
  132. throw runtime.newErrnoEBADFError();
  133. }
  134. RubySocket socket = (RubySocket)((RubyClass)socketClass).allocate();
  135. socket.initFieldsFromDescriptor(runtime, fd);
  136. socket.initSocket(fd);
  137. return socket;
  138. } else {
  139. throw runtime.newTypeError(_fd, context.runtime.getFixnum());
  140. }
  141. }
  142. @JRubyMethod(name = "initialize", visibility = Visibility.PRIVATE)
  143. public IRubyObject initialize(ThreadContext context, IRubyObject domain, IRubyObject type) {
  144. Ruby runtime = context.runtime;
  145. initFieldsFromArgs(runtime, domain, type);
  146. ChannelFD fd = initChannelFD(runtime);
  147. initSocket(fd);
  148. return this;
  149. }
  150. @JRubyMethod(name = "initialize", visibility = Visibility.PRIVATE)
  151. public IRubyObject initialize(ThreadContext context, IRubyObject domain, IRubyObject type, IRubyObject protocol) {
  152. Ruby runtime = context.runtime;
  153. initFieldsFromArgs(runtime, domain, type, protocol);
  154. ChannelFD fd = initChannelFD(runtime);
  155. initSocket(fd);
  156. return this;
  157. }
  158. @JRubyMethod()
  159. public IRubyObject connect_nonblock(ThreadContext context, IRubyObject arg) {
  160. return connect_nonblock(context, arg, context.nil);
  161. }
  162. @JRubyMethod()
  163. public IRubyObject connect_nonblock(ThreadContext context, IRubyObject arg, IRubyObject opts) {
  164. Ruby runtime = context.runtime;
  165. SocketAddress addr = addressForChannel(context, arg);
  166. boolean exception = ArgsUtil.extractKeywordArg(context, "exception", opts) != runtime.getFalse();
  167. return doConnectNonblock(context, getChannel(), addr, exception);
  168. }
  169. @JRubyMethod()
  170. public IRubyObject connect(ThreadContext context, IRubyObject arg) {
  171. SocketAddress addr = addressForChannel(context, arg);
  172. return doConnect(context, getChannel(), addr, true);
  173. }
  174. @JRubyMethod()
  175. public IRubyObject bind(ThreadContext context, IRubyObject arg) {
  176. final InetSocketAddress iaddr;
  177. if (arg instanceof Addrinfo) {
  178. Addrinfo addr = (Addrinfo) arg;
  179. iaddr = new InetSocketAddress(addr.getInetAddress().getHostAddress(), addr.getPort());
  180. }
  181. else {
  182. iaddr = Sockaddr.addressFromSockaddr_in(context, arg);
  183. }
  184. doBind(context, getChannel(), iaddr);
  185. return RubyFixnum.zero(context.runtime);
  186. }
  187. @JRubyMethod
  188. public IRubyObject recvfrom(ThreadContext context, IRubyObject length) {
  189. return super.recv(context, length);
  190. }
  191. @JRubyMethod
  192. public IRubyObject recvfrom(ThreadContext context, IRubyObject length, IRubyObject flags) {
  193. return super.recv(context, length, flags);
  194. }
  195. @JRubyMethod
  196. public IRubyObject recvfrom_nonblock(ThreadContext context, IRubyObject length) {
  197. return super.recv_nonblock(context, length);
  198. }
  199. @JRubyMethod(required = 1, optional = 3)
  200. public IRubyObject recvfrom_nonblock(ThreadContext context, IRubyObject[] args) {
  201. return super.recv_nonblock(context, args);
  202. }
  203. @JRubyMethod(notImplemented = true)
  204. public IRubyObject listen(ThreadContext context, IRubyObject backlog) {
  205. throw SocketUtils.sockerr(context.runtime, JRUBY_SERVER_SOCKET_ERROR);
  206. }
  207. @JRubyMethod(notImplemented = true)
  208. public IRubyObject accept(ThreadContext context) {
  209. throw SocketUtils.sockerr(context.runtime, JRUBY_SERVER_SOCKET_ERROR);
  210. }
  211. @JRubyMethod(notImplemented = true, optional = 1)
  212. public IRubyObject accept_nonblock(ThreadContext context, IRubyObject[] args) {
  213. throw SocketUtils.sockerr(context.runtime, JRUBY_SERVER_SOCKET_ERROR);
  214. }
  215. @JRubyMethod(meta = true)
  216. public static IRubyObject gethostname(ThreadContext context, IRubyObject recv) {
  217. return SocketUtils.gethostname(context);
  218. }
  219. @JRubyMethod(meta = true)
  220. public static IRubyObject getifaddrs(ThreadContext context, IRubyObject recv) {
  221. RubyArray list = RubyArray.newArray(context.runtime);
  222. try {
  223. Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
  224. RubyClass Ifaddr = (RubyClass) context.runtime.getClassFromPath("Socket::Ifaddr");
  225. while (en.hasMoreElements()) {
  226. NetworkInterface ni = en.nextElement();
  227. // create interface link layer ifaddr
  228. list.append(new Ifaddr(context.runtime, Ifaddr, ni));
  229. for ( InterfaceAddress ia : ni.getInterfaceAddresses() ) {
  230. list.append(new Ifaddr(context.runtime, Ifaddr, ni, ia));
  231. }
  232. }
  233. }
  234. catch (Exception ex) {
  235. if ( ex instanceof RaiseException ) throw (RaiseException) ex;
  236. throw SocketUtils.sockerr_with_trace(context.runtime, "getifaddrs: " + ex.toString(), ex.getStackTrace());
  237. }
  238. return list;
  239. }
  240. @JRubyMethod(required = 1, rest = true, meta = true)
  241. public static IRubyObject gethostbyaddr(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  242. return SocketUtils.gethostbyaddr(context, args);
  243. }
  244. @JRubyMethod(required = 1, optional = 1, meta = true)
  245. public static IRubyObject getservbyname(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  246. return SocketUtils.getservbyname(context, args);
  247. }
  248. @JRubyMethod(name = {"pack_sockaddr_in", "sockaddr_in"}, meta = true)
  249. public static IRubyObject pack_sockaddr_in(ThreadContext context, IRubyObject recv, IRubyObject port, IRubyObject host) {
  250. return SocketUtils.pack_sockaddr_in(context, port, host);
  251. }
  252. @JRubyMethod(meta = true)
  253. public static IRubyObject unpack_sockaddr_in(ThreadContext context, IRubyObject recv, IRubyObject addr) {
  254. return Sockaddr.unpack_sockaddr_in(context, addr);
  255. }
  256. @JRubyMethod(name = {"pack_sockaddr_un", "sockaddr_un"}, meta = true)
  257. public static IRubyObject pack_sockaddr_un(ThreadContext context, IRubyObject recv, IRubyObject filename) {
  258. return SocketUtils.pack_sockaddr_un(context, filename);
  259. }
  260. @JRubyMethod(meta = true)
  261. public static IRubyObject gethostbyname(ThreadContext context, IRubyObject recv, IRubyObject hostname) {
  262. return SocketUtils.gethostbyname(context, hostname);
  263. }
  264. @JRubyMethod(required = 2, optional = 5, meta = true)
  265. public static IRubyObject getaddrinfo(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  266. return SocketUtils.getaddrinfo(context, args);
  267. }
  268. @JRubyMethod(required = 1, optional = 1, meta = true)
  269. public static IRubyObject getnameinfo(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
  270. return SocketUtils.getnameinfo(context, args);
  271. }
  272. @JRubyMethod(meta = true)
  273. public static IRubyObject ip_address_list(ThreadContext context, IRubyObject self) {
  274. return SocketUtils.ip_address_list(context);
  275. }
  276. @JRubyMethod(name = {"socketpair", "pair"}, meta = true)
  277. public static IRubyObject socketpair(ThreadContext context, IRubyObject recv, IRubyObject domain, IRubyObject type, IRubyObject protocol) {
  278. ProtocolFamily pf = SocketUtils.protocolFamilyFromArg(protocol);
  279. if (pf == null ) pf = ProtocolFamily.PF_UNIX;
  280. if (pf != ProtocolFamily.PF_UNIX && pf.ordinal() != 0) {
  281. throw context.runtime.newErrnoEOPNOTSUPPError("Socket.socketpair only supports streaming UNIX sockets");
  282. }
  283. return socketpair(context, recv, domain, type);
  284. }
  285. @JRubyMethod(name = {"socketpair", "pair"}, meta = true)
  286. public static IRubyObject socketpair(ThreadContext context, IRubyObject recv, IRubyObject domain, IRubyObject type) {
  287. AddressFamily af = SocketUtils.addressFamilyFromArg(domain);
  288. if (af == null) af = AddressFamily.AF_UNIX;
  289. Sock s = SocketUtils.sockFromArg(type);
  290. if (s == null) s = Sock.SOCK_STREAM;
  291. if (af != AddressFamily.AF_UNIX || s != Sock.SOCK_STREAM) {
  292. throw context.runtime.newErrnoEOPNOTSUPPError("Socket.socketpair only supports streaming UNIX sockets");
  293. }
  294. return RubyUNIXSocket.socketpair(context, recv, arrayOf(domain, type));
  295. }
  296. @Override
  297. protected Sock getDefaultSocketType() {
  298. return soType;
  299. }
  300. private void initFieldsFromDescriptor(Ruby runtime, ChannelFD fd) {
  301. Channel mainChannel = fd.ch;
  302. if (mainChannel instanceof SocketChannel) {
  303. // ok, it's a socket...set values accordingly
  304. // just using AF_INET since we can't tell from SocketChannel...
  305. soDomain = AddressFamily.AF_INET;
  306. soType = Sock.SOCK_STREAM;
  307. soProtocolFamily = ProtocolFamily.PF_INET;
  308. soProtocol = Protocol.getProtocolByName("tcp");
  309. } else if (mainChannel instanceof UnixSocketChannel) {
  310. soDomain = AddressFamily.AF_UNIX;
  311. soType = Sock.SOCK_STREAM;
  312. soProtocolFamily = ProtocolFamily.PF_UNIX;
  313. } else if (mainChannel instanceof DatagramChannel) {
  314. // datagram, set accordingly
  315. // again, AF_INET
  316. soDomain = AddressFamily.AF_INET;
  317. soType = Sock.SOCK_DGRAM;
  318. soProtocolFamily = ProtocolFamily.PF_INET;
  319. } else {
  320. throw runtime.newErrnoENOTSOCKError("can't Socket.new/for_fd against a non-socket");
  321. }
  322. }
  323. private void initFieldsFromArgs(Ruby runtime, IRubyObject domain, IRubyObject type, IRubyObject protocol) {
  324. initDomain(runtime, domain);
  325. initType(runtime, type);
  326. initProtocol(protocol);
  327. }
  328. private void initFieldsFromArgs(Ruby runtime, IRubyObject domain, IRubyObject type) {
  329. initDomain(runtime, domain);
  330. initType(runtime, type);
  331. }
  332. protected void initFromServer(Ruby runtime, RubyServerSocket serverSocket, SocketChannel socketChannel) {
  333. soDomain = serverSocket.soDomain;
  334. soType = serverSocket.soType;
  335. soProtocol = serverSocket.soProtocol;
  336. initSocket(newChannelFD(runtime, socketChannel));
  337. }
  338. protected ChannelFD initChannelFD(Ruby runtime) {
  339. try {
  340. Channel channel;
  341. switch (soType) {
  342. case SOCK_STREAM:
  343. if ( soProtocolFamily == ProtocolFamily.PF_UNIX ||
  344. soProtocolFamily == ProtocolFamily.PF_LOCAL ) {
  345. channel = UnixSocketChannel.open();
  346. }
  347. else if ( soProtocolFamily == ProtocolFamily.PF_INET ||
  348. soProtocolFamily == ProtocolFamily.PF_INET6 ||
  349. soProtocolFamily == ProtocolFamily.PF_UNSPEC ) {
  350. channel = SocketChannel.open();
  351. }
  352. else {
  353. throw runtime.newArgumentError("unsupported protocol family `" + soProtocolFamily + "'");
  354. }
  355. break;
  356. case SOCK_DGRAM:
  357. channel = DatagramChannel.open();
  358. break;
  359. default:
  360. throw runtime.newArgumentError("unsupported socket type `" + soType + "'");
  361. }
  362. return newChannelFD(runtime, channel);
  363. }
  364. catch (IOException e) {
  365. throw sockerr(runtime, "initialize: " + e.toString(), e);
  366. }
  367. }
  368. private void initProtocol(IRubyObject protocol) {
  369. soProtocol = SocketUtils.protocolFromArg(protocol);
  370. }
  371. private void initType(Ruby runtime, IRubyObject type) {
  372. Sock sockType = SocketUtils.sockFromArg(type);
  373. if (sockType == null) {
  374. throw SocketUtils.sockerr(runtime, "unknown socket type " + type);
  375. }
  376. soType = sockType;
  377. }
  378. private void initDomain(Ruby runtime, IRubyObject domain) {
  379. AddressFamily family = SocketUtils.addressFamilyFromArg(domain);
  380. if (family == null) {
  381. throw SocketUtils.sockerr(runtime, "unknown socket domain " + domain);
  382. }
  383. soDomain = family;
  384. String name = soDomain.name();
  385. if (name.startsWith("pseudo_")) name = name.substring(7);
  386. soProtocolFamily = ProtocolFamily.valueOf("PF" + name.substring(2));
  387. }
  388. private IRubyObject doConnectNonblock(ThreadContext context, Channel channel, SocketAddress addr, boolean ex) {
  389. if ( ! (channel instanceof SelectableChannel) ) {
  390. throw context.runtime.newErrnoENOPROTOOPTError();
  391. }
  392. SelectableChannel selectable = (SelectableChannel) channel;
  393. synchronized (selectable.blockingLock()) {
  394. boolean oldBlocking = selectable.isBlocking();
  395. try {
  396. selectable.configureBlocking(false);
  397. try {
  398. return doConnect(context, channel, addr, ex);
  399. } finally {
  400. selectable.configureBlocking(oldBlocking);
  401. }
  402. }
  403. catch (ClosedChannelException e) {
  404. throw context.runtime.newErrnoECONNREFUSEDError();
  405. }
  406. catch (IOException e) {
  407. throw sockerr(context.runtime, "connect(2): name or service not known", e);
  408. }
  409. }
  410. }
  411. protected IRubyObject doConnect(ThreadContext context, Channel channel, SocketAddress addr, boolean ex) {
  412. Ruby runtime = context.runtime;
  413. try {
  414. boolean result = true;
  415. if (channel instanceof SocketChannel) {
  416. SocketChannel socket = (SocketChannel) channel;
  417. if (socket.isConnectionPending()) {
  418. // connection initiated but not finished
  419. result = socket.finishConnect();
  420. } else {
  421. result = socket.connect(addr);
  422. }
  423. }
  424. else if (channel instanceof UnixSocketChannel) {
  425. result = ((UnixSocketChannel) channel).connect((UnixSocketAddress) addr);
  426. }
  427. else if (channel instanceof DatagramChannel) {
  428. ((DatagramChannel)channel).connect(addr);
  429. }
  430. else {
  431. throw runtime.newErrnoENOPROTOOPTError();
  432. }
  433. if ( ! result ) {
  434. if (!ex) return runtime.newSymbol("wait_writable");
  435. throw runtime.newErrnoEINPROGRESSWritableError();
  436. }
  437. }
  438. catch (AlreadyConnectedException e) {
  439. if (!ex) return runtime.newFixnum(0);
  440. throw runtime.newErrnoEISCONNError();
  441. }
  442. catch (ConnectionPendingException e) {
  443. throw runtime.newErrnoEINPROGRESSWritableError();
  444. }
  445. catch (UnknownHostException e) {
  446. throw SocketUtils.sockerr(runtime, "connect(2): unknown host");
  447. }
  448. catch (SocketException e) {
  449. handleSocketException(runtime, e, "connect(2)", addr);
  450. }
  451. catch (IOException e) {
  452. throw sockerr(runtime, "connect(2): name or service not known", e);
  453. }
  454. catch (IllegalArgumentException e) {
  455. throw sockerr(runtime, e.getMessage(), e);
  456. }
  457. return runtime.newFixnum(0);
  458. }
  459. protected void doBind(ThreadContext context, Channel channel, InetSocketAddress iaddr) {
  460. Ruby runtime = context.runtime;
  461. try {
  462. if (channel instanceof SocketChannel) {
  463. Socket socket = ((SocketChannel) channel).socket();
  464. socket.bind(iaddr);
  465. }
  466. else if (channel instanceof UnixSocketChannel) {
  467. // do nothing
  468. }
  469. else if (channel instanceof DatagramChannel) {
  470. DatagramSocket socket = ((DatagramChannel) channel).socket();
  471. socket.bind(iaddr);
  472. }
  473. else {
  474. throw runtime.newErrnoENOPROTOOPTError();
  475. }
  476. }
  477. catch (UnknownHostException e) {
  478. throw SocketUtils.sockerr(runtime, "bind(2): unknown host");
  479. }
  480. catch (SocketException e) {
  481. handleSocketException(runtime, e, "bind(2)", iaddr); // throws
  482. }
  483. catch (IOException e) {
  484. throw sockerr(runtime, "bind(2): name or service not known", e);
  485. }
  486. catch (IllegalArgumentException e) {
  487. throw sockerr(runtime, e.getMessage(), e);
  488. }
  489. }
  490. static void handleSocketException(final Ruby runtime, final SocketException ex,
  491. final String caller, final SocketAddress addr) {
  492. final String message = ex.getMessage();
  493. if ( message != null ) {
  494. switch ( message ) {
  495. case "permission denied" :
  496. case "Permission denied" :
  497. if ( addr == null ) {
  498. throw runtime.newErrnoEACCESError(caller + " - " + message);
  499. }
  500. throw runtime.newErrnoEACCESError("Address already in use - " + caller + " for " + formatAddress(addr));
  501. case "Address already in use" :
  502. throw runtime.newErrnoEADDRINUSEError(caller + " for " + formatAddress(addr));
  503. }
  504. // This is ugly, but what can we do, Java provides the same exception type
  505. // for different situations, so we differentiate the errors
  506. // based on the exception's message.
  507. if (ALREADY_BOUND_PATTERN.matcher(message).find()) {
  508. throw runtime.newErrnoEINVALError(caller + " - " + message);
  509. }
  510. if (ADDR_NOT_AVAIL_PATTERN.matcher(message).find()) {
  511. throw runtime.newErrnoEADDRNOTAVAILError(caller + " - " + message);
  512. }
  513. }
  514. throw runtime.newErrnoEADDRINUSEError(caller + " - " + message);
  515. }
  516. private static CharSequence formatAddress(final SocketAddress addr) {
  517. if ( addr == null ) return null;
  518. final String str = addr.toString();
  519. if ( str.length() > 0 && str.charAt(0) == '/' ) {
  520. return str.substring(1);
  521. }
  522. return str;
  523. }
  524. private SocketAddress addressForChannel(ThreadContext context, IRubyObject arg) {
  525. if (arg instanceof Addrinfo) return Sockaddr.addressFromArg(context, arg);
  526. switch (soProtocolFamily) {
  527. case PF_UNIX:
  528. case PF_LOCAL:
  529. return Sockaddr.addressFromSockaddr_un(context, arg);
  530. case PF_INET:
  531. case PF_INET6:
  532. case PF_UNSPEC:
  533. return Sockaddr.addressFromSockaddr_in(context, arg);
  534. default:
  535. throw context.runtime.newArgumentError("unsupported protocol family `" + soProtocolFamily + "'");
  536. }
  537. }
  538. @Deprecated
  539. public static RuntimeException sockerr(Ruby runtime, String msg) {
  540. return SocketUtils.sockerr(runtime, msg);
  541. }
  542. private static final Pattern ALREADY_BOUND_PATTERN = Pattern.compile("[Aa]lready.*bound");
  543. private static final Pattern ADDR_NOT_AVAIL_PATTERN = Pattern.compile("assign.*address");
  544. //private static final Pattern PERM_DENIED_PATTERN = Pattern.compile("[Pp]ermission.*denied");
  545. public static final int MSG_OOB = 0x1;
  546. public static final int MSG_PEEK = 0x2;
  547. public static final int MSG_DONTROUTE = 0x4;
  548. public static final int MSG_WAITALL = 0x100;
  549. protected AddressFamily soDomain;
  550. protected ProtocolFamily soProtocolFamily;
  551. protected Sock soType;
  552. protected Protocol soProtocol = Protocol.getProtocolByNumber(0);
  553. private static final String JRUBY_SERVER_SOCKET_ERROR =
  554. "use ServerSocket for servers (http://wiki.jruby.org/ServerSocket)";
  555. }// RubySocket