PageRenderTime 70ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/CoolEngine/IronPython/Src/IronPython.Modules/socket.cs

#
C# | 1715 lines | 1422 code | 172 blank | 121 comment | 186 complexity | 636155de9ac01bb0d7edad2af9e81902 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Microsoft Public License, please send an email to
  8. * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. #if !SILVERLIGHT // System.NET
  16. using System;
  17. using System.Collections;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.IO;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Runtime.InteropServices;
  24. using System.Text;
  25. using Microsoft.Scripting;
  26. using Microsoft.Scripting.Actions;
  27. using Microsoft.Scripting.Math;
  28. using Microsoft.Scripting.Runtime;
  29. using IronPython.Runtime;
  30. using IronPython.Runtime.Calls;
  31. using IronPython.Runtime.Types;
  32. using IronPython.Runtime.Operations;
  33. using IronPython.Runtime.Exceptions;
  34. using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
  35. [assembly: PythonModule("socket", typeof(IronPython.Modules.PythonSocket))]
  36. namespace IronPython.Modules {
  37. public static class PythonSocket {
  38. private static readonly object _defaultTimeoutKey = new object();
  39. private static readonly object _defaultBufsizeKey = new object();
  40. private const int DefaultBufferSize = 8192;
  41. [SpecialName]
  42. public static void PerformModuleReload(PythonContext/*!*/ context, IAttributesCollection/*!*/ dict) {
  43. if (!context.HasModuleState(_defaultTimeoutKey)) {
  44. context.SetModuleState(_defaultTimeoutKey, null);
  45. }
  46. context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize);
  47. }
  48. public const string __doc__ = "Implementation module for socket operations.\n\n"
  49. + "This module is a loose wrapper around the .NET System.Net.Sockets API, so you\n"
  50. + "may find the corresponding MSDN documentation helpful in decoding error\n"
  51. + "messages and understanding corner cases.\n"
  52. + "\n"
  53. + "This implementation of socket differs slightly from the standard CPython\n"
  54. + "socket module. Many of these differences are due to the implementation of the\n"
  55. + ".NET socket libraries. These differences are summarized below. For full\n"
  56. + "details, check the docstrings of the functions mentioned.\n"
  57. + " - s.accept(), s.connect(), and s.connect_ex() do not support timeouts.\n"
  58. + " - Timeouts in s.sendall() don't work correctly.\n"
  59. + " - s.dup() is not implemented.\n"
  60. + " - getservbyname() and getservbyport() are not implemented.\n"
  61. + " - SSL support is not implemented."
  62. + "\n"
  63. + "An Extra IronPython-specific function is exposed only if the clr module is\n"
  64. + "imported:\n"
  65. + " - s.HandleToSocket() returns the System.Net.Sockets.Socket object associated\n"
  66. + " with a particular \"file descriptor number\" (as returned by s.fileno()).\n"
  67. ;
  68. #region Socket object
  69. public static PythonType SocketType = DynamicHelpers.GetPythonTypeFromType(typeof(socket));
  70. [PythonSystemType]
  71. [Documentation("socket([family[, type[, proto]]]) -> socket object\n\n"
  72. + "Create a socket (a network connection endpoint) of the given family, type,\n"
  73. + "and protocol. socket() accepts keyword arguments.\n"
  74. + " - family (address family) defaults to AF_INET\n"
  75. + " - type (socket type) defaults to SOCK_STREAM\n"
  76. + " - proto (protocol type) defaults to 0, which specifies the default protocol\n"
  77. + "\n"
  78. + "This module supports only IP sockets. It does not support raw or Unix sockets.\n"
  79. + "Both IPv4 and IPv6 are supported.")]
  80. public class socket : IWeakReferenceable {
  81. #region Fields
  82. /// <summary>
  83. /// handleToSocket allows us to translate from Python's idea of a socket resource (file
  84. /// descriptor numbers) to .NET's idea of a socket resource (System.Net.Socket objects).
  85. /// In particular, this allows the select module to convert file numbers (as returned by
  86. /// fileno()) and convert them to Socket objects so that it can do something useful with them.
  87. /// </summary>
  88. private static readonly Dictionary<IntPtr, List<Socket>> handleToSocket = new Dictionary<IntPtr, List<Socket>>();
  89. private const int DefaultAddressFamily = (int)AddressFamily.InterNetwork;
  90. private const int DefaultSocketType = (int)System.Net.Sockets.SocketType.Stream;
  91. private const int DefaultProtocolType = (int)ProtocolType.Unspecified;
  92. internal Socket _socket;
  93. private WeakRefTracker weakRefTracker = null;
  94. #endregion
  95. #region Public API
  96. public socket(CodeContext/*!*/ context, [DefaultParameterValue(DefaultAddressFamily)] int addressFamily,
  97. [DefaultParameterValue(DefaultSocketType)] int socketType,
  98. [DefaultParameterValue(DefaultProtocolType)] int protocolType) {
  99. System.Net.Sockets.SocketType type = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socketType);
  100. if (!Enum.IsDefined(typeof(System.Net.Sockets.SocketType), type)) {
  101. throw MakeException(new SocketException((int)SocketError.SocketNotSupported));
  102. }
  103. AddressFamily family = (AddressFamily)Enum.ToObject(typeof(AddressFamily), addressFamily);
  104. if (!Enum.IsDefined(typeof(AddressFamily), family)) {
  105. throw MakeException(new SocketException((int)SocketError.AddressFamilyNotSupported));
  106. }
  107. ProtocolType proto = (ProtocolType)Enum.ToObject(typeof(ProtocolType), protocolType);
  108. if (!Enum.IsDefined(typeof(ProtocolType), proto)) {
  109. throw MakeException(new SocketException((int)SocketError.ProtocolNotSupported));
  110. }
  111. Socket newSocket;
  112. try {
  113. newSocket = new Socket(family, type, proto);
  114. } catch (SocketException e) {
  115. throw MakeException(e);
  116. }
  117. Initialize(context, newSocket);
  118. }
  119. [Documentation("accept() -> (conn, address)\n\n"
  120. + "Accept a connection. The socket must be bound and listening before calling\n"
  121. + "accept(). conn is a new socket object connected to the remote host, and\n"
  122. + "address is the remote host's address (e.g. a (host, port) tuple for IPv4).\n"
  123. + "\n"
  124. + "Difference from CPython: accept() does not support timeouts in blocking mode.\n"
  125. + "If a timeout is set and the socket is in blocking mode, accept() will block\n"
  126. + "indefinitely until a connection is ready."
  127. )]
  128. public PythonTuple accept(CodeContext/*!*/ context) {
  129. socket wrappedRemoteSocket;
  130. Socket realRemoteSocket;
  131. try {
  132. realRemoteSocket = _socket.Accept();
  133. } catch (Exception e) {
  134. throw MakeException(e);
  135. }
  136. wrappedRemoteSocket = new socket(context, realRemoteSocket);
  137. return PythonTuple.MakeTuple(wrappedRemoteSocket, wrappedRemoteSocket.getpeername());
  138. }
  139. [Documentation("bind(address) -> None\n\n"
  140. + "Bind to an address. If the socket is already bound, socket.error is raised.\n"
  141. + "For IP sockets, address is a (host, port) tuple. Raw sockets are not\n"
  142. + "supported.\n"
  143. + "\n"
  144. + "If you do not care which local address is assigned, set host to INADDR_ANY and\n"
  145. + "the system will assign the most appropriate network address. Similarly, if you\n"
  146. + "set port to 0, the system will assign an available port number between 1024\n"
  147. + "and 5000."
  148. )]
  149. public void bind(PythonTuple address) {
  150. IPEndPoint localEP = TupleToEndPoint(address, _socket.AddressFamily);
  151. try {
  152. _socket.Bind(localEP);
  153. } catch (Exception e) {
  154. throw MakeException(e);
  155. }
  156. }
  157. [Documentation("close() -> None\n\nClose the socket. It cannot be used after being closed.")]
  158. public void close() {
  159. RemoveHandleSocketMapping(this);
  160. }
  161. internal static void RemoveHandleSocketMapping(socket socket) {
  162. lock (handleToSocket) {
  163. List<Socket> sockets;
  164. if (handleToSocket.TryGetValue((IntPtr)socket._socket.Handle, out sockets)) {
  165. for (int i = sockets.Count-1; i >= 0; i--) {
  166. if (sockets[i] == socket._socket) {
  167. sockets.RemoveAt(i);
  168. break;
  169. }
  170. }
  171. if (sockets.Count == 0) {
  172. handleToSocket.Remove(socket._socket.Handle);
  173. try {
  174. socket._socket.Close();
  175. } catch (Exception e) {
  176. throw MakeException(e);
  177. }
  178. }
  179. }
  180. }
  181. }
  182. [Documentation("connect(address) -> None\n\n"
  183. + "Connect to a remote socket at the given address. IP addresses are expressed\n"
  184. + "as (host, port).\n"
  185. + "\n"
  186. + "Raises socket.error if the socket has been closed, the socket is listening, or\n"
  187. + "another connection error occurred."
  188. + "\n"
  189. + "Difference from CPython: connect() does not support timeouts in blocking mode.\n"
  190. + "If a timeout is set and the socket is in blocking mode, connect() will block\n"
  191. + "indefinitely until a connection is made or an error occurs."
  192. )]
  193. public void connect(PythonTuple address) {
  194. IPEndPoint remoteEP = TupleToEndPoint(address, _socket.AddressFamily);
  195. try {
  196. _socket.Connect(remoteEP);
  197. } catch (Exception e) {
  198. throw MakeException(e);
  199. }
  200. }
  201. [Documentation("connect_ex(address) -> error_code\n\n"
  202. + "Like connect(), but return an error code insted of raising an exception for\n"
  203. + "socket exceptions raised by the underlying system Connect() call. Note that\n"
  204. + "exceptions other than SocketException generated by the system Connect() call\n"
  205. + "will still be raised.\n"
  206. + "\n"
  207. + "A return value of 0 indicates that the connect call was successful."
  208. + "\n"
  209. + "Difference from CPython: connect_ex() does not support timeouts in blocking\n"
  210. + "mode. If a timeout is set and the socket is in blocking mode, connect_ex() will\n"
  211. + "block indefinitely until a connection is made or an error occurs."
  212. )]
  213. public int connect_ex(PythonTuple address) {
  214. IPEndPoint remoteEP = TupleToEndPoint(address, _socket.AddressFamily);
  215. try {
  216. _socket.Connect(remoteEP);
  217. } catch (SocketException e) {
  218. return e.ErrorCode;
  219. }
  220. return (int)SocketError.Success;
  221. }
  222. [Documentation("fileno() -> file_handle\n\n"
  223. + "Return the underlying system handle for this socket (a 64-bit integer)."
  224. )]
  225. public Int64 fileno() {
  226. try {
  227. return _socket.Handle.ToInt64();
  228. } catch (Exception e) {
  229. throw MakeException(e);
  230. }
  231. }
  232. [Documentation("getpeername() -> address\n\n"
  233. + "Return the address of the remote end of this socket. The address format is\n"
  234. + "family-dependent (e.g. a (host, port) tuple for IPv4)."
  235. )]
  236. public PythonTuple getpeername() {
  237. try {
  238. IPEndPoint remoteEP = _socket.RemoteEndPoint as IPEndPoint;
  239. if (remoteEP == null) {
  240. throw MakeException(new SocketException((int)SocketError.AddressFamilyNotSupported));
  241. }
  242. return EndPointToTuple(remoteEP);
  243. } catch (Exception e) {
  244. throw MakeException(e);
  245. }
  246. }
  247. [Documentation("getsockname() -> address\n\n"
  248. + "Return the address of the local end of this socket. The address format is\n"
  249. + "family-dependent (e.g. a (host, port) tuple for IPv4)."
  250. )]
  251. public PythonTuple getsockname() {
  252. try {
  253. IPEndPoint localEP = _socket.LocalEndPoint as IPEndPoint;
  254. if (localEP == null) {
  255. throw MakeException(new SocketException((int)SocketError.InvalidArgument));
  256. }
  257. return EndPointToTuple(localEP);
  258. } catch (Exception e) {
  259. throw MakeException(e);
  260. }
  261. }
  262. [Documentation("getsockopt(level, optname[, buflen]) -> value\n\n"
  263. + "Return the value of a socket option. level is one of the SOL_* constants\n"
  264. + "defined in this module, and optname is one of the SO_* constants. If buflen is\n"
  265. + "omitted or zero, an integer value is returned. If it is present, a byte string\n"
  266. + "whose maximum length is buflen bytes) is returned. The caller must the decode\n"
  267. + "the resulting byte string."
  268. )]
  269. public object getsockopt(int optionLevel, int optionName, [DefaultParameterValue(0)] int optionLength) {
  270. SocketOptionLevel level = (SocketOptionLevel)Enum.ToObject(typeof(SocketOptionLevel), optionLevel);
  271. if (!Enum.IsDefined(typeof(SocketOptionLevel), level)) {
  272. throw MakeException(new SocketException((int)SocketError.InvalidArgument));
  273. }
  274. SocketOptionName name = (SocketOptionName)Enum.ToObject(typeof(SocketOptionName), optionName);
  275. if (!Enum.IsDefined(typeof(SocketOptionName), name)) {
  276. throw MakeException(new SocketException((int)SocketError.ProtocolOption));
  277. }
  278. try {
  279. if (optionLength == 0) {
  280. // Integer return value
  281. return (int)_socket.GetSocketOption(level, name);
  282. } else {
  283. // Byte string return value
  284. return StringOps.FromByteArray(_socket.GetSocketOption(level, name, optionLength));
  285. }
  286. } catch (Exception e) {
  287. throw MakeException(e);
  288. }
  289. }
  290. [Documentation("listen(backlog) -> None\n\n"
  291. + "Listen for connections on the socket. Backlog is the maximum length of the\n"
  292. + "pending connections queue. The maximum value is system-dependent."
  293. )]
  294. public void listen(int backlog) {
  295. try {
  296. _socket.Listen(backlog);
  297. } catch (Exception e) {
  298. throw MakeException(e);
  299. }
  300. }
  301. [Documentation("makefile([mode[, bufsize]]) -> file object\n\n"
  302. + "Return a regular file object corresponding to the socket. The mode\n"
  303. + "and bufsize arguments are as for the built-in open() function.")]
  304. public PythonFile makefile(CodeContext/*!*/ context, [DefaultParameterValue("r")]string mode, [DefaultParameterValue(8192)]int bufSize) {
  305. AddHandleMapping(this); // dup our handle
  306. return new _fileobject(context, this, mode, bufSize);
  307. }
  308. [Documentation("recv(bufsize[, flags]) -> string\n\n"
  309. + "Receive data from the socket, up to bufsize bytes. For connection-oriented\n"
  310. + "protocols (e.g. SOCK_STREAM), you must first call either connect() or\n"
  311. + "accept(). Connectionless protocols (e.g. SOCK_DGRAM) may also use recvfrom().\n"
  312. + "\n"
  313. + "recv() blocks until data is available, unless a timeout was set using\n"
  314. + "settimeout(). If the timeout was exceeded, socket.timeout is raised."
  315. + "recv() returns immediately with zero bytes when the connection is closed."
  316. )]
  317. public string recv(int maxBytes, [DefaultParameterValue(0)] int flags) {
  318. int bytesRead;
  319. byte[] buffer = new byte[maxBytes];
  320. try {
  321. bytesRead = _socket.Receive(buffer, (SocketFlags)flags);
  322. } catch (Exception e) {
  323. throw MakeException(e);
  324. }
  325. return StringOps.FromByteArray(buffer, bytesRead);
  326. }
  327. [Documentation("recvfrom(bufsize[, flags]) -> (string, address)\n\n"
  328. + "Receive data from the socket, up to bufsize bytes. string is the data\n"
  329. + "received, and address (whose format is protocol-dependent) is the address of\n"
  330. + "the socket from which the data was received."
  331. )]
  332. public PythonTuple recvfrom(int maxBytes, [DefaultParameterValue(0)] int flags) {
  333. int bytesRead;
  334. byte[] buffer = new byte[maxBytes];
  335. IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
  336. EndPoint remoteEP = remoteIPEP;
  337. try {
  338. bytesRead = _socket.ReceiveFrom(buffer, (SocketFlags)flags, ref remoteEP);
  339. } catch (Exception e) {
  340. throw MakeException(e);
  341. }
  342. string data = StringOps.FromByteArray(buffer, bytesRead);
  343. PythonTuple remoteAddress = EndPointToTuple((IPEndPoint)remoteEP);
  344. return PythonTuple.MakeTuple(data, remoteAddress);
  345. }
  346. [Documentation("send(string[, flags]) -> bytes_sent\n\n"
  347. + "Send data to the remote socket. The socket must be connected to a remote\n"
  348. + "socket (by calling either connect() or accept(). Returns the number of bytes\n"
  349. + "sent to the remote socket.\n"
  350. + "\n"
  351. + "Note that the successful completion of a send() call does not mean that all of\n"
  352. + "the data was sent. The caller must keep track of the number of bytes sent and\n"
  353. + "retry the operation until all of the data has been sent.\n"
  354. + "\n"
  355. + "Also note that there is no guarantee that the data you send will appear on the\n"
  356. + "network immediately. To increase network efficiency, the underlying system may\n"
  357. + "delay transmission until a significant amount of outgoing data is collected. A\n"
  358. + "successful completion of the Send method means that the underlying system has\n"
  359. + "had room to buffer your data for a network send"
  360. )]
  361. public int send(string data, [DefaultParameterValue(0)] int flags) {
  362. byte[] buffer = StringOps.ToByteArray(data);
  363. try {
  364. return _socket.Send(buffer, (SocketFlags)flags);
  365. } catch (Exception e) {
  366. throw MakeException(e);
  367. }
  368. }
  369. [Documentation("sendall(string[, flags]) -> None\n\n"
  370. + "Send data to the remote socket. The socket must be connected to a remote\n"
  371. + "socket (by calling either connect() or accept().\n"
  372. + "\n"
  373. + "Unlike send(), sendall() blocks until all of the data has been sent or until a\n"
  374. + "timeout or an error occurs. None is returned on success. If an error occurs,\n"
  375. + "there is no way to tell how much data, if any, was sent.\n"
  376. + "\n"
  377. + "Difference from CPython: timeouts do not function as you would expect. The\n"
  378. + "function is implemented using multiple calls to send(), so the timeout timer\n"
  379. + "is reset after each of those calls. That means that the upper bound on the\n"
  380. + "time that it will take for sendall() to return is the number of bytes in\n"
  381. + "string times the timeout interval.\n"
  382. + "\n"
  383. + "Also note that there is no guarantee that the data you send will appear on the\n"
  384. + "network immediately. To increase network efficiency, the underlying system may\n"
  385. + "delay transmission until a significant amount of outgoing data is collected. A\n"
  386. + "successful completion of the Send method means that the underlying system has\n"
  387. + "had room to buffer your data for a network send"
  388. )]
  389. public void sendall(string data, [DefaultParameterValue(0)] int flags) {
  390. byte[] buffer = StringOps.ToByteArray(data);
  391. try {
  392. int bytesTotal = buffer.Length;
  393. int bytesRemaining = bytesTotal;
  394. while (bytesRemaining > 0) {
  395. bytesRemaining -= _socket.Send(buffer, bytesTotal - bytesRemaining, bytesRemaining, (SocketFlags)flags);
  396. }
  397. } catch (Exception e) {
  398. throw MakeException(e);
  399. }
  400. }
  401. [Documentation("sendto(string[, flags], address) -> bytes_sent\n\n"
  402. + "Send data to the remote socket. The socket does not need to be connected to a\n"
  403. + "remote socket since the address is specified in the call to sendto(). Returns\n"
  404. + "the number of bytes sent to the remote socket.\n"
  405. + "\n"
  406. + "Blocking sockets will block until the all of the bytes in the buffer are sent.\n"
  407. + "Since a nonblocking Socket completes immediately, it might not send all of the\n"
  408. + "bytes in the buffer. It is your application's responsibility to keep track of\n"
  409. + "the number of bytes sent and to retry the operation until the application sends\n"
  410. + "all of the bytes in the buffer.\n"
  411. + "\n"
  412. + "Note that there is no guarantee that the data you send will appear on the\n"
  413. + "network immediately. To increase network efficiency, the underlying system may\n"
  414. + "delay transmission until a significant amount of outgoing data is collected. A\n"
  415. + "successful completion of the Send method means that the underlying system has\n"
  416. + "had room to buffer your data for a network send"
  417. )]
  418. public int sendto(string data, int flags, PythonTuple address) {
  419. byte[] buffer = StringOps.ToByteArray(data);
  420. EndPoint remoteEP = TupleToEndPoint(address, _socket.AddressFamily);
  421. try {
  422. return _socket.SendTo(buffer, (SocketFlags)flags, remoteEP);
  423. } catch (Exception e) {
  424. throw MakeException(e);
  425. }
  426. }
  427. [Documentation("")]
  428. public int sendto(string data, PythonTuple address) {
  429. return sendto(data, 0, address);
  430. }
  431. [Documentation("setblocking(flag) -> None\n\n"
  432. + "Set the blocking mode of the socket. If flag is 0, the socket will be set to\n"
  433. + "non-blocking mode; otherwise, it will be set to blocking mode. If the socket is\n"
  434. + "in blocking mode, and a method is called (such as send() or recv() which does\n"
  435. + "not complete immediately, the caller will block execution until the requested\n"
  436. + "operation completes. In non-blocking mode, a socket.timeout exception would\n"
  437. + "would be raised in this case.\n"
  438. + "\n"
  439. + "Note that changing blocking mode also affects the timeout setting:\n"
  440. + "setblocking(0) is equivalent to settimeout(0), and setblocking(1) is equivalent\n"
  441. + "to settimeout(None)."
  442. )]
  443. public void setblocking(int shouldBlock) {
  444. if (shouldBlock == 0) {
  445. settimeout(0);
  446. } else {
  447. settimeout(null);
  448. }
  449. }
  450. [Documentation("settimeout(value) -> None\n\n"
  451. + "Set a timeout on blocking socket methods. value may be either None or a\n"
  452. + "non-negative float, with one of the following meanings:\n"
  453. + " - None: disable timeouts and block indefinitely"
  454. + " - 0.0: don't block at all (return immediately if the operation can be\n"
  455. + " completed; raise socket.error otherwise)\n"
  456. + " - float > 0.0: block for up to the specified number of seconds; raise\n"
  457. + " socket.timeout if the operation cannot be completed in time\n"
  458. + "\n"
  459. + "settimeout(None) is equivalent to setblocking(1), and settimeout(0.0) is\n"
  460. + "equivalent to setblocking(0)."
  461. + "\n"
  462. + "If the timeout is non-zero and is less than 0.5, it will be set to 0.5. This\n"
  463. + "limitation is specific to IronPython.\n"
  464. )]
  465. public void settimeout(object timeout) {
  466. try {
  467. if (timeout == null) {
  468. _socket.Blocking = true;
  469. _socket.SendTimeout = 0;
  470. } else {
  471. double seconds;
  472. seconds = Converter.ConvertToDouble(timeout);
  473. if (seconds < 0) {
  474. throw PythonOps.TypeError("a non-negative float is required");
  475. }
  476. _socket.Blocking = seconds > 0; // 0 timeout means non-blocking mode
  477. _socket.SendTimeout = (int)(seconds * MillisecondsPerSecond);
  478. }
  479. } finally {
  480. _socket.ReceiveTimeout = _socket.SendTimeout;
  481. }
  482. }
  483. [Documentation("gettimeout() -> value\n\n"
  484. + "Return the timeout duration in seconds for this socket as a float. If no\n"
  485. + "timeout is set, return None. For more details on timeouts and blocking, see the\n"
  486. + "Python socket module documentation."
  487. )]
  488. public object gettimeout() {
  489. try {
  490. if (_socket.Blocking && _socket.SendTimeout == 0) {
  491. return null;
  492. } else {
  493. return (double)_socket.SendTimeout / MillisecondsPerSecond;
  494. }
  495. } catch (Exception e) {
  496. throw MakeException(e);
  497. }
  498. }
  499. [Documentation("setsockopt(level, optname[, value]) -> None\n\n"
  500. + "Set the value of a socket option. level is one of the SOL_* constants defined\n"
  501. + "in this module, and optname is one of the SO_* constants. value may be either\n"
  502. + "an integer or a string containing a binary structure. The caller is responsible\n"
  503. + "for properly encoding the byte string."
  504. )]
  505. public void setsockopt(int optionLevel, int optionName, object value) {
  506. SocketOptionLevel level = (SocketOptionLevel)Enum.ToObject(typeof(SocketOptionLevel), optionLevel);
  507. if (!Enum.IsDefined(typeof(SocketOptionLevel), level)) {
  508. throw MakeException(new SocketException((int)SocketError.InvalidArgument));
  509. }
  510. SocketOptionName name = (SocketOptionName)Enum.ToObject(typeof(SocketOptionName), optionName);
  511. if (!Enum.IsDefined(typeof(SocketOptionName), name)) {
  512. throw MakeException(new SocketException((int)SocketError.ProtocolOption));
  513. }
  514. try {
  515. int intValue;
  516. if (Converter.TryConvertToInt32(value, out intValue)) {
  517. _socket.SetSocketOption(level, name, intValue);
  518. return;
  519. }
  520. string strValue;
  521. if (Converter.TryConvertToString(value, out strValue)) {
  522. _socket.SetSocketOption(level, name, StringOps.ToByteArray(strValue));
  523. return;
  524. }
  525. } catch (Exception e) {
  526. throw MakeException(e);
  527. }
  528. throw PythonOps.TypeError("setsockopt() argument 3 must be int or string");
  529. }
  530. [Documentation("shutdown() -> None\n\n"
  531. + "Return the timeout duration in seconds for this socket as a float. If no\n"
  532. + "timeout is set, return None. For more details on timeouts and blocking, see the\n"
  533. + "Python socket module documentation."
  534. )]
  535. public void shutdown(int how) {
  536. SocketShutdown howValue = (SocketShutdown)Enum.ToObject(typeof(SocketShutdown), how);
  537. if (!Enum.IsDefined(typeof(SocketShutdown), howValue)) {
  538. throw MakeException(new SocketException((int)SocketError.InvalidArgument));
  539. }
  540. try {
  541. _socket.Shutdown(howValue);
  542. } catch (Exception e) {
  543. throw MakeException(e);
  544. }
  545. }
  546. public override string ToString() {
  547. try {
  548. return "<socket object, fd=" + fileno().ToString()
  549. + ", family=" + ((int)_socket.AddressFamily).ToString()
  550. + ", type=" + ((int)_socket.SocketType).ToString()
  551. + ", protocol=" + ((int)_socket.ProtocolType).ToString()
  552. + ">"
  553. ;
  554. } catch {
  555. return "<socket object, fd=?, family=?, type=, protocol=>";
  556. }
  557. }
  558. /// <summary>
  559. /// Return the internal System.Net.Sockets.Socket socket object associated with the given
  560. /// handle (as returned by GetHandle()), or null if no corresponding socket exists. This is
  561. /// primarily intended to be used by other modules (such as select) that implement
  562. /// networking primitives. User code should not normally need to call this function.
  563. /// </summary>
  564. internal static Socket HandleToSocket(Int64 handle) {
  565. List<Socket> sockets;
  566. lock (handleToSocket) {
  567. if (handleToSocket.TryGetValue((IntPtr)handle, out sockets)) {
  568. return sockets[sockets.Count - 1];
  569. }
  570. }
  571. return null;
  572. }
  573. #endregion
  574. #region IWeakReferenceable Implementation
  575. WeakRefTracker IWeakReferenceable.GetWeakRef() {
  576. return weakRefTracker;
  577. }
  578. bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
  579. weakRefTracker = value;
  580. return true;
  581. }
  582. void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
  583. weakRefTracker = value;
  584. }
  585. #endregion
  586. #region Private Implementation
  587. /// <summary>
  588. /// Create a Python socket object from an existing .NET socket object
  589. /// (like one returned from Socket.Accept())
  590. /// </summary>
  591. private socket(CodeContext/*!*/ context, Socket socket) {
  592. Initialize(context, socket);
  593. }
  594. /// <summary>
  595. /// Perform initialization common to all constructors
  596. /// </summary>
  597. private void Initialize(CodeContext/*!*/ context, Socket socket) {
  598. this._socket = socket;
  599. int? defaultTimeout = GetDefaultTimeout(context);
  600. if (defaultTimeout == null) {
  601. settimeout(null);
  602. } else {
  603. settimeout((double)defaultTimeout / MillisecondsPerSecond);
  604. }
  605. AddHandleMapping(this);
  606. }
  607. private static void AddHandleMapping(socket socket) {
  608. lock (handleToSocket) {
  609. if (!handleToSocket.ContainsKey(socket._socket.Handle)) {
  610. handleToSocket[socket._socket.Handle] = new List<Socket>(1);
  611. }
  612. handleToSocket[socket._socket.Handle].Add(socket._socket);
  613. }
  614. }
  615. #endregion
  616. }
  617. #endregion
  618. #region Fields
  619. public static PythonType error = PythonExceptions.CreateSubType(PythonExceptions.Exception, "error", "socket", "");
  620. public static PythonType herror = PythonExceptions.CreateSubType(error, "herror", "socket", "");
  621. public static PythonType gaierror = PythonExceptions.CreateSubType(error, "gaierror", "socket", "");
  622. public static PythonType timeout = PythonExceptions.CreateSubType(error, "timeout", "socket", "");
  623. private const string AnyAddrToken = "";
  624. private const string BroadcastAddrToken = "<broadcast>";
  625. private const string LocalhostAddrToken = "";
  626. private const int IPv4AddrBytes = 4;
  627. private const int IPv6AddrBytes = 16;
  628. private const double MillisecondsPerSecond = 1000.0;
  629. #endregion
  630. #region Public API
  631. [Documentation("")]
  632. public static List getaddrinfo(
  633. string host,
  634. object port,
  635. [DefaultParameterValue((int)AddressFamily.Unspecified)] int family,
  636. [DefaultParameterValue(0)] int socktype,
  637. [DefaultParameterValue((int)ProtocolType.IP)] int proto,
  638. [DefaultParameterValue((int)SocketFlags.None)] int flags
  639. ) {
  640. int numericPort;
  641. if (port == null) {
  642. numericPort = 0;
  643. } else if (port is int) {
  644. numericPort = (int)port;
  645. } else if (port is Extensible<int>) {
  646. numericPort = ((Extensible<int>)port).Value;
  647. } else if (port is string) {
  648. if (!Int32.TryParse((string)port, out numericPort)) {
  649. // TODO: also should consult GetServiceByName
  650. throw PythonExceptions.CreateThrowable(gaierror, "getaddrinfo failed");
  651. }
  652. } else if (port is ExtensibleString) {
  653. if (!Int32.TryParse(((ExtensibleString)port).Value, out numericPort)) {
  654. // TODO: also should consult GetServiceByName
  655. throw PythonExceptions.CreateThrowable(gaierror, "getaddrinfo failed");
  656. }
  657. } else {
  658. throw PythonExceptions.CreateThrowable(gaierror, "getaddrinfo failed");
  659. }
  660. if (socktype != 0) {
  661. // we just use this to validate; socketType isn't actually used
  662. System.Net.Sockets.SocketType socketType = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socktype);
  663. if (socketType == System.Net.Sockets.SocketType.Unknown || !Enum.IsDefined(typeof(System.Net.Sockets.SocketType), socketType)) {
  664. throw PythonExceptions.CreateThrowable(gaierror, PythonTuple.MakeTuple((int)SocketError.SocketNotSupported, "getaddrinfo failed"));
  665. }
  666. }
  667. AddressFamily addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family);
  668. if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) {
  669. throw PythonExceptions.CreateThrowable(gaierror, PythonTuple.MakeTuple((int)SocketError.AddressFamilyNotSupported, "getaddrinfo failed"));
  670. }
  671. // Again, we just validate, but don't actually use protocolType
  672. ProtocolType protocolType = (ProtocolType)Enum.ToObject(typeof(ProtocolType), proto);
  673. IPAddress[] ips = HostToAddresses(host, addressFamily);
  674. List results = new List();
  675. foreach (IPAddress ip in ips) {
  676. results.append(PythonTuple.MakeTuple(
  677. (int)ip.AddressFamily,
  678. socktype,
  679. proto,
  680. "",
  681. EndPointToTuple(new IPEndPoint(ip, numericPort))
  682. ));
  683. }
  684. return results;
  685. }
  686. [Documentation("getfqdn([hostname_or_ip]) -> hostname\n\n"
  687. + "Return the fully-qualified domain name for the specified hostname or IP\n"
  688. + "address. An unspecified or empty name is interpreted as the local host. If the\n"
  689. + "name lookup fails, the passed-in name is returned as-is."
  690. )]
  691. public static string getfqdn(string host) {
  692. host = host.Trim();
  693. if (host == BroadcastAddrToken) {
  694. return host;
  695. }
  696. try {
  697. IPHostEntry hostEntry = Dns.GetHostEntry(host);
  698. if (hostEntry.HostName.Contains(".")) {
  699. return hostEntry.HostName;
  700. } else {
  701. foreach (string addr in hostEntry.Aliases) {
  702. if (addr.Contains(".")) {
  703. return addr;
  704. }
  705. }
  706. }
  707. } catch (SocketException) {
  708. // ignore and return host below
  709. }
  710. // seems to match CPython behavior, although docs say gethostname() should be returned
  711. return host;
  712. }
  713. [Documentation("")]
  714. public static string getfqdn() {
  715. return getfqdn(LocalhostAddrToken);
  716. }
  717. [Documentation("gethostbyname(hostname) -> ip address\n\n"
  718. + "Return the string IPv4 address associated with the given hostname (e.g.\n"
  719. + "'10.10.0.1'). The hostname is returned as-is if it an IPv4 address. The empty\n"
  720. + "string is treated as the local host.\n"
  721. + "\n"
  722. + "gethostbyname() doesn't support IPv6; for IPv4/IPv6 support, use getaddrinfo()."
  723. )]
  724. public static string gethostbyname(string host) {
  725. return HostToAddress(host, AddressFamily.InterNetwork).ToString();
  726. }
  727. [Documentation("gethostbyname_ex(hostname) -> (hostname, aliases, ip_addresses)\n\n"
  728. + "Return the real host name, a list of aliases, and a list of IP addresses\n"
  729. + "associated with the given hostname. If the hostname is an IPv4 address, the\n"
  730. + "tuple ([hostname, [], [hostname]) is returned without doing a DNS lookup.\n"
  731. + "\n"
  732. + "gethostbyname_ex() doesn't support IPv6; for IPv4/IPv6 support, use\n"
  733. + "getaddrinfo()."
  734. )]
  735. public static PythonTuple gethostbyname_ex(string host) {
  736. string hostname;
  737. List aliases;
  738. List ips = PythonOps.MakeList();
  739. IPAddress addr;
  740. if (IPAddress.TryParse(host, out addr)) {
  741. if (AddressFamily.InterNetwork == addr.AddressFamily) {
  742. hostname = host;
  743. aliases = PythonOps.MakeEmptyList(0);
  744. ips.append(host);
  745. } else {
  746. throw PythonExceptions.CreateThrowable(gaierror, (int)SocketError.HostNotFound, "no IPv4 addresses associated with host");
  747. }
  748. } else {
  749. IPHostEntry hostEntry;
  750. try {
  751. hostEntry = Dns.GetHostEntry(host);
  752. } catch (SocketException e) {
  753. throw PythonExceptions.CreateThrowable(gaierror, e.ErrorCode, "no IPv4 addresses associated with host");
  754. }
  755. hostname = hostEntry.HostName;
  756. aliases = PythonOps.MakeList(hostEntry.Aliases);
  757. foreach (IPAddress ip in hostEntry.AddressList) {
  758. if (AddressFamily.InterNetwork == ip.AddressFamily) {
  759. ips.append(ip.ToString());
  760. }
  761. }
  762. }
  763. return PythonTuple.MakeTuple(hostname, aliases, ips);
  764. }
  765. [Documentation("gethostname() -> hostname\nReturn this machine's hostname")]
  766. public static string gethostname() {
  767. return Dns.GetHostName();
  768. }
  769. [Documentation("gethostbyaddr(host) -> (hostname, aliases, ipaddrs)\n\n"
  770. + "Return a tuple of (primary hostname, alias hostnames, ip addresses). host may\n"
  771. + "be either a hostname or an IP address."
  772. )]
  773. public static object gethostbyaddr(string host) {
  774. if (host == "") {
  775. host = gethostname();
  776. }
  777. // This conversion seems to match CPython behavior
  778. host = gethostbyname(host);
  779. IPAddress[] ips = null;
  780. IPHostEntry hostEntry = null;
  781. try {
  782. ips = Dns.GetHostAddresses(host);
  783. hostEntry = Dns.GetHostEntry(host);
  784. } catch (Exception e) {
  785. throw MakeException(e);
  786. }
  787. List ipStrings = PythonOps.MakeList();
  788. foreach (IPAddress ip in ips) {
  789. ipStrings.append(ip.ToString());
  790. }
  791. return PythonTuple.MakeTuple(hostEntry.HostName, PythonOps.MakeList(hostEntry.Aliases), ipStrings);
  792. }
  793. [Documentation("getnameinfo(socketaddr, flags) -> (host, port)\n"
  794. + "Given a socket address, the return a tuple of the corresponding hostname and\n"
  795. + "port. Available flags:\n"
  796. + " - NI_NOFQDN: Return only the hostname part of the domain name for hosts on the\n"
  797. + " same domain as the executing machine.\n"
  798. + " - NI_NUMERICHOST: return the numeric form of the host (e.g. '127.0.0.1' or\n"
  799. + " '::1' rather than 'localhost').\n"
  800. + " - NI_NAMEREQD: Raise an error if the hostname cannot be looked up.\n"
  801. + " - NI_NUMERICSERV: Return string containing the numeric form of the port (e.g.\n"
  802. + " '80' rather than 'http'). This flag is required (see below).\n"
  803. + " - NI_DGRAM: Silently ignored (see below).\n"
  804. + "\n"
  805. + "Difference from CPython: the following flag behavior differs from CPython\n"
  806. + "because the .NET framework libraries offer no name-to-port conversion APIs:\n"
  807. + " - NI_NUMERICSERV: This flag is required because the .NET framework libraries\n"
  808. + " offer no port-to-name mapping APIs. If it is omitted, getnameinfo() will\n"
  809. + " raise a NotImplementedError.\n"
  810. + " - The NI_DGRAM flag is ignored because it only applies when NI_NUMERICSERV is\n"
  811. + " omitted. It it were supported, it would return the UDP-based port name\n"
  812. + " rather than the TCP-based port name.\n"
  813. )]
  814. public static object getnameinfo(PythonTuple socketAddr, int flags) {
  815. if (socketAddr.__len__() < 2 || socketAddr.__len__() > 4) {
  816. throw PythonOps.TypeError("socket address must be a 2-tuple (IPv4 or IPv6) or 4-tuple (IPv6)");
  817. }
  818. if ((flags & (int)NI_NUMERICSERV) == 0) {
  819. throw PythonOps.NotImplementedError("getnameinfo() required the NI_NUMERICSERV flag (see docstring)");
  820. }
  821. string host = Converter.ConvertToString(socketAddr[0]);
  822. if (host == null) throw PythonOps.TypeError("argument 1 must be string");
  823. int port = 0;
  824. try {
  825. port = (int)socketAddr[1];
  826. } catch (InvalidCastException) {
  827. throw PythonOps.TypeError("an integer is required");
  828. }
  829. string resultHost = null;
  830. string resultPort = null;
  831. // Host
  832. IPHostEntry hostEntry = null;
  833. try {
  834. // Do double lookup to force reverse DNS lookup to match CPython behavior
  835. hostEntry = Dns.GetHostEntry(host);
  836. if (hostEntry.AddressList.Length < 1) {
  837. throw PythonExceptions.CreateThrowable(error, "sockaddr resolved to zero addresses");
  838. }
  839. hostEntry = Dns.GetHostEntry(hostEntry.AddressList[0]);
  840. } catch (SocketException e) {
  841. throw PythonExceptions.CreateThrowable(gaierror, e.ErrorCode, e.Message);
  842. } catch (IndexOutOfRangeException) {
  843. throw PythonExceptions.CreateThrowable(gaierror, "sockaddr resolved to zero addresses");
  844. }
  845. IList<IPAddress> addrs = hostEntry.AddressList;
  846. if (addrs.Count > 1) {
  847. // ignore non-IPV4 addresses
  848. List<IPAddress> newAddrs = new List<IPAddress>(addrs.Count);
  849. foreach (IPAddress addr in hostEntry.AddressList) {
  850. if (addr.AddressFamily == AddressFamily.InterNetwork) {
  851. newAddrs.Add(addr);
  852. }
  853. }
  854. if (newAddrs.Count > 1) {
  855. throw PythonExceptions.CreateThrowable(error, "sockaddr resolved to multiple addresses");
  856. }
  857. addrs = newAddrs;
  858. }
  859. if (addrs.Count < 1) {
  860. throw PythonExceptions.CreateThrowable(error, "sockaddr resolved to zero addresses");
  861. }
  862. if ((flags & (int)NI_NUMERICHOST) != 0) {
  863. resultHost = addrs[0].ToString();
  864. } else if ((flags & (int)NI_NOFQDN) != 0) {
  865. resultHost = RemoveLocalDomain(hostEntry.HostName);
  866. } else {
  867. resultHost = hostEntry.HostName;
  868. }
  869. // Port
  870. // We don't branch on NI_NUMERICSERV here since we throw above if it's not set
  871. resultPort = port.ToString();
  872. return PythonTuple.MakeTuple(resultHost, resultPort);
  873. }
  874. [Documentation("getprotobyname(protoname) -> integer proto\n\n"
  875. + "Given a string protocol name (e.g. \"udp\"), return the associated integer\n"
  876. + "protocol number, suitable for passing to socket(). The name is case\n"
  877. + "insensitive.\n"
  878. + "\n"
  879. + "Raises socket.error if no protocol number can be found."
  880. )]
  881. public static object getprotobyname(string protocolName) {
  882. switch (protocolName.ToLower()) {
  883. case "ah": return IPPROTO_AH;
  884. case "esp": return IPPROTO_ESP;
  885. case "dstopts": return IPPROTO_DSTOPTS;
  886. case "fragment": return IPPROTO_FRAGMENT;
  887. case "ggp": return IPPROTO_GGP;
  888. case "icmp": return IPPROTO_ICMP;
  889. case "icmpv6": return IPPROTO_ICMPV6;
  890. case "ip": r

Large files files are truncated, but you can click here to view the full file