forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_socket.cs
More file actions
2289 lines (2035 loc) · 116 KB
/
_socket.cs
File metadata and controls
2289 lines (2035 loc) · 116 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
#if FEATURE_FULL_NET
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
[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;
#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
if (!context.HasModuleState(_defaultTimeoutKey)) {
context.SetModuleState(_defaultTimeoutKey, null);
}
context.SetModuleState(_defaultBufsizeKey, DefaultBufferSize);
context.EnsureModuleException("socketherror", error, dict, "herror", "socket");
context.EnsureModuleException("socketgaierror", error, dict, "gaierror", "socket");
context.EnsureModuleException("sockettimeout", error, dict, "timeout", "socket");
}
#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute
public static PythonType error => PythonExceptions.OSError;
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"
+ " - 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;
private int _referenceCount = 1; // TODO: this is no longer incremented by anything...
public const string __module__ = "socket";
internal CodeContext/*!*/ _context;
private int _timeout;
#endregion
#region Public API
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public socket() { } // TODO: _socket and _context are null!
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public void __init__(CodeContext/*!*/ context, int family = DefaultAddressFamily,
int type = DefaultSocketType,
int proto = DefaultProtocolType,
object? fileno = null) {
var socketType = (SocketType)Enum.ToObject(typeof(SocketType), type);
if (!Enum.IsDefined(typeof(SocketType), socketType)) {
throw MakeException(context, new SocketException((int)SocketError.SocketNotSupported));
}
var addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family);
if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) {
throw MakeException(context, new SocketException((int)SocketError.AddressFamilyNotSupported));
}
var protocolType = (ProtocolType)Enum.ToObject(typeof(ProtocolType), proto);
if (!Enum.IsDefined(typeof(ProtocolType), protocolType)) {
throw MakeException(context, new SocketException((int)SocketError.ProtocolNotSupported));
}
Socket? socket;
if (fileno is socket sock) {
socket = sock._socket;
_hostName = sock._hostName;
// we now own the lifetime of the socket
GC.SuppressFinalize(sock);
} else if (fileno != null && (socket = HandleToSocket((long)fileno)) != null) {
// nothing to do here
} else {
try {
socket = new Socket(addressFamily, socketType, protocolType);
if (ClrModule.IsMono) {
// for whatever reason Mono sets this to true on Linux
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
}
} catch (SocketException e) {
throw MakeException(context, e);
}
}
Initialize(context, socket);
}
public void __del__() {
_close();
}
~socket() {
_close();
}
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 new SocketException((int)SocketError.TimedOut);
}
} 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([NotNone] 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() {
var refs = System.Threading.Interlocked.Decrement(ref _referenceCount);
// Don't actually close the socket if other file objects are
// still referring to this socket.
if (refs < 1) {
_close();
}
}
private void _close() {
if (_socket != null) {
lock (_handleToSocket) {
if (_handleToSocket.TryGetValue(_socket.Handle, out WeakReference? weakref)) {
Socket? target = weakref.Target as Socket;
if (target == _socket || target == null) {
_handleToSocket.Remove(_socket.Handle);
}
}
}
((IDisposable)_socket).Dispose();
if (System.Threading.Interlocked.Exchange(ref _referenceCount, 0) > 0) {
try { // this may throw when called from the Finalizer (on Mono) so just swallow any exception
PythonOps.Warn(_context, PythonExceptions.ResourceWarning, $"unclosed {PythonOps.Repr(_context, this)}");
} catch { }
}
}
}
[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([NotNone] 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([NotNone] PythonTuple address) {
IPEndPoint remoteEP = TupleToEndPoint(_context, address, _socket.AddressFamily, out _hostName);
try {
_socket.Connect(remoteEP);
} catch (SocketException ex) {
return !ClrModule.IsMono ? ex.NativeErrorCode : MapMonoSocketErrorToErrno(ex.SocketErrorCode);
}
return PythonErrorNumber.ENOERROR;
}
public long detach() {
var fd = fileno();
_socket = null!; // TODO: this is wrong, no null checks on _socket anywhere!
return fd;
}
[Documentation("fileno() -> file_handle\n\n"
+ "Return the underlying system handle for this socket (a 64-bit integer)."
)]
public long 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.NotConnected));
}
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, int optionLength = 0) {
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() => listen(Math.Min(SOMAXCONN, 128)); // new in CPython 3.5
public void listen(int backlog) {
try {
_socket.Listen(backlog);
} catch (Exception e) {
throw MakeException(_context, e);
}
}
private static ArrayPool<byte> ArrayPool => ArrayPool<byte>.Shared;
[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 Bytes recv(int bufsize, int flags = 0) {
if (bufsize < 0) throw PythonOps.ValueError($"negative buffersize in {nameof(recv)}");
var buffer = ArrayPool.Rent(bufsize);
try {
int bytesRead;
try {
bytesRead = _socket.Receive(buffer, bufsize, (SocketFlags)flags);
} catch (Exception e) {
throw MakeRecvException(e, SocketError.NotConnected);
}
var bytes = new byte[bytesRead];
Array.Copy(buffer, bytes, bytes.Length);
return Bytes.Make(bytes);
} finally {
ArrayPool.Return(buffer);
}
}
[Documentation("recv_into(memoryview, [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([NotNone] IBufferProtocol buffer, int nbytes = 0, int flags = 0) {
using var buf = buffer.GetBufferNoThrow(BufferFlags.Writable);
if (buf is null) throw PythonOps.TypeError($"{nameof(recv_into)}() argument 1 must be read-write buffer, not {PythonOps.GetPythonTypeName(buffer)}");
var span = buf.AsSpan();
if (nbytes < 0) throw PythonOps.ValueError("negative buffersize in " + nameof(recv_into));
if (nbytes > span.Length) throw PythonOps.ValueError("buffer too small for requested bytes");
if (nbytes == 0) nbytes = span.Length;
var byteBuffer = ArrayPool.Rent(nbytes);
try {
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
int bytesRead;
try {
bytesRead = _socket.Receive(byteBuffer, nbytes, (SocketFlags)flags);
} catch (Exception e) {
throw MakeRecvException(e, SocketError.NotConnected);
}
byteBuffer.AsSpan(0, bytesRead).CopyTo(span);
return bytesRead;
} finally {
ArrayPool.Return(byteBuffer);
}
}
[Documentation("")]
public int recv_into(object? buffer, int nbytes = 0, int flags = 0) {
if (Converter.TryConvert<IBufferProtocol>(buffer, out var bufferProtocol) && bufferProtocol is not null) {
return recv_into(bufferProtocol, nbytes, flags);
}
throw PythonOps.TypeError($"{nameof(recv_into)}() argument 1 must be read-write buffer, not {PythonOps.GetPythonTypeName(buffer)}");
}
[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 bufsize, int flags = 0) {
if (bufsize < 0) throw PythonOps.ValueError($"negative buffersize in {nameof(recvfrom)}");
var buffer = ArrayPool.Rent(bufsize);
try {
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
int bytesRead;
try {
bytesRead = _socket.ReceiveFrom(buffer, bufsize, (SocketFlags)flags, ref remoteEP);
} catch (Exception e) {
throw MakeRecvException(e, SocketError.InvalidArgument);
}
var bytes = new byte[bytesRead];
Array.Copy(buffer, bytes, bytes.Length);
return PythonTuple.MakeTuple(Bytes.Make(bytes), EndPointToTuple((IPEndPoint)remoteEP));
} finally {
ArrayPool.Return(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([NotNone] IBufferProtocol buffer, int nbytes = 0, int flags = 0) {
using var buf = buffer.GetBufferNoThrow(BufferFlags.Writable);
if (buf is null) throw PythonOps.TypeError($"{nameof(recvfrom_into)}() argument 1 must be read-write buffer, not {PythonOps.GetPythonTypeName(buffer)}");
var span = buf.AsSpan();
if (nbytes < 0) throw PythonOps.ValueError("negative buffersize in " + nameof(recvfrom_into));
if (nbytes > span.Length) throw PythonOps.ValueError("nbytes is greater than the length of the buffer");
if (nbytes == 0) nbytes = span.Length;
var byteBuffer = ArrayPool.Rent(nbytes);
try {
IPEndPoint remoteIPEP = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEP = remoteIPEP;
int bytesRead;
try {
bytesRead = _socket.ReceiveFrom(byteBuffer, nbytes, (SocketFlags)flags, ref remoteEP);
} catch (Exception e) {
throw MakeRecvException(e, SocketError.InvalidArgument);
}
byteBuffer.AsSpan(0, bytesRead).CopyTo(span);
return PythonTuple.MakeTuple(bytesRead, EndPointToTuple((IPEndPoint)remoteEP));
} finally {
ArrayPool.Return(byteBuffer);
}
}
[Documentation("")]
public PythonTuple recvfrom_into(object? buffer, int nbytes = 0, int flags = 0) {
if (Converter.TryConvert<IBufferProtocol>(buffer, out var bufferProtocol) && bufferProtocol is not null) {
return recvfrom_into(bufferProtocol, nbytes, flags);
}
throw PythonOps.TypeError($"{nameof(recvfrom_into)}() argument 1 must be read-write buffer, not {PythonOps.GetPythonTypeName(buffer)}");
}
private static int byteBufferSize(string funcName, int nbytes, int bufLength, int itemSize = 1) {
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);
}
}
private Exception MakeRecvException(Exception e, SocketError errorCode = SocketError.InvalidArgument) {
if (e is ObjectDisposedException) return MakeException(_context, e);
// on the socket recv throw a special socket error code when SendTimeout is zero
if (_socket.SendTimeout == 0) {
var s = new SocketException((int)errorCode);
return PythonExceptions.CreateThrowable(error, s.ErrorCode, s.Message);
} else {
return 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([NotNone] Bytes data, int flags = 0) {
return sendWorker(data.UnsafeByteArray, flags);
}
public int send([NotNone] IBufferProtocol data, int flags = 0) {
using IPythonBuffer buffer = data.GetBuffer();
return sendWorker(buffer.AsUnsafeArray() ?? buffer.ToArray(), flags);
}
private int sendWorker(byte[] buffer, int flags) {
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([NotNone] Bytes data, int flags = 0) {
sendallWorker(data.UnsafeByteArray, flags);
}
public void sendall([NotNone] IBufferProtocol data, int flags = 0) {
using IPythonBuffer buffer = data.GetBuffer();
sendallWorker(buffer.AsUnsafeArray() ?? buffer.ToArray(), flags);
}
private void sendallWorker(byte[] buffer, int flags) {
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([NotNone] Bytes data, int flags, [NotNone] PythonTuple address) {
return sendtoWorker(data.UnsafeByteArray, flags, address);
}
public int sendto([NotNone] IBufferProtocol data, int flags, [NotNone] PythonTuple address) {
using IPythonBuffer buffer = data.GetBuffer();
return sendtoWorker(buffer.AsUnsafeArray() ?? buffer.ToArray(), flags, address);
}
[Documentation("")]
public int sendto([NotNone] Bytes data, [NotNone] PythonTuple address)
=> sendto(data, 0, address);
public int sendto([NotNone] IBufferProtocol data, [NotNone] PythonTuple address)
=> sendto(data, 0, address);
private int sendtoWorker(byte[] buffer, int flags, PythonTuple address) {
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("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"
)]
// NOTE: The above IronPython specific timeout behavior is due to the underlying
// .Net Socket.SendTimeout behavior and is outside of our control.
public void settimeout(object? timeout) {
bool blocking = true;
int timeoutVal = 0;
if (timeout is not null) {
double seconds;
seconds = Converter.ConvertToDouble(timeout);
if (seconds < 0) {
throw PythonOps.ValueError("Timeout value out of range");
}
blocking = seconds > 0; // 0 timeout means non-blocking mode
timeoutVal = (int)(seconds * MillisecondsPerSecond);
}
try {
_socket.Blocking = blocking;
_socket.SendTimeout = timeoutVal;
_socket.ReceiveTimeout = _socket.SendTimeout;
_timeout = timeoutVal;
} catch (Exception ex) {
throw MakeException(_context, ex);
}
}
[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;
}
if (value is IBufferProtocol bp) {
using IPythonBuffer buf = bp.GetBuffer();
_socket.SetSocketOption(level, name, buf.AsReadOnlySpan().ToArray());
return;
}
throw PythonOps.TypeError("a bytes-like object is required, not '{0}'", PythonOps.GetPythonTypeName(value));
} catch (Exception e) {
throw MakeException(_context, e);
}
}
[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 => (int)_socket.AddressFamily;
public int type => (int)_socket.SocketType;
public int proto => (int)_socket.ProtocolType;
public int ioctl(BigInteger cmd, object? option) {
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw PythonOps.ValueError(string.Format("invalid ioctl command {0}", cmd));
if (cmd == SIO_KEEPALIVE_VALS) {
if (!(option is PythonTuple))
throw PythonOps.TypeError("option must be 3-item sequence, not int");
var tOption = (PythonTuple)option;
if (tOption.Count != 3)
throw PythonOps.TypeError(string.Format("option must be sequence of length 3, not {0}", tOption.Count));
//(onoff, timeout, interval)
if ((!(tOption[0] is int)) && (!(tOption[1] is int)) && (!(tOption[2] is int)))
throw PythonOps.TypeError("option integer required");
int onoff = (int)tOption[0]!;
int timeout = (int)tOption[1]!;
int interval = (int)tOption[2]!;
int size = sizeof(UInt32);
byte[] inArray = new byte[size * 3];
Array.Copy(BitConverter.GetBytes(onoff), 0, inArray, 0, size);
Array.Copy(BitConverter.GetBytes(timeout), 0, inArray, size, size);
Array.Copy(BitConverter.GetBytes(size), 0, inArray, size * 2, size);
return _socket.IOControl((IOControlCode)(long)cmd, inArray, null);
} else if (cmd == SIO_RCVALL) {
if (!(option is int))
throw PythonOps.TypeError("option integer required");
return _socket.IOControl((IOControlCode)(long)cmd, BitConverter.GetBytes((int)option), null);
} else {
throw PythonOps.ValueError(string.Format("invalid ioctl command {0}", cmd));
}
}
public string __repr__(CodeContext context) {
try {
return $"<socket object, fd={fileno()}, family={family}, type={type}, proto={proto}>";
} catch {
return "<socket object, fd=-1, family=0, type=0, proto=0>";
}
}
/// <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) {
lock (_handleToSocket) {
if (_handleToSocket.TryGetValue(checked((IntPtr)handle), out WeakReference? 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>
[System.Diagnostics.CodeAnalysis.MemberNotNull(nameof(_socket), nameof(_context))]
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
[Documentation("")]
public static PythonList getaddrinfo(
CodeContext/*!*/ context,
string? host,
object? port,
int family = (int)AddressFamily.Unspecified,
int socktype = 0,
int proto = (int)ProtocolType.IP,
int flags = (int)SocketFlags.None
) {
var numericPort = port switch {
null => 0,
int i => i,
BigInteger bi => (int)bi,
Extensible<BigInteger> bi => (int)bi.Value,
Bytes b => ParsePort(context, b.MakeString()),
string s => ParsePort(context, s),
ExtensibleString es => ParsePort(context, es.Value),
_ => throw MakeGaiException(context, EAI_NONAME),
};
static int ParsePort(CodeContext context, string port) {
if (int.TryParse(port, out var numericPort)) return numericPort;
try {
return getservbyname(context, port);
} catch {
throw MakeGaiException(context, EAI_NONAME);
}
}
if (socktype != 0) {
// we just use this to validate; socketType isn't actually used
System.Net.Sockets.SocketType socketType = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socktype);
if (socketType == System.Net.Sockets.SocketType.Unknown || !Enum.IsDefined(typeof(System.Net.Sockets.SocketType), socketType)) {
throw MakeGaiException(context, EAI_BADHINTS);
}
}
AddressFamily addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family);
if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) {
throw MakeGaiException(context, EAI_FAMILY);
}
// Again, we just validate, but don't actually use protocolType
Enum.ToObject(typeof(ProtocolType), proto);
if (host == null)
host = "localhost";
IPAddress[] ips = HostToAddresses(context, host, addressFamily);
PythonList results = new PythonList();
foreach (IPAddress ip in ips) {
results.append(PythonTuple.MakeTuple(
(int)ip.AddressFamily,
socktype,
proto,
"",
EndPointToTuple(new IPEndPoint(ip, numericPort))
));
}