-
-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
socketmodule.c
9006 lines (8042 loc) · 254 KB
/
socketmodule.c
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
/* Socket module */
/*
This module provides an interface to Berkeley socket IPC.
Limitations:
- Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
portable manner, though AF_PACKET, AF_NETLINK, AF_QIPCRTR and AF_TIPC are
supported under Linux.
- No read/write operations (use sendall/recv or makefile instead).
- Additional restrictions apply on some non-Unix platforms (compensated
for by socket.py).
Module interface:
- socket.error: exception raised for socket specific errors, alias for OSError
- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
a subclass of socket.error
- socket.herror: exception raised for gethostby* errors,
a subclass of socket.error
- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
- socket.getprotobyname(protocolname) --> protocol number
- socket.getservbyname(servicename[, protocolname]) --> port number
- socket.getservbyport(portnumber[, protocolname]) --> service name
- socket.socket([family[, type [, proto, fileno]]]) --> new socket object
(fileno specifies a pre-existing socket file descriptor)
- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
- socket.ntohs(16 bit value) --> new int object
- socket.ntohl(32 bit value) --> new int object
- socket.htons(16 bit value) --> new int object
- socket.htonl(32 bit value) --> new int object
- socket.getaddrinfo(host, port [, family, type, proto, flags])
--> List of (family, type, proto, canonname, sockaddr)
- socket.getnameinfo(sockaddr, flags) --> (host, port)
- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
- socket.has_ipv6: boolean value indicating if IPv6 is supported
- socket.inet_aton(IP address) -> 32-bit packed IP representation
- socket.inet_ntoa(packed IP) -> IP address string
- socket.getdefaulttimeout() -> None | float
- socket.setdefaulttimeout(None | float)
- socket.if_nameindex() -> list of tuples (if_index, if_name)
- socket.if_nametoindex(name) -> corresponding interface index
- socket.if_indextoname(index) -> corresponding interface name
- an internet socket address is a pair (hostname, port)
where hostname can be anything recognized by gethostbyname()
(including the dd.dd.dd.dd notation) and port is in host byte order
- where a hostname is returned, the dd.dd.dd.dd notation is used
- a UNIX domain socket address is a string specifying the pathname
- an AF_PACKET socket address is a tuple containing a string
specifying the ethernet interface and an integer specifying
the Ethernet protocol number to be received. For example:
("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
specify packet-type and ha-type/addr.
- an AF_QIPCRTR socket address is a (node, port) tuple where the
node and port are non-negative integers.
- an AF_TIPC socket address is expressed as
(addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
and scope can be one of:
TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
The meaning of v1, v2 and v3 depends on the value of addr_type:
if addr_type is TIPC_ADDR_NAME:
v1 is the server type
v2 is the port identifier
v3 is ignored
if addr_type is TIPC_ADDR_NAMESEQ:
v1 is the server type
v2 is the lower port number
v3 is the upper port number
if addr_type is TIPC_ADDR_ID:
v1 is the node
v2 is the ref
v3 is ignored
Local naming conventions:
- names starting with sock_ are socket object methods
- names starting with socket_ are module-level functions
- names starting with PySocket are exported through socketmodule.h
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#ifdef __APPLE__
// Issue #35569: Expose RFC 3542 socket options.
#define __APPLE_USE_RFC_3542 1
#include <AvailabilityMacros.h>
/* for getaddrinfo thread safety test on old versions of OS X */
#ifndef MAC_OS_X_VERSION_10_5
#define MAC_OS_X_VERSION_10_5 1050
#endif
/*
* inet_aton is not available on OSX 10.3, yet we want to use a binary
* that was build on 10.4 or later to work on that release, weak linking
* comes to the rescue.
*/
# pragma weak inet_aton
#endif
#include "Python.h"
#include "pycore_capsule.h" // _PyCapsule_SetTraverse()
#include "pycore_fileutils.h" // _Py_set_inheritable()
#include "pycore_moduleobject.h" // _PyModule_GetState
#include "pycore_time.h" // _PyTime_AsMilliseconds()
#ifdef _Py_MEMORY_SANITIZER
# include <sanitizer/msan_interface.h>
#endif
/* Socket object documentation */
PyDoc_STRVAR(sock_doc,
"socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object\n\
socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object\n\
\n\
Open a socket of the given type. The family argument specifies the\n\
address family; it defaults to AF_INET. The type argument specifies\n\
whether this is a stream (SOCK_STREAM, this is the default)\n\
or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
specifying the default protocol. Keyword arguments are accepted.\n\
The socket is created as non-inheritable.\n\
\n\
When a fileno is passed in, family, type and proto are auto-detected,\n\
unless they are explicitly set.\n\
\n\
A socket object represents one endpoint of a network connection.\n\
\n\
Methods of socket objects (keyword arguments not allowed):\n\
\n\
_accept() -- accept connection, returning new socket fd and client address\n\
bind(addr) -- bind the socket to a local address\n\
close() -- close the socket\n\
connect(addr) -- connect the socket to a remote address\n\
connect_ex(addr) -- connect, return an error code instead of an exception\n\
dup() -- return a new socket fd duplicated from fileno()\n\
fileno() -- return underlying file descriptor\n\
getpeername() -- return remote address [*]\n\
getsockname() -- return local address\n\
getsockopt(level, optname[, buflen]) -- get socket options\n\
gettimeout() -- return timeout or None\n\
listen([n]) -- start listening for incoming connections\n\
recv(buflen[, flags]) -- receive data\n\
recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
recvfrom_into(buffer[, nbytes, [, flags])\n\
-- receive data and sender\'s address (into a buffer)\n\
sendall(data[, flags]) -- send all data\n\
send(data[, flags]) -- send data, may not send all of it\n\
sendto(data[, flags], addr) -- send data to a given address\n\
setblocking(bool) -- set or clear the blocking I/O flag\n\
getblocking() -- return True if socket is blocking, False if non-blocking\n\
setsockopt(level, optname, value[, optlen]) -- set socket options\n\
settimeout(None | float) -- set or clear the timeout\n\
shutdown(how) -- shut down traffic in one or both directions\n\
\n\
[*] not available on all platforms!");
/* XXX This is a terrible mess of platform-dependent preprocessor hacks.
I hope some day someone can clean this up please... */
/* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
script doesn't get this right, so we hardcode some platform checks below.
On the other hand, not all Linux versions agree, so there the settings
computed by the configure script are needed! */
#ifndef __linux__
# undef HAVE_GETHOSTBYNAME_R_3_ARG
# undef HAVE_GETHOSTBYNAME_R_5_ARG
# undef HAVE_GETHOSTBYNAME_R_6_ARG
#endif
#if defined(__OpenBSD__)
# include <sys/uio.h>
#endif
#if defined(__ANDROID__) && __ANDROID_API__ < 23
# undef HAVE_GETHOSTBYNAME_R
#endif
#ifdef HAVE_GETHOSTBYNAME_R
# if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
# define HAVE_GETHOSTBYNAME_R_3_ARG
# elif defined(__sun) || defined(__sgi)
# define HAVE_GETHOSTBYNAME_R_5_ARG
# elif defined(__linux__)
/* Rely on the configure script */
# elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
# define HAVE_GETHOSTBYNAME_R_6_ARG
# else
# undef HAVE_GETHOSTBYNAME_R
# endif
#endif
#if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
# define USE_GETHOSTBYNAME_LOCK
#endif
#if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
# include <sys/ioctl.h>
#endif
#if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
/* make sure that the reentrant (gethostbyaddr_r etc)
functions are declared correctly if compiling with
MIPSPro 7.x in ANSI C mode (default) */
/* XXX Using _SGIAPI is the wrong thing,
but I don't know what the right thing is. */
#undef _SGIAPI /* to avoid warning */
#define _SGIAPI 1
#undef _XOPEN_SOURCE
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#ifdef _SS_ALIGNSIZE
#define HAVE_GETADDRINFO 1
#define HAVE_GETNAMEINFO 1
#endif
#define HAVE_INET_PTON
#include <netdb.h>
#endif // __sgi
/* Solaris fails to define this variable at all. */
#if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
#define INET_ADDRSTRLEN 16
#endif
/* Generic includes */
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_NET_ETHERNET_H
#include <net/ethernet.h>
#endif
/* Generic socket object definitions and includes */
#define PySocket_BUILDING_SOCKET
#include "socketmodule.h"
/* Addressing includes */
#ifndef MS_WINDOWS
/* Non-MS WINDOWS includes */
#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif
#include <unistd.h> // close()
/* Headers needed for inet_ntoa() and inet_addr() */
# include <arpa/inet.h>
# include <fcntl.h>
#else /* MS_WINDOWS */
/* MS_WINDOWS includes */
# ifdef HAVE_FCNTL_H
# include <fcntl.h>
# endif
/* Helpers needed for AF_HYPERV */
# include <Rpc.h>
/* Macros based on the IPPROTO enum, see: https://bugs.python.org/issue29515 */
#define IPPROTO_ICMP IPPROTO_ICMP
#define IPPROTO_IGMP IPPROTO_IGMP
#define IPPROTO_GGP IPPROTO_GGP
#define IPPROTO_TCP IPPROTO_TCP
#define IPPROTO_PUP IPPROTO_PUP
#define IPPROTO_UDP IPPROTO_UDP
#define IPPROTO_IDP IPPROTO_IDP
#define IPPROTO_ND IPPROTO_ND
#define IPPROTO_RAW IPPROTO_RAW
#define IPPROTO_MAX IPPROTO_MAX
#define IPPROTO_HOPOPTS IPPROTO_HOPOPTS
#define IPPROTO_IPV4 IPPROTO_IPV4
#define IPPROTO_IPV6 IPPROTO_IPV6
#define IPPROTO_ROUTING IPPROTO_ROUTING
#define IPPROTO_FRAGMENT IPPROTO_FRAGMENT
#define IPPROTO_ESP IPPROTO_ESP
#define IPPROTO_AH IPPROTO_AH
#define IPPROTO_ICMPV6 IPPROTO_ICMPV6
#define IPPROTO_NONE IPPROTO_NONE
#define IPPROTO_DSTOPTS IPPROTO_DSTOPTS
#define IPPROTO_EGP IPPROTO_EGP
#define IPPROTO_PIM IPPROTO_PIM
#define IPPROTO_ICLFXBM IPPROTO_ICLFXBM // WinSock2 only
#define IPPROTO_ST IPPROTO_ST // WinSock2 only
#define IPPROTO_CBT IPPROTO_CBT // WinSock2 only
#define IPPROTO_IGP IPPROTO_IGP // WinSock2 only
#define IPPROTO_RDP IPPROTO_RDP // WinSock2 only
#define IPPROTO_PGM IPPROTO_PGM // WinSock2 only
#define IPPROTO_L2TP IPPROTO_L2TP // WinSock2 only
#define IPPROTO_SCTP IPPROTO_SCTP // WinSock2 only
/* Provides the IsWindows7SP1OrGreater() function */
#include <versionhelpers.h>
// For if_nametoindex() and if_indextoname()
#include <iphlpapi.h>
/* remove some flags on older version Windows during run-time.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
typedef struct {
DWORD build_number; /* available starting with this Win10 BuildNumber */
const char flag_name[20];
} FlagRuntimeInfo;
/* IMPORTANT: make sure the list ordered by descending build_number */
static FlagRuntimeInfo win_runtime_flags[] = {
/* available starting with Windows 10 1709 */
{16299, "TCP_KEEPIDLE"},
{16299, "TCP_KEEPINTVL"},
/* available starting with Windows 10 1703 */
{15063, "TCP_KEEPCNT"},
/* available starting with Windows 10 1607 */
{14393, "TCP_FASTOPEN"}
};
/*[clinic input]
module _socket
class _socket.socket "PySocketSockObject *" "clinic_state()->sock_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2db2489bd2219fd8]*/
static int
remove_unusable_flags(PyObject *m)
{
PyObject *dict;
OSVERSIONINFOEX info;
dict = PyModule_GetDict(m);
if (dict == NULL) {
return -1;
}
#ifndef MS_WINDOWS_DESKTOP
info.dwOSVersionInfoSize = sizeof(info);
if (!GetVersionEx((OSVERSIONINFO*) &info)) {
PyErr_SetFromWindowsErr(0);
return -1;
}
#else
/* set to Windows 10, except BuildNumber. */
memset(&info, 0, sizeof(info));
info.dwOSVersionInfoSize = sizeof(info);
info.dwMajorVersion = 10;
info.dwMinorVersion = 0;
/* set Condition Mask */
DWORDLONG dwlConditionMask = 0;
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
#endif
for (int i=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
#ifdef MS_WINDOWS_DESKTOP
info.dwBuildNumber = win_runtime_flags[i].build_number;
/* greater than or equal to the specified version?
Compatibility Mode will not cheat VerifyVersionInfo(...) */
BOOL isSupported = VerifyVersionInfo(
&info,
VER_MAJORVERSION|VER_MINORVERSION|VER_BUILDNUMBER,
dwlConditionMask);
#else
/* note in this case 'info' is the actual OS version, whereas above
it is the version to compare against. */
BOOL isSupported = info.dwMajorVersion > 10 ||
(info.dwMajorVersion == 10 && info.dwMinorVersion > 0) ||
(info.dwMajorVersion == 10 && info.dwMinorVersion == 0 &&
info.dwBuildNumber >= win_runtime_flags[i].build_number);
#endif
if (isSupported) {
break;
}
else {
if (PyDict_PopString(dict, win_runtime_flags[i].flag_name,
NULL) < 0) {
return -1;
}
}
}
return 0;
}
#endif
#include <stddef.h>
#ifndef O_NONBLOCK
# define O_NONBLOCK O_NDELAY
#endif
/* include Python's addrinfo.h unless it causes trouble */
#if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
/* Do not include addinfo.h on some newer IRIX versions.
* _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
* for example, but not by 6.5.10.
*/
#elif defined(_MSC_VER) && _MSC_VER>1201
/* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
* EAI_* constants are defined in (the already included) ws2tcpip.h.
*/
#else
# include "addrinfo.h"
#endif
#ifdef __APPLE__
/* On OS X, getaddrinfo returns no error indication of lookup
failure, so we must use the emulation instead of the libinfo
implementation. Unfortunately, performing an autoconf test
for this bug would require DNS access for the machine performing
the configuration, which is not acceptable. Therefore, we
determine the bug just by checking for __APPLE__. If this bug
gets ever fixed, perhaps checking for sys/version.h would be
appropriate, which is 10/0 on the system with the bug. */
#ifndef HAVE_GETNAMEINFO
/* This bug seems to be fixed in Jaguar. The easiest way I could
Find to check for Jaguar is that it has getnameinfo(), which
older releases don't have */
#undef HAVE_GETADDRINFO
#endif
#ifdef HAVE_INET_ATON
#define USE_INET_ATON_WEAKLINK
#endif
#endif
/* I know this is a bad practice, but it is the easiest... */
#if !defined(HAVE_GETADDRINFO)
/* avoid clashes with the C library definition of the symbol. */
#define getaddrinfo fake_getaddrinfo
#define gai_strerror fake_gai_strerror
#define freeaddrinfo fake_freeaddrinfo
#include "getaddrinfo.c"
#endif
#if !defined(HAVE_GETNAMEINFO)
#define getnameinfo fake_getnameinfo
#include "getnameinfo.c"
#endif // HAVE_GETNAMEINFO
#ifdef MS_WINDOWS
#define SOCKETCLOSE closesocket
#endif
#ifdef MS_WIN32
# undef EAFNOSUPPORT
# define EAFNOSUPPORT WSAEAFNOSUPPORT
#endif
#ifndef SOCKETCLOSE
# define SOCKETCLOSE close
#endif
#if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
#define USE_BLUETOOTH 1
#if defined(__FreeBSD__)
#define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
#define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
#define BTPROTO_HCI BLUETOOTH_PROTO_HCI
#define SOL_HCI SOL_HCI_RAW
#define HCI_FILTER SO_HCI_RAW_FILTER
#define sockaddr_l2 sockaddr_l2cap
#define sockaddr_rc sockaddr_rfcomm
#define hci_dev hci_node
#define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#elif defined(__NetBSD__) || defined(__DragonFly__)
#define sockaddr_l2 sockaddr_bt
#define sockaddr_rc sockaddr_bt
#define sockaddr_hci sockaddr_bt
#define sockaddr_sco sockaddr_bt
#define SOL_HCI BTPROTO_HCI
#define HCI_DATA_DIR SO_HCI_DIRECTION
#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
#else
#define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
#endif
#endif
#ifdef MS_WINDOWS_DESKTOP
#define sockaddr_rc SOCKADDR_BTH_REDEF
#define USE_BLUETOOTH 1
#define AF_BLUETOOTH AF_BTH
#define BTPROTO_RFCOMM BTHPROTO_RFCOMM
#define _BT_RC_MEMB(sa, memb) ((sa)->memb)
#endif /* MS_WINDOWS_DESKTOP */
/* Convert "sock_addr_t *" to "struct sockaddr *". */
#define SAS2SA(x) (&((x)->sa))
/*
* Constants for getnameinfo()
*/
#if !defined(NI_MAXHOST)
#define NI_MAXHOST 1025
#endif
#if !defined(NI_MAXSERV)
#define NI_MAXSERV 32
#endif
#ifndef INVALID_SOCKET /* MS defines this */
#define INVALID_SOCKET (-1)
#endif
#ifndef INADDR_NONE
#define INADDR_NONE (-1)
#endif
typedef struct _socket_state {
/* The sock_type variable contains pointers to various functions,
some of which call new_sockobject(), which uses sock_type, so
there has to be a circular reference. */
PyTypeObject *sock_type;
/* Global variable holding the exception type for errors detected
by this module (but not argument type or memory errors, etc.). */
PyObject *socket_herror;
PyObject *socket_gaierror;
/* Default timeout for new sockets */
PyTime_t defaulttimeout;
#if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
/* accept4() is available on Linux 2.6.28+ and glibc 2.10 */
int accept4_works;
#endif
#endif
#ifdef SOCK_CLOEXEC
/* socket() and socketpair() fail with EINVAL on Linux kernel older
* than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */
int sock_cloexec_works;
#endif
} socket_state;
static inline socket_state *
get_module_state(PyObject *mod)
{
void *state = _PyModule_GetState(mod);
assert(state != NULL);
return (socket_state *)state;
}
static struct PyModuleDef socketmodule;
static inline socket_state *
find_module_state_by_def(PyTypeObject *type)
{
PyObject *mod = PyType_GetModuleByDef(type, &socketmodule);
assert(mod != NULL);
return get_module_state(mod);
}
#define clinic_state() (find_module_state_by_def(type))
#include "clinic/socketmodule.c.h"
#undef clinic_state
/* XXX There's a problem here: *static* functions are not supposed to have
a Py prefix (or use CapitalizedWords). Later... */
#if defined(HAVE_POLL_H)
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
#endif
/* Largest value to try to store in a socklen_t (used when handling
ancillary data). POSIX requires socklen_t to hold at least
(2**31)-1 and recommends against storing larger values, but
socklen_t was originally int in the BSD interface, so to be on the
safe side we use the smaller of (2**31)-1 and INT_MAX. */
#if INT_MAX > 0x7fffffff
#define SOCKLEN_T_LIMIT 0x7fffffff
#else
#define SOCKLEN_T_LIMIT INT_MAX
#endif
#ifdef HAVE_POLL
/* Instead of select(), we'll use poll() since poll() works on any fd. */
#define IS_SELECTABLE(s) 1
/* Can we call select() with this socket without a buffer overrun? */
#else
/* If there's no timeout left, we don't have to call select, so it's a safe,
* little white lie. */
#define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0)
#endif
static PyObject*
select_error(void)
{
PyErr_SetString(PyExc_OSError, "unable to select on socket");
return NULL;
}
#ifdef MS_WINDOWS
#ifndef WSAEAGAIN
#define WSAEAGAIN WSAEWOULDBLOCK
#endif
#define CHECK_ERRNO(expected) \
(WSAGetLastError() == WSA ## expected)
#else
#define CHECK_ERRNO(expected) \
(errno == expected)
#endif
#ifdef MS_WINDOWS
# define GET_SOCK_ERROR WSAGetLastError()
# define SET_SOCK_ERROR(err) WSASetLastError(err)
# define SOCK_TIMEOUT_ERR WSAEWOULDBLOCK
# define SOCK_INPROGRESS_ERR WSAEWOULDBLOCK
#else
# define GET_SOCK_ERROR errno
# define SET_SOCK_ERROR(err) do { errno = err; } while (0)
# define SOCK_TIMEOUT_ERR EWOULDBLOCK
# define SOCK_INPROGRESS_ERR EINPROGRESS
#endif
#ifdef _MSC_VER
# define SUPPRESS_DEPRECATED_CALL __pragma(warning(suppress: 4996))
#else
# define SUPPRESS_DEPRECATED_CALL
#endif
/* Convenience function to raise an error according to errno
and return a NULL pointer from a function. */
static PyObject *
set_error(void)
{
#ifdef MS_WINDOWS
int err_no = WSAGetLastError();
/* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
recognizes the error codes used by both GetLastError() and
WSAGetLastError */
if (err_no)
return PyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
#endif
return PyErr_SetFromErrno(PyExc_OSError);
}
#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
static PyObject *
set_herror(socket_state *state, int h_error)
{
PyObject *v;
#ifdef HAVE_HSTRERROR
v = Py_BuildValue("(is)", h_error, hstrerror(h_error));
#else
v = Py_BuildValue("(is)", h_error, "host not found");
#endif
if (v != NULL) {
PyErr_SetObject(state->socket_herror, v);
Py_DECREF(v);
}
return NULL;
}
#endif
#ifdef HAVE_GETADDRINFO
static PyObject *
set_gaierror(socket_state *state, int error)
{
PyObject *v;
#ifdef EAI_SYSTEM
/* EAI_SYSTEM is not available on Windows XP. */
if (error == EAI_SYSTEM)
return set_error();
#endif
#ifdef HAVE_GAI_STRERROR
v = Py_BuildValue("(is)", error, gai_strerror(error));
#else
v = Py_BuildValue("(is)", error, "getaddrinfo failed");
#endif
if (v != NULL) {
PyErr_SetObject(state->socket_gaierror, v);
Py_DECREF(v);
}
return NULL;
}
#endif
/* Function to perform the setting of socket blocking mode
internally. block = (1 | 0). */
static int
internal_setblocking(PySocketSockObject *s, int block)
{
int result = -1;
#ifdef MS_WINDOWS
u_long arg;
#endif
#if !defined(MS_WINDOWS) \
&& !((defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)))
int delay_flag, new_delay_flag;
#endif
Py_BEGIN_ALLOW_THREADS
#ifndef MS_WINDOWS
#if (defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO))
block = !block;
if (ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block) == -1)
goto done;
#else
delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
if (delay_flag == -1)
goto done;
if (block)
new_delay_flag = delay_flag & (~O_NONBLOCK);
else
new_delay_flag = delay_flag | O_NONBLOCK;
if (new_delay_flag != delay_flag)
if (fcntl(s->sock_fd, F_SETFL, new_delay_flag) == -1)
goto done;
#endif
#else /* MS_WINDOWS */
arg = !block;
if (ioctlsocket(s->sock_fd, FIONBIO, &arg) != 0)
goto done;
#endif /* MS_WINDOWS */
result = 0;
done:
Py_END_ALLOW_THREADS
if (result) {
#ifndef MS_WINDOWS
PyErr_SetFromErrno(PyExc_OSError);
#else
PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
#endif
}
return result;
}
static int
internal_select(PySocketSockObject *s, int writing, PyTime_t interval,
int connect)
{
int n;
#ifdef HAVE_POLL
struct pollfd pollfd;
PyTime_t ms;
#else
fd_set fds, efds;
struct timeval tv, *tvp;
#endif
/* must be called with the GIL held */
assert(PyGILState_Check());
/* Error condition is for output only */
assert(!(connect && !writing));
/* Guard against closed socket */
if (s->sock_fd == INVALID_SOCKET)
return 0;
/* Prefer poll, if available, since you can poll() any fd
* which can't be done with select(). */
#ifdef HAVE_POLL
pollfd.fd = s->sock_fd;
pollfd.events = writing ? POLLOUT : POLLIN;
if (connect) {
/* On Windows, the socket becomes writable on connection success,
but a connection failure is notified as an error. On POSIX, the
socket becomes writable on connection success or on connection
failure. */
pollfd.events |= POLLERR;
}
/* s->sock_timeout is in seconds, timeout in ms */
ms = _PyTime_AsMilliseconds(interval, _PyTime_ROUND_CEILING);
assert(ms <= INT_MAX);
/* On some OSes, typically BSD-based ones, the timeout parameter of the
poll() syscall, when negative, must be exactly INFTIM, where defined,
or -1. See issue 37811. */
if (ms < 0) {
#ifdef INFTIM
ms = INFTIM;
#else
ms = -1;
#endif
}
Py_BEGIN_ALLOW_THREADS;
n = poll(&pollfd, 1, (int)ms);
Py_END_ALLOW_THREADS;
#else
if (interval >= 0) {
_PyTime_AsTimeval_clamp(interval, &tv, _PyTime_ROUND_CEILING);
tvp = &tv;
}
else
tvp = NULL;
FD_ZERO(&fds);
FD_SET(s->sock_fd, &fds);
FD_ZERO(&efds);
if (connect) {
/* On Windows, the socket becomes writable on connection success,
but a connection failure is notified as an error. On POSIX, the
socket becomes writable on connection success or on connection
failure. */
FD_SET(s->sock_fd, &efds);
}
/* See if the socket is ready */
Py_BEGIN_ALLOW_THREADS;
if (writing)
n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
NULL, &fds, &efds, tvp);
else
n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
&fds, NULL, &efds, tvp);
Py_END_ALLOW_THREADS;
#endif
if (n < 0)
return -1;
if (n == 0)
return 1;
return 0;
}
/* Call a socket function.
On error, raise an exception and return -1 if err is set, or fill err and
return -1 otherwise. If a signal was received and the signal handler raised
an exception, return -1, and set err to -1 if err is set.
On success, return 0, and set err to 0 if err is set.
If the socket has a timeout, wait until the socket is ready before calling
the function: wait until the socket is writable if writing is nonzero, wait
until the socket received data otherwise.
If the socket function is interrupted by a signal (failed with EINTR): retry
the function, except if the signal handler raised an exception (PEP 475).
When the function is retried, recompute the timeout using a monotonic clock.
sock_call_ex() must be called with the GIL held. The socket function is
called with the GIL released. */
static int
sock_call_ex(PySocketSockObject *s,
int writing,
int (*sock_func) (PySocketSockObject *s, void *data),
void *data,
int connect,
int *err,
PyTime_t timeout)
{
int has_timeout = (timeout > 0);
PyTime_t deadline = 0;
int deadline_initialized = 0;
int res;
/* sock_call() must be called with the GIL held. */
assert(PyGILState_Check());
/* outer loop to retry select() when select() is interrupted by a signal
or to retry select()+sock_func() on false positive (see above) */
while (1) {
/* For connect(), poll even for blocking socket. The connection
runs asynchronously. */
if (has_timeout || connect) {
if (has_timeout) {
PyTime_t interval;
if (deadline_initialized) {
/* recompute the timeout */
interval = _PyDeadline_Get(deadline);
}
else {
deadline_initialized = 1;
deadline = _PyDeadline_Init(timeout);
interval = timeout;
}
if (interval >= 0) {
res = internal_select(s, writing, interval, connect);
}
else {
res = 1;
}
}
else {
res = internal_select(s, writing, timeout, connect);
}
if (res == -1) {
if (err)
*err = GET_SOCK_ERROR;
if (CHECK_ERRNO(EINTR)) {
/* select() was interrupted by a signal */
if (PyErr_CheckSignals()) {
if (err)
*err = -1;
return -1;
}
/* retry select() */
continue;
}
/* select() failed */
s->errorhandler();
return -1;
}
if (res == 1) {
if (err)
*err = SOCK_TIMEOUT_ERR;
else
PyErr_SetString(PyExc_TimeoutError, "timed out");
return -1;
}
/* the socket is ready */
}
/* inner loop to retry sock_func() when sock_func() is interrupted
by a signal */
while (1) {
Py_BEGIN_ALLOW_THREADS
res = sock_func(s, data);
Py_END_ALLOW_THREADS
if (res) {
/* sock_func() succeeded */
if (err)
*err = 0;
return 0;
}
if (err)
*err = GET_SOCK_ERROR;
if (!CHECK_ERRNO(EINTR))
break;
/* sock_func() was interrupted by a signal */
if (PyErr_CheckSignals()) {
if (err)
*err = -1;
return -1;
}
/* retry sock_func() */
}
if (s->sock_timeout > 0
&& (CHECK_ERRNO(EWOULDBLOCK) || CHECK_ERRNO(EAGAIN))) {
/* False positive: sock_func() failed with EWOULDBLOCK or EAGAIN.
For example, select() could indicate a socket is ready for
reading, but the data then discarded by the OS because of a
wrong checksum.