forked from IronLanguages/main
-
Notifications
You must be signed in to change notification settings - Fork 4
/
socket.cs
2455 lines (2182 loc) · 117 KB
/
socket.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_SYNC_SOCKETS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
#endif
using PythonArray = IronPython.Modules.ArrayModule.array;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("socket", typeof(IronPython.Modules.PythonSocket))]
namespace IronPython.Modules {
public static class PythonSocket {
private static readonly object _defaultTimeoutKey = new object();
private static readonly object _defaultBufsizeKey = new object();
private const int DefaultBufferSize = 8192;
public static PythonTuple _delegate_methods = PythonTuple.MakeTuple("recv", "recvfrom", "recv_into", "recvfrom_into", "send", "sendto");
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
if (!context.HasModuleState(_defaultTimeoutKey)) {
context.SetModuleState(_defaultTimeoutKey, null);
}
context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize);
PythonType socketErr = GetSocketError(context, dict);
context.EnsureModuleException("socketherror", socketErr, dict, "herror", "socket");
context.EnsureModuleException("socketgaierror", socketErr, dict, "gaierror", "socket");
context.EnsureModuleException("sockettimeout", socketErr, dict, "timeout", "socket");
}
internal static PythonType GetSocketError(PythonContext context, PythonDictionary dict) {
return context.EnsureModuleException("socketerror", PythonExceptions.IOError, dict, "error", "socket");
}
public const string __doc__ = "Implementation module for socket operations.\n\n"
+ "This module is a loose wrapper around the .NET System.Net.Sockets API, so you\n"
+ "may find the corresponding MSDN documentation helpful in decoding error\n"
+ "messages and understanding corner cases.\n"
+ "\n"
+ "This implementation of socket differs slightly from the standard CPython\n"
+ "socket module. Many of these differences are due to the implementation of the\n"
+ ".NET socket libraries. These differences are summarized below. For full\n"
+ "details, check the docstrings of the functions mentioned.\n"
+ " - s.accept(), s.connect(), and s.connect_ex() do not support timeouts.\n"
+ " - Timeouts in s.sendall() don't work correctly.\n"
+ " - s.dup() is not implemented.\n"
+ " - getservbyname() and getservbyport() are not implemented.\n"
+ " - SSL support is not implemented."
+ "\n"
+ "An Extra IronPython-specific function is exposed only if the clr module is\n"
+ "imported:\n"
+ " - s.HandleToSocket() returns the System.Net.Sockets.Socket object associated\n"
+ " with a particular \"file descriptor number\" (as returned by s.fileno()).\n"
;
#region Socket object
public static PythonType SocketType = DynamicHelpers.GetPythonTypeFromType(typeof(socket));
[PythonType]
[Documentation("socket([family[, type[, proto]]]) -> socket object\n\n"
+ "Create a socket (a network connection endpoint) of the given family, type,\n"
+ "and protocol. socket() accepts keyword arguments.\n"
+ " - family (address family) defaults to AF_INET\n"
+ " - type (socket type) defaults to SOCK_STREAM\n"
+ " - proto (protocol type) defaults to 0, which specifies the default protocol\n"
+ "\n"
+ "This module supports only IP sockets. It does not support raw or Unix sockets.\n"
+ "Both IPv4 and IPv6 are supported.")]
public class socket : IWeakReferenceable {
#region Fields
/// <summary>
/// handleToSocket allows us to translate from Python's idea of a socket resource (file
/// descriptor numbers) to .NET's idea of a socket resource (System.Net.Socket objects).
/// In particular, this allows the select module to convert file numbers (as returned by
/// fileno()) and convert them to Socket objects so that it can do something useful with them.
/// </summary>
private static readonly Dictionary<IntPtr, WeakReference> _handleToSocket = new Dictionary<IntPtr, WeakReference>();
private const int DefaultAddressFamily = (int)AddressFamily.InterNetwork;
private const int DefaultSocketType = (int)System.Net.Sockets.SocketType.Stream;
private const int DefaultProtocolType = (int)ProtocolType.Unspecified;
internal Socket _socket;
internal string _hostName;
private WeakRefTracker _weakRefTracker = null;
private int _referenceCount = 1;
public const string __module__ = "socket";
internal CodeContext/*!*/ _context;
private int _timeout;
#endregion
#region Public API
public socket() {
}
public void __init__(CodeContext/*!*/ context, [DefaultParameterValue(DefaultAddressFamily)] int addressFamily,
[DefaultParameterValue(DefaultSocketType)] int socketType,
[DefaultParameterValue(DefaultProtocolType)] int protocolType,
[DefaultParameterValue(null)]socket _sock) {
System.Net.Sockets.SocketType type = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socketType);
if (!Enum.IsDefined(typeof(System.Net.Sockets.SocketType), type)) {
throw MakeException(context, new SocketException((int)SocketError.SocketNotSupported));
}
AddressFamily family = (AddressFamily)Enum.ToObject(typeof(AddressFamily), addressFamily);
if (!Enum.IsDefined(typeof(AddressFamily), family)) {
throw MakeException(context, new SocketException((int)SocketError.AddressFamilyNotSupported));
}
ProtocolType proto = (ProtocolType)Enum.ToObject(typeof(ProtocolType), protocolType);
if (!Enum.IsDefined(typeof(ProtocolType), proto)) {
throw MakeException(context, new SocketException((int)SocketError.ProtocolNotSupported));
}
if (_sock == null) {
Socket newSocket;
try {
newSocket = new Socket(family, type, proto);
} catch (SocketException e) {
throw MakeException(context, e);
}
Initialize(context, newSocket);
} else {
_socket = _sock._socket;
_hostName = _sock._hostName;
// we now own the lifetime of the socket
GC.SuppressFinalize(_sock);
Initialize(context, _socket);
}
}
public void __del__() {
_close();
}
~socket() {
_close();
}
public socket _sock {
get {
return this;
}
}
private IAsyncResult _acceptResult;
[Documentation("accept() -> (conn, address)\n\n"
+ "Accept a connection. The socket must be bound and listening before calling\n"
+ "accept(). conn is a new socket object connected to the remote host, and\n"
+ "address is the remote host's address (e.g. a (host, port) tuple for IPv4).\n"
+ "\n"
)]
public PythonTuple accept() {
socket wrappedRemoteSocket;
Socket realRemoteSocket;
try {
if (_acceptResult != null && _acceptResult.IsCompleted) {
// previous async result has completed
realRemoteSocket = _socket.EndAccept(_acceptResult);
} else {
int timeoutTime = _timeout;
if (timeoutTime != 0) {
// use the existing or create a new async request
var asyncResult = _acceptResult ?? _socket.BeginAccept((x) => { }, null);
if (asyncResult.AsyncWaitHandle.WaitOne(timeoutTime)) {
// it's completed, end and throw it away
realRemoteSocket = _socket.EndAccept(asyncResult);
_acceptResult = null;
} else {
// save the async result for later incase it completes
_acceptResult = asyncResult;
throw PythonExceptions.CreateThrowable(timeout(_context), 0, "timeout");
}
} else {
realRemoteSocket = _socket.Accept();
}
}
} catch (Exception e) {
throw MakeException(_context, e);
}
wrappedRemoteSocket = new socket(_context, realRemoteSocket);
return PythonTuple.MakeTuple(wrappedRemoteSocket, wrappedRemoteSocket.getpeername());
}
[Documentation("bind(address) -> None\n\n"
+ "Bind to an address. If the socket is already bound, socket.error is raised.\n"
+ "For IP sockets, address is a (host, port) tuple. Raw sockets are not\n"
+ "supported.\n"
+ "\n"
+ "If you do not care which local address is assigned, set host to INADDR_ANY and\n"
+ "the system will assign the most appropriate network address. Similarly, if you\n"
+ "set port to 0, the system will assign an available port number between 1024\n"
+ "and 5000."
)]
public void bind(PythonTuple address) {
IPEndPoint localEP = TupleToEndPoint(_context, address, _socket.AddressFamily, out _hostName);
try {
_socket.Bind(localEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("close() -> None\n\nClose the socket. It cannot be used after being closed.")]
public void close() {
// Don't actually close the socket if other file objects are
// still referring to this socket.
if (_referenceCount < 1) {
_close();
} else {
var refs = System.Threading.Interlocked.Decrement(ref _referenceCount);
}
}
internal void _close() {
if (_socket != null) {
lock (_handleToSocket) {
WeakReference weakref;
if (_handleToSocket.TryGetValue(_socket.Handle, out weakref)) {
Socket target = (weakref.Target as Socket);
if (target == _socket || target == null) {
_handleToSocket.Remove(_socket.Handle);
}
}
}
_socket.Close();
_referenceCount = 0;
}
}
[Documentation("connect(address) -> None\n\n"
+ "Connect to a remote socket at the given address. IP addresses are expressed\n"
+ "as (host, port).\n"
+ "\n"
+ "Raises socket.error if the socket has been closed, the socket is listening, or\n"
+ "another connection error occurred."
+ "\n"
+ "Difference from CPython: connect() does not support timeouts in blocking mode.\n"
+ "If a timeout is set and the socket is in blocking mode, connect() will block\n"
+ "indefinitely until a connection is made or an error occurs."
)]
public void connect(PythonTuple address) {
IPEndPoint remoteEP = TupleToEndPoint(_context, address, _socket.AddressFamily, out _hostName);
try {
_socket.Connect(remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("connect_ex(address) -> error_code\n\n"
+ "Like connect(), but return an error code insted of raising an exception for\n"
+ "socket exceptions raised by the underlying system Connect() call. Note that\n"
+ "exceptions other than SocketException generated by the system Connect() call\n"
+ "will still be raised.\n"
+ "\n"
+ "A return value of 0 indicates that the connect call was successful."
+ "\n"
+ "Difference from CPython: connect_ex() does not support timeouts in blocking\n"
+ "mode. If a timeout is set and the socket is in blocking mode, connect_ex() will\n"
+ "block indefinitely until a connection is made or an error occurs."
)]
public int connect_ex(PythonTuple address) {
IPEndPoint remoteEP = TupleToEndPoint(_context, address, _socket.AddressFamily, out _hostName);
try {
_socket.Connect(remoteEP);
} catch (SocketException e) {
return e.ErrorCode;
}
return (int)SocketError.Success;
}
[Documentation("fileno() -> file_handle\n\n"
+ "Return the underlying system handle for this socket (a 64-bit integer)."
)]
public Int64 fileno() {
try {
return _socket.Handle.ToInt64();
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("getpeername() -> address\n\n"
+ "Return the address of the remote end of this socket. The address format is\n"
+ "family-dependent (e.g. a (host, port) tuple for IPv4)."
)]
public PythonTuple getpeername() {
try {
IPEndPoint remoteEP = _socket.RemoteEndPoint as IPEndPoint;
if (remoteEP == null) {
throw MakeException(_context, new SocketException((int)SocketError.AddressFamilyNotSupported));
}
return EndPointToTuple(remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("getsockname() -> address\n\n"
+ "Return the address of the local end of this socket. The address format is\n"
+ "family-dependent (e.g. a (host, port) tuple for IPv4)."
)]
public PythonTuple getsockname() {
try {
IPEndPoint localEP = _socket.LocalEndPoint as IPEndPoint;
if (localEP == null) {
throw MakeException(_context, new SocketException((int)SocketError.InvalidArgument));
}
return EndPointToTuple(localEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("getsockopt(level, optname[, buflen]) -> value\n\n"
+ "Return the value of a socket option. level is one of the SOL_* constants\n"
+ "defined in this module, and optname is one of the SO_* constants. If buflen is\n"
+ "omitted or zero, an integer value is returned. If it is present, a byte string\n"
+ "whose maximum length is buflen bytes) is returned. The caller must the decode\n"
+ "the resulting byte string."
)]
public object getsockopt(int optionLevel, int optionName, [DefaultParameterValue(0)] int optionLength) {
SocketOptionLevel level = (SocketOptionLevel)Enum.ToObject(typeof(SocketOptionLevel), optionLevel);
if (!Enum.IsDefined(typeof(SocketOptionLevel), level)) {
throw MakeException(_context, new SocketException((int)SocketError.InvalidArgument));
}
SocketOptionName name = (SocketOptionName)Enum.ToObject(typeof(SocketOptionName), optionName);
if (!Enum.IsDefined(typeof(SocketOptionName), name)) {
throw MakeException(_context, new SocketException((int)SocketError.ProtocolOption));
}
try {
if (optionLength == 0) {
// Integer return value
return (int)_socket.GetSocketOption(level, name);
} else {
// Byte string return value
return _socket.GetSocketOption(level, name, optionLength).MakeString();
}
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("listen(backlog) -> None\n\n"
+ "Listen for connections on the socket. Backlog is the maximum length of the\n"
+ "pending connections queue. The maximum value is system-dependent."
)]
public void listen(int backlog) {
try {
_socket.Listen(backlog);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("makefile([mode[, bufsize]]) -> file object\n\n"
+ "Return a regular file object corresponding to the socket. The mode\n"
+ "and bufsize arguments are as for the built-in open() function.")]
public PythonFile makefile([DefaultParameterValue("r")]string mode, [DefaultParameterValue(8192)]int bufSize) {
System.Threading.Interlocked.Increment(ref _referenceCount); // dup our handle
return new _fileobject(_context, this, mode, bufSize, false);
}
[Documentation("recv(bufsize[, flags]) -> string\n\n"
+ "Receive data from the socket, up to bufsize bytes. For connection-oriented\n"
+ "protocols (e.g. SOCK_STREAM), you must first call either connect() or\n"
+ "accept(). Connectionless protocols (e.g. SOCK_DGRAM) may also use recvfrom().\n"
+ "\n"
+ "recv() blocks until data is available, unless a timeout was set using\n"
+ "settimeout(). If the timeout was exceeded, socket.timeout is raised."
+ "recv() returns immediately with zero bytes when the connection is closed."
)]
public string recv(int maxBytes, [DefaultParameterValue(0)] int flags) {
int bytesRead;
byte[] buffer = new byte[maxBytes];
try {
bytesRead = _socket.Receive(buffer, (SocketFlags)flags);
} catch (Exception e) {
throw MakeException(_context, e);
}
return PythonOps.MakeString(buffer, bytesRead);
}
[Documentation("recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\n"
+ "A version of recv() that stores its data into a buffer rather than creating\n"
+ "a new string. Receive up to buffersize bytes from the socket. If buffersize\n"
+ "is not specified (or 0), receive up to the size available in the given buffer.\n\n"
+ "See recv() for documentation about the flags.\n"
)]
public int recv_into(PythonBuffer buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
if (nbytes < 0) {
throw PythonOps.ValueError("negative buffersize in recv_into");
}
throw PythonOps.TypeError("buffer is read-only");
}
[Documentation("recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\n"
+ "A version of recv() that stores its data into a buffer rather than creating\n"
+ "a new string. Receive up to buffersize bytes from the socket. If buffersize\n"
+ "is not specified (or 0), receive up to the size available in the given buffer.\n\n"
+ "See recv() for documentation about the flags.\n"
)]
public int recv_into(string buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
throw PythonOps.TypeError("Cannot use string as modifiable buffer");
}
[Documentation("recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\n"
+ "A version of recv() that stores its data into a buffer rather than creating\n"
+ "a new string. Receive up to buffersize bytes from the socket. If buffersize\n"
+ "is not specified (or 0), receive up to the size available in the given buffer.\n\n"
+ "See recv() for documentation about the flags.\n"
)]
public int recv_into(PythonArray buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
int bytesRead;
byte[] byteBuffer = new byte[byteBufferSize("recv_into", nbytes, buffer.__len__(), buffer.itemsize)];
try {
bytesRead = _socket.Receive(byteBuffer, (SocketFlags)flags);
} catch (Exception e) {
throw MakeException(_context, e);
}
buffer.FromStream(new MemoryStream(byteBuffer), 0);
return bytesRead;
}
[Documentation("recv_into(bytearray, [nbytes[, flags]]) -> nbytes_read\n\n"
+ "A version of recv() that stores its data into a bytearray rather than creating\n"
+ "a new string. Receive up to buffersize bytes from the socket. If buffersize\n"
+ "is not specified (or 0), receive up to the size available in the given buffer.\n\n"
+ "See recv() for documentation about the flags.\n"
)]
public int recv_into(ByteArray buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
int bytesRead;
byte[] byteBuffer = new byte[byteBufferSize("recv_into", nbytes, buffer.Count, 1)];
try {
bytesRead = _socket.Receive(byteBuffer, (SocketFlags)flags);
} catch (Exception e) {
throw MakeException(_context, e);
}
for (int i = 0; i < bytesRead; i++) {
buffer[i] = byteBuffer[i];
}
return bytesRead;
}
[Documentation("recvfrom(bufsize[, flags]) -> (string, address)\n\n"
+ "Receive data from the socket, up to bufsize bytes. string is the data\n"
+ "received, and address (whose format is protocol-dependent) is the address of\n"
+ "the socket from which the data was received."
)]
public PythonTuple recvfrom(int maxBytes, [DefaultParameterValue(0)] int flags) {
if (maxBytes < 0) {
throw PythonOps.ValueError("negative buffersize in recvfrom");
}
int bytesRead;
byte[] buffer = new byte[maxBytes];
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
try {
bytesRead = _socket.ReceiveFrom(buffer, (SocketFlags)flags, ref remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
string data = PythonOps.MakeString(buffer, bytesRead);
PythonTuple remoteAddress = EndPointToTuple((IPEndPoint)remoteEP);
return PythonTuple.MakeTuple(data, remoteAddress);
}
[Documentation("recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\n"
+ "Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.\n"
)]
public PythonTuple recvfrom_into(PythonBuffer buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
if (nbytes < 0) {
throw PythonOps.ValueError("negative buffersize in recvfrom_into");
}
throw PythonOps.TypeError("buffer is read-only");
}
[Documentation("recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\n"
+ "Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.\n"
)]
public PythonTuple recvfrom_into(string buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
throw PythonOps.TypeError("Cannot use string as modifiable buffer");
}
[Documentation("recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\n"
+ "Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.\n"
)]
public PythonTuple recvfrom_into(PythonArray buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
int bytesRead;
byte[] byteBuffer = new byte[byteBufferSize("recvfrom_into", nbytes, buffer.__len__(), buffer.itemsize)];
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
try {
bytesRead = _socket.ReceiveFrom(byteBuffer, (SocketFlags)flags, ref remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
buffer.FromStream(new MemoryStream(byteBuffer), 0);
PythonTuple remoteAddress = EndPointToTuple((IPEndPoint)remoteEP);
return PythonTuple.MakeTuple(bytesRead, remoteAddress);
}
[Documentation("recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\n"
+ "Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.\n"
)]
public PythonTuple recvfrom_into(IList<byte> buffer, [DefaultParameterValue(0)]int nbytes, [DefaultParameterValue(0)]int flags) {
int bytesRead;
byte[] byteBuffer = new byte[byteBufferSize("recvfrom_into", nbytes, buffer.Count, 1)];
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
try {
bytesRead = _socket.ReceiveFrom(byteBuffer, (SocketFlags)flags, ref remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
for (int i = 0; i < byteBuffer.Length; i++) {
buffer[i] = byteBuffer[i];
}
PythonTuple remoteAddress = EndPointToTuple((IPEndPoint)remoteEP);
return PythonTuple.MakeTuple(bytesRead, remoteAddress);
}
private static int byteBufferSize(string funcName, int nbytes, int bufLength, int itemSize) {
if (nbytes < 0) {
throw PythonOps.ValueError("negative buffersize in " + funcName);
} else if (nbytes == 0) {
return bufLength * itemSize;
} else {
int remainder = nbytes % itemSize;
return Math.Min(remainder == 0 ? nbytes : nbytes + itemSize - remainder,
bufLength * itemSize);
}
}
[Documentation("send(string[, flags]) -> bytes_sent\n\n"
+ "Send data to the remote socket. The socket must be connected to a remote\n"
+ "socket (by calling either connect() or accept(). Returns the number of bytes\n"
+ "sent to the remote socket.\n"
+ "\n"
+ "Note that the successful completion of a send() call does not mean that all of\n"
+ "the data was sent. The caller must keep track of the number of bytes sent and\n"
+ "retry the operation until all of the data has been sent.\n"
+ "\n"
+ "Also note that there is no guarantee that the data you send will appear on the\n"
+ "network immediately. To increase network efficiency, the underlying system may\n"
+ "delay transmission until a significant amount of outgoing data is collected. A\n"
+ "successful completion of the Send method means that the underlying system has\n"
+ "had room to buffer your data for a network send"
)]
public int send(string data, [DefaultParameterValue(0)] int flags) {
byte[] buffer = data.MakeByteArray();
try {
return _socket.Send(buffer, (SocketFlags)flags);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("send(string[, flags]) -> bytes_sent\n\n"
+ "Send data to the remote socket. The socket must be connected to a remote\n"
+ "socket (by calling either connect() or accept(). Returns the number of bytes\n"
+ "sent to the remote socket.\n"
+ "\n"
+ "Note that the successful completion of a send() call does not mean that all of\n"
+ "the data was sent. The caller must keep track of the number of bytes sent and\n"
+ "retry the operation until all of the data has been sent.\n"
+ "\n"
+ "Also note that there is no guarantee that the data you send will appear on the\n"
+ "network immediately. To increase network efficiency, the underlying system may\n"
+ "delay transmission until a significant amount of outgoing data is collected. A\n"
+ "successful completion of the Send method means that the underlying system has\n"
+ "had room to buffer your data for a network send"
)]
public int send(PythonBuffer data, [DefaultParameterValue(0)] int flags) {
byte[] buffer = data.byteCache;
try {
return _socket.Send(buffer, (SocketFlags)flags);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("sendall(string[, flags]) -> None\n\n"
+ "Send data to the remote socket. The socket must be connected to a remote\n"
+ "socket (by calling either connect() or accept().\n"
+ "\n"
+ "Unlike send(), sendall() blocks until all of the data has been sent or until a\n"
+ "timeout or an error occurs. None is returned on success. If an error occurs,\n"
+ "there is no way to tell how much data, if any, was sent.\n"
+ "\n"
+ "Difference from CPython: timeouts do not function as you would expect. The\n"
+ "function is implemented using multiple calls to send(), so the timeout timer\n"
+ "is reset after each of those calls. That means that the upper bound on the\n"
+ "time that it will take for sendall() to return is the number of bytes in\n"
+ "string times the timeout interval.\n"
+ "\n"
+ "Also note that there is no guarantee that the data you send will appear on the\n"
+ "network immediately. To increase network efficiency, the underlying system may\n"
+ "delay transmission until a significant amount of outgoing data is collected. A\n"
+ "successful completion of the Send method means that the underlying system has\n"
+ "had room to buffer your data for a network send"
)]
public void sendall(string data, [DefaultParameterValue(0)] int flags) {
byte[] buffer = data.MakeByteArray();
try {
int bytesTotal = buffer.Length;
int bytesRemaining = bytesTotal;
while (bytesRemaining > 0) {
bytesRemaining -= _socket.Send(buffer, bytesTotal - bytesRemaining, bytesRemaining, (SocketFlags)flags);
}
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("sendall(string[, flags]) -> None\n\n"
+ "Send data to the remote socket. The socket must be connected to a remote\n"
+ "socket (by calling either connect() or accept().\n"
+ "\n"
+ "Unlike send(), sendall() blocks until all of the data has been sent or until a\n"
+ "timeout or an error occurs. None is returned on success. If an error occurs,\n"
+ "there is no way to tell how much data, if any, was sent.\n"
+ "\n"
+ "Difference from CPython: timeouts do not function as you would expect. The\n"
+ "function is implemented using multiple calls to send(), so the timeout timer\n"
+ "is reset after each of those calls. That means that the upper bound on the\n"
+ "time that it will take for sendall() to return is the number of bytes in\n"
+ "string times the timeout interval.\n"
+ "\n"
+ "Also note that there is no guarantee that the data you send will appear on the\n"
+ "network immediately. To increase network efficiency, the underlying system may\n"
+ "delay transmission until a significant amount of outgoing data is collected. A\n"
+ "successful completion of the Send method means that the underlying system has\n"
+ "had room to buffer your data for a network send"
)]
public void sendall(PythonBuffer data, [DefaultParameterValue(0)] int flags) {
byte[] buffer = data.byteCache;
try {
int bytesTotal = buffer.Length;
int bytesRemaining = bytesTotal;
while (bytesRemaining > 0) {
bytesRemaining -= _socket.Send(buffer, bytesTotal - bytesRemaining, bytesRemaining, (SocketFlags)flags);
}
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("sendto(string[, flags], address) -> bytes_sent\n\n"
+ "Send data to the remote socket. The socket does not need to be connected to a\n"
+ "remote socket since the address is specified in the call to sendto(). Returns\n"
+ "the number of bytes sent to the remote socket.\n"
+ "\n"
+ "Blocking sockets will block until the all of the bytes in the buffer are sent.\n"
+ "Since a nonblocking Socket completes immediately, it might not send all of the\n"
+ "bytes in the buffer. It is your application's responsibility to keep track of\n"
+ "the number of bytes sent and to retry the operation until the application sends\n"
+ "all of the bytes in the buffer.\n"
+ "\n"
+ "Note that there is no guarantee that the data you send will appear on the\n"
+ "network immediately. To increase network efficiency, the underlying system may\n"
+ "delay transmission until a significant amount of outgoing data is collected. A\n"
+ "successful completion of the Send method means that the underlying system has\n"
+ "had room to buffer your data for a network send"
)]
public int sendto(string data, int flags, PythonTuple address) {
byte[] buffer = data.MakeByteArray();
EndPoint remoteEP = TupleToEndPoint(_context, address, _socket.AddressFamily, out _hostName);
try {
return _socket.SendTo(buffer, (SocketFlags)flags, remoteEP);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("")]
public int sendto(string data, PythonTuple address) {
return sendto(data, 0, address);
}
[Documentation("setblocking(flag) -> None\n\n"
+ "Set the blocking mode of the socket. If flag is 0, the socket will be set to\n"
+ "non-blocking mode; otherwise, it will be set to blocking mode. If the socket is\n"
+ "in blocking mode, and a method is called (such as send() or recv() which does\n"
+ "not complete immediately, the caller will block execution until the requested\n"
+ "operation completes. In non-blocking mode, a socket.timeout exception would\n"
+ "would be raised in this case.\n"
+ "\n"
+ "Note that changing blocking mode also affects the timeout setting:\n"
+ "setblocking(0) is equivalent to settimeout(0), and setblocking(1) is equivalent\n"
+ "to settimeout(None)."
)]
public void setblocking(int shouldBlock) {
if (shouldBlock == 0) {
settimeout(0);
} else {
settimeout(null);
}
}
[Documentation("settimeout(value) -> None\n\n"
+ "Set a timeout on blocking socket methods. value may be either None or a\n"
+ "non-negative float, with one of the following meanings:\n"
+ " - None: disable timeouts and block indefinitely"
+ " - 0.0: don't block at all (return immediately if the operation can be\n"
+ " completed; raise socket.error otherwise)\n"
+ " - float > 0.0: block for up to the specified number of seconds; raise\n"
+ " socket.timeout if the operation cannot be completed in time\n"
+ "\n"
+ "settimeout(None) is equivalent to setblocking(1), and settimeout(0.0) is\n"
+ "equivalent to setblocking(0)."
+ "\n"
+ "If the timeout is non-zero and is less than 0.5, it will be set to 0.5. This\n"
+ "limitation is specific to IronPython.\n"
)]
public void settimeout(object timeout) {
try {
if (timeout == null) {
_socket.Blocking = true;
_socket.SendTimeout = 0;
} else {
double seconds;
seconds = Converter.ConvertToDouble(timeout);
if (seconds < 0) {
throw PythonOps.TypeError("a non-negative float is required");
}
_socket.Blocking = seconds > 0; // 0 timeout means non-blocking mode
_socket.SendTimeout = (int)(seconds * MillisecondsPerSecond);
_timeout = (int)(seconds * MillisecondsPerSecond);
}
} finally {
_socket.ReceiveTimeout = _socket.SendTimeout;
}
}
[Documentation("gettimeout() -> value\n\n"
+ "Return the timeout duration in seconds for this socket as a float. If no\n"
+ "timeout is set, return None. For more details on timeouts and blocking, see the\n"
+ "Python socket module documentation."
)]
public object gettimeout() {
try {
if (_socket.Blocking && _socket.SendTimeout == 0) {
return null;
} else {
return (double)_socket.SendTimeout / MillisecondsPerSecond;
}
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[Documentation("setsockopt(level, optname[, value]) -> None\n\n"
+ "Set the value of a socket option. level is one of the SOL_* constants defined\n"
+ "in this module, and optname is one of the SO_* constants. value may be either\n"
+ "an integer or a string containing a binary structure. The caller is responsible\n"
+ "for properly encoding the byte string."
)]
public void setsockopt(int optionLevel, int optionName, object value) {
SocketOptionLevel level = (SocketOptionLevel)Enum.ToObject(typeof(SocketOptionLevel), optionLevel);
if (!Enum.IsDefined(typeof(SocketOptionLevel), level)) {
throw MakeException(_context, new SocketException((int)SocketError.InvalidArgument));
}
SocketOptionName name = (SocketOptionName)Enum.ToObject(typeof(SocketOptionName), optionName);
if (!Enum.IsDefined(typeof(SocketOptionName), name)) {
throw MakeException(_context, new SocketException((int)SocketError.ProtocolOption));
}
try {
int intValue;
if (Converter.TryConvertToInt32(value, out intValue)) {
_socket.SetSocketOption(level, name, intValue);
return;
}
string strValue;
if (Converter.TryConvertToString(value, out strValue)) {
_socket.SetSocketOption(level, name, strValue.MakeByteArray());
return;
}
} catch (Exception e) {
throw MakeException(_context, e);
}
throw PythonOps.TypeError("setsockopt() argument 3 must be int or string");
}
[Documentation("shutdown() -> None\n\n"
+ "Return the timeout duration in seconds for this socket as a float. If no\n"
+ "timeout is set, return None. For more details on timeouts and blocking, see the\n"
+ "Python socket module documentation."
)]
public void shutdown(int how) {
SocketShutdown howValue = (SocketShutdown)Enum.ToObject(typeof(SocketShutdown), how);
if (!Enum.IsDefined(typeof(SocketShutdown), howValue)) {
throw MakeException(_context, new SocketException((int)SocketError.InvalidArgument));
}
try {
_socket.Shutdown(howValue);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
public int family {
get { return (int)_socket.AddressFamily; }
}
public int type {
get { return (int)_socket.SocketType; }
}
public int proto {
get { return (int)_socket.ProtocolType; }
}
public int ioctl(BigInteger cmd, int option) {
return _socket.IOControl((IOControlCode)(long)cmd, BitConverter.GetBytes(option), null);
}
public override string ToString() {
try {
return String.Format("<socket object, fd={0}, family={1}, type={2}, protocol={3}>",
fileno(), family, type, proto);
} catch {
return "<socket object, fd=?, family=?, type=, protocol=>";
}
}
/// <summary>
/// Return the internal System.Net.Sockets.Socket socket object associated with the given
/// handle (as returned by GetHandle()), or null if no corresponding socket exists. This is
/// primarily intended to be used by other modules (such as select) that implement
/// networking primitives. User code should not normally need to call this function.
/// </summary>
internal static Socket HandleToSocket(Int64 handle) {
WeakReference weakref;
lock (_handleToSocket) {
if (_handleToSocket.TryGetValue((IntPtr)handle, out weakref)) {
return (weakref.Target as Socket);
}
}
return null;
}
#endregion
#region IWeakReferenceable Implementation
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _weakRefTracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_weakRefTracker = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_weakRefTracker = value;
}
#endregion
#region Private Implementation
/// <summary>
/// Create a Python socket object from an existing .NET socket object
/// (like one returned from Socket.Accept())
/// </summary>
private socket(CodeContext/*!*/ context, Socket socket) {
Initialize(context, socket);
}
/// <summary>
/// Perform initialization common to all constructors
/// </summary>
private void Initialize(CodeContext context, Socket socket) {
_socket = socket;
_context = context;
int? defaultTimeout = GetDefaultTimeout(context);
if (defaultTimeout == null) {
settimeout(null);
} else {
settimeout((double)defaultTimeout / MillisecondsPerSecond);
}
lock (_handleToSocket) {
_handleToSocket[socket.Handle] = new WeakReference(socket);
}
}
#endregion
}
#endregion
#region Fields
private const string AnyAddrToken = "";
private const string BroadcastAddrToken = "<broadcast>";
private const string LocalhostAddrToken = "";
private const int IPv4AddrBytes = 4;
private const int IPv6AddrBytes = 16;
private const double MillisecondsPerSecond = 1000.0;
#endregion
#region Public API
public static object _GLOBAL_DEFAULT_TIMEOUT = new object();
[Documentation("Connect to *address* and return the socket object.\n\n"
+ "Convenience function. Connect to *address* (a 2-tuple ``(host,\n"
+ "port)``) and return the socket object. Passing the optional\n"
+ "*timeout* parameter will set the timeout on the socket instance\n"
+ "before attempting to connect. If no *timeout* is supplied, the\n"
+ "global default timeout setting returned by :func:`getdefaulttimeout`\n"
+ "is used.\n"
)]
public static socket create_connection(CodeContext/*!*/ context, PythonTuple address) {
return create_connection(context, address, _GLOBAL_DEFAULT_TIMEOUT);
}
[Documentation("Connect to *address* and return the socket object.\n\n"
+ "Convenience function. Connect to *address* (a 2-tuple ``(host,\n"
+ "port)``) and return the socket object. Passing the optional\n"
+ "*timeout* parameter will set the timeout on the socket instance\n"
+ "before attempting to connect. If no *timeout* is supplied, the\n"
+ "global default timeout setting returned by :func:`getdefaulttimeout`\n"
+ "is used.\n"
)]
public static socket create_connection(CodeContext/*!*/ context, PythonTuple address, object timeout) {
return create_connection(context, address, timeout, null);
}