Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
Expand file tree
/
Copy pathsocketmodule.c
More file actions
Latest commit
9372 lines (8369 loc) · 266 KB
/
Copy pathsocketmodule.c
File metadata and controls
9372 lines (8369 loc) · 266 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
/* 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
*/
#ifndefPy_BUILD_CORE_BUILTIN
# definePy_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 */
#ifndefMAC_OS_X_VERSION_10_5
#defineMAC_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_object.h"// _PyObject_VisitType()
#include"pycore_time.h"// _PyTime_AsMilliseconds()
#include"pycore_tuple.h"// _PyTuple_FromPairSteal
#include"pycore_pystate.h"// _Py_AssertHoldsTstate()
#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
#ifdefHAVE_GETHOSTBYNAME_R
# if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
# defineHAVE_GETHOSTBYNAME_R_3_ARG
# elif defined(__sun) || defined(__sgi)
# defineHAVE_GETHOSTBYNAME_R_5_ARG
# elif defined(__linux__)
/* Rely on the configure script */
# elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
# defineHAVE_GETHOSTBYNAME_R_6_ARG
# else
# undef HAVE_GETHOSTBYNAME_R
# endif
#endif
#if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
# defineUSE_GETHOSTBYNAME_LOCK
#endif
#if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
# include<sys/ioctl.h>
#endif
#if defined(HAVE_BLUETOOTH_H) && !defined(__FreeBSD__)
# include<netbt/l2cap.h>
# include<netbt/rfcomm.h>
# include<netbt/hci.h>
# include<netbt/sco.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
#defineHAVE_GETADDRINFO 1
#defineHAVE_GETNAMEINFO 1
#endif
#defineHAVE_INET_PTON
#include<netdb.h>
#endif// __sgi
/* Solaris fails to define this variable at all. */
#if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
#defineINET_ADDRSTRLEN 16
#endif
/* Generic includes */
#ifdefHAVE_SYS_TYPES_H
#include<sys/types.h>
#endif
#ifdefHAVE_SYS_SOCKET_H
#include<sys/socket.h>
#endif
#ifdefHAVE_NET_IF_H
#include<net/if.h>
#endif
#ifdefHAVE_NET_ETHERNET_H
#include<net/ethernet.h>
#endif
/* Generic socket object definitions and includes */
#definePySocket_BUILDING_SOCKET
#include"socketmodule.h"
/* Addressing includes */
#ifndefMS_WINDOWS
/* Non-MS WINDOWS includes */
#ifdefHAVE_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 */
# ifdefHAVE_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 */
#defineIPPROTO_ICMP IPPROTO_ICMP
#defineIPPROTO_IGMP IPPROTO_IGMP
#defineIPPROTO_GGP IPPROTO_GGP
#defineIPPROTO_TCP IPPROTO_TCP
#defineIPPROTO_PUP IPPROTO_PUP
#defineIPPROTO_UDP IPPROTO_UDP
#defineIPPROTO_IDP IPPROTO_IDP
#defineIPPROTO_ND IPPROTO_ND
#defineIPPROTO_RAW IPPROTO_RAW
#defineIPPROTO_MAX IPPROTO_MAX
#defineIPPROTO_HOPOPTS IPPROTO_HOPOPTS
#defineIPPROTO_IPV4 IPPROTO_IPV4
#defineIPPROTO_IPV6 IPPROTO_IPV6
#defineIPPROTO_ROUTING IPPROTO_ROUTING
#defineIPPROTO_FRAGMENT IPPROTO_FRAGMENT
#defineIPPROTO_ESP IPPROTO_ESP
#defineIPPROTO_AH IPPROTO_AH
#defineIPPROTO_ICMPV6 IPPROTO_ICMPV6
#defineIPPROTO_NONE IPPROTO_NONE
#defineIPPROTO_DSTOPTS IPPROTO_DSTOPTS
#defineIPPROTO_EGP IPPROTO_EGP
#defineIPPROTO_PIM IPPROTO_PIM
#defineIPPROTO_ICLFXBM IPPROTO_ICLFXBM // WinSock2 only
#defineIPPROTO_ST IPPROTO_ST // WinSock2 only
#defineIPPROTO_CBT IPPROTO_CBT // WinSock2 only
#defineIPPROTO_IGP IPPROTO_IGP // WinSock2 only
#defineIPPROTO_RDP IPPROTO_RDP // WinSock2 only
#defineIPPROTO_PGM IPPROTO_PGM // WinSock2 only
#defineIPPROTO_L2TP IPPROTO_L2TP // WinSock2 only
#defineIPPROTO_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 */
typedefstruct {
DWORDbuild_number; /* available starting with this Win10 BuildNumber */
constcharflag_name[20];
} FlagRuntimeInfo;
/* IMPORTANT: make sure the list ordered by descending build_number */
staticFlagRuntimeInfowin_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"}
};
staticint
remove_unusable_flags(PyObject*m)
{
PyObject*dict;
OSVERSIONINFOEXinfo;
dict=PyModule_GetDict(m);
if (dict==NULL) {
return-1;
}
#ifndefMS_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 */
DWORDLONGdwlConditionMask=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 (inti=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
#ifdefMS_WINDOWS_DESKTOP
info.dwBuildNumber=win_runtime_flags[i].build_number;
/* greater than or equal to the specified version?
Compatibility Mode will not cheat VerifyVersionInfo(...) */
BOOLisSupported=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. */
BOOLisSupported=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;
}
}
}
return0;
}
#endif
#include<stddef.h>
#ifndefO_NONBLOCK
# defineO_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__
#ifdefHAVE_INET_ATON
#defineUSE_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. */
#definegetaddrinfo fake_getaddrinfo
#definegai_strerror fake_gai_strerror
#definefreeaddrinfo fake_freeaddrinfo
#include"getaddrinfo.c"
#endif
#if !defined(HAVE_GETNAMEINFO)
#definegetnameinfo fake_getnameinfo
#include"getnameinfo.c"
#endif// HAVE_GETNAMEINFO
#ifdefMS_WINDOWS
#defineSOCKETCLOSE closesocket
#endif
#ifdefMS_WIN32
# undef EAFNOSUPPORT
# defineEAFNOSUPPORT WSAEAFNOSUPPORT
#endif
#ifndefSOCKETCLOSE
# defineSOCKETCLOSE close
#endif
#if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)
# defineUSE_BLUETOOTH 1
# if defined(HAVE_BLUETOOTH_BLUETOOTH_H) // Linux
# 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)
# elif defined(__FreeBSD__)
# defineBTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
# defineBTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
# defineBTPROTO_HCI BLUETOOTH_PROTO_HCI
# defineBTPROTO_SCO BLUETOOTH_PROTO_SCO
# defineSOL_HCI SOL_HCI_RAW
# defineHCI_FILTER SO_HCI_RAW_FILTER
# defineHCI_DATA_DIR SO_HCI_RAW_DIRECTION
# definesockaddr_l2 sockaddr_l2cap
# definesockaddr_rc sockaddr_rfcomm
# definehci_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)
# define_BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
# else// NetBSD, DragonFly BSD
# definesockaddr_l2 sockaddr_bt
# definesockaddr_rc sockaddr_bt
# definesockaddr_hci sockaddr_bt
# definesockaddr_sco sockaddr_bt
# definebt_l2 bt
# definebt_rc bt
# definebt_sco bt
# definebt_hci bt
# definebt_cid bt_channel
# defineSOL_L2CAP BTPROTO_L2CAP
# defineSOL_RFCOMM BTPROTO_RFCOMM
# defineSOL_HCI BTPROTO_HCI
# defineSOL_SCO BTPROTO_SCO
# defineHCI_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)
# endif
#endif
#ifdefMS_WINDOWS_DESKTOP
#definesockaddr_rc SOCKADDR_BTH_REDEF
#defineUSE_BLUETOOTH 1
#defineAF_BLUETOOTH AF_BTH
#defineBTPROTO_RFCOMM BTHPROTO_RFCOMM
#define_BT_RC_MEMB(sa, memb) ((sa)->memb)
#endif/* MS_WINDOWS_DESKTOP */
/* Convert "sock_addr_t *" to "struct sockaddr *". */
#defineSAS2SA(x) (&((x)->sa))
/*
* Constants for getnameinfo()
*/
#if !defined(NI_MAXHOST)
#defineNI_MAXHOST 1025
#endif
#if !defined(NI_MAXSERV)
#defineNI_MAXSERV 32
#endif
#ifndefINVALID_SOCKET/* MS defines this */
#defineINVALID_SOCKET (-1)
#endif
#ifndefINADDR_NONE
#defineINADDR_NONE (-1)
#endif
typedefstruct_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_tdefaulttimeout;
} socket_state;
#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 */
staticintaccept4_works=-1;
#endif
#endif
#ifdefSOCK_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. */
staticintsock_cloexec_works=-1;
#endif
staticinlinevoid
set_sock_fd(PySocketSockObject*s, SOCKET_Tfd)
{
#ifSIZEOF_SOCKET_T==SIZEOF_INT
_Py_atomic_store_int_relaxed((int*)&s->sock_fd, (int)fd);
#elifSIZEOF_SOCKET_T==SIZEOF_LONG
_Py_atomic_store_long_relaxed((long*)&s->sock_fd, (long)fd);
#elifSIZEOF_SOCKET_T==SIZEOF_LONG_LONG
_Py_atomic_store_llong_relaxed((long long*)&s->sock_fd, (long long)fd);
#else
#error "Unsupported SIZEOF_SOCKET_T"
#endif
}
staticinlineSOCKET_T
get_sock_fd(PySocketSockObject*s)
{
#ifSIZEOF_SOCKET_T==SIZEOF_INT
return (SOCKET_T)_Py_atomic_load_int_relaxed((int*)&s->sock_fd);
#elifSIZEOF_SOCKET_T==SIZEOF_LONG
return (SOCKET_T)_Py_atomic_load_long_relaxed((long*)&s->sock_fd);
#elifSIZEOF_SOCKET_T==SIZEOF_LONG_LONG
return (SOCKET_T)_Py_atomic_load_llong_relaxed((long long*)&s->sock_fd);
#else
#error "Unsupported SIZEOF_SOCKET_T"
#endif
}
#define_PySocketSockObject_CAST(op) ((PySocketSockObject *)(op))
staticinlinesocket_state*
get_module_state(PyObject*mod)
{
void*state=_PyModule_GetState(mod);
assert(state!=NULL);
return (socket_state*)state;
}
staticstructPyModuleDefsocketmodule;
staticinlinesocket_state*
find_module_state_by_def(PyTypeObject*type)
{
PyObject*mod=PyType_GetModuleByDef(type, &socketmodule);
assert(mod!=NULL);
returnget_module_state(mod);
}
#defineUNSIGNED_INT_CONVERTER(NAME, TYPE) \
static int \
_PyLong_##NAME##_Converter(PyObject *obj, void *ptr) \
{ \
Py_ssize_t bytes = PyLong_AsNativeBytes(obj, ptr, sizeof(TYPE), \
Py_ASNATIVEBYTES_NATIVE_ENDIAN | \
Py_ASNATIVEBYTES_ALLOW_INDEX | \
Py_ASNATIVEBYTES_REJECT_NEGATIVE | \
Py_ASNATIVEBYTES_UNSIGNED_BUFFER); \
if (bytes < 0) { \
return 0; \
} \
if ((size_t)bytes > sizeof(TYPE)) { \
PyErr_SetString(PyExc_OverflowError, \
"Python int too large for C " #TYPE); \
return 0; \
} \
return 1; \
}
#if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
# ifdefMS_WINDOWS
UNSIGNED_INT_CONVERTER(NetIfindex, NET_IFINDEX)
# else
# define_PyLong_NetIfindex_Converter _PyLong_UnsignedInt_Converter
# defineNET_IFINDEX unsigned int
# endif
#endif// defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
/*[python input]
class NET_IFINDEX_converter(CConverter):
type = "NET_IFINDEX"
converter = '_PyLong_NetIfindex_Converter'
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=1cf809c40a407c34]*/
/*[clinic input]
module _socket
class _socket.socket "PySocketSockObject *" "clinic_state()->sock_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2db2489bd2219fd8]*/
/* 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. */
#ifINT_MAX>0x7fffffff
#defineSOCKLEN_T_LIMIT 0x7fffffff
#else
#defineSOCKLEN_T_LIMIT INT_MAX
#endif
#ifdefHAVE_POLL
/* Instead of select(), we'll use poll() since poll() works on any fd. */
#defineIS_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. */
#defineIS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0)
#endif
// SCM_RIGHTS, sendmsg(), recvmsg() and sethostname() don't work properly on
// Cygwin: disable these features.
#ifdef__CYGWIN__
# undef CMSG_LEN
# undef SCM_RIGHTS
# undef HAVE_SETHOSTNAME
#endif
#defineclinic_state() (find_module_state_by_def(type))
#include"clinic/socketmodule.c.h"
#undef clinic_state
staticPyObject*
select_error(void)
{
PyErr_SetString(PyExc_OSError, "unable to select on socket");
returnNULL;
}
#ifdefMS_WINDOWS
#ifndefWSAEAGAIN
#defineWSAEAGAIN WSAEWOULDBLOCK
#endif
#defineCHECK_ERRNO(expected) \
(WSAGetLastError() == WSA ## expected)
#else
#defineCHECK_ERRNO(expected) \
(errno == expected)
#endif
#ifdefMS_WINDOWS
# defineGET_SOCK_ERROR WSAGetLastError()
# defineSET_SOCK_ERROR(err) WSASetLastError(err)
# defineSOCK_TIMEOUT_ERR WSAEWOULDBLOCK
# defineSOCK_INPROGRESS_ERR WSAEWOULDBLOCK
#else
# defineGET_SOCK_ERROR errno
# defineSET_SOCK_ERROR(err) do { errno = err; } while (0)
# defineSOCK_TIMEOUT_ERR EWOULDBLOCK
# defineSOCK_INPROGRESS_ERR EINPROGRESS
#endif
/* Convenience function to raise an error according to errno
and return a NULL pointer from a function. */
staticPyObject*
set_error(void)
{
#ifdefMS_WINDOWS
interr_no=WSAGetLastError();
/* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
recognizes the error codes used by both GetLastError() and
WSAGetLastError */
if (err_no)
returnPyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
#endif
returnPyErr_SetFromErrno(PyExc_OSError);
}
#if defined(HAVE_HSTRERROR) || defined(HAVE_GAI_STRERROR)
/* Decode a locale-encoded error message from the C library.
It can be localized and use a non-UTF-8 encoding. */
staticPyObject*
decode_error_message(constchar*str)
{
returnPyUnicode_DecodeLocale(str, "surrogateescape");
}
#endif
#if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
staticPyObject*
set_herror(socket_state*state, inth_error)
{
PyObject*v;
#ifdefHAVE_HSTRERROR
v=Py_BuildValue("(iN)", h_error, decode_error_message(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);
}
returnNULL;
}
#endif
#ifdefHAVE_GETADDRINFO
staticPyObject*
set_gaierror(socket_state*state, interror)
{
PyObject*v;
#ifdefEAI_SYSTEM
/* EAI_SYSTEM is not available on Windows XP. */
if (error==EAI_SYSTEM)
returnset_error();
#endif
#ifdefHAVE_GAI_STRERROR
v=Py_BuildValue("(iN)", error, decode_error_message(gai_strerror(error)));
#else
v=Py_BuildValue("(is)", error, "getaddrinfo failed");
#endif
if (v!=NULL) {
PyErr_SetObject(state->socket_gaierror, v);
Py_DECREF(v);
}
returnNULL;
}
#endif
/* Function to perform the setting of socket blocking mode
internally. block = (1 | 0). */
staticint
internal_setblocking(PySocketSockObject*s, intblock)
{
intresult=-1;
#ifdefMS_WINDOWS
u_longarg;
#endif
#if !defined(MS_WINDOWS) \
&& !((defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)))
intdelay_flag, new_delay_flag;
#endif
Py_BEGIN_ALLOW_THREADS
#ifndefMS_WINDOWS
#if (defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO))
block= !block;
if (ioctl(get_sock_fd(s), FIONBIO, (unsigned int*)&block) ==-1)
goto done;
#else
delay_flag=fcntl(get_sock_fd(s), 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(get_sock_fd(s), F_SETFL, new_delay_flag) ==-1)
goto done;
#endif
#else/* MS_WINDOWS */
arg= !block;
if (ioctlsocket(get_sock_fd(s), FIONBIO, &arg) !=0)
goto done;
#endif/* MS_WINDOWS */
result=0;
done:
Py_END_ALLOW_THREADS
if (result) {
#ifndefMS_WINDOWS
PyErr_SetFromErrno(PyExc_OSError);
#else
PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
#endif
}
returnresult;
}
staticint
internal_select(PySocketSockObject*s, intwriting, PyTime_tinterval,
intconnect)
{
intn;
#ifdefHAVE_POLL
structpollfdpollfd;
PyTime_tms;
#else
fd_setfds, efds;
structtimevaltv, *tvp;
#endif
/* must be called with a thread state */
_Py_AssertHoldsTstate();
/* Error condition is for output only */
assert(!(connect&& !writing));
/* Guard against closed socket */
if (get_sock_fd(s) ==INVALID_SOCKET)
return0;
/* Prefer poll, if available, since you can poll() any fd
* which can't be done with select(). */
#ifdefHAVE_POLL
pollfd.fd=get_sock_fd(s);
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);
if (ms>INT_MAX) {
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) {
#ifdefINFTIM
ms=INFTIM;
#else
ms=-1;
#endif
}
assert(INT_MIN <= ms&&ms <= INT_MAX);
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(get_sock_fd(s), &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(get_sock_fd(s), &efds);
}
/* See if the socket is ready */
Py_BEGIN_ALLOW_THREADS;
if (writing)
n=select(Py_SAFE_DOWNCAST(get_sock_fd(s)+1, SOCKET_T, int),
NULL, &fds, &efds, tvp);
else
n=select(Py_SAFE_DOWNCAST(get_sock_fd(s)+1, SOCKET_T, int),
&fds, NULL, &efds, tvp);
Py_END_ALLOW_THREADS;
#endif
if (n<0)
return-1;
if (n==0)
return1;
return0;
}
/* 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. */
staticint
sock_call_ex(PySocketSockObject*s,
intwriting,
int (*sock_func) (PySocketSockObject*s, void*data),
void*data,
intconnect,
int*err,
PyTime_ttimeout)
{
inthas_timeout= (timeout>0);
PyTime_tdeadline=0;
intdeadline_initialized=0;
intres;
/* sock_call() must be called with a thread state. */
_Py_AssertHoldsTstate();
/* 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_tinterval;
if (deadline_initialized) {
/* recompute the timeout */
interval=_PyDeadline_Get(deadline);