Branch data Line data Source code
1 : : /* Socket module */
2 : :
3 : : /*
4 : :
5 : : This module provides an interface to Berkeley socket IPC.
6 : :
7 : : Limitations:
8 : :
9 : : - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
10 : : portable manner, though AF_PACKET, AF_NETLINK, AF_QIPCRTR and AF_TIPC are
11 : : supported under Linux.
12 : : - No read/write operations (use sendall/recv or makefile instead).
13 : : - Additional restrictions apply on some non-Unix platforms (compensated
14 : : for by socket.py).
15 : :
16 : : Module interface:
17 : :
18 : : - socket.error: exception raised for socket specific errors, alias for OSError
19 : : - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
20 : : a subclass of socket.error
21 : : - socket.herror: exception raised for gethostby* errors,
22 : : a subclass of socket.error
23 : : - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
24 : : - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
25 : : - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
26 : : - socket.getprotobyname(protocolname) --> protocol number
27 : : - socket.getservbyname(servicename[, protocolname]) --> port number
28 : : - socket.getservbyport(portnumber[, protocolname]) --> service name
29 : : - socket.socket([family[, type [, proto, fileno]]]) --> new socket object
30 : : (fileno specifies a pre-existing socket file descriptor)
31 : : - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
32 : : - socket.ntohs(16 bit value) --> new int object
33 : : - socket.ntohl(32 bit value) --> new int object
34 : : - socket.htons(16 bit value) --> new int object
35 : : - socket.htonl(32 bit value) --> new int object
36 : : - socket.getaddrinfo(host, port [, family, type, proto, flags])
37 : : --> List of (family, type, proto, canonname, sockaddr)
38 : : - socket.getnameinfo(sockaddr, flags) --> (host, port)
39 : : - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
40 : : - socket.has_ipv6: boolean value indicating if IPv6 is supported
41 : : - socket.inet_aton(IP address) -> 32-bit packed IP representation
42 : : - socket.inet_ntoa(packed IP) -> IP address string
43 : : - socket.getdefaulttimeout() -> None | float
44 : : - socket.setdefaulttimeout(None | float)
45 : : - socket.if_nameindex() -> list of tuples (if_index, if_name)
46 : : - socket.if_nametoindex(name) -> corresponding interface index
47 : : - socket.if_indextoname(index) -> corresponding interface name
48 : : - an internet socket address is a pair (hostname, port)
49 : : where hostname can be anything recognized by gethostbyname()
50 : : (including the dd.dd.dd.dd notation) and port is in host byte order
51 : : - where a hostname is returned, the dd.dd.dd.dd notation is used
52 : : - a UNIX domain socket address is a string specifying the pathname
53 : : - an AF_PACKET socket address is a tuple containing a string
54 : : specifying the ethernet interface and an integer specifying
55 : : the Ethernet protocol number to be received. For example:
56 : : ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
57 : : specify packet-type and ha-type/addr.
58 : : - an AF_QIPCRTR socket address is a (node, port) tuple where the
59 : : node and port are non-negative integers.
60 : : - an AF_TIPC socket address is expressed as
61 : : (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
62 : : TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
63 : : and scope can be one of:
64 : : TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
65 : : The meaning of v1, v2 and v3 depends on the value of addr_type:
66 : : if addr_type is TIPC_ADDR_NAME:
67 : : v1 is the server type
68 : : v2 is the port identifier
69 : : v3 is ignored
70 : : if addr_type is TIPC_ADDR_NAMESEQ:
71 : : v1 is the server type
72 : : v2 is the lower port number
73 : : v3 is the upper port number
74 : : if addr_type is TIPC_ADDR_ID:
75 : : v1 is the node
76 : : v2 is the ref
77 : : v3 is ignored
78 : :
79 : :
80 : : Local naming conventions:
81 : :
82 : : - names starting with sock_ are socket object methods
83 : : - names starting with socket_ are module-level functions
84 : : - names starting with PySocket are exported through socketmodule.h
85 : :
86 : : */
87 : :
88 : : #ifndef Py_BUILD_CORE_BUILTIN
89 : : # define Py_BUILD_CORE_MODULE 1
90 : : #endif
91 : :
92 : : #ifdef __APPLE__
93 : : // Issue #35569: Expose RFC 3542 socket options.
94 : : #define __APPLE_USE_RFC_3542 1
95 : : #include <AvailabilityMacros.h>
96 : : /* for getaddrinfo thread safety test on old versions of OS X */
97 : : #ifndef MAC_OS_X_VERSION_10_5
98 : : #define MAC_OS_X_VERSION_10_5 1050
99 : : #endif
100 : : /*
101 : : * inet_aton is not available on OSX 10.3, yet we want to use a binary
102 : : * that was build on 10.4 or later to work on that release, weak linking
103 : : * comes to the rescue.
104 : : */
105 : : # pragma weak inet_aton
106 : : #endif
107 : :
108 : : #define PY_SSIZE_T_CLEAN
109 : : #include "Python.h"
110 : : #include "pycore_fileutils.h" // _Py_set_inheritable()
111 : : #include "structmember.h" // PyMemberDef
112 : :
113 : : #ifdef _Py_MEMORY_SANITIZER
114 : : # include <sanitizer/msan_interface.h>
115 : : #endif
116 : :
117 : : /* Socket object documentation */
118 : : PyDoc_STRVAR(sock_doc,
119 : : "socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object\n\
120 : : socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object\n\
121 : : \n\
122 : : Open a socket of the given type. The family argument specifies the\n\
123 : : address family; it defaults to AF_INET. The type argument specifies\n\
124 : : whether this is a stream (SOCK_STREAM, this is the default)\n\
125 : : or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
126 : : specifying the default protocol. Keyword arguments are accepted.\n\
127 : : The socket is created as non-inheritable.\n\
128 : : \n\
129 : : When a fileno is passed in, family, type and proto are auto-detected,\n\
130 : : unless they are explicitly set.\n\
131 : : \n\
132 : : A socket object represents one endpoint of a network connection.\n\
133 : : \n\
134 : : Methods of socket objects (keyword arguments not allowed):\n\
135 : : \n\
136 : : _accept() -- accept connection, returning new socket fd and client address\n\
137 : : bind(addr) -- bind the socket to a local address\n\
138 : : close() -- close the socket\n\
139 : : connect(addr) -- connect the socket to a remote address\n\
140 : : connect_ex(addr) -- connect, return an error code instead of an exception\n\
141 : : dup() -- return a new socket fd duplicated from fileno()\n\
142 : : fileno() -- return underlying file descriptor\n\
143 : : getpeername() -- return remote address [*]\n\
144 : : getsockname() -- return local address\n\
145 : : getsockopt(level, optname[, buflen]) -- get socket options\n\
146 : : gettimeout() -- return timeout or None\n\
147 : : listen([n]) -- start listening for incoming connections\n\
148 : : recv(buflen[, flags]) -- receive data\n\
149 : : recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
150 : : recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
151 : : recvfrom_into(buffer[, nbytes, [, flags])\n\
152 : : -- receive data and sender\'s address (into a buffer)\n\
153 : : sendall(data[, flags]) -- send all data\n\
154 : : send(data[, flags]) -- send data, may not send all of it\n\
155 : : sendto(data[, flags], addr) -- send data to a given address\n\
156 : : setblocking(bool) -- set or clear the blocking I/O flag\n\
157 : : getblocking() -- return True if socket is blocking, False if non-blocking\n\
158 : : setsockopt(level, optname, value[, optlen]) -- set socket options\n\
159 : : settimeout(None | float) -- set or clear the timeout\n\
160 : : shutdown(how) -- shut down traffic in one or both directions\n\
161 : : \n\
162 : : [*] not available on all platforms!");
163 : :
164 : : /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
165 : : I hope some day someone can clean this up please... */
166 : :
167 : : /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
168 : : script doesn't get this right, so we hardcode some platform checks below.
169 : : On the other hand, not all Linux versions agree, so there the settings
170 : : computed by the configure script are needed! */
171 : :
172 : : #ifndef __linux__
173 : : # undef HAVE_GETHOSTBYNAME_R_3_ARG
174 : : # undef HAVE_GETHOSTBYNAME_R_5_ARG
175 : : # undef HAVE_GETHOSTBYNAME_R_6_ARG
176 : : #endif
177 : :
178 : : #if defined(__OpenBSD__)
179 : : # include <sys/uio.h>
180 : : #endif
181 : :
182 : : #if defined(__ANDROID__) && __ANDROID_API__ < 23
183 : : # undef HAVE_GETHOSTBYNAME_R
184 : : #endif
185 : :
186 : : #ifdef HAVE_GETHOSTBYNAME_R
187 : : # if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
188 : : # define HAVE_GETHOSTBYNAME_R_3_ARG
189 : : # elif defined(__sun) || defined(__sgi)
190 : : # define HAVE_GETHOSTBYNAME_R_5_ARG
191 : : # elif defined(__linux__)
192 : : /* Rely on the configure script */
193 : : # elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
194 : : # define HAVE_GETHOSTBYNAME_R_6_ARG
195 : : # else
196 : : # undef HAVE_GETHOSTBYNAME_R
197 : : # endif
198 : : #endif
199 : :
200 : : #if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
201 : : # define USE_GETHOSTBYNAME_LOCK
202 : : #endif
203 : :
204 : : #if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
205 : : # include <sys/ioctl.h>
206 : : #endif
207 : :
208 : :
209 : : #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
210 : : /* make sure that the reentrant (gethostbyaddr_r etc)
211 : : functions are declared correctly if compiling with
212 : : MIPSPro 7.x in ANSI C mode (default) */
213 : :
214 : : /* XXX Using _SGIAPI is the wrong thing,
215 : : but I don't know what the right thing is. */
216 : : #undef _SGIAPI /* to avoid warning */
217 : : #define _SGIAPI 1
218 : :
219 : : #undef _XOPEN_SOURCE
220 : : #include <sys/socket.h>
221 : : #include <sys/types.h>
222 : : #include <netinet/in.h>
223 : : #ifdef _SS_ALIGNSIZE
224 : : #define HAVE_GETADDRINFO 1
225 : : #define HAVE_GETNAMEINFO 1
226 : : #endif
227 : :
228 : : #define HAVE_INET_PTON
229 : : #include <netdb.h>
230 : : #endif // __sgi
231 : :
232 : : /* Solaris fails to define this variable at all. */
233 : : #if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
234 : : #define INET_ADDRSTRLEN 16
235 : : #endif
236 : :
237 : : /* Generic includes */
238 : : #ifdef HAVE_SYS_TYPES_H
239 : : #include <sys/types.h>
240 : : #endif
241 : :
242 : : #ifdef HAVE_SYS_SOCKET_H
243 : : #include <sys/socket.h>
244 : : #endif
245 : :
246 : : #ifdef HAVE_NET_IF_H
247 : : #include <net/if.h>
248 : : #endif
249 : :
250 : : #ifdef HAVE_NET_ETHERNET_H
251 : : #include <net/ethernet.h>
252 : : #endif
253 : :
254 : : /* Generic socket object definitions and includes */
255 : : #define PySocket_BUILDING_SOCKET
256 : : #include "socketmodule.h"
257 : :
258 : : /* Addressing includes */
259 : :
260 : : #ifndef MS_WINDOWS
261 : :
262 : : /* Non-MS WINDOWS includes */
263 : : #ifdef HAVE_NETDB_H
264 : : # include <netdb.h>
265 : : #endif
266 : : # include <unistd.h>
267 : :
268 : : /* Headers needed for inet_ntoa() and inet_addr() */
269 : : # include <arpa/inet.h>
270 : :
271 : : # include <fcntl.h>
272 : :
273 : : #else /* MS_WINDOWS */
274 : :
275 : : /* MS_WINDOWS includes */
276 : : # ifdef HAVE_FCNTL_H
277 : : # include <fcntl.h>
278 : : # endif
279 : :
280 : : /* Helpers needed for AF_HYPERV */
281 : : # include <Rpc.h>
282 : :
283 : : /* Macros based on the IPPROTO enum, see: https://bugs.python.org/issue29515 */
284 : : #define IPPROTO_ICMP IPPROTO_ICMP
285 : : #define IPPROTO_IGMP IPPROTO_IGMP
286 : : #define IPPROTO_GGP IPPROTO_GGP
287 : : #define IPPROTO_TCP IPPROTO_TCP
288 : : #define IPPROTO_PUP IPPROTO_PUP
289 : : #define IPPROTO_UDP IPPROTO_UDP
290 : : #define IPPROTO_IDP IPPROTO_IDP
291 : : #define IPPROTO_ND IPPROTO_ND
292 : : #define IPPROTO_RAW IPPROTO_RAW
293 : : #define IPPROTO_MAX IPPROTO_MAX
294 : : #define IPPROTO_HOPOPTS IPPROTO_HOPOPTS
295 : : #define IPPROTO_IPV4 IPPROTO_IPV4
296 : : #define IPPROTO_IPV6 IPPROTO_IPV6
297 : : #define IPPROTO_ROUTING IPPROTO_ROUTING
298 : : #define IPPROTO_FRAGMENT IPPROTO_FRAGMENT
299 : : #define IPPROTO_ESP IPPROTO_ESP
300 : : #define IPPROTO_AH IPPROTO_AH
301 : : #define IPPROTO_ICMPV6 IPPROTO_ICMPV6
302 : : #define IPPROTO_NONE IPPROTO_NONE
303 : : #define IPPROTO_DSTOPTS IPPROTO_DSTOPTS
304 : : #define IPPROTO_EGP IPPROTO_EGP
305 : : #define IPPROTO_PIM IPPROTO_PIM
306 : : #define IPPROTO_ICLFXBM IPPROTO_ICLFXBM // WinSock2 only
307 : : #define IPPROTO_ST IPPROTO_ST // WinSock2 only
308 : : #define IPPROTO_CBT IPPROTO_CBT // WinSock2 only
309 : : #define IPPROTO_IGP IPPROTO_IGP // WinSock2 only
310 : : #define IPPROTO_RDP IPPROTO_RDP // WinSock2 only
311 : : #define IPPROTO_PGM IPPROTO_PGM // WinSock2 only
312 : : #define IPPROTO_L2TP IPPROTO_L2TP // WinSock2 only
313 : : #define IPPROTO_SCTP IPPROTO_SCTP // WinSock2 only
314 : :
315 : : /* Provides the IsWindows7SP1OrGreater() function */
316 : : #include <versionhelpers.h>
317 : : // For if_nametoindex() and if_indextoname()
318 : : #include <iphlpapi.h>
319 : :
320 : : /* remove some flags on older version Windows during run-time.
321 : : https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
322 : : typedef struct {
323 : : DWORD build_number; /* available starting with this Win10 BuildNumber */
324 : : const char flag_name[20];
325 : : } FlagRuntimeInfo;
326 : :
327 : : /* IMPORTANT: make sure the list ordered by descending build_number */
328 : : static FlagRuntimeInfo win_runtime_flags[] = {
329 : : /* available starting with Windows 10 1709 */
330 : : {16299, "TCP_KEEPIDLE"},
331 : : {16299, "TCP_KEEPINTVL"},
332 : : /* available starting with Windows 10 1703 */
333 : : {15063, "TCP_KEEPCNT"},
334 : : /* available starting with Windows 10 1607 */
335 : : {14393, "TCP_FASTOPEN"}
336 : : };
337 : :
338 : : /*[clinic input]
339 : : module _socket
340 : : class _socket.socket "PySocketSockObject *" "&sock_type"
341 : : [clinic start generated code]*/
342 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a8313d9b7f51988]*/
343 : :
344 : : static int
345 : : remove_unusable_flags(PyObject *m)
346 : : {
347 : : PyObject *dict;
348 : : OSVERSIONINFOEX info;
349 : :
350 : : dict = PyModule_GetDict(m);
351 : : if (dict == NULL) {
352 : : return -1;
353 : : }
354 : : #ifndef MS_WINDOWS_DESKTOP
355 : : info.dwOSVersionInfoSize = sizeof(info);
356 : : if (!GetVersionExW((OSVERSIONINFOW*) &info)) {
357 : : PyErr_SetFromWindowsErr(0);
358 : : return -1;
359 : : }
360 : : #else
361 : : /* set to Windows 10, except BuildNumber. */
362 : : memset(&info, 0, sizeof(info));
363 : : info.dwOSVersionInfoSize = sizeof(info);
364 : : info.dwMajorVersion = 10;
365 : : info.dwMinorVersion = 0;
366 : :
367 : : /* set Condition Mask */
368 : : DWORDLONG dwlConditionMask = 0;
369 : : VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
370 : : VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
371 : : VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
372 : : #endif
373 : :
374 : : for (int i=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
375 : : #ifdef MS_WINDOWS_DESKTOP
376 : : info.dwBuildNumber = win_runtime_flags[i].build_number;
377 : : /* greater than or equal to the specified version?
378 : : Compatibility Mode will not cheat VerifyVersionInfo(...) */
379 : : BOOL isSupported = VerifyVersionInfo(
380 : : &info,
381 : : VER_MAJORVERSION|VER_MINORVERSION|VER_BUILDNUMBER,
382 : : dwlConditionMask);
383 : : #else
384 : : /* note in this case 'info' is the actual OS version, whereas above
385 : : it is the version to compare against. */
386 : : BOOL isSupported = info.dwMajorVersion > 10 ||
387 : : (info.dwMajorVersion == 10 && info.dwMinorVersion > 0) ||
388 : : (info.dwMajorVersion == 10 && info.dwMinorVersion == 0 &&
389 : : info.dwBuildNumber >= win_runtime_flags[i].build_number);
390 : : #endif
391 : : if (isSupported) {
392 : : break;
393 : : }
394 : : else {
395 : : PyObject *flag_name = PyUnicode_FromString(win_runtime_flags[i].flag_name);
396 : : if (flag_name == NULL) {
397 : : return -1;
398 : : }
399 : : PyObject *v = _PyDict_Pop(dict, flag_name, Py_None);
400 : : Py_DECREF(flag_name);
401 : : if (v == NULL) {
402 : : return -1;
403 : : }
404 : : Py_DECREF(v);
405 : : }
406 : : }
407 : : return 0;
408 : : }
409 : :
410 : : #endif
411 : :
412 : : #include <stddef.h>
413 : :
414 : : #ifndef O_NONBLOCK
415 : : # define O_NONBLOCK O_NDELAY
416 : : #endif
417 : :
418 : : /* include Python's addrinfo.h unless it causes trouble */
419 : : #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
420 : : /* Do not include addinfo.h on some newer IRIX versions.
421 : : * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
422 : : * for example, but not by 6.5.10.
423 : : */
424 : : #elif defined(_MSC_VER) && _MSC_VER>1201
425 : : /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
426 : : * EAI_* constants are defined in (the already included) ws2tcpip.h.
427 : : */
428 : : #else
429 : : # include "addrinfo.h"
430 : : #endif
431 : :
432 : : #ifdef __APPLE__
433 : : /* On OS X, getaddrinfo returns no error indication of lookup
434 : : failure, so we must use the emulation instead of the libinfo
435 : : implementation. Unfortunately, performing an autoconf test
436 : : for this bug would require DNS access for the machine performing
437 : : the configuration, which is not acceptable. Therefore, we
438 : : determine the bug just by checking for __APPLE__. If this bug
439 : : gets ever fixed, perhaps checking for sys/version.h would be
440 : : appropriate, which is 10/0 on the system with the bug. */
441 : : #ifndef HAVE_GETNAMEINFO
442 : : /* This bug seems to be fixed in Jaguar. The easiest way I could
443 : : Find to check for Jaguar is that it has getnameinfo(), which
444 : : older releases don't have */
445 : : #undef HAVE_GETADDRINFO
446 : : #endif
447 : :
448 : : #ifdef HAVE_INET_ATON
449 : : #define USE_INET_ATON_WEAKLINK
450 : : #endif
451 : :
452 : : #endif
453 : :
454 : : /* I know this is a bad practice, but it is the easiest... */
455 : : #if !defined(HAVE_GETADDRINFO)
456 : : /* avoid clashes with the C library definition of the symbol. */
457 : : #define getaddrinfo fake_getaddrinfo
458 : : #define gai_strerror fake_gai_strerror
459 : : #define freeaddrinfo fake_freeaddrinfo
460 : : #include "getaddrinfo.c"
461 : : #endif
462 : :
463 : : #if !defined(HAVE_GETNAMEINFO)
464 : : #define getnameinfo fake_getnameinfo
465 : : #include "getnameinfo.c"
466 : : #endif // HAVE_GETNAMEINFO
467 : :
468 : : #ifdef MS_WINDOWS
469 : : #define SOCKETCLOSE closesocket
470 : : #endif
471 : :
472 : : #ifdef MS_WIN32
473 : : # undef EAFNOSUPPORT
474 : : # define EAFNOSUPPORT WSAEAFNOSUPPORT
475 : : #endif
476 : :
477 : : #ifndef SOCKETCLOSE
478 : : # define SOCKETCLOSE close
479 : : #endif
480 : :
481 : : #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
482 : : #define USE_BLUETOOTH 1
483 : : #if defined(__FreeBSD__)
484 : : #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
485 : : #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
486 : : #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
487 : : #define SOL_HCI SOL_HCI_RAW
488 : : #define HCI_FILTER SO_HCI_RAW_FILTER
489 : : #define sockaddr_l2 sockaddr_l2cap
490 : : #define sockaddr_rc sockaddr_rfcomm
491 : : #define hci_dev hci_node
492 : : #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
493 : : #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
494 : : #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
495 : : #elif defined(__NetBSD__) || defined(__DragonFly__)
496 : : #define sockaddr_l2 sockaddr_bt
497 : : #define sockaddr_rc sockaddr_bt
498 : : #define sockaddr_hci sockaddr_bt
499 : : #define sockaddr_sco sockaddr_bt
500 : : #define SOL_HCI BTPROTO_HCI
501 : : #define HCI_DATA_DIR SO_HCI_DIRECTION
502 : : #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
503 : : #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
504 : : #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
505 : : #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
506 : : #else
507 : : #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
508 : : #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
509 : : #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
510 : : #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
511 : : #endif
512 : : #endif
513 : :
514 : : #ifdef MS_WINDOWS_DESKTOP
515 : : #define sockaddr_rc SOCKADDR_BTH_REDEF
516 : :
517 : : #define USE_BLUETOOTH 1
518 : : #define AF_BLUETOOTH AF_BTH
519 : : #define BTPROTO_RFCOMM BTHPROTO_RFCOMM
520 : : #define _BT_RC_MEMB(sa, memb) ((sa)->memb)
521 : : #endif /* MS_WINDOWS_DESKTOP */
522 : :
523 : : /* Convert "sock_addr_t *" to "struct sockaddr *". */
524 : : #define SAS2SA(x) (&((x)->sa))
525 : :
526 : : /*
527 : : * Constants for getnameinfo()
528 : : */
529 : : #if !defined(NI_MAXHOST)
530 : : #define NI_MAXHOST 1025
531 : : #endif
532 : : #if !defined(NI_MAXSERV)
533 : : #define NI_MAXSERV 32
534 : : #endif
535 : :
536 : : #ifndef INVALID_SOCKET /* MS defines this */
537 : : #define INVALID_SOCKET (-1)
538 : : #endif
539 : :
540 : : #ifndef INADDR_NONE
541 : : #define INADDR_NONE (-1)
542 : : #endif
543 : :
544 : : #include "clinic/socketmodule.c.h"
545 : :
546 : : /* XXX There's a problem here: *static* functions are not supposed to have
547 : : a Py prefix (or use CapitalizedWords). Later... */
548 : :
549 : : /* Global variable holding the exception type for errors detected
550 : : by this module (but not argument type or memory errors, etc.). */
551 : : static PyObject *socket_herror;
552 : : static PyObject *socket_gaierror;
553 : :
554 : : /* A forward reference to the socket type object.
555 : : The sock_type variable contains pointers to various functions,
556 : : some of which call new_sockobject(), which uses sock_type, so
557 : : there has to be a circular reference. */
558 : : static PyTypeObject sock_type;
559 : :
560 : : #if defined(HAVE_POLL_H)
561 : : #include <poll.h>
562 : : #elif defined(HAVE_SYS_POLL_H)
563 : : #include <sys/poll.h>
564 : : #endif
565 : :
566 : : /* Largest value to try to store in a socklen_t (used when handling
567 : : ancillary data). POSIX requires socklen_t to hold at least
568 : : (2**31)-1 and recommends against storing larger values, but
569 : : socklen_t was originally int in the BSD interface, so to be on the
570 : : safe side we use the smaller of (2**31)-1 and INT_MAX. */
571 : : #if INT_MAX > 0x7fffffff
572 : : #define SOCKLEN_T_LIMIT 0x7fffffff
573 : : #else
574 : : #define SOCKLEN_T_LIMIT INT_MAX
575 : : #endif
576 : :
577 : : #ifdef HAVE_POLL
578 : : /* Instead of select(), we'll use poll() since poll() works on any fd. */
579 : : #define IS_SELECTABLE(s) 1
580 : : /* Can we call select() with this socket without a buffer overrun? */
581 : : #else
582 : : /* If there's no timeout left, we don't have to call select, so it's a safe,
583 : : * little white lie. */
584 : : #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0)
585 : : #endif
586 : :
587 : : static PyObject*
588 : 0 : select_error(void)
589 : : {
590 : 0 : PyErr_SetString(PyExc_OSError, "unable to select on socket");
591 : 0 : return NULL;
592 : : }
593 : :
594 : : #ifdef MS_WINDOWS
595 : : #ifndef WSAEAGAIN
596 : : #define WSAEAGAIN WSAEWOULDBLOCK
597 : : #endif
598 : : #define CHECK_ERRNO(expected) \
599 : : (WSAGetLastError() == WSA ## expected)
600 : : #else
601 : : #define CHECK_ERRNO(expected) \
602 : : (errno == expected)
603 : : #endif
604 : :
605 : : #ifdef MS_WINDOWS
606 : : # define GET_SOCK_ERROR WSAGetLastError()
607 : : # define SET_SOCK_ERROR(err) WSASetLastError(err)
608 : : # define SOCK_TIMEOUT_ERR WSAEWOULDBLOCK
609 : : # define SOCK_INPROGRESS_ERR WSAEWOULDBLOCK
610 : : #else
611 : : # define GET_SOCK_ERROR errno
612 : : # define SET_SOCK_ERROR(err) do { errno = err; } while (0)
613 : : # define SOCK_TIMEOUT_ERR EWOULDBLOCK
614 : : # define SOCK_INPROGRESS_ERR EINPROGRESS
615 : : #endif
616 : :
617 : : #ifdef _MSC_VER
618 : : # define SUPPRESS_DEPRECATED_CALL __pragma(warning(suppress: 4996))
619 : : #else
620 : : # define SUPPRESS_DEPRECATED_CALL
621 : : #endif
622 : :
623 : : /* Convenience function to raise an error according to errno
624 : : and return a NULL pointer from a function. */
625 : :
626 : : static PyObject *
627 : 0 : set_error(void)
628 : : {
629 : : #ifdef MS_WINDOWS
630 : : int err_no = WSAGetLastError();
631 : : /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
632 : : recognizes the error codes used by both GetLastError() and
633 : : WSAGetLastError */
634 : : if (err_no)
635 : : return PyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
636 : : #endif
637 : :
638 : 0 : return PyErr_SetFromErrno(PyExc_OSError);
639 : : }
640 : :
641 : :
642 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
643 : : static PyObject *
644 : 0 : set_herror(int h_error)
645 : : {
646 : : PyObject *v;
647 : :
648 : : #ifdef HAVE_HSTRERROR
649 : 0 : v = Py_BuildValue("(is)", h_error, hstrerror(h_error));
650 : : #else
651 : : v = Py_BuildValue("(is)", h_error, "host not found");
652 : : #endif
653 [ # # ]: 0 : if (v != NULL) {
654 : 0 : PyErr_SetObject(socket_herror, v);
655 : 0 : Py_DECREF(v);
656 : : }
657 : :
658 : 0 : return NULL;
659 : : }
660 : : #endif
661 : :
662 : :
663 : : #ifdef HAVE_GETADDRINFO
664 : : static PyObject *
665 : 0 : set_gaierror(int error)
666 : : {
667 : : PyObject *v;
668 : :
669 : : #ifdef EAI_SYSTEM
670 : : /* EAI_SYSTEM is not available on Windows XP. */
671 [ # # ]: 0 : if (error == EAI_SYSTEM)
672 : 0 : return set_error();
673 : : #endif
674 : :
675 : : #ifdef HAVE_GAI_STRERROR
676 : 0 : v = Py_BuildValue("(is)", error, gai_strerror(error));
677 : : #else
678 : : v = Py_BuildValue("(is)", error, "getaddrinfo failed");
679 : : #endif
680 [ # # ]: 0 : if (v != NULL) {
681 : 0 : PyErr_SetObject(socket_gaierror, v);
682 : 0 : Py_DECREF(v);
683 : : }
684 : :
685 : 0 : return NULL;
686 : : }
687 : : #endif
688 : :
689 : : /* Function to perform the setting of socket blocking mode
690 : : internally. block = (1 | 0). */
691 : : static int
692 : 0 : internal_setblocking(PySocketSockObject *s, int block)
693 : : {
694 : 0 : int result = -1;
695 : : #ifdef MS_WINDOWS
696 : : u_long arg;
697 : : #endif
698 : : #if !defined(MS_WINDOWS) \
699 : : && !((defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)))
700 : : int delay_flag, new_delay_flag;
701 : : #endif
702 : :
703 : 0 : Py_BEGIN_ALLOW_THREADS
704 : : #ifndef MS_WINDOWS
705 : : #if (defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO))
706 : 0 : block = !block;
707 [ # # ]: 0 : if (ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block) == -1)
708 : 0 : goto done;
709 : : #else
710 : : delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
711 : : if (delay_flag == -1)
712 : : goto done;
713 : : if (block)
714 : : new_delay_flag = delay_flag & (~O_NONBLOCK);
715 : : else
716 : : new_delay_flag = delay_flag | O_NONBLOCK;
717 : : if (new_delay_flag != delay_flag)
718 : : if (fcntl(s->sock_fd, F_SETFL, new_delay_flag) == -1)
719 : : goto done;
720 : : #endif
721 : : #else /* MS_WINDOWS */
722 : : arg = !block;
723 : : if (ioctlsocket(s->sock_fd, FIONBIO, &arg) != 0)
724 : : goto done;
725 : : #endif /* MS_WINDOWS */
726 : :
727 : 0 : result = 0;
728 : :
729 : 0 : done:
730 : 0 : Py_END_ALLOW_THREADS
731 : :
732 [ # # ]: 0 : if (result) {
733 : : #ifndef MS_WINDOWS
734 : 0 : PyErr_SetFromErrno(PyExc_OSError);
735 : : #else
736 : : PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
737 : : #endif
738 : : }
739 : :
740 : 0 : return result;
741 : : }
742 : :
743 : : static int
744 : 0 : internal_select(PySocketSockObject *s, int writing, _PyTime_t interval,
745 : : int connect)
746 : : {
747 : : int n;
748 : : #ifdef HAVE_POLL
749 : : struct pollfd pollfd;
750 : : _PyTime_t ms;
751 : : #else
752 : : fd_set fds, efds;
753 : : struct timeval tv, *tvp;
754 : : #endif
755 : :
756 : : /* must be called with the GIL held */
757 : : assert(PyGILState_Check());
758 : :
759 : : /* Error condition is for output only */
760 : : assert(!(connect && !writing));
761 : :
762 : : /* Guard against closed socket */
763 [ # # ]: 0 : if (s->sock_fd == INVALID_SOCKET)
764 : 0 : return 0;
765 : :
766 : : /* Prefer poll, if available, since you can poll() any fd
767 : : * which can't be done with select(). */
768 : : #ifdef HAVE_POLL
769 : 0 : pollfd.fd = s->sock_fd;
770 [ # # ]: 0 : pollfd.events = writing ? POLLOUT : POLLIN;
771 [ # # ]: 0 : if (connect) {
772 : : /* On Windows, the socket becomes writable on connection success,
773 : : but a connection failure is notified as an error. On POSIX, the
774 : : socket becomes writable on connection success or on connection
775 : : failure. */
776 : 0 : pollfd.events |= POLLERR;
777 : : }
778 : :
779 : : /* s->sock_timeout is in seconds, timeout in ms */
780 : 0 : ms = _PyTime_AsMilliseconds(interval, _PyTime_ROUND_CEILING);
781 : : assert(ms <= INT_MAX);
782 : :
783 : : /* On some OSes, typically BSD-based ones, the timeout parameter of the
784 : : poll() syscall, when negative, must be exactly INFTIM, where defined,
785 : : or -1. See issue 37811. */
786 [ # # ]: 0 : if (ms < 0) {
787 : : #ifdef INFTIM
788 : : ms = INFTIM;
789 : : #else
790 : 0 : ms = -1;
791 : : #endif
792 : : }
793 : :
794 : 0 : Py_BEGIN_ALLOW_THREADS;
795 : 0 : n = poll(&pollfd, 1, (int)ms);
796 : 0 : Py_END_ALLOW_THREADS;
797 : : #else
798 : : if (interval >= 0) {
799 : : _PyTime_AsTimeval_clamp(interval, &tv, _PyTime_ROUND_CEILING);
800 : : tvp = &tv;
801 : : }
802 : : else
803 : : tvp = NULL;
804 : :
805 : : FD_ZERO(&fds);
806 : : FD_SET(s->sock_fd, &fds);
807 : : FD_ZERO(&efds);
808 : : if (connect) {
809 : : /* On Windows, the socket becomes writable on connection success,
810 : : but a connection failure is notified as an error. On POSIX, the
811 : : socket becomes writable on connection success or on connection
812 : : failure. */
813 : : FD_SET(s->sock_fd, &efds);
814 : : }
815 : :
816 : : /* See if the socket is ready */
817 : : Py_BEGIN_ALLOW_THREADS;
818 : : if (writing)
819 : : n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
820 : : NULL, &fds, &efds, tvp);
821 : : else
822 : : n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
823 : : &fds, NULL, &efds, tvp);
824 : : Py_END_ALLOW_THREADS;
825 : : #endif
826 : :
827 [ # # ]: 0 : if (n < 0)
828 : 0 : return -1;
829 [ # # ]: 0 : if (n == 0)
830 : 0 : return 1;
831 : 0 : return 0;
832 : : }
833 : :
834 : : /* Call a socket function.
835 : :
836 : : On error, raise an exception and return -1 if err is set, or fill err and
837 : : return -1 otherwise. If a signal was received and the signal handler raised
838 : : an exception, return -1, and set err to -1 if err is set.
839 : :
840 : : On success, return 0, and set err to 0 if err is set.
841 : :
842 : : If the socket has a timeout, wait until the socket is ready before calling
843 : : the function: wait until the socket is writable if writing is nonzero, wait
844 : : until the socket received data otherwise.
845 : :
846 : : If the socket function is interrupted by a signal (failed with EINTR): retry
847 : : the function, except if the signal handler raised an exception (PEP 475).
848 : :
849 : : When the function is retried, recompute the timeout using a monotonic clock.
850 : :
851 : : sock_call_ex() must be called with the GIL held. The socket function is
852 : : called with the GIL released. */
853 : : static int
854 : 0 : sock_call_ex(PySocketSockObject *s,
855 : : int writing,
856 : : int (*sock_func) (PySocketSockObject *s, void *data),
857 : : void *data,
858 : : int connect,
859 : : int *err,
860 : : _PyTime_t timeout)
861 : : {
862 : 0 : int has_timeout = (timeout > 0);
863 : 0 : _PyTime_t deadline = 0;
864 : 0 : int deadline_initialized = 0;
865 : : int res;
866 : :
867 : : /* sock_call() must be called with the GIL held. */
868 : : assert(PyGILState_Check());
869 : :
870 : : /* outer loop to retry select() when select() is interrupted by a signal
871 : : or to retry select()+sock_func() on false positive (see above) */
872 : : while (1) {
873 : : /* For connect(), poll even for blocking socket. The connection
874 : : runs asynchronously. */
875 [ # # # # ]: 0 : if (has_timeout || connect) {
876 [ # # ]: 0 : if (has_timeout) {
877 : : _PyTime_t interval;
878 : :
879 [ # # ]: 0 : if (deadline_initialized) {
880 : : /* recompute the timeout */
881 : 0 : interval = _PyDeadline_Get(deadline);
882 : : }
883 : : else {
884 : 0 : deadline_initialized = 1;
885 : 0 : deadline = _PyDeadline_Init(timeout);
886 : 0 : interval = timeout;
887 : : }
888 : :
889 [ # # ]: 0 : if (interval >= 0) {
890 : 0 : res = internal_select(s, writing, interval, connect);
891 : : }
892 : : else {
893 : 0 : res = 1;
894 : : }
895 : : }
896 : : else {
897 : 0 : res = internal_select(s, writing, timeout, connect);
898 : : }
899 : :
900 [ # # ]: 0 : if (res == -1) {
901 [ # # ]: 0 : if (err)
902 : 0 : *err = GET_SOCK_ERROR;
903 : :
904 [ # # ]: 0 : if (CHECK_ERRNO(EINTR)) {
905 : : /* select() was interrupted by a signal */
906 [ # # ]: 0 : if (PyErr_CheckSignals()) {
907 [ # # ]: 0 : if (err)
908 : 0 : *err = -1;
909 : 0 : return -1;
910 : : }
911 : :
912 : : /* retry select() */
913 : 0 : continue;
914 : : }
915 : :
916 : : /* select() failed */
917 : 0 : s->errorhandler();
918 : 0 : return -1;
919 : : }
920 : :
921 [ # # ]: 0 : if (res == 1) {
922 [ # # ]: 0 : if (err)
923 : 0 : *err = SOCK_TIMEOUT_ERR;
924 : : else
925 : 0 : PyErr_SetString(PyExc_TimeoutError, "timed out");
926 : 0 : return -1;
927 : : }
928 : :
929 : : /* the socket is ready */
930 : : }
931 : :
932 : : /* inner loop to retry sock_func() when sock_func() is interrupted
933 : : by a signal */
934 : : while (1) {
935 : 0 : Py_BEGIN_ALLOW_THREADS
936 : 0 : res = sock_func(s, data);
937 : 0 : Py_END_ALLOW_THREADS
938 : :
939 [ # # ]: 0 : if (res) {
940 : : /* sock_func() succeeded */
941 [ # # ]: 0 : if (err)
942 : 0 : *err = 0;
943 : 0 : return 0;
944 : : }
945 : :
946 [ # # ]: 0 : if (err)
947 : 0 : *err = GET_SOCK_ERROR;
948 : :
949 [ # # ]: 0 : if (!CHECK_ERRNO(EINTR))
950 : 0 : break;
951 : :
952 : : /* sock_func() was interrupted by a signal */
953 [ # # ]: 0 : if (PyErr_CheckSignals()) {
954 [ # # ]: 0 : if (err)
955 : 0 : *err = -1;
956 : 0 : return -1;
957 : : }
958 : :
959 : : /* retry sock_func() */
960 : : }
961 : :
962 [ # # ]: 0 : if (s->sock_timeout > 0
963 [ # # # # ]: 0 : && (CHECK_ERRNO(EWOULDBLOCK) || CHECK_ERRNO(EAGAIN))) {
964 : : /* False positive: sock_func() failed with EWOULDBLOCK or EAGAIN.
965 : :
966 : : For example, select() could indicate a socket is ready for
967 : : reading, but the data then discarded by the OS because of a
968 : : wrong checksum.
969 : :
970 : : Loop on select() to recheck for socket readiness. */
971 : 0 : continue;
972 : : }
973 : :
974 : : /* sock_func() failed */
975 [ # # ]: 0 : if (!err)
976 : 0 : s->errorhandler();
977 : : /* else: err was already set before */
978 : 0 : return -1;
979 : : }
980 : : }
981 : :
982 : : static int
983 : 0 : sock_call(PySocketSockObject *s,
984 : : int writing,
985 : : int (*func) (PySocketSockObject *s, void *data),
986 : : void *data)
987 : : {
988 : 0 : return sock_call_ex(s, writing, func, data, 0, NULL, s->sock_timeout);
989 : : }
990 : :
991 : :
992 : : /* Initialize a new socket object. */
993 : :
994 : : /* Default timeout for new sockets */
995 : : static _PyTime_t defaulttimeout = _PYTIME_FROMSECONDS(-1);
996 : :
997 : : static int
998 : 0 : init_sockobject(PySocketSockObject *s,
999 : : SOCKET_T fd, int family, int type, int proto)
1000 : : {
1001 : 0 : s->sock_fd = fd;
1002 : 0 : s->sock_family = family;
1003 : :
1004 : 0 : s->sock_type = type;
1005 : :
1006 : : /* It's possible to pass SOCK_NONBLOCK and SOCK_CLOEXEC bit flags
1007 : : on some OSes as part of socket.type. We want to reset them here,
1008 : : to make socket.type be set to the same value on all platforms.
1009 : : Otherwise, simple code like 'if sock.type == SOCK_STREAM' is
1010 : : not portable.
1011 : : */
1012 : : #ifdef SOCK_NONBLOCK
1013 : 0 : s->sock_type = s->sock_type & ~SOCK_NONBLOCK;
1014 : : #endif
1015 : : #ifdef SOCK_CLOEXEC
1016 : 0 : s->sock_type = s->sock_type & ~SOCK_CLOEXEC;
1017 : : #endif
1018 : :
1019 : 0 : s->sock_proto = proto;
1020 : :
1021 : 0 : s->errorhandler = &set_error;
1022 : : #ifdef SOCK_NONBLOCK
1023 [ # # ]: 0 : if (type & SOCK_NONBLOCK)
1024 : 0 : s->sock_timeout = 0;
1025 : : else
1026 : : #endif
1027 : : {
1028 : 0 : s->sock_timeout = defaulttimeout;
1029 [ # # ]: 0 : if (defaulttimeout >= 0) {
1030 [ # # ]: 0 : if (internal_setblocking(s, 0) == -1) {
1031 : 0 : return -1;
1032 : : }
1033 : : }
1034 : : }
1035 : 0 : return 0;
1036 : : }
1037 : :
1038 : :
1039 : : #ifdef HAVE_SOCKETPAIR
1040 : : /* Create a new socket object.
1041 : : This just creates the object and initializes it.
1042 : : If the creation fails, return NULL and set an exception (implicit
1043 : : in NEWOBJ()). */
1044 : :
1045 : : static PySocketSockObject *
1046 : 0 : new_sockobject(SOCKET_T fd, int family, int type, int proto)
1047 : : {
1048 : : PySocketSockObject *s;
1049 : : s = (PySocketSockObject *)
1050 : 0 : PyType_GenericNew(&sock_type, NULL, NULL);
1051 [ # # ]: 0 : if (s == NULL)
1052 : 0 : return NULL;
1053 [ # # ]: 0 : if (init_sockobject(s, fd, family, type, proto) == -1) {
1054 : 0 : Py_DECREF(s);
1055 : 0 : return NULL;
1056 : : }
1057 : 0 : return s;
1058 : : }
1059 : : #endif
1060 : :
1061 : :
1062 : : /* Lock to allow python interpreter to continue, but only allow one
1063 : : thread to be in gethostbyname or getaddrinfo */
1064 : : #if defined(USE_GETHOSTBYNAME_LOCK)
1065 : : static PyThread_type_lock netdb_lock;
1066 : : #endif
1067 : :
1068 : :
1069 : : #ifdef HAVE_GETADDRINFO
1070 : : /* Convert a string specifying a host name or one of a few symbolic
1071 : : names to a numeric IP address. This usually calls gethostbyname()
1072 : : to do the work; the names "" and "<broadcast>" are special.
1073 : : Return the length (IPv4 should be 4 bytes), or negative if
1074 : : an error occurred; then an exception is raised. */
1075 : :
1076 : : static int
1077 : 0 : setipaddr(const char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
1078 : : {
1079 : : struct addrinfo hints, *res;
1080 : : int error;
1081 : :
1082 : 0 : memset((void *) addr_ret, '\0', sizeof(*addr_ret));
1083 [ # # ]: 0 : if (name[0] == '\0') {
1084 : : int siz;
1085 : 0 : memset(&hints, 0, sizeof(hints));
1086 : 0 : hints.ai_family = af;
1087 : 0 : hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1088 : 0 : hints.ai_flags = AI_PASSIVE;
1089 : 0 : Py_BEGIN_ALLOW_THREADS
1090 : 0 : error = getaddrinfo(NULL, "0", &hints, &res);
1091 : 0 : Py_END_ALLOW_THREADS
1092 : : /* We assume that those thread-unsafe getaddrinfo() versions
1093 : : *are* safe regarding their return value, ie. that a
1094 : : subsequent call to getaddrinfo() does not destroy the
1095 : : outcome of the first call. */
1096 [ # # ]: 0 : if (error) {
1097 : 0 : res = NULL; // no-op, remind us that it is invalid; gh-100795
1098 : 0 : set_gaierror(error);
1099 : 0 : return -1;
1100 : : }
1101 [ # # # ]: 0 : switch (res->ai_family) {
1102 : 0 : case AF_INET:
1103 : 0 : siz = 4;
1104 : 0 : break;
1105 : : #ifdef ENABLE_IPV6
1106 : 0 : case AF_INET6:
1107 : 0 : siz = 16;
1108 : 0 : break;
1109 : : #endif
1110 : 0 : default:
1111 : 0 : freeaddrinfo(res);
1112 : 0 : PyErr_SetString(PyExc_OSError,
1113 : : "unsupported address family");
1114 : 0 : return -1;
1115 : : }
1116 [ # # ]: 0 : if (res->ai_next) {
1117 : 0 : freeaddrinfo(res);
1118 : 0 : PyErr_SetString(PyExc_OSError,
1119 : : "wildcard resolved to multiple address");
1120 : 0 : return -1;
1121 : : }
1122 [ # # ]: 0 : if (res->ai_addrlen < addr_ret_size)
1123 : 0 : addr_ret_size = res->ai_addrlen;
1124 : 0 : memcpy(addr_ret, res->ai_addr, addr_ret_size);
1125 : 0 : freeaddrinfo(res);
1126 : 0 : return siz;
1127 : : }
1128 : : /* special-case broadcast - inet_addr() below can return INADDR_NONE for
1129 : : * this */
1130 [ # # ]: 0 : if (strcmp(name, "255.255.255.255") == 0 ||
1131 [ # # ]: 0 : strcmp(name, "<broadcast>") == 0) {
1132 : : struct sockaddr_in *sin;
1133 [ # # # # ]: 0 : if (af != AF_INET && af != AF_UNSPEC) {
1134 : 0 : PyErr_SetString(PyExc_OSError,
1135 : : "address family mismatched");
1136 : 0 : return -1;
1137 : : }
1138 : 0 : sin = (struct sockaddr_in *)addr_ret;
1139 : 0 : memset((void *) sin, '\0', sizeof(*sin));
1140 : 0 : sin->sin_family = AF_INET;
1141 : : #ifdef HAVE_SOCKADDR_SA_LEN
1142 : : sin->sin_len = sizeof(*sin);
1143 : : #endif
1144 : 0 : sin->sin_addr.s_addr = INADDR_BROADCAST;
1145 : 0 : return sizeof(sin->sin_addr);
1146 : : }
1147 : :
1148 : : /* avoid a name resolution in case of numeric address */
1149 : : #ifdef HAVE_INET_PTON
1150 : : /* check for an IPv4 address */
1151 [ # # # # ]: 0 : if (af == AF_UNSPEC || af == AF_INET) {
1152 : 0 : struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
1153 : 0 : memset(sin, 0, sizeof(*sin));
1154 [ # # ]: 0 : if (inet_pton(AF_INET, name, &sin->sin_addr) > 0) {
1155 : 0 : sin->sin_family = AF_INET;
1156 : : #ifdef HAVE_SOCKADDR_SA_LEN
1157 : : sin->sin_len = sizeof(*sin);
1158 : : #endif
1159 : 0 : return 4;
1160 : : }
1161 : : }
1162 : : #ifdef ENABLE_IPV6
1163 : : /* check for an IPv6 address - if the address contains a scope ID, we
1164 : : * fallback to getaddrinfo(), which can handle translation from interface
1165 : : * name to interface index */
1166 [ # # # # : 0 : if ((af == AF_UNSPEC || af == AF_INET6) && !strchr(name, '%')) {
# # ]
1167 : 0 : struct sockaddr_in6 *sin = (struct sockaddr_in6 *)addr_ret;
1168 : 0 : memset(sin, 0, sizeof(*sin));
1169 [ # # ]: 0 : if (inet_pton(AF_INET6, name, &sin->sin6_addr) > 0) {
1170 : 0 : sin->sin6_family = AF_INET6;
1171 : : #ifdef HAVE_SOCKADDR_SA_LEN
1172 : : sin->sin6_len = sizeof(*sin);
1173 : : #endif
1174 : 0 : return 16;
1175 : : }
1176 : : }
1177 : : #endif /* ENABLE_IPV6 */
1178 : : #else /* HAVE_INET_PTON */
1179 : : /* check for an IPv4 address */
1180 : : if (af == AF_INET || af == AF_UNSPEC) {
1181 : : struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
1182 : : memset(sin, 0, sizeof(*sin));
1183 : : if ((sin->sin_addr.s_addr = inet_addr(name)) != INADDR_NONE) {
1184 : : sin->sin_family = AF_INET;
1185 : : #ifdef HAVE_SOCKADDR_SA_LEN
1186 : : sin->sin_len = sizeof(*sin);
1187 : : #endif
1188 : : return 4;
1189 : : }
1190 : : }
1191 : : #endif /* HAVE_INET_PTON */
1192 : :
1193 : : /* perform a name resolution */
1194 : 0 : memset(&hints, 0, sizeof(hints));
1195 : 0 : hints.ai_family = af;
1196 : 0 : Py_BEGIN_ALLOW_THREADS
1197 : 0 : error = getaddrinfo(name, NULL, &hints, &res);
1198 : : #if defined(__digital__) && defined(__unix__)
1199 : : if (error == EAI_NONAME && af == AF_UNSPEC) {
1200 : : /* On Tru64 V5.1, numeric-to-addr conversion fails
1201 : : if no address family is given. Assume IPv4 for now.*/
1202 : : hints.ai_family = AF_INET;
1203 : : error = getaddrinfo(name, NULL, &hints, &res);
1204 : : }
1205 : : #endif
1206 : 0 : Py_END_ALLOW_THREADS
1207 [ # # ]: 0 : if (error) {
1208 : 0 : res = NULL; // no-op, remind us that it is invalid; gh-100795
1209 : 0 : set_gaierror(error);
1210 : 0 : return -1;
1211 : : }
1212 [ # # ]: 0 : if (res->ai_addrlen < addr_ret_size)
1213 : 0 : addr_ret_size = res->ai_addrlen;
1214 : 0 : memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
1215 : 0 : freeaddrinfo(res);
1216 [ # # # ]: 0 : switch (addr_ret->sa_family) {
1217 : 0 : case AF_INET:
1218 : 0 : return 4;
1219 : : #ifdef ENABLE_IPV6
1220 : 0 : case AF_INET6:
1221 : 0 : return 16;
1222 : : #endif
1223 : 0 : default:
1224 : 0 : PyErr_SetString(PyExc_OSError, "unknown address family");
1225 : 0 : return -1;
1226 : : }
1227 : : }
1228 : : #endif // HAVE_GETADDRINFO
1229 : :
1230 : : /* Convert IPv4 sockaddr to a Python str. */
1231 : :
1232 : : static PyObject *
1233 : 0 : make_ipv4_addr(const struct sockaddr_in *addr)
1234 : : {
1235 : : char buf[INET_ADDRSTRLEN];
1236 [ # # ]: 0 : if (inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) == NULL) {
1237 : 0 : PyErr_SetFromErrno(PyExc_OSError);
1238 : 0 : return NULL;
1239 : : }
1240 : 0 : return PyUnicode_FromString(buf);
1241 : : }
1242 : :
1243 : : #ifdef ENABLE_IPV6
1244 : : /* Convert IPv6 sockaddr to a Python str. */
1245 : :
1246 : : static PyObject *
1247 : 0 : make_ipv6_addr(const struct sockaddr_in6 *addr)
1248 : : {
1249 : : char buf[INET6_ADDRSTRLEN];
1250 [ # # ]: 0 : if (inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)) == NULL) {
1251 : 0 : PyErr_SetFromErrno(PyExc_OSError);
1252 : 0 : return NULL;
1253 : : }
1254 : 0 : return PyUnicode_FromString(buf);
1255 : : }
1256 : : #endif
1257 : :
1258 : : #ifdef USE_BLUETOOTH
1259 : : /* Convert a string representation of a Bluetooth address into a numeric
1260 : : address. Returns the length (6), or raises an exception and returns -1 if
1261 : : an error occurred. */
1262 : :
1263 : : static int
1264 : : setbdaddr(const char *name, bdaddr_t *bdaddr)
1265 : : {
1266 : : unsigned int b0, b1, b2, b3, b4, b5;
1267 : : char ch;
1268 : : int n;
1269 : :
1270 : : n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
1271 : : &b5, &b4, &b3, &b2, &b1, &b0, &ch);
1272 : : if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
1273 : :
1274 : : #ifdef MS_WINDOWS
1275 : : *bdaddr = (ULONGLONG)(b0 & 0xFF);
1276 : : *bdaddr |= ((ULONGLONG)(b1 & 0xFF) << 8);
1277 : : *bdaddr |= ((ULONGLONG)(b2 & 0xFF) << 16);
1278 : : *bdaddr |= ((ULONGLONG)(b3 & 0xFF) << 24);
1279 : : *bdaddr |= ((ULONGLONG)(b4 & 0xFF) << 32);
1280 : : *bdaddr |= ((ULONGLONG)(b5 & 0xFF) << 40);
1281 : : #else
1282 : : bdaddr->b[0] = b0;
1283 : : bdaddr->b[1] = b1;
1284 : : bdaddr->b[2] = b2;
1285 : : bdaddr->b[3] = b3;
1286 : : bdaddr->b[4] = b4;
1287 : : bdaddr->b[5] = b5;
1288 : : #endif
1289 : :
1290 : : return 6;
1291 : : } else {
1292 : : PyErr_SetString(PyExc_OSError, "bad bluetooth address");
1293 : : return -1;
1294 : : }
1295 : : }
1296 : :
1297 : : /* Create a string representation of the Bluetooth address. This is always a
1298 : : string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
1299 : : value (zero padded if necessary). */
1300 : :
1301 : : static PyObject *
1302 : : makebdaddr(bdaddr_t *bdaddr)
1303 : : {
1304 : : char buf[(6 * 2) + 5 + 1];
1305 : :
1306 : : #ifdef MS_WINDOWS
1307 : : int i;
1308 : : unsigned int octets[6];
1309 : :
1310 : : for (i = 0; i < 6; ++i) {
1311 : : octets[i] = ((*bdaddr) >> (8 * i)) & 0xFF;
1312 : : }
1313 : :
1314 : : sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1315 : : octets[5], octets[4], octets[3],
1316 : : octets[2], octets[1], octets[0]);
1317 : : #else
1318 : : sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
1319 : : bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
1320 : : bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
1321 : : #endif
1322 : :
1323 : : return PyUnicode_FromString(buf);
1324 : : }
1325 : : #endif
1326 : :
1327 : :
1328 : : /* Create an object representing the given socket address,
1329 : : suitable for passing it back to bind(), connect() etc.
1330 : : The family field of the sockaddr structure is inspected
1331 : : to determine what kind of address it really is. */
1332 : :
1333 : : /*ARGSUSED*/
1334 : : static PyObject *
1335 : 0 : makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
1336 : : {
1337 [ # # ]: 0 : if (addrlen == 0) {
1338 : : /* No address -- may be recvfrom() from known socket */
1339 : 0 : Py_RETURN_NONE;
1340 : : }
1341 : :
1342 [ # # # # : 0 : switch (addr->sa_family) {
# # # # #
# # ]
1343 : :
1344 : 0 : case AF_INET:
1345 : : {
1346 : 0 : const struct sockaddr_in *a = (const struct sockaddr_in *)addr;
1347 : 0 : PyObject *addrobj = make_ipv4_addr(a);
1348 : 0 : PyObject *ret = NULL;
1349 [ # # ]: 0 : if (addrobj) {
1350 : 0 : ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
1351 : 0 : Py_DECREF(addrobj);
1352 : : }
1353 : 0 : return ret;
1354 : : }
1355 : :
1356 : : #if defined(AF_UNIX)
1357 : 0 : case AF_UNIX:
1358 : : {
1359 : 0 : struct sockaddr_un *a = (struct sockaddr_un *) addr;
1360 : : #ifdef __linux__
1361 : 0 : size_t linuxaddrlen = addrlen - offsetof(struct sockaddr_un, sun_path);
1362 [ # # # # ]: 0 : if (linuxaddrlen > 0 && a->sun_path[0] == 0) { /* Linux abstract namespace */
1363 : 0 : return PyBytes_FromStringAndSize(a->sun_path, linuxaddrlen);
1364 : : }
1365 : : else
1366 : : #endif /* linux */
1367 : : {
1368 : : /* regular NULL-terminated string */
1369 : 0 : return PyUnicode_DecodeFSDefault(a->sun_path);
1370 : : }
1371 : : }
1372 : : #endif /* AF_UNIX */
1373 : :
1374 : : #if defined(AF_NETLINK)
1375 : 0 : case AF_NETLINK:
1376 : : {
1377 : 0 : struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
1378 : 0 : return Py_BuildValue("II", a->nl_pid, a->nl_groups);
1379 : : }
1380 : : #endif /* AF_NETLINK */
1381 : :
1382 : : #if defined(AF_QIPCRTR)
1383 : 0 : case AF_QIPCRTR:
1384 : : {
1385 : 0 : struct sockaddr_qrtr *a = (struct sockaddr_qrtr *) addr;
1386 : 0 : return Py_BuildValue("II", a->sq_node, a->sq_port);
1387 : : }
1388 : : #endif /* AF_QIPCRTR */
1389 : :
1390 : : #if defined(AF_VSOCK)
1391 : 0 : case AF_VSOCK:
1392 : : {
1393 : 0 : struct sockaddr_vm *a = (struct sockaddr_vm *) addr;
1394 : 0 : return Py_BuildValue("II", a->svm_cid, a->svm_port);
1395 : : }
1396 : : #endif /* AF_VSOCK */
1397 : :
1398 : : #ifdef ENABLE_IPV6
1399 : 0 : case AF_INET6:
1400 : : {
1401 : 0 : const struct sockaddr_in6 *a = (const struct sockaddr_in6 *)addr;
1402 : 0 : PyObject *addrobj = make_ipv6_addr(a);
1403 : 0 : PyObject *ret = NULL;
1404 [ # # ]: 0 : if (addrobj) {
1405 : 0 : ret = Py_BuildValue("OiII",
1406 : : addrobj,
1407 : 0 : ntohs(a->sin6_port),
1408 : : ntohl(a->sin6_flowinfo),
1409 : : a->sin6_scope_id);
1410 : 0 : Py_DECREF(addrobj);
1411 : : }
1412 : 0 : return ret;
1413 : : }
1414 : : #endif /* ENABLE_IPV6 */
1415 : :
1416 : : #ifdef USE_BLUETOOTH
1417 : : case AF_BLUETOOTH:
1418 : : switch (proto) {
1419 : :
1420 : : #ifdef BTPROTO_L2CAP
1421 : : case BTPROTO_L2CAP:
1422 : : {
1423 : : struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
1424 : : PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
1425 : : PyObject *ret = NULL;
1426 : : if (addrobj) {
1427 : : ret = Py_BuildValue("Oi",
1428 : : addrobj,
1429 : : _BT_L2_MEMB(a, psm));
1430 : : Py_DECREF(addrobj);
1431 : : }
1432 : : return ret;
1433 : : }
1434 : :
1435 : : #endif /* BTPROTO_L2CAP */
1436 : :
1437 : : case BTPROTO_RFCOMM:
1438 : : {
1439 : : struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
1440 : : PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
1441 : : PyObject *ret = NULL;
1442 : : if (addrobj) {
1443 : : ret = Py_BuildValue("Oi",
1444 : : addrobj,
1445 : : _BT_RC_MEMB(a, channel));
1446 : : Py_DECREF(addrobj);
1447 : : }
1448 : : return ret;
1449 : : }
1450 : :
1451 : : #ifdef BTPROTO_HCI
1452 : : case BTPROTO_HCI:
1453 : : {
1454 : : struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
1455 : : #if defined(__NetBSD__) || defined(__DragonFly__)
1456 : : return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
1457 : : #else /* __NetBSD__ || __DragonFly__ */
1458 : : PyObject *ret = NULL;
1459 : : ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
1460 : : return ret;
1461 : : #endif /* !(__NetBSD__ || __DragonFly__) */
1462 : : }
1463 : :
1464 : : #if !defined(__FreeBSD__)
1465 : : case BTPROTO_SCO:
1466 : : {
1467 : : struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
1468 : : return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
1469 : : }
1470 : : #endif /* !__FreeBSD__ */
1471 : : #endif /* BTPROTO_HCI */
1472 : :
1473 : : default:
1474 : : PyErr_SetString(PyExc_ValueError,
1475 : : "Unknown Bluetooth protocol");
1476 : : return NULL;
1477 : : }
1478 : : #endif /* USE_BLUETOOTH */
1479 : :
1480 : : #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
1481 : 0 : case AF_PACKET:
1482 : : {
1483 : 0 : struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
1484 : 0 : const char *ifname = "";
1485 : : struct ifreq ifr;
1486 : : /* need to look up interface name give index */
1487 [ # # ]: 0 : if (a->sll_ifindex) {
1488 : 0 : ifr.ifr_ifindex = a->sll_ifindex;
1489 [ # # ]: 0 : if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1490 : 0 : ifname = ifr.ifr_name;
1491 : : }
1492 : 0 : return Py_BuildValue("shbhy#",
1493 : : ifname,
1494 : 0 : ntohs(a->sll_protocol),
1495 : 0 : a->sll_pkttype,
1496 : 0 : a->sll_hatype,
1497 : 0 : a->sll_addr,
1498 : 0 : (Py_ssize_t)a->sll_halen);
1499 : : }
1500 : : #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFNAME */
1501 : :
1502 : : #ifdef HAVE_LINUX_TIPC_H
1503 : 0 : case AF_TIPC:
1504 : : {
1505 : 0 : struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
1506 [ # # ]: 0 : if (a->addrtype == TIPC_ADDR_NAMESEQ) {
1507 : 0 : return Py_BuildValue("IIIII",
1508 : 0 : a->addrtype,
1509 : : a->addr.nameseq.type,
1510 : : a->addr.nameseq.lower,
1511 : : a->addr.nameseq.upper,
1512 : 0 : a->scope);
1513 [ # # ]: 0 : } else if (a->addrtype == TIPC_ADDR_NAME) {
1514 : 0 : return Py_BuildValue("IIIII",
1515 : 0 : a->addrtype,
1516 : : a->addr.name.name.type,
1517 : : a->addr.name.name.instance,
1518 : : a->addr.name.name.instance,
1519 : 0 : a->scope);
1520 [ # # ]: 0 : } else if (a->addrtype == TIPC_ADDR_ID) {
1521 : 0 : return Py_BuildValue("IIIII",
1522 : 0 : a->addrtype,
1523 : : a->addr.id.node,
1524 : : a->addr.id.ref,
1525 : : 0,
1526 : 0 : a->scope);
1527 : : } else {
1528 : 0 : PyErr_SetString(PyExc_ValueError,
1529 : : "Invalid address type");
1530 : 0 : return NULL;
1531 : : }
1532 : : }
1533 : : #endif /* HAVE_LINUX_TIPC_H */
1534 : :
1535 : : #if defined(AF_CAN) && defined(SIOCGIFNAME)
1536 : 0 : case AF_CAN:
1537 : : {
1538 : 0 : struct sockaddr_can *a = (struct sockaddr_can *)addr;
1539 : 0 : const char *ifname = "";
1540 : : struct ifreq ifr;
1541 : : /* need to look up interface name given index */
1542 [ # # ]: 0 : if (a->can_ifindex) {
1543 : 0 : ifr.ifr_ifindex = a->can_ifindex;
1544 [ # # ]: 0 : if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
1545 : 0 : ifname = ifr.ifr_name;
1546 : : }
1547 : :
1548 [ # # # ]: 0 : switch (proto) {
1549 : : #ifdef CAN_ISOTP
1550 : 0 : case CAN_ISOTP:
1551 : : {
1552 : 0 : return Py_BuildValue("O&kk", PyUnicode_DecodeFSDefault,
1553 : : ifname,
1554 : : a->can_addr.tp.rx_id,
1555 : : a->can_addr.tp.tx_id);
1556 : : }
1557 : : #endif /* CAN_ISOTP */
1558 : : #ifdef CAN_J1939
1559 : 0 : case CAN_J1939:
1560 : : {
1561 : 0 : return Py_BuildValue("O&KIB", PyUnicode_DecodeFSDefault,
1562 : : ifname,
1563 : 0 : (unsigned long long)a->can_addr.j1939.name,
1564 : 0 : (unsigned int)a->can_addr.j1939.pgn,
1565 : 0 : a->can_addr.j1939.addr);
1566 : : }
1567 : : #endif /* CAN_J1939 */
1568 : 0 : default:
1569 : : {
1570 : 0 : return Py_BuildValue("(O&)", PyUnicode_DecodeFSDefault,
1571 : : ifname);
1572 : : }
1573 : : }
1574 : : }
1575 : : #endif /* AF_CAN && SIOCGIFNAME */
1576 : :
1577 : : #ifdef PF_SYSTEM
1578 : : case PF_SYSTEM:
1579 : : switch(proto) {
1580 : : #ifdef SYSPROTO_CONTROL
1581 : : case SYSPROTO_CONTROL:
1582 : : {
1583 : : struct sockaddr_ctl *a = (struct sockaddr_ctl *)addr;
1584 : : return Py_BuildValue("(II)", a->sc_id, a->sc_unit);
1585 : : }
1586 : : #endif /* SYSPROTO_CONTROL */
1587 : : default:
1588 : : PyErr_SetString(PyExc_ValueError,
1589 : : "Invalid address type");
1590 : : return 0;
1591 : : }
1592 : : #endif /* PF_SYSTEM */
1593 : :
1594 : : #ifdef HAVE_SOCKADDR_ALG
1595 : 0 : case AF_ALG:
1596 : : {
1597 : 0 : struct sockaddr_alg *a = (struct sockaddr_alg *)addr;
1598 : 0 : return Py_BuildValue("s#s#HH",
1599 : 0 : a->salg_type,
1600 : 0 : strnlen((const char*)a->salg_type,
1601 : : sizeof(a->salg_type)),
1602 : 0 : a->salg_name,
1603 : 0 : strnlen((const char*)a->salg_name,
1604 : : sizeof(a->salg_name)),
1605 : : a->salg_feat,
1606 : : a->salg_mask);
1607 : : }
1608 : : #endif /* HAVE_SOCKADDR_ALG */
1609 : :
1610 : : #ifdef HAVE_AF_HYPERV
1611 : : case AF_HYPERV:
1612 : : {
1613 : : SOCKADDR_HV *a = (SOCKADDR_HV *) addr;
1614 : :
1615 : : wchar_t *guidStr;
1616 : : RPC_STATUS res = UuidToStringW(&a->VmId, &guidStr);
1617 : : if (res != RPC_S_OK) {
1618 : : PyErr_SetFromWindowsErr(res);
1619 : : return 0;
1620 : : }
1621 : : PyObject *vmId = PyUnicode_FromWideChar(guidStr, -1);
1622 : : res = RpcStringFreeW(&guidStr);
1623 : : assert(res == RPC_S_OK);
1624 : :
1625 : : res = UuidToStringW(&a->ServiceId, &guidStr);
1626 : : if (res != RPC_S_OK) {
1627 : : Py_DECREF(vmId);
1628 : : PyErr_SetFromWindowsErr(res);
1629 : : return 0;
1630 : : }
1631 : : PyObject *serviceId = PyUnicode_FromWideChar(guidStr, -1);
1632 : : res = RpcStringFreeW(&guidStr);
1633 : : assert(res == RPC_S_OK);
1634 : :
1635 : : return Py_BuildValue("NN", vmId, serviceId);
1636 : : }
1637 : : #endif /* AF_HYPERV */
1638 : :
1639 : : /* More cases here... */
1640 : :
1641 : 0 : default:
1642 : : /* If we don't know the address family, don't raise an
1643 : : exception -- return it as an (int, bytes) tuple. */
1644 : 0 : return Py_BuildValue("iy#",
1645 : 0 : addr->sa_family,
1646 : 0 : addr->sa_data,
1647 : : sizeof(addr->sa_data));
1648 : :
1649 : : }
1650 : : }
1651 : :
1652 : : #if defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
1653 : : /* Helper for getsockaddrarg: bypass IDNA for ASCII-only host names
1654 : : (in particular, numeric IP addresses). */
1655 : : struct maybe_idna {
1656 : : PyObject *obj;
1657 : : char *buf;
1658 : : };
1659 : :
1660 : : static void
1661 : 0 : idna_cleanup(struct maybe_idna *data)
1662 : : {
1663 [ # # ]: 0 : Py_CLEAR(data->obj);
1664 : 0 : }
1665 : :
1666 : : static int
1667 : 0 : idna_converter(PyObject *obj, struct maybe_idna *data)
1668 : : {
1669 : : size_t len;
1670 : : PyObject *obj2;
1671 [ # # ]: 0 : if (obj == NULL) {
1672 : 0 : idna_cleanup(data);
1673 : 0 : return 1;
1674 : : }
1675 : 0 : data->obj = NULL;
1676 : 0 : len = -1;
1677 [ # # ]: 0 : if (PyBytes_Check(obj)) {
1678 : 0 : data->buf = PyBytes_AsString(obj);
1679 : 0 : len = PyBytes_Size(obj);
1680 : : }
1681 [ # # ]: 0 : else if (PyByteArray_Check(obj)) {
1682 : 0 : data->buf = PyByteArray_AsString(obj);
1683 : 0 : len = PyByteArray_Size(obj);
1684 : : }
1685 [ # # ]: 0 : else if (PyUnicode_Check(obj)) {
1686 [ # # ]: 0 : if (PyUnicode_READY(obj) == -1) {
1687 : 0 : return 0;
1688 : : }
1689 [ # # ]: 0 : if (PyUnicode_IS_COMPACT_ASCII(obj)) {
1690 : 0 : data->buf = PyUnicode_DATA(obj);
1691 : 0 : len = PyUnicode_GET_LENGTH(obj);
1692 : : }
1693 : : else {
1694 : 0 : obj2 = PyUnicode_AsEncodedString(obj, "idna", NULL);
1695 [ # # ]: 0 : if (!obj2) {
1696 : 0 : PyErr_SetString(PyExc_TypeError, "encoding of hostname failed");
1697 : 0 : return 0;
1698 : : }
1699 : : assert(PyBytes_Check(obj2));
1700 : 0 : data->obj = obj2;
1701 : 0 : data->buf = PyBytes_AS_STRING(obj2);
1702 : 0 : len = PyBytes_GET_SIZE(obj2);
1703 : : }
1704 : : }
1705 : : else {
1706 : 0 : PyErr_Format(PyExc_TypeError, "str, bytes or bytearray expected, not %s",
1707 : 0 : Py_TYPE(obj)->tp_name);
1708 : 0 : return 0;
1709 : : }
1710 [ # # ]: 0 : if (strlen(data->buf) != len) {
1711 [ # # ]: 0 : Py_CLEAR(data->obj);
1712 : 0 : PyErr_SetString(PyExc_TypeError, "host name must not contain null character");
1713 : 0 : return 0;
1714 : : }
1715 : 0 : return Py_CLEANUP_SUPPORTED;
1716 : : }
1717 : :
1718 : : /* Parse a socket address argument according to the socket object's
1719 : : address family. Return 1 if the address was in the proper format,
1720 : : 0 of not. The address is returned through addr_ret, its length
1721 : : through len_ret. */
1722 : :
1723 : : static int
1724 : 0 : getsockaddrarg(PySocketSockObject *s, PyObject *args,
1725 : : sock_addr_t *addrbuf, int *len_ret, const char *caller)
1726 : : {
1727 [ # # # # : 0 : switch (s->sock_family) {
# # # # #
# # ]
1728 : :
1729 : : #if defined(AF_UNIX)
1730 : 0 : case AF_UNIX:
1731 : : {
1732 : : Py_buffer path;
1733 : 0 : int retval = 0;
1734 : :
1735 : : /* PEP 383. Not using PyUnicode_FSConverter since we need to
1736 : : allow embedded nulls on Linux. */
1737 [ # # ]: 0 : if (PyUnicode_Check(args)) {
1738 [ # # ]: 0 : if ((args = PyUnicode_EncodeFSDefault(args)) == NULL)
1739 : 0 : return 0;
1740 : : }
1741 : : else
1742 : 0 : Py_INCREF(args);
1743 [ # # ]: 0 : if (!PyArg_Parse(args, "y*", &path)) {
1744 : 0 : Py_DECREF(args);
1745 : 0 : return retval;
1746 : : }
1747 : : assert(path.len >= 0);
1748 : :
1749 : 0 : struct sockaddr_un* addr = &addrbuf->un;
1750 : : #ifdef __linux__
1751 [ # # # # ]: 0 : if (path.len == 0 || *(const char *)path.buf == 0) {
1752 : : /* Linux abstract namespace extension:
1753 : : - Empty address auto-binding to an abstract address
1754 : : - Address that starts with null byte */
1755 [ # # ]: 0 : if ((size_t)path.len > sizeof addr->sun_path) {
1756 : 0 : PyErr_SetString(PyExc_OSError,
1757 : : "AF_UNIX path too long");
1758 : 0 : goto unix_out;
1759 : : }
1760 : :
1761 : 0 : *len_ret = path.len + offsetof(struct sockaddr_un, sun_path);
1762 : : }
1763 : : else
1764 : : #endif /* linux */
1765 : : {
1766 : : /* regular NULL-terminated string */
1767 [ # # ]: 0 : if ((size_t)path.len >= sizeof addr->sun_path) {
1768 : 0 : PyErr_SetString(PyExc_OSError,
1769 : : "AF_UNIX path too long");
1770 : 0 : goto unix_out;
1771 : : }
1772 : 0 : addr->sun_path[path.len] = 0;
1773 : :
1774 : : /* including the tailing NUL */
1775 : 0 : *len_ret = path.len + offsetof(struct sockaddr_un, sun_path) + 1;
1776 : : }
1777 : 0 : addr->sun_family = s->sock_family;
1778 : 0 : memcpy(addr->sun_path, path.buf, path.len);
1779 : :
1780 : 0 : retval = 1;
1781 : 0 : unix_out:
1782 : 0 : PyBuffer_Release(&path);
1783 : 0 : Py_DECREF(args);
1784 : 0 : return retval;
1785 : : }
1786 : : #endif /* AF_UNIX */
1787 : :
1788 : : #if defined(AF_NETLINK)
1789 : 0 : case AF_NETLINK:
1790 : : {
1791 : : int pid, groups;
1792 : 0 : struct sockaddr_nl* addr = &addrbuf->nl;
1793 [ # # ]: 0 : if (!PyTuple_Check(args)) {
1794 : 0 : PyErr_Format(
1795 : : PyExc_TypeError,
1796 : : "%s(): AF_NETLINK address must be tuple, not %.500s",
1797 : 0 : caller, Py_TYPE(args)->tp_name);
1798 : 0 : return 0;
1799 : : }
1800 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
1801 : : "II;AF_NETLINK address must be a pair "
1802 : : "(pid, groups)",
1803 : : &pid, &groups))
1804 : : {
1805 : 0 : return 0;
1806 : : }
1807 : 0 : addr->nl_family = AF_NETLINK;
1808 : 0 : addr->nl_pid = pid;
1809 : 0 : addr->nl_groups = groups;
1810 : 0 : *len_ret = sizeof(*addr);
1811 : 0 : return 1;
1812 : : }
1813 : : #endif /* AF_NETLINK */
1814 : :
1815 : : #if defined(AF_QIPCRTR)
1816 : 0 : case AF_QIPCRTR:
1817 : : {
1818 : : unsigned int node, port;
1819 : 0 : struct sockaddr_qrtr* addr = &addrbuf->sq;
1820 [ # # ]: 0 : if (!PyTuple_Check(args)) {
1821 : 0 : PyErr_Format(
1822 : : PyExc_TypeError,
1823 : : "getsockaddrarg: "
1824 : : "AF_QIPCRTR address must be tuple, not %.500s",
1825 : 0 : Py_TYPE(args)->tp_name);
1826 : 0 : return 0;
1827 : : }
1828 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &node, &port))
1829 : 0 : return 0;
1830 : 0 : addr->sq_family = AF_QIPCRTR;
1831 : 0 : addr->sq_node = node;
1832 : 0 : addr->sq_port = port;
1833 : 0 : *len_ret = sizeof(*addr);
1834 : 0 : return 1;
1835 : : }
1836 : : #endif /* AF_QIPCRTR */
1837 : :
1838 : : #if defined(AF_VSOCK)
1839 : 0 : case AF_VSOCK:
1840 : : {
1841 : 0 : struct sockaddr_vm* addr = &addrbuf->vm;
1842 : : int port, cid;
1843 : 0 : memset(addr, 0, sizeof(struct sockaddr_vm));
1844 [ # # ]: 0 : if (!PyTuple_Check(args)) {
1845 : 0 : PyErr_Format(
1846 : : PyExc_TypeError,
1847 : : "getsockaddrarg: "
1848 : : "AF_VSOCK address must be tuple, not %.500s",
1849 : 0 : Py_TYPE(args)->tp_name);
1850 : 0 : return 0;
1851 : : }
1852 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &cid, &port))
1853 : 0 : return 0;
1854 : 0 : addr->svm_family = s->sock_family;
1855 : 0 : addr->svm_port = port;
1856 : 0 : addr->svm_cid = cid;
1857 : 0 : *len_ret = sizeof(*addr);
1858 : 0 : return 1;
1859 : : }
1860 : : #endif /* AF_VSOCK */
1861 : :
1862 : :
1863 : : #ifdef AF_RDS
1864 : 0 : case AF_RDS:
1865 : : /* RDS sockets use sockaddr_in: fall-through */
1866 : : #endif /* AF_RDS */
1867 : :
1868 : : case AF_INET:
1869 : : {
1870 : 0 : struct maybe_idna host = {NULL, NULL};
1871 : : int port, result;
1872 [ # # ]: 0 : if (!PyTuple_Check(args)) {
1873 : 0 : PyErr_Format(
1874 : : PyExc_TypeError,
1875 : : "%s(): AF_INET address must be tuple, not %.500s",
1876 : 0 : caller, Py_TYPE(args)->tp_name);
1877 : 0 : return 0;
1878 : : }
1879 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
1880 : : "O&i;AF_INET address must be a pair "
1881 : : "(host, port)",
1882 : : idna_converter, &host, &port))
1883 : : {
1884 : : assert(PyErr_Occurred());
1885 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1886 : 0 : PyErr_Format(PyExc_OverflowError,
1887 : : "%s(): port must be 0-65535.", caller);
1888 : : }
1889 : 0 : return 0;
1890 : : }
1891 : 0 : struct sockaddr_in* addr = &addrbuf->in;
1892 : 0 : result = setipaddr(host.buf, (struct sockaddr *)addr,
1893 : : sizeof(*addr), AF_INET);
1894 : 0 : idna_cleanup(&host);
1895 [ # # ]: 0 : if (result < 0)
1896 : 0 : return 0;
1897 [ # # # # ]: 0 : if (port < 0 || port > 0xffff) {
1898 : 0 : PyErr_Format(
1899 : : PyExc_OverflowError,
1900 : : "%s(): port must be 0-65535.", caller);
1901 : 0 : return 0;
1902 : : }
1903 : 0 : addr->sin_family = AF_INET;
1904 : 0 : addr->sin_port = htons((short)port);
1905 : 0 : *len_ret = sizeof *addr;
1906 : 0 : return 1;
1907 : : }
1908 : :
1909 : : #ifdef ENABLE_IPV6
1910 : 0 : case AF_INET6:
1911 : : {
1912 : 0 : struct maybe_idna host = {NULL, NULL};
1913 : : int port, result;
1914 : : unsigned int flowinfo, scope_id;
1915 : 0 : flowinfo = scope_id = 0;
1916 [ # # ]: 0 : if (!PyTuple_Check(args)) {
1917 : 0 : PyErr_Format(
1918 : : PyExc_TypeError,
1919 : : "%s(): AF_INET6 address must be tuple, not %.500s",
1920 : 0 : caller, Py_TYPE(args)->tp_name);
1921 : 0 : return 0;
1922 : : }
1923 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
1924 : : "O&i|II;AF_INET6 address must be a tuple "
1925 : : "(host, port[, flowinfo[, scopeid]])",
1926 : : idna_converter, &host, &port, &flowinfo,
1927 : : &scope_id))
1928 : : {
1929 : : assert(PyErr_Occurred());
1930 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1931 : 0 : PyErr_Format(PyExc_OverflowError,
1932 : : "%s(): port must be 0-65535.", caller);
1933 : : }
1934 : 0 : return 0;
1935 : : }
1936 : 0 : struct sockaddr_in6* addr = &addrbuf->in6;
1937 : 0 : result = setipaddr(host.buf, (struct sockaddr *)addr,
1938 : : sizeof(*addr), AF_INET6);
1939 : 0 : idna_cleanup(&host);
1940 [ # # ]: 0 : if (result < 0)
1941 : 0 : return 0;
1942 [ # # # # ]: 0 : if (port < 0 || port > 0xffff) {
1943 : 0 : PyErr_Format(
1944 : : PyExc_OverflowError,
1945 : : "%s(): port must be 0-65535.", caller);
1946 : 0 : return 0;
1947 : : }
1948 [ # # ]: 0 : if (flowinfo > 0xfffff) {
1949 : 0 : PyErr_Format(
1950 : : PyExc_OverflowError,
1951 : : "%s(): flowinfo must be 0-1048575.", caller);
1952 : 0 : return 0;
1953 : : }
1954 : 0 : addr->sin6_family = s->sock_family;
1955 : 0 : addr->sin6_port = htons((short)port);
1956 : 0 : addr->sin6_flowinfo = htonl(flowinfo);
1957 : 0 : addr->sin6_scope_id = scope_id;
1958 : 0 : *len_ret = sizeof *addr;
1959 : 0 : return 1;
1960 : : }
1961 : : #endif /* ENABLE_IPV6 */
1962 : :
1963 : : #ifdef USE_BLUETOOTH
1964 : : case AF_BLUETOOTH:
1965 : : {
1966 : : switch (s->sock_proto) {
1967 : : #ifdef BTPROTO_L2CAP
1968 : : case BTPROTO_L2CAP:
1969 : : {
1970 : : const char *straddr;
1971 : :
1972 : : struct sockaddr_l2 *addr = &addrbuf->bt_l2;
1973 : : memset(addr, 0, sizeof(struct sockaddr_l2));
1974 : : _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
1975 : : if (!PyArg_ParseTuple(args, "si", &straddr,
1976 : : &_BT_L2_MEMB(addr, psm))) {
1977 : : PyErr_Format(PyExc_OSError,
1978 : : "%s(): wrong format", caller);
1979 : : return 0;
1980 : : }
1981 : : if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
1982 : : return 0;
1983 : :
1984 : : *len_ret = sizeof *addr;
1985 : : return 1;
1986 : : }
1987 : : #endif /* BTPROTO_L2CAP */
1988 : : case BTPROTO_RFCOMM:
1989 : : {
1990 : : const char *straddr;
1991 : : struct sockaddr_rc *addr = &addrbuf->bt_rc;
1992 : : _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
1993 : : if (!PyArg_ParseTuple(args, "si", &straddr,
1994 : : &_BT_RC_MEMB(addr, channel))) {
1995 : : PyErr_Format(PyExc_OSError,
1996 : : "%s(): wrong format", caller);
1997 : : return 0;
1998 : : }
1999 : : if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
2000 : : return 0;
2001 : :
2002 : : *len_ret = sizeof *addr;
2003 : : return 1;
2004 : : }
2005 : : #ifdef BTPROTO_HCI
2006 : : case BTPROTO_HCI:
2007 : : {
2008 : : struct sockaddr_hci *addr = &addrbuf->bt_hci;
2009 : : #if defined(__NetBSD__) || defined(__DragonFly__)
2010 : : const char *straddr;
2011 : : _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
2012 : : if (!PyBytes_Check(args)) {
2013 : : PyErr_Format(PyExc_OSError, "%s: "
2014 : : "wrong format", caller);
2015 : : return 0;
2016 : : }
2017 : : straddr = PyBytes_AS_STRING(args);
2018 : : if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
2019 : : return 0;
2020 : : #else /* __NetBSD__ || __DragonFly__ */
2021 : : _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
2022 : : if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
2023 : : PyErr_Format(PyExc_OSError,
2024 : : "%s(): wrong format", caller);
2025 : : return 0;
2026 : : }
2027 : : #endif /* !(__NetBSD__ || __DragonFly__) */
2028 : : *len_ret = sizeof *addr;
2029 : : return 1;
2030 : : }
2031 : : #if !defined(__FreeBSD__)
2032 : : case BTPROTO_SCO:
2033 : : {
2034 : : const char *straddr;
2035 : :
2036 : : struct sockaddr_sco *addr = &addrbuf->bt_sco;
2037 : : _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
2038 : : if (!PyBytes_Check(args)) {
2039 : : PyErr_Format(PyExc_OSError,
2040 : : "%s(): wrong format", caller);
2041 : : return 0;
2042 : : }
2043 : : straddr = PyBytes_AS_STRING(args);
2044 : : if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
2045 : : return 0;
2046 : :
2047 : : *len_ret = sizeof *addr;
2048 : : return 1;
2049 : : }
2050 : : #endif /* !__FreeBSD__ */
2051 : : #endif /* BTPROTO_HCI */
2052 : : default:
2053 : : PyErr_Format(PyExc_OSError,
2054 : : "%s(): unknown Bluetooth protocol", caller);
2055 : : return 0;
2056 : : }
2057 : : }
2058 : : #endif /* USE_BLUETOOTH */
2059 : :
2060 : : #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
2061 : 0 : case AF_PACKET:
2062 : : {
2063 : : struct ifreq ifr;
2064 : : const char *interfaceName;
2065 : : int protoNumber;
2066 : 0 : int hatype = 0;
2067 : 0 : int pkttype = PACKET_HOST;
2068 : 0 : Py_buffer haddr = {NULL, NULL};
2069 : :
2070 [ # # ]: 0 : if (!PyTuple_Check(args)) {
2071 : 0 : PyErr_Format(
2072 : : PyExc_TypeError,
2073 : : "%s(): AF_PACKET address must be tuple, not %.500s",
2074 : 0 : caller, Py_TYPE(args)->tp_name);
2075 : 0 : return 0;
2076 : : }
2077 : : /* XXX: improve the default error message according to the
2078 : : documentation of AF_PACKET, which would be added as part
2079 : : of bpo-25041. */
2080 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
2081 : : "si|iiy*;AF_PACKET address must be a tuple of "
2082 : : "two to five elements",
2083 : : &interfaceName, &protoNumber, &pkttype, &hatype,
2084 : : &haddr))
2085 : : {
2086 : : assert(PyErr_Occurred());
2087 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
2088 : 0 : PyErr_Format(PyExc_OverflowError,
2089 : : "%s(): address argument out of range", caller);
2090 : : }
2091 : 0 : return 0;
2092 : : }
2093 : 0 : strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
2094 : 0 : ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2095 [ # # ]: 0 : if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2096 : 0 : s->errorhandler();
2097 : 0 : PyBuffer_Release(&haddr);
2098 : 0 : return 0;
2099 : : }
2100 [ # # # # ]: 0 : if (haddr.buf && haddr.len > 8) {
2101 : 0 : PyErr_SetString(PyExc_ValueError,
2102 : : "Hardware address must be 8 bytes or less");
2103 : 0 : PyBuffer_Release(&haddr);
2104 : 0 : return 0;
2105 : : }
2106 [ # # # # ]: 0 : if (protoNumber < 0 || protoNumber > 0xffff) {
2107 : 0 : PyErr_Format(
2108 : : PyExc_OverflowError,
2109 : : "%s(): proto must be 0-65535.", caller);
2110 : 0 : PyBuffer_Release(&haddr);
2111 : 0 : return 0;
2112 : : }
2113 : 0 : struct sockaddr_ll* addr = &addrbuf->ll;
2114 : 0 : addr->sll_family = AF_PACKET;
2115 : 0 : addr->sll_protocol = htons((short)protoNumber);
2116 : 0 : addr->sll_ifindex = ifr.ifr_ifindex;
2117 : 0 : addr->sll_pkttype = pkttype;
2118 : 0 : addr->sll_hatype = hatype;
2119 [ # # ]: 0 : if (haddr.buf) {
2120 : 0 : memcpy(&addr->sll_addr, haddr.buf, haddr.len);
2121 : 0 : addr->sll_halen = haddr.len;
2122 : : }
2123 : : else
2124 : 0 : addr->sll_halen = 0;
2125 : 0 : *len_ret = sizeof *addr;
2126 : 0 : PyBuffer_Release(&haddr);
2127 : 0 : return 1;
2128 : : }
2129 : : #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFINDEX */
2130 : :
2131 : : #ifdef HAVE_LINUX_TIPC_H
2132 : 0 : case AF_TIPC:
2133 : : {
2134 : : unsigned int atype, v1, v2, v3;
2135 : 0 : unsigned int scope = TIPC_CLUSTER_SCOPE;
2136 : :
2137 [ # # ]: 0 : if (!PyTuple_Check(args)) {
2138 : 0 : PyErr_Format(
2139 : : PyExc_TypeError,
2140 : : "%s(): AF_TIPC address must be tuple, not %.500s",
2141 : 0 : caller, Py_TYPE(args)->tp_name);
2142 : 0 : return 0;
2143 : : }
2144 : :
2145 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
2146 : : "IIII|I;AF_TIPC address must be a tuple "
2147 : : "(addr_type, v1, v2, v3[, scope])",
2148 : : &atype, &v1, &v2, &v3, &scope))
2149 : : {
2150 : 0 : return 0;
2151 : : }
2152 : :
2153 : 0 : struct sockaddr_tipc *addr = &addrbuf->tipc;
2154 : 0 : memset(addr, 0, sizeof(struct sockaddr_tipc));
2155 : :
2156 : 0 : addr->family = AF_TIPC;
2157 : 0 : addr->scope = scope;
2158 : 0 : addr->addrtype = atype;
2159 : :
2160 [ # # ]: 0 : if (atype == TIPC_ADDR_NAMESEQ) {
2161 : 0 : addr->addr.nameseq.type = v1;
2162 : 0 : addr->addr.nameseq.lower = v2;
2163 : 0 : addr->addr.nameseq.upper = v3;
2164 [ # # ]: 0 : } else if (atype == TIPC_ADDR_NAME) {
2165 : 0 : addr->addr.name.name.type = v1;
2166 : 0 : addr->addr.name.name.instance = v2;
2167 [ # # ]: 0 : } else if (atype == TIPC_ADDR_ID) {
2168 : 0 : addr->addr.id.node = v1;
2169 : 0 : addr->addr.id.ref = v2;
2170 : : } else {
2171 : : /* Shouldn't happen */
2172 : 0 : PyErr_SetString(PyExc_TypeError, "Invalid address type");
2173 : 0 : return 0;
2174 : : }
2175 : :
2176 : 0 : *len_ret = sizeof(*addr);
2177 : :
2178 : 0 : return 1;
2179 : : }
2180 : : #endif /* HAVE_LINUX_TIPC_H */
2181 : :
2182 : : #if defined(AF_CAN) && defined(SIOCGIFINDEX)
2183 : 0 : case AF_CAN:
2184 [ # # # # ]: 0 : switch (s->sock_proto) {
2185 : : #ifdef CAN_RAW
2186 : 0 : case CAN_RAW:
2187 : : /* fall-through */
2188 : : #endif
2189 : : #ifdef CAN_BCM
2190 : : case CAN_BCM:
2191 : : #endif
2192 : : #if defined(CAN_RAW) || defined(CAN_BCM)
2193 : : {
2194 : : PyObject *interfaceName;
2195 : : struct ifreq ifr;
2196 : : Py_ssize_t len;
2197 : 0 : struct sockaddr_can *addr = &addrbuf->can;
2198 : :
2199 [ # # ]: 0 : if (!PyTuple_Check(args)) {
2200 : 0 : PyErr_Format(PyExc_TypeError,
2201 : : "%s(): AF_CAN address must be tuple, not %.500s",
2202 : 0 : caller, Py_TYPE(args)->tp_name);
2203 : 0 : return 0;
2204 : : }
2205 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
2206 : : "O&;AF_CAN address must be a tuple "
2207 : : "(interface, )",
2208 : : PyUnicode_FSConverter, &interfaceName))
2209 : : {
2210 : 0 : return 0;
2211 : : }
2212 : :
2213 : 0 : len = PyBytes_GET_SIZE(interfaceName);
2214 : :
2215 [ # # ]: 0 : if (len == 0) {
2216 : 0 : ifr.ifr_ifindex = 0;
2217 [ # # ]: 0 : } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2218 : 0 : strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2219 : 0 : ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2220 [ # # ]: 0 : if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2221 : 0 : s->errorhandler();
2222 : 0 : Py_DECREF(interfaceName);
2223 : 0 : return 0;
2224 : : }
2225 : : } else {
2226 : 0 : PyErr_SetString(PyExc_OSError,
2227 : : "AF_CAN interface name too long");
2228 : 0 : Py_DECREF(interfaceName);
2229 : 0 : return 0;
2230 : : }
2231 : :
2232 : 0 : addr->can_family = AF_CAN;
2233 : 0 : addr->can_ifindex = ifr.ifr_ifindex;
2234 : :
2235 : 0 : *len_ret = sizeof(*addr);
2236 : 0 : Py_DECREF(interfaceName);
2237 : 0 : return 1;
2238 : : }
2239 : : #endif /* CAN_RAW || CAN_BCM */
2240 : :
2241 : : #ifdef CAN_ISOTP
2242 : 0 : case CAN_ISOTP:
2243 : : {
2244 : : PyObject *interfaceName;
2245 : : struct ifreq ifr;
2246 : : Py_ssize_t len;
2247 : : unsigned long int rx_id, tx_id;
2248 : :
2249 : 0 : struct sockaddr_can *addr = &addrbuf->can;
2250 : :
2251 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O&kk", PyUnicode_FSConverter,
2252 : : &interfaceName,
2253 : : &rx_id,
2254 : : &tx_id))
2255 : 0 : return 0;
2256 : :
2257 : 0 : len = PyBytes_GET_SIZE(interfaceName);
2258 : :
2259 [ # # ]: 0 : if (len == 0) {
2260 : 0 : ifr.ifr_ifindex = 0;
2261 [ # # ]: 0 : } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2262 : 0 : strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2263 : 0 : ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2264 [ # # ]: 0 : if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2265 : 0 : s->errorhandler();
2266 : 0 : Py_DECREF(interfaceName);
2267 : 0 : return 0;
2268 : : }
2269 : : } else {
2270 : 0 : PyErr_SetString(PyExc_OSError,
2271 : : "AF_CAN interface name too long");
2272 : 0 : Py_DECREF(interfaceName);
2273 : 0 : return 0;
2274 : : }
2275 : :
2276 : 0 : addr->can_family = AF_CAN;
2277 : 0 : addr->can_ifindex = ifr.ifr_ifindex;
2278 : 0 : addr->can_addr.tp.rx_id = rx_id;
2279 : 0 : addr->can_addr.tp.tx_id = tx_id;
2280 : :
2281 : 0 : *len_ret = sizeof(*addr);
2282 : 0 : Py_DECREF(interfaceName);
2283 : 0 : return 1;
2284 : : }
2285 : : #endif /* CAN_ISOTP */
2286 : : #ifdef CAN_J1939
2287 : 0 : case CAN_J1939:
2288 : : {
2289 : : PyObject *interfaceName;
2290 : : struct ifreq ifr;
2291 : : Py_ssize_t len;
2292 : : unsigned long long j1939_name; /* at least 64 bits */
2293 : : unsigned int j1939_pgn; /* at least 32 bits */
2294 : : uint8_t j1939_addr;
2295 : :
2296 : 0 : struct sockaddr_can *addr = &addrbuf->can;
2297 : :
2298 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O&KIB", PyUnicode_FSConverter,
2299 : : &interfaceName,
2300 : : &j1939_name,
2301 : : &j1939_pgn,
2302 : : &j1939_addr))
2303 : 0 : return 0;
2304 : :
2305 : 0 : len = PyBytes_GET_SIZE(interfaceName);
2306 : :
2307 [ # # ]: 0 : if (len == 0) {
2308 : 0 : ifr.ifr_ifindex = 0;
2309 [ # # ]: 0 : } else if ((size_t)len < sizeof(ifr.ifr_name)) {
2310 : 0 : strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
2311 : 0 : ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
2312 [ # # ]: 0 : if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
2313 : 0 : s->errorhandler();
2314 : 0 : Py_DECREF(interfaceName);
2315 : 0 : return 0;
2316 : : }
2317 : : } else {
2318 : 0 : PyErr_SetString(PyExc_OSError,
2319 : : "AF_CAN interface name too long");
2320 : 0 : Py_DECREF(interfaceName);
2321 : 0 : return 0;
2322 : : }
2323 : :
2324 : 0 : addr->can_family = AF_CAN;
2325 : 0 : addr->can_ifindex = ifr.ifr_ifindex;
2326 : 0 : addr->can_addr.j1939.name = (uint64_t)j1939_name;
2327 : 0 : addr->can_addr.j1939.pgn = (uint32_t)j1939_pgn;
2328 : 0 : addr->can_addr.j1939.addr = j1939_addr;
2329 : :
2330 : 0 : *len_ret = sizeof(*addr);
2331 : 0 : Py_DECREF(interfaceName);
2332 : 0 : return 1;
2333 : : }
2334 : : #endif /* CAN_J1939 */
2335 : 0 : default:
2336 : 0 : PyErr_Format(PyExc_OSError,
2337 : : "%s(): unsupported CAN protocol", caller);
2338 : 0 : return 0;
2339 : : }
2340 : : #endif /* AF_CAN && SIOCGIFINDEX */
2341 : :
2342 : : #ifdef PF_SYSTEM
2343 : : case PF_SYSTEM:
2344 : : switch (s->sock_proto) {
2345 : : #ifdef SYSPROTO_CONTROL
2346 : : case SYSPROTO_CONTROL:
2347 : : {
2348 : : struct sockaddr_ctl *addr = &addrbuf->ctl;
2349 : : addr->sc_family = AF_SYSTEM;
2350 : : addr->ss_sysaddr = AF_SYS_CONTROL;
2351 : :
2352 : : if (PyUnicode_Check(args)) {
2353 : : struct ctl_info info;
2354 : : PyObject *ctl_name;
2355 : :
2356 : : if (!PyArg_Parse(args, "O&",
2357 : : PyUnicode_FSConverter, &ctl_name)) {
2358 : : return 0;
2359 : : }
2360 : :
2361 : : if (PyBytes_GET_SIZE(ctl_name) > (Py_ssize_t)sizeof(info.ctl_name)) {
2362 : : PyErr_SetString(PyExc_ValueError,
2363 : : "provided string is too long");
2364 : : Py_DECREF(ctl_name);
2365 : : return 0;
2366 : : }
2367 : : strncpy(info.ctl_name, PyBytes_AS_STRING(ctl_name),
2368 : : sizeof(info.ctl_name));
2369 : : Py_DECREF(ctl_name);
2370 : :
2371 : : if (ioctl(s->sock_fd, CTLIOCGINFO, &info)) {
2372 : : PyErr_SetString(PyExc_OSError,
2373 : : "cannot find kernel control with provided name");
2374 : : return 0;
2375 : : }
2376 : :
2377 : : addr->sc_id = info.ctl_id;
2378 : : addr->sc_unit = 0;
2379 : : } else if (!PyArg_ParseTuple(args, "II",
2380 : : &(addr->sc_id), &(addr->sc_unit))) {
2381 : : PyErr_Format(PyExc_TypeError,
2382 : : "%s(): PF_SYSTEM address must be a str or "
2383 : : "a pair (id, unit)", caller);
2384 : : return 0;
2385 : : }
2386 : :
2387 : : *len_ret = sizeof(*addr);
2388 : : return 1;
2389 : : }
2390 : : #endif /* SYSPROTO_CONTROL */
2391 : : default:
2392 : : PyErr_Format(PyExc_OSError,
2393 : : "%s(): unsupported PF_SYSTEM protocol", caller);
2394 : : return 0;
2395 : : }
2396 : : #endif /* PF_SYSTEM */
2397 : : #ifdef HAVE_SOCKADDR_ALG
2398 : 0 : case AF_ALG:
2399 : : {
2400 : : const char *type;
2401 : : const char *name;
2402 : 0 : struct sockaddr_alg *sa = &addrbuf->alg;
2403 : :
2404 : 0 : memset(sa, 0, sizeof(*sa));
2405 : 0 : sa->salg_family = AF_ALG;
2406 : :
2407 [ # # ]: 0 : if (!PyTuple_Check(args)) {
2408 : 0 : PyErr_Format(PyExc_TypeError,
2409 : : "%s(): AF_ALG address must be tuple, not %.500s",
2410 : 0 : caller, Py_TYPE(args)->tp_name);
2411 : 0 : return 0;
2412 : : }
2413 [ # # ]: 0 : if (!PyArg_ParseTuple(args,
2414 : : "ss|HH;AF_ALG address must be a tuple "
2415 : : "(type, name[, feat[, mask]])",
2416 : : &type, &name, &sa->salg_feat, &sa->salg_mask))
2417 : : {
2418 : 0 : return 0;
2419 : : }
2420 : : /* sockaddr_alg has fixed-sized char arrays for type, and name
2421 : : * both must be NULL terminated.
2422 : : */
2423 [ # # ]: 0 : if (strlen(type) >= sizeof(sa->salg_type)) {
2424 : 0 : PyErr_SetString(PyExc_ValueError, "AF_ALG type too long.");
2425 : 0 : return 0;
2426 : : }
2427 : 0 : strncpy((char *)sa->salg_type, type, sizeof(sa->salg_type));
2428 [ # # ]: 0 : if (strlen(name) >= sizeof(sa->salg_name)) {
2429 : 0 : PyErr_SetString(PyExc_ValueError, "AF_ALG name too long.");
2430 : 0 : return 0;
2431 : : }
2432 : 0 : strncpy((char *)sa->salg_name, name, sizeof(sa->salg_name));
2433 : :
2434 : 0 : *len_ret = sizeof(*sa);
2435 : 0 : return 1;
2436 : : }
2437 : : #endif /* HAVE_SOCKADDR_ALG */
2438 : : #ifdef HAVE_AF_HYPERV
2439 : : case AF_HYPERV:
2440 : : {
2441 : : switch (s->sock_proto) {
2442 : : case HV_PROTOCOL_RAW:
2443 : : {
2444 : : PyObject *vm_id_obj = NULL;
2445 : : PyObject *service_id_obj = NULL;
2446 : :
2447 : : SOCKADDR_HV *addr = &addrbuf->hv;
2448 : :
2449 : : memset(addr, 0, sizeof(*addr));
2450 : : addr->Family = AF_HYPERV;
2451 : :
2452 : : if (!PyTuple_Check(args)) {
2453 : : PyErr_Format(PyExc_TypeError,
2454 : : "%s(): AF_HYPERV address must be tuple, not %.500s",
2455 : : caller, Py_TYPE(args)->tp_name);
2456 : : return 0;
2457 : : }
2458 : : if (!PyArg_ParseTuple(args,
2459 : : "UU;AF_HYPERV address must be a str tuple (vm_id, service_id)",
2460 : : &vm_id_obj, &service_id_obj))
2461 : : {
2462 : : return 0;
2463 : : }
2464 : :
2465 : : wchar_t *guid_str = PyUnicode_AsWideCharString(vm_id_obj, NULL);
2466 : : if (guid_str == NULL) {
2467 : : PyErr_Format(PyExc_ValueError,
2468 : : "%s(): AF_HYPERV address vm_id is not a valid UUID string",
2469 : : caller);
2470 : : return 0;
2471 : : }
2472 : : RPC_STATUS rc = UuidFromStringW(guid_str, &addr->VmId);
2473 : : PyMem_Free(guid_str);
2474 : : if (rc != RPC_S_OK) {
2475 : : PyErr_Format(PyExc_ValueError,
2476 : : "%s(): AF_HYPERV address vm_id is not a valid UUID string",
2477 : : caller);
2478 : : return 0;
2479 : : }
2480 : :
2481 : : guid_str = PyUnicode_AsWideCharString(service_id_obj, NULL);
2482 : : if (guid_str == NULL) {
2483 : : PyErr_Format(PyExc_ValueError,
2484 : : "%s(): AF_HYPERV address service_id is not a valid UUID string",
2485 : : caller);
2486 : : return 0;
2487 : : }
2488 : : rc = UuidFromStringW(guid_str, &addr->ServiceId);
2489 : : PyMem_Free(guid_str);
2490 : : if (rc != RPC_S_OK) {
2491 : : PyErr_Format(PyExc_ValueError,
2492 : : "%s(): AF_HYPERV address service_id is not a valid UUID string",
2493 : : caller);
2494 : : return 0;
2495 : : }
2496 : :
2497 : : *len_ret = sizeof(*addr);
2498 : : return 1;
2499 : : }
2500 : : default:
2501 : : PyErr_Format(PyExc_OSError,
2502 : : "%s(): unsupported AF_HYPERV protocol: %d",
2503 : : caller, s->sock_proto);
2504 : : return 0;
2505 : : }
2506 : : }
2507 : : #endif /* HAVE_AF_HYPERV */
2508 : :
2509 : : /* More cases here... */
2510 : :
2511 : 0 : default:
2512 : 0 : PyErr_Format(PyExc_OSError, "%s(): bad family", caller);
2513 : 0 : return 0;
2514 : :
2515 : : }
2516 : : }
2517 : : #endif // defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
2518 : :
2519 : :
2520 : : /* Get the address length according to the socket object's address family.
2521 : : Return 1 if the family is known, 0 otherwise. The length is returned
2522 : : through len_ret. */
2523 : :
2524 : : static int
2525 : 0 : getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
2526 : : {
2527 [ # # # # : 0 : switch (s->sock_family) {
# # # # #
# # ]
2528 : :
2529 : : #if defined(AF_UNIX)
2530 : 0 : case AF_UNIX:
2531 : : {
2532 : 0 : *len_ret = sizeof (struct sockaddr_un);
2533 : 0 : return 1;
2534 : : }
2535 : : #endif /* AF_UNIX */
2536 : :
2537 : : #if defined(AF_NETLINK)
2538 : 0 : case AF_NETLINK:
2539 : : {
2540 : 0 : *len_ret = sizeof (struct sockaddr_nl);
2541 : 0 : return 1;
2542 : : }
2543 : : #endif /* AF_NETLINK */
2544 : :
2545 : : #if defined(AF_QIPCRTR)
2546 : 0 : case AF_QIPCRTR:
2547 : : {
2548 : 0 : *len_ret = sizeof (struct sockaddr_qrtr);
2549 : 0 : return 1;
2550 : : }
2551 : : #endif /* AF_QIPCRTR */
2552 : :
2553 : : #if defined(AF_VSOCK)
2554 : 0 : case AF_VSOCK:
2555 : : {
2556 : 0 : *len_ret = sizeof (struct sockaddr_vm);
2557 : 0 : return 1;
2558 : : }
2559 : : #endif /* AF_VSOCK */
2560 : :
2561 : : #ifdef AF_RDS
2562 : 0 : case AF_RDS:
2563 : : /* RDS sockets use sockaddr_in: fall-through */
2564 : : #endif /* AF_RDS */
2565 : :
2566 : : case AF_INET:
2567 : : {
2568 : 0 : *len_ret = sizeof (struct sockaddr_in);
2569 : 0 : return 1;
2570 : : }
2571 : :
2572 : : #ifdef ENABLE_IPV6
2573 : 0 : case AF_INET6:
2574 : : {
2575 : 0 : *len_ret = sizeof (struct sockaddr_in6);
2576 : 0 : return 1;
2577 : : }
2578 : : #endif /* ENABLE_IPV6 */
2579 : :
2580 : : #ifdef USE_BLUETOOTH
2581 : : case AF_BLUETOOTH:
2582 : : {
2583 : : switch(s->sock_proto)
2584 : : {
2585 : :
2586 : : #ifdef BTPROTO_L2CAP
2587 : : case BTPROTO_L2CAP:
2588 : : *len_ret = sizeof (struct sockaddr_l2);
2589 : : return 1;
2590 : : #endif /* BTPROTO_L2CAP */
2591 : : case BTPROTO_RFCOMM:
2592 : : *len_ret = sizeof (struct sockaddr_rc);
2593 : : return 1;
2594 : : #ifdef BTPROTO_HCI
2595 : : case BTPROTO_HCI:
2596 : : *len_ret = sizeof (struct sockaddr_hci);
2597 : : return 1;
2598 : : #if !defined(__FreeBSD__)
2599 : : case BTPROTO_SCO:
2600 : : *len_ret = sizeof (struct sockaddr_sco);
2601 : : return 1;
2602 : : #endif /* !__FreeBSD__ */
2603 : : #endif /* BTPROTO_HCI */
2604 : : default:
2605 : : PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
2606 : : "unknown BT protocol");
2607 : : return 0;
2608 : :
2609 : : }
2610 : : }
2611 : : #endif /* USE_BLUETOOTH */
2612 : :
2613 : : #ifdef HAVE_NETPACKET_PACKET_H
2614 : 0 : case AF_PACKET:
2615 : : {
2616 : 0 : *len_ret = sizeof (struct sockaddr_ll);
2617 : 0 : return 1;
2618 : : }
2619 : : #endif /* HAVE_NETPACKET_PACKET_H */
2620 : :
2621 : : #ifdef HAVE_LINUX_TIPC_H
2622 : 0 : case AF_TIPC:
2623 : : {
2624 : 0 : *len_ret = sizeof (struct sockaddr_tipc);
2625 : 0 : return 1;
2626 : : }
2627 : : #endif /* HAVE_LINUX_TIPC_H */
2628 : :
2629 : : #ifdef AF_CAN
2630 : 0 : case AF_CAN:
2631 : : {
2632 : 0 : *len_ret = sizeof (struct sockaddr_can);
2633 : 0 : return 1;
2634 : : }
2635 : : #endif /* AF_CAN */
2636 : :
2637 : : #ifdef PF_SYSTEM
2638 : : case PF_SYSTEM:
2639 : : switch(s->sock_proto) {
2640 : : #ifdef SYSPROTO_CONTROL
2641 : : case SYSPROTO_CONTROL:
2642 : : *len_ret = sizeof (struct sockaddr_ctl);
2643 : : return 1;
2644 : : #endif /* SYSPROTO_CONTROL */
2645 : : default:
2646 : : PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
2647 : : "unknown PF_SYSTEM protocol");
2648 : : return 0;
2649 : : }
2650 : : #endif /* PF_SYSTEM */
2651 : : #ifdef HAVE_SOCKADDR_ALG
2652 : 0 : case AF_ALG:
2653 : : {
2654 : 0 : *len_ret = sizeof (struct sockaddr_alg);
2655 : 0 : return 1;
2656 : : }
2657 : : #endif /* HAVE_SOCKADDR_ALG */
2658 : : #ifdef HAVE_AF_HYPERV
2659 : : case AF_HYPERV:
2660 : : {
2661 : : *len_ret = sizeof (SOCKADDR_HV);
2662 : : return 1;
2663 : : }
2664 : : #endif /* HAVE_AF_HYPERV */
2665 : :
2666 : : /* More cases here... */
2667 : :
2668 : 0 : default:
2669 : 0 : PyErr_SetString(PyExc_OSError, "getsockaddrlen: bad family");
2670 : 0 : return 0;
2671 : :
2672 : : }
2673 : : }
2674 : :
2675 : :
2676 : : /* Support functions for the sendmsg() and recvmsg[_into]() methods.
2677 : : Currently, these methods are only compiled if the RFC 2292/3542
2678 : : CMSG_LEN() macro is available. Older systems seem to have used
2679 : : sizeof(struct cmsghdr) + (length) where CMSG_LEN() is used now, so
2680 : : it may be possible to define CMSG_LEN() that way if it's not
2681 : : provided. Some architectures might need extra padding after the
2682 : : cmsghdr, however, and CMSG_LEN() would have to take account of
2683 : : this. */
2684 : : #ifdef CMSG_LEN
2685 : : /* If length is in range, set *result to CMSG_LEN(length) and return
2686 : : true; otherwise, return false. */
2687 : : static int
2688 : 0 : get_CMSG_LEN(size_t length, size_t *result)
2689 : : {
2690 : : size_t tmp;
2691 : :
2692 [ # # ]: 0 : if (length > (SOCKLEN_T_LIMIT - CMSG_LEN(0)))
2693 : 0 : return 0;
2694 : 0 : tmp = CMSG_LEN(length);
2695 [ # # # # ]: 0 : if (tmp > SOCKLEN_T_LIMIT || tmp < length)
2696 : 0 : return 0;
2697 : 0 : *result = tmp;
2698 : 0 : return 1;
2699 : : }
2700 : :
2701 : : #ifdef CMSG_SPACE
2702 : : /* If length is in range, set *result to CMSG_SPACE(length) and return
2703 : : true; otherwise, return false. */
2704 : : static int
2705 : 0 : get_CMSG_SPACE(size_t length, size_t *result)
2706 : : {
2707 : : size_t tmp;
2708 : :
2709 : : /* Use CMSG_SPACE(1) here in order to take account of the padding
2710 : : necessary before *and* after the data. */
2711 [ # # ]: 0 : if (length > (SOCKLEN_T_LIMIT - CMSG_SPACE(1)))
2712 : 0 : return 0;
2713 : 0 : tmp = CMSG_SPACE(length);
2714 [ # # # # ]: 0 : if (tmp > SOCKLEN_T_LIMIT || tmp < length)
2715 : 0 : return 0;
2716 : 0 : *result = tmp;
2717 : 0 : return 1;
2718 : : }
2719 : : #endif
2720 : :
2721 : : /* Return true iff msg->msg_controllen is valid, cmsgh is a valid
2722 : : pointer in msg->msg_control with at least "space" bytes after it,
2723 : : and its cmsg_len member inside the buffer. */
2724 : : static int
2725 : 0 : cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space)
2726 : : {
2727 : : size_t cmsg_offset;
2728 : : static const size_t cmsg_len_end = (offsetof(struct cmsghdr, cmsg_len) +
2729 : : sizeof(cmsgh->cmsg_len));
2730 : :
2731 : : /* Note that POSIX allows msg_controllen to be of signed type. */
2732 [ # # # # ]: 0 : if (cmsgh == NULL || msg->msg_control == NULL)
2733 : 0 : return 0;
2734 : : /* Note that POSIX allows msg_controllen to be of a signed type. This is
2735 : : annoying under OS X as it's unsigned there and so it triggers a
2736 : : tautological comparison warning under Clang when compared against 0.
2737 : : Since the check is valid on other platforms, silence the warning under
2738 : : Clang. */
2739 : : #ifdef __clang__
2740 : : #pragma clang diagnostic push
2741 : : #pragma clang diagnostic ignored "-Wtautological-compare"
2742 : : #endif
2743 : : #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
2744 : : #pragma GCC diagnostic push
2745 : : #pragma GCC diagnostic ignored "-Wtype-limits"
2746 : : #endif
2747 : : if (msg->msg_controllen < 0)
2748 : : return 0;
2749 : : #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
2750 : : #pragma GCC diagnostic pop
2751 : : #endif
2752 : : #ifdef __clang__
2753 : : #pragma clang diagnostic pop
2754 : : #endif
2755 [ # # ]: 0 : if (space < cmsg_len_end)
2756 : 0 : space = cmsg_len_end;
2757 : 0 : cmsg_offset = (char *)cmsgh - (char *)msg->msg_control;
2758 [ # # ]: 0 : return (cmsg_offset <= (size_t)-1 - space &&
2759 [ # # ]: 0 : cmsg_offset + space <= msg->msg_controllen);
2760 : : }
2761 : :
2762 : : /* If pointer CMSG_DATA(cmsgh) is in buffer msg->msg_control, set
2763 : : *space to number of bytes following it in the buffer and return
2764 : : true; otherwise, return false. Assumes cmsgh, msg->msg_control and
2765 : : msg->msg_controllen are valid. */
2766 : : static int
2767 : 0 : get_cmsg_data_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *space)
2768 : : {
2769 : : size_t data_offset;
2770 : : char *data_ptr;
2771 : :
2772 [ # # ]: 0 : if ((data_ptr = (char *)CMSG_DATA(cmsgh)) == NULL)
2773 : 0 : return 0;
2774 : 0 : data_offset = data_ptr - (char *)msg->msg_control;
2775 [ # # ]: 0 : if (data_offset > msg->msg_controllen)
2776 : 0 : return 0;
2777 : 0 : *space = msg->msg_controllen - data_offset;
2778 : 0 : return 1;
2779 : : }
2780 : :
2781 : : /* If cmsgh is invalid or not contained in the buffer pointed to by
2782 : : msg->msg_control, return -1. If cmsgh is valid and its associated
2783 : : data is entirely contained in the buffer, set *data_len to the
2784 : : length of the associated data and return 0. If only part of the
2785 : : associated data is contained in the buffer but cmsgh is otherwise
2786 : : valid, set *data_len to the length contained in the buffer and
2787 : : return 1. */
2788 : : static int
2789 : 0 : get_cmsg_data_len(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *data_len)
2790 : : {
2791 : : size_t space, cmsg_data_len;
2792 : :
2793 [ # # ]: 0 : if (!cmsg_min_space(msg, cmsgh, CMSG_LEN(0)) ||
2794 [ # # ]: 0 : cmsgh->cmsg_len < CMSG_LEN(0))
2795 : 0 : return -1;
2796 : 0 : cmsg_data_len = cmsgh->cmsg_len - CMSG_LEN(0);
2797 [ # # ]: 0 : if (!get_cmsg_data_space(msg, cmsgh, &space))
2798 : 0 : return -1;
2799 [ # # ]: 0 : if (space >= cmsg_data_len) {
2800 : 0 : *data_len = cmsg_data_len;
2801 : 0 : return 0;
2802 : : }
2803 : 0 : *data_len = space;
2804 : 0 : return 1;
2805 : : }
2806 : : #endif /* CMSG_LEN */
2807 : :
2808 : :
2809 : : struct sock_accept {
2810 : : socklen_t *addrlen;
2811 : : sock_addr_t *addrbuf;
2812 : : SOCKET_T result;
2813 : : };
2814 : :
2815 : : #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
2816 : : #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
2817 : : /* accept4() is available on Linux 2.6.28+ and glibc 2.10 */
2818 : : static int accept4_works = -1;
2819 : : #endif
2820 : :
2821 : : static int
2822 : 0 : sock_accept_impl(PySocketSockObject *s, void *data)
2823 : : {
2824 : 0 : struct sock_accept *ctx = data;
2825 : 0 : struct sockaddr *addr = SAS2SA(ctx->addrbuf);
2826 : 0 : socklen_t *paddrlen = ctx->addrlen;
2827 : : #ifdef HAVE_SOCKADDR_ALG
2828 : : /* AF_ALG does not support accept() with addr and raises
2829 : : * ECONNABORTED instead. */
2830 [ # # ]: 0 : if (s->sock_family == AF_ALG) {
2831 : 0 : addr = NULL;
2832 : 0 : paddrlen = NULL;
2833 : 0 : *ctx->addrlen = 0;
2834 : : }
2835 : : #endif
2836 : :
2837 : : #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
2838 [ # # ]: 0 : if (accept4_works != 0) {
2839 : 0 : ctx->result = accept4(s->sock_fd, addr, paddrlen,
2840 : : SOCK_CLOEXEC);
2841 [ # # # # ]: 0 : if (ctx->result == INVALID_SOCKET && accept4_works == -1) {
2842 : : /* On Linux older than 2.6.28, accept4() fails with ENOSYS */
2843 : 0 : accept4_works = (errno != ENOSYS);
2844 : : }
2845 : : }
2846 [ # # ]: 0 : if (accept4_works == 0)
2847 : 0 : ctx->result = accept(s->sock_fd, addr, paddrlen);
2848 : : #else
2849 : : ctx->result = accept(s->sock_fd, addr, paddrlen);
2850 : : #endif
2851 : :
2852 : : #ifdef MS_WINDOWS
2853 : : return (ctx->result != INVALID_SOCKET);
2854 : : #else
2855 : 0 : return (ctx->result >= 0);
2856 : : #endif
2857 : : }
2858 : :
2859 : : /* s._accept() -> (fd, address) */
2860 : :
2861 : : static PyObject *
2862 : 0 : sock_accept(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
2863 : : {
2864 : : sock_addr_t addrbuf;
2865 : : SOCKET_T newfd;
2866 : : socklen_t addrlen;
2867 : 0 : PyObject *sock = NULL;
2868 : 0 : PyObject *addr = NULL;
2869 : 0 : PyObject *res = NULL;
2870 : : struct sock_accept ctx;
2871 : :
2872 [ # # ]: 0 : if (!getsockaddrlen(s, &addrlen))
2873 : 0 : return NULL;
2874 : 0 : memset(&addrbuf, 0, addrlen);
2875 : :
2876 : : if (!IS_SELECTABLE(s))
2877 : : return select_error();
2878 : :
2879 : 0 : ctx.addrlen = &addrlen;
2880 : 0 : ctx.addrbuf = &addrbuf;
2881 [ # # ]: 0 : if (sock_call(s, 0, sock_accept_impl, &ctx) < 0)
2882 : 0 : return NULL;
2883 : 0 : newfd = ctx.result;
2884 : :
2885 : : #ifdef MS_WINDOWS
2886 : : #if defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
2887 : : #ifndef HANDLE_FLAG_INHERIT
2888 : : #define HANDLE_FLAG_INHERIT 0x00000001
2889 : : #endif
2890 : : if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
2891 : : PyErr_SetFromWindowsErr(0);
2892 : : SOCKETCLOSE(newfd);
2893 : : goto finally;
2894 : : }
2895 : : #endif
2896 : : #else
2897 : :
2898 : : #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
2899 [ # # ]: 0 : if (!accept4_works)
2900 : : #endif
2901 : : {
2902 [ # # ]: 0 : if (_Py_set_inheritable(newfd, 0, NULL) < 0) {
2903 : 0 : SOCKETCLOSE(newfd);
2904 : 0 : goto finally;
2905 : : }
2906 : : }
2907 : : #endif
2908 : :
2909 : 0 : sock = PyLong_FromSocket_t(newfd);
2910 [ # # ]: 0 : if (sock == NULL) {
2911 : 0 : SOCKETCLOSE(newfd);
2912 : 0 : goto finally;
2913 : : }
2914 : :
2915 : 0 : addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
2916 : : addrlen, s->sock_proto);
2917 [ # # ]: 0 : if (addr == NULL)
2918 : 0 : goto finally;
2919 : :
2920 : 0 : res = PyTuple_Pack(2, sock, addr);
2921 : :
2922 : 0 : finally:
2923 : 0 : Py_XDECREF(sock);
2924 : 0 : Py_XDECREF(addr);
2925 : 0 : return res;
2926 : : }
2927 : :
2928 : : PyDoc_STRVAR(accept_doc,
2929 : : "_accept() -> (integer, address info)\n\
2930 : : \n\
2931 : : Wait for an incoming connection. Return a new socket file descriptor\n\
2932 : : representing the connection, and the address of the client.\n\
2933 : : For IP sockets, the address info is a pair (hostaddr, port).");
2934 : : #endif // defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
2935 : :
2936 : :
2937 : : /* s.setblocking(flag) method. Argument:
2938 : : False -- non-blocking mode; same as settimeout(0)
2939 : : True -- blocking mode; same as settimeout(None)
2940 : : */
2941 : :
2942 : : static PyObject *
2943 : 0 : sock_setblocking(PySocketSockObject *s, PyObject *arg)
2944 : : {
2945 : : long block;
2946 : :
2947 : 0 : block = PyObject_IsTrue(arg);
2948 [ # # ]: 0 : if (block < 0)
2949 : 0 : return NULL;
2950 : :
2951 [ # # ]: 0 : s->sock_timeout = _PyTime_FromSeconds(block ? -1 : 0);
2952 [ # # ]: 0 : if (internal_setblocking(s, block) == -1) {
2953 : 0 : return NULL;
2954 : : }
2955 : 0 : Py_RETURN_NONE;
2956 : : }
2957 : :
2958 : : PyDoc_STRVAR(setblocking_doc,
2959 : : "setblocking(flag)\n\
2960 : : \n\
2961 : : Set the socket to blocking (flag is true) or non-blocking (false).\n\
2962 : : setblocking(True) is equivalent to settimeout(None);\n\
2963 : : setblocking(False) is equivalent to settimeout(0.0).");
2964 : :
2965 : : /* s.getblocking() method.
2966 : : Returns True if socket is in blocking mode,
2967 : : False if it is in non-blocking mode.
2968 : : */
2969 : : static PyObject *
2970 : 0 : sock_getblocking(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
2971 : : {
2972 [ # # ]: 0 : if (s->sock_timeout) {
2973 : 0 : Py_RETURN_TRUE;
2974 : : }
2975 : : else {
2976 : 0 : Py_RETURN_FALSE;
2977 : : }
2978 : : }
2979 : :
2980 : : PyDoc_STRVAR(getblocking_doc,
2981 : : "getblocking()\n\
2982 : : \n\
2983 : : Returns True if socket is in blocking mode, or False if it\n\
2984 : : is in non-blocking mode.");
2985 : :
2986 : : static int
2987 : 0 : socket_parse_timeout(_PyTime_t *timeout, PyObject *timeout_obj)
2988 : : {
2989 : : #ifdef MS_WINDOWS
2990 : : struct timeval tv;
2991 : : #endif
2992 : : #ifndef HAVE_POLL
2993 : : _PyTime_t ms;
2994 : : #endif
2995 : 0 : int overflow = 0;
2996 : :
2997 [ # # ]: 0 : if (timeout_obj == Py_None) {
2998 : 0 : *timeout = _PyTime_FromSeconds(-1);
2999 : 0 : return 0;
3000 : : }
3001 : :
3002 [ # # ]: 0 : if (_PyTime_FromSecondsObject(timeout,
3003 : : timeout_obj, _PyTime_ROUND_TIMEOUT) < 0)
3004 : 0 : return -1;
3005 : :
3006 [ # # ]: 0 : if (*timeout < 0) {
3007 : 0 : PyErr_SetString(PyExc_ValueError, "Timeout value out of range");
3008 : 0 : return -1;
3009 : : }
3010 : :
3011 : : #ifdef MS_WINDOWS
3012 : : overflow |= (_PyTime_AsTimeval(*timeout, &tv, _PyTime_ROUND_TIMEOUT) < 0);
3013 : : #endif
3014 : : #ifndef HAVE_POLL
3015 : : ms = _PyTime_AsMilliseconds(*timeout, _PyTime_ROUND_TIMEOUT);
3016 : : overflow |= (ms > INT_MAX);
3017 : : #endif
3018 [ # # ]: 0 : if (overflow) {
3019 : 0 : PyErr_SetString(PyExc_OverflowError,
3020 : : "timeout doesn't fit into C timeval");
3021 : 0 : return -1;
3022 : : }
3023 : :
3024 : 0 : return 0;
3025 : : }
3026 : :
3027 : : /* s.settimeout(timeout) method. Argument:
3028 : : None -- no timeout, blocking mode; same as setblocking(True)
3029 : : 0.0 -- non-blocking mode; same as setblocking(False)
3030 : : > 0 -- timeout mode; operations time out after timeout seconds
3031 : : < 0 -- illegal; raises an exception
3032 : : */
3033 : : static PyObject *
3034 : 0 : sock_settimeout(PySocketSockObject *s, PyObject *arg)
3035 : : {
3036 : : _PyTime_t timeout;
3037 : :
3038 [ # # ]: 0 : if (socket_parse_timeout(&timeout, arg) < 0)
3039 : 0 : return NULL;
3040 : :
3041 : 0 : s->sock_timeout = timeout;
3042 : :
3043 : 0 : int block = timeout < 0;
3044 : : /* Blocking mode for a Python socket object means that operations
3045 : : like :meth:`recv` or :meth:`sendall` will block the execution of
3046 : : the current thread until they are complete or aborted with a
3047 : : `TimeoutError` or `socket.error` errors. When timeout is `None`,
3048 : : the underlying FD is in a blocking mode. When timeout is a positive
3049 : : number, the FD is in a non-blocking mode, and socket ops are
3050 : : implemented with a `select()` call.
3051 : :
3052 : : When timeout is 0.0, the FD is in a non-blocking mode.
3053 : :
3054 : : This table summarizes all states in which the socket object and
3055 : : its underlying FD can be:
3056 : :
3057 : : ==================== ===================== ==============
3058 : : `gettimeout()` `getblocking()` FD
3059 : : ==================== ===================== ==============
3060 : : ``None`` ``True`` blocking
3061 : : ``0.0`` ``False`` non-blocking
3062 : : ``> 0`` ``True`` non-blocking
3063 : : */
3064 : :
3065 [ # # ]: 0 : if (internal_setblocking(s, block) == -1) {
3066 : 0 : return NULL;
3067 : : }
3068 : 0 : Py_RETURN_NONE;
3069 : : }
3070 : :
3071 : : PyDoc_STRVAR(settimeout_doc,
3072 : : "settimeout(timeout)\n\
3073 : : \n\
3074 : : Set a timeout on socket operations. 'timeout' can be a float,\n\
3075 : : giving in seconds, or None. Setting a timeout of None disables\n\
3076 : : the timeout feature and is equivalent to setblocking(1).\n\
3077 : : Setting a timeout of zero is the same as setblocking(0).");
3078 : :
3079 : : /* s.gettimeout() method.
3080 : : Returns the timeout associated with a socket. */
3081 : : static PyObject *
3082 : 0 : sock_gettimeout(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3083 : : {
3084 [ # # ]: 0 : if (s->sock_timeout < 0) {
3085 : 0 : Py_RETURN_NONE;
3086 : : }
3087 : : else {
3088 : 0 : double seconds = _PyTime_AsSecondsDouble(s->sock_timeout);
3089 : 0 : return PyFloat_FromDouble(seconds);
3090 : : }
3091 : : }
3092 : :
3093 : : PyDoc_STRVAR(gettimeout_doc,
3094 : : "gettimeout() -> timeout\n\
3095 : : \n\
3096 : : Returns the timeout in seconds (float) associated with socket\n\
3097 : : operations. A timeout of None indicates that timeouts on socket\n\
3098 : : operations are disabled.");
3099 : :
3100 : : #ifdef HAVE_SETSOCKOPT
3101 : : /* s.setsockopt() method.
3102 : : With an integer third argument, sets an integer optval with optlen=4.
3103 : : With None as third argument and an integer fourth argument, set
3104 : : optval=NULL with unsigned int as optlen.
3105 : : With a string third argument, sets an option from a buffer;
3106 : : use optional built-in module 'struct' to encode the string.
3107 : : */
3108 : :
3109 : : static PyObject *
3110 : 0 : sock_setsockopt(PySocketSockObject *s, PyObject *args)
3111 : : {
3112 : : int level;
3113 : : int optname;
3114 : : int res;
3115 : : Py_buffer optval;
3116 : : int flag;
3117 : : unsigned int optlen;
3118 : : PyObject *none;
3119 : :
3120 : : #ifdef AF_VSOCK
3121 [ # # ]: 0 : if (s->sock_family == AF_VSOCK) {
3122 : : uint64_t vflag; // Must be set width of 64 bits
3123 : : /* setsockopt(level, opt, flag) */
3124 [ # # ]: 0 : if (PyArg_ParseTuple(args, "iiK:setsockopt",
3125 : : &level, &optname, &vflag)) {
3126 : : // level should always be set to AF_VSOCK
3127 : 0 : res = setsockopt(s->sock_fd, level, optname,
3128 : : (void*)&vflag, sizeof vflag);
3129 : 0 : goto done;
3130 : : }
3131 : 0 : return NULL;
3132 : : }
3133 : : #endif
3134 : :
3135 : : /* setsockopt(level, opt, flag) */
3136 [ # # ]: 0 : if (PyArg_ParseTuple(args, "iii:setsockopt",
3137 : : &level, &optname, &flag)) {
3138 : 0 : res = setsockopt(s->sock_fd, level, optname,
3139 : : (char*)&flag, sizeof flag);
3140 : 0 : goto done;
3141 : : }
3142 : :
3143 : 0 : PyErr_Clear();
3144 : : /* setsockopt(level, opt, None, flag) */
3145 [ # # ]: 0 : if (PyArg_ParseTuple(args, "iiO!I:setsockopt",
3146 : : &level, &optname, Py_TYPE(Py_None), &none, &optlen)) {
3147 : : assert(sizeof(socklen_t) >= sizeof(unsigned int));
3148 : 0 : res = setsockopt(s->sock_fd, level, optname,
3149 : : NULL, (socklen_t)optlen);
3150 : 0 : goto done;
3151 : : }
3152 : :
3153 : 0 : PyErr_Clear();
3154 : : /* setsockopt(level, opt, buffer) */
3155 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "iiy*:setsockopt",
3156 : : &level, &optname, &optval))
3157 : 0 : return NULL;
3158 : :
3159 : : #ifdef MS_WINDOWS
3160 : : if (optval.len > INT_MAX) {
3161 : : PyBuffer_Release(&optval);
3162 : : PyErr_Format(PyExc_OverflowError,
3163 : : "socket option is larger than %i bytes",
3164 : : INT_MAX);
3165 : : return NULL;
3166 : : }
3167 : : res = setsockopt(s->sock_fd, level, optname,
3168 : : optval.buf, (int)optval.len);
3169 : : #else
3170 : 0 : res = setsockopt(s->sock_fd, level, optname, optval.buf, optval.len);
3171 : : #endif
3172 : 0 : PyBuffer_Release(&optval);
3173 : :
3174 : 0 : done:
3175 [ # # ]: 0 : if (res < 0) {
3176 : 0 : return s->errorhandler();
3177 : : }
3178 : :
3179 : 0 : Py_RETURN_NONE;
3180 : : }
3181 : :
3182 : : PyDoc_STRVAR(setsockopt_doc,
3183 : : "setsockopt(level, option, value: int)\n\
3184 : : setsockopt(level, option, value: buffer)\n\
3185 : : setsockopt(level, option, None, optlen: int)\n\
3186 : : \n\
3187 : : Set a socket option. See the Unix manual for level and option.\n\
3188 : : The value argument can either be an integer, a string buffer, or\n\
3189 : : None, optlen.");
3190 : : #endif
3191 : :
3192 : : /* s.getsockopt() method.
3193 : : With two arguments, retrieves an integer option.
3194 : : With a third integer argument, retrieves a string buffer of that size;
3195 : : use optional built-in module 'struct' to decode the string. */
3196 : :
3197 : : static PyObject *
3198 : 0 : sock_getsockopt(PySocketSockObject *s, PyObject *args)
3199 : : {
3200 : : int level;
3201 : : int optname;
3202 : : int res;
3203 : : PyObject *buf;
3204 : 0 : socklen_t buflen = 0;
3205 : 0 : int flag = 0;
3206 : : socklen_t flagsize;
3207 : :
3208 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
3209 : : &level, &optname, &buflen))
3210 : 0 : return NULL;
3211 : :
3212 [ # # ]: 0 : if (buflen == 0) {
3213 : : #ifdef AF_VSOCK
3214 [ # # ]: 0 : if (s->sock_family == AF_VSOCK) {
3215 : 0 : uint64_t vflag = 0; // Must be set width of 64 bits
3216 : 0 : flagsize = sizeof vflag;
3217 : 0 : res = getsockopt(s->sock_fd, level, optname,
3218 : : (void *)&vflag, &flagsize);
3219 [ # # ]: 0 : if (res < 0)
3220 : 0 : return s->errorhandler();
3221 : 0 : return PyLong_FromUnsignedLong(vflag);
3222 : : }
3223 : : #endif
3224 : 0 : flagsize = sizeof flag;
3225 : 0 : res = getsockopt(s->sock_fd, level, optname,
3226 : : (void *)&flag, &flagsize);
3227 [ # # ]: 0 : if (res < 0)
3228 : 0 : return s->errorhandler();
3229 : 0 : return PyLong_FromLong(flag);
3230 : : }
3231 : : #ifdef AF_VSOCK
3232 [ # # ]: 0 : if (s->sock_family == AF_VSOCK) {
3233 : 0 : PyErr_SetString(PyExc_OSError,
3234 : : "getsockopt string buffer not allowed");
3235 : 0 : return NULL;
3236 : : }
3237 : : #endif
3238 [ # # # # ]: 0 : if (buflen <= 0 || buflen > 1024) {
3239 : 0 : PyErr_SetString(PyExc_OSError,
3240 : : "getsockopt buflen out of range");
3241 : 0 : return NULL;
3242 : : }
3243 : 0 : buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
3244 [ # # ]: 0 : if (buf == NULL)
3245 : 0 : return NULL;
3246 : 0 : res = getsockopt(s->sock_fd, level, optname,
3247 : 0 : (void *)PyBytes_AS_STRING(buf), &buflen);
3248 [ # # ]: 0 : if (res < 0) {
3249 : 0 : Py_DECREF(buf);
3250 : 0 : return s->errorhandler();
3251 : : }
3252 : 0 : _PyBytes_Resize(&buf, buflen);
3253 : 0 : return buf;
3254 : : }
3255 : :
3256 : : PyDoc_STRVAR(getsockopt_doc,
3257 : : "getsockopt(level, option[, buffersize]) -> value\n\
3258 : : \n\
3259 : : Get a socket option. See the Unix manual for level and option.\n\
3260 : : If a nonzero buffersize argument is given, the return value is a\n\
3261 : : string of that length; otherwise it is an integer.");
3262 : :
3263 : :
3264 : : #ifdef HAVE_BIND
3265 : : /* s.bind(sockaddr) method */
3266 : :
3267 : : static PyObject *
3268 : 0 : sock_bind(PySocketSockObject *s, PyObject *addro)
3269 : : {
3270 : : sock_addr_t addrbuf;
3271 : : int addrlen;
3272 : : int res;
3273 : :
3274 [ # # ]: 0 : if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "bind")) {
3275 : 0 : return NULL;
3276 : : }
3277 : :
3278 [ # # ]: 0 : if (PySys_Audit("socket.bind", "OO", s, addro) < 0) {
3279 : 0 : return NULL;
3280 : : }
3281 : :
3282 : 0 : Py_BEGIN_ALLOW_THREADS
3283 : 0 : res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
3284 : 0 : Py_END_ALLOW_THREADS
3285 [ # # ]: 0 : if (res < 0)
3286 : 0 : return s->errorhandler();
3287 : 0 : Py_RETURN_NONE;
3288 : : }
3289 : :
3290 : : PyDoc_STRVAR(bind_doc,
3291 : : "bind(address)\n\
3292 : : \n\
3293 : : Bind the socket to a local address. For IP sockets, the address is a\n\
3294 : : pair (host, port); the host must refer to the local host. For raw packet\n\
3295 : : sockets the address is a tuple (ifname, proto [,pkttype [,hatype [,addr]]])");
3296 : : #endif
3297 : :
3298 : :
3299 : : /* s.close() method.
3300 : : Set the file descriptor to -1 so operations tried subsequently
3301 : : will surely fail. */
3302 : :
3303 : : static PyObject *
3304 : 0 : sock_close(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3305 : : {
3306 : : SOCKET_T fd;
3307 : : int res;
3308 : :
3309 : 0 : fd = s->sock_fd;
3310 [ # # ]: 0 : if (fd != INVALID_SOCKET) {
3311 : 0 : s->sock_fd = INVALID_SOCKET;
3312 : :
3313 : : /* We do not want to retry upon EINTR: see
3314 : : http://lwn.net/Articles/576478/ and
3315 : : http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
3316 : : for more details. */
3317 : 0 : Py_BEGIN_ALLOW_THREADS
3318 : 0 : res = SOCKETCLOSE(fd);
3319 : 0 : Py_END_ALLOW_THREADS
3320 : : /* bpo-30319: The peer can already have closed the connection.
3321 : : Python ignores ECONNRESET on close(). */
3322 [ # # # # ]: 0 : if (res < 0 && errno != ECONNRESET) {
3323 : 0 : return s->errorhandler();
3324 : : }
3325 : : }
3326 : 0 : Py_RETURN_NONE;
3327 : : }
3328 : :
3329 : : PyDoc_STRVAR(sock_close_doc,
3330 : : "close()\n\
3331 : : \n\
3332 : : Close the socket. It cannot be used after this call.");
3333 : :
3334 : : static PyObject *
3335 : 0 : sock_detach(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3336 : : {
3337 : 0 : SOCKET_T fd = s->sock_fd;
3338 : 0 : s->sock_fd = INVALID_SOCKET;
3339 : 0 : return PyLong_FromSocket_t(fd);
3340 : : }
3341 : :
3342 : : PyDoc_STRVAR(detach_doc,
3343 : : "detach()\n\
3344 : : \n\
3345 : : Close the socket object without closing the underlying file descriptor.\n\
3346 : : The object cannot be used after this call, but the file descriptor\n\
3347 : : can be reused for other purposes. The file descriptor is returned.");
3348 : :
3349 : : #ifdef HAVE_CONNECT
3350 : : static int
3351 : 0 : sock_connect_impl(PySocketSockObject *s, void* Py_UNUSED(data))
3352 : : {
3353 : : int err;
3354 : 0 : socklen_t size = sizeof err;
3355 : :
3356 [ # # ]: 0 : if (getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, (void *)&err, &size)) {
3357 : : /* getsockopt() failed */
3358 : 0 : return 0;
3359 : : }
3360 : :
3361 [ # # ]: 0 : if (err == EISCONN)
3362 : 0 : return 1;
3363 [ # # ]: 0 : if (err != 0) {
3364 : : /* sock_call_ex() uses GET_SOCK_ERROR() to get the error code */
3365 : 0 : SET_SOCK_ERROR(err);
3366 : 0 : return 0;
3367 : : }
3368 : 0 : return 1;
3369 : : }
3370 : :
3371 : : static int
3372 : 0 : internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
3373 : : int raise)
3374 : : {
3375 : : int res, err, wait_connect;
3376 : :
3377 : 0 : Py_BEGIN_ALLOW_THREADS
3378 : 0 : res = connect(s->sock_fd, addr, addrlen);
3379 : 0 : Py_END_ALLOW_THREADS
3380 : :
3381 [ # # ]: 0 : if (!res) {
3382 : : /* connect() succeeded, the socket is connected */
3383 : 0 : return 0;
3384 : : }
3385 : :
3386 : : /* connect() failed */
3387 : :
3388 : : /* save error, PyErr_CheckSignals() can replace it */
3389 : 0 : err = GET_SOCK_ERROR;
3390 [ # # ]: 0 : if (CHECK_ERRNO(EINTR)) {
3391 [ # # ]: 0 : if (PyErr_CheckSignals())
3392 : 0 : return -1;
3393 : :
3394 : : /* Issue #23618: when connect() fails with EINTR, the connection is
3395 : : running asynchronously.
3396 : :
3397 : : If the socket is blocking or has a timeout, wait until the
3398 : : connection completes, fails or timed out using select(), and then
3399 : : get the connection status using getsockopt(SO_ERROR).
3400 : :
3401 : : If the socket is non-blocking, raise InterruptedError. The caller is
3402 : : responsible to wait until the connection completes, fails or timed
3403 : : out (it's the case in asyncio for example). */
3404 : 0 : wait_connect = (s->sock_timeout != 0 && IS_SELECTABLE(s));
3405 : : }
3406 : : else {
3407 : 0 : wait_connect = (s->sock_timeout > 0 && err == SOCK_INPROGRESS_ERR
3408 [ # # # # ]: 0 : && IS_SELECTABLE(s));
3409 : : }
3410 : :
3411 [ # # ]: 0 : if (!wait_connect) {
3412 [ # # ]: 0 : if (raise) {
3413 : : /* restore error, maybe replaced by PyErr_CheckSignals() */
3414 : 0 : SET_SOCK_ERROR(err);
3415 : 0 : s->errorhandler();
3416 : 0 : return -1;
3417 : : }
3418 : : else
3419 : 0 : return err;
3420 : : }
3421 : :
3422 [ # # ]: 0 : if (raise) {
3423 : : /* socket.connect() raises an exception on error */
3424 [ # # ]: 0 : if (sock_call_ex(s, 1, sock_connect_impl, NULL,
3425 : : 1, NULL, s->sock_timeout) < 0)
3426 : 0 : return -1;
3427 : : }
3428 : : else {
3429 : : /* socket.connect_ex() returns the error code on error */
3430 [ # # ]: 0 : if (sock_call_ex(s, 1, sock_connect_impl, NULL,
3431 : : 1, &err, s->sock_timeout) < 0)
3432 : 0 : return err;
3433 : : }
3434 : 0 : return 0;
3435 : : }
3436 : :
3437 : : /* s.connect(sockaddr) method */
3438 : :
3439 : : static PyObject *
3440 : 0 : sock_connect(PySocketSockObject *s, PyObject *addro)
3441 : : {
3442 : : sock_addr_t addrbuf;
3443 : : int addrlen;
3444 : : int res;
3445 : :
3446 [ # # ]: 0 : if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect")) {
3447 : 0 : return NULL;
3448 : : }
3449 : :
3450 [ # # ]: 0 : if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
3451 : 0 : return NULL;
3452 : : }
3453 : :
3454 : 0 : res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 1);
3455 [ # # ]: 0 : if (res < 0)
3456 : 0 : return NULL;
3457 : :
3458 : 0 : Py_RETURN_NONE;
3459 : : }
3460 : :
3461 : : PyDoc_STRVAR(connect_doc,
3462 : : "connect(address)\n\
3463 : : \n\
3464 : : Connect the socket to a remote address. For IP sockets, the address\n\
3465 : : is a pair (host, port).");
3466 : :
3467 : :
3468 : : /* s.connect_ex(sockaddr) method */
3469 : :
3470 : : static PyObject *
3471 : 0 : sock_connect_ex(PySocketSockObject *s, PyObject *addro)
3472 : : {
3473 : : sock_addr_t addrbuf;
3474 : : int addrlen;
3475 : : int res;
3476 : :
3477 [ # # ]: 0 : if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect_ex")) {
3478 : 0 : return NULL;
3479 : : }
3480 : :
3481 [ # # ]: 0 : if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
3482 : 0 : return NULL;
3483 : : }
3484 : :
3485 : 0 : res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 0);
3486 [ # # ]: 0 : if (res < 0)
3487 : 0 : return NULL;
3488 : :
3489 : 0 : return PyLong_FromLong((long) res);
3490 : : }
3491 : :
3492 : : PyDoc_STRVAR(connect_ex_doc,
3493 : : "connect_ex(address) -> errno\n\
3494 : : \n\
3495 : : This is like connect(address), but returns an error code (the errno value)\n\
3496 : : instead of raising an exception when an error occurs.");
3497 : : #endif // HAVE_CONNECT
3498 : :
3499 : :
3500 : : /* s.fileno() method */
3501 : :
3502 : : static PyObject *
3503 : 0 : sock_fileno(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3504 : : {
3505 : 0 : return PyLong_FromSocket_t(s->sock_fd);
3506 : : }
3507 : :
3508 : : PyDoc_STRVAR(fileno_doc,
3509 : : "fileno() -> integer\n\
3510 : : \n\
3511 : : Return the integer file descriptor of the socket.");
3512 : :
3513 : :
3514 : : #ifdef HAVE_GETSOCKNAME
3515 : : /* s.getsockname() method */
3516 : :
3517 : : static PyObject *
3518 : 0 : sock_getsockname(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3519 : : {
3520 : : sock_addr_t addrbuf;
3521 : : int res;
3522 : : socklen_t addrlen;
3523 : :
3524 [ # # ]: 0 : if (!getsockaddrlen(s, &addrlen))
3525 : 0 : return NULL;
3526 : 0 : memset(&addrbuf, 0, addrlen);
3527 : 0 : Py_BEGIN_ALLOW_THREADS
3528 : 0 : res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
3529 : 0 : Py_END_ALLOW_THREADS
3530 [ # # ]: 0 : if (res < 0)
3531 : 0 : return s->errorhandler();
3532 : 0 : return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3533 : : s->sock_proto);
3534 : : }
3535 : :
3536 : : PyDoc_STRVAR(getsockname_doc,
3537 : : "getsockname() -> address info\n\
3538 : : \n\
3539 : : Return the address of the local endpoint. The format depends on the\n\
3540 : : address family. For IPv4 sockets, the address info is a pair\n\
3541 : : (hostaddr, port).");
3542 : : #endif
3543 : :
3544 : :
3545 : : #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
3546 : : /* s.getpeername() method */
3547 : :
3548 : : static PyObject *
3549 : 0 : sock_getpeername(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
3550 : : {
3551 : : sock_addr_t addrbuf;
3552 : : int res;
3553 : : socklen_t addrlen;
3554 : :
3555 [ # # ]: 0 : if (!getsockaddrlen(s, &addrlen))
3556 : 0 : return NULL;
3557 : 0 : memset(&addrbuf, 0, addrlen);
3558 : 0 : Py_BEGIN_ALLOW_THREADS
3559 : 0 : res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
3560 : 0 : Py_END_ALLOW_THREADS
3561 [ # # ]: 0 : if (res < 0)
3562 : 0 : return s->errorhandler();
3563 : 0 : return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3564 : : s->sock_proto);
3565 : : }
3566 : :
3567 : : PyDoc_STRVAR(getpeername_doc,
3568 : : "getpeername() -> address info\n\
3569 : : \n\
3570 : : Return the address of the remote endpoint. For IP sockets, the address\n\
3571 : : info is a pair (hostaddr, port).");
3572 : :
3573 : : #endif /* HAVE_GETPEERNAME */
3574 : :
3575 : :
3576 : : #ifdef HAVE_LISTEN
3577 : : /* s.listen(n) method */
3578 : :
3579 : : static PyObject *
3580 : 0 : sock_listen(PySocketSockObject *s, PyObject *args)
3581 : : {
3582 : : /* We try to choose a default backlog high enough to avoid connection drops
3583 : : * for common workloads, yet not too high to limit resource usage. */
3584 : 0 : int backlog = Py_MIN(SOMAXCONN, 128);
3585 : : int res;
3586 : :
3587 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "|i:listen", &backlog))
3588 : 0 : return NULL;
3589 : :
3590 : 0 : Py_BEGIN_ALLOW_THREADS
3591 : : /* To avoid problems on systems that don't allow a negative backlog
3592 : : * (which doesn't make sense anyway) we force a minimum value of 0. */
3593 [ # # ]: 0 : if (backlog < 0)
3594 : 0 : backlog = 0;
3595 : 0 : res = listen(s->sock_fd, backlog);
3596 : 0 : Py_END_ALLOW_THREADS
3597 [ # # ]: 0 : if (res < 0)
3598 : 0 : return s->errorhandler();
3599 : 0 : Py_RETURN_NONE;
3600 : : }
3601 : :
3602 : : PyDoc_STRVAR(listen_doc,
3603 : : "listen([backlog])\n\
3604 : : \n\
3605 : : Enable a server to accept connections. If backlog is specified, it must be\n\
3606 : : at least 0 (if it is lower, it is set to 0); it specifies the number of\n\
3607 : : unaccepted connections that the system will allow before refusing new\n\
3608 : : connections. If not specified, a default reasonable value is chosen.");
3609 : : #endif
3610 : :
3611 : : struct sock_recv {
3612 : : char *cbuf;
3613 : : Py_ssize_t len;
3614 : : int flags;
3615 : : Py_ssize_t result;
3616 : : };
3617 : :
3618 : : static int
3619 : 0 : sock_recv_impl(PySocketSockObject *s, void *data)
3620 : : {
3621 : 0 : struct sock_recv *ctx = data;
3622 : :
3623 : : #ifdef MS_WINDOWS
3624 : : if (ctx->len > INT_MAX)
3625 : : ctx->len = INT_MAX;
3626 : : ctx->result = recv(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags);
3627 : : #else
3628 : 0 : ctx->result = recv(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags);
3629 : : #endif
3630 : 0 : return (ctx->result >= 0);
3631 : : }
3632 : :
3633 : :
3634 : : /*
3635 : : * This is the guts of the recv() and recv_into() methods, which reads into a
3636 : : * char buffer. If you have any inc/dec ref to do to the objects that contain
3637 : : * the buffer, do it in the caller. This function returns the number of bytes
3638 : : * successfully read. If there was an error, it returns -1. Note that it is
3639 : : * also possible that we return a number of bytes smaller than the request
3640 : : * bytes.
3641 : : */
3642 : :
3643 : : static Py_ssize_t
3644 : 0 : sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
3645 : : {
3646 : : struct sock_recv ctx;
3647 : :
3648 : : if (!IS_SELECTABLE(s)) {
3649 : : select_error();
3650 : : return -1;
3651 : : }
3652 [ # # ]: 0 : if (len == 0) {
3653 : : /* If 0 bytes were requested, do nothing. */
3654 : 0 : return 0;
3655 : : }
3656 : :
3657 : 0 : ctx.cbuf = cbuf;
3658 : 0 : ctx.len = len;
3659 : 0 : ctx.flags = flags;
3660 [ # # ]: 0 : if (sock_call(s, 0, sock_recv_impl, &ctx) < 0)
3661 : 0 : return -1;
3662 : :
3663 : 0 : return ctx.result;
3664 : : }
3665 : :
3666 : :
3667 : : /* s.recv(nbytes [,flags]) method */
3668 : :
3669 : : static PyObject *
3670 : 0 : sock_recv(PySocketSockObject *s, PyObject *args)
3671 : : {
3672 : : Py_ssize_t recvlen, outlen;
3673 : 0 : int flags = 0;
3674 : : PyObject *buf;
3675 : :
3676 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
3677 : 0 : return NULL;
3678 : :
3679 [ # # ]: 0 : if (recvlen < 0) {
3680 : 0 : PyErr_SetString(PyExc_ValueError,
3681 : : "negative buffersize in recv");
3682 : 0 : return NULL;
3683 : : }
3684 : :
3685 : : /* Allocate a new string. */
3686 : 0 : buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3687 [ # # ]: 0 : if (buf == NULL)
3688 : 0 : return NULL;
3689 : :
3690 : : /* Call the guts */
3691 : 0 : outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
3692 [ # # ]: 0 : if (outlen < 0) {
3693 : : /* An error occurred, release the string and return an
3694 : : error. */
3695 : 0 : Py_DECREF(buf);
3696 : 0 : return NULL;
3697 : : }
3698 [ # # ]: 0 : if (outlen != recvlen) {
3699 : : /* We did not read as many bytes as we anticipated, resize the
3700 : : string if possible and be successful. */
3701 : 0 : _PyBytes_Resize(&buf, outlen);
3702 : : }
3703 : :
3704 : 0 : return buf;
3705 : : }
3706 : :
3707 : : PyDoc_STRVAR(recv_doc,
3708 : : "recv(buffersize[, flags]) -> data\n\
3709 : : \n\
3710 : : Receive up to buffersize bytes from the socket. For the optional flags\n\
3711 : : argument, see the Unix manual. When no data is available, block until\n\
3712 : : at least one byte is available or until the remote end is closed. When\n\
3713 : : the remote end is closed and all data is read, return the empty string.");
3714 : :
3715 : :
3716 : : /* s.recv_into(buffer, [nbytes [,flags]]) method */
3717 : :
3718 : : static PyObject*
3719 : 0 : sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
3720 : : {
3721 : : static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3722 : :
3723 : 0 : int flags = 0;
3724 : : Py_buffer pbuf;
3725 : : char *buf;
3726 : 0 : Py_ssize_t buflen, readlen, recvlen = 0;
3727 : :
3728 : : /* Get the buffer's memory */
3729 [ # # ]: 0 : if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
3730 : : &pbuf, &recvlen, &flags))
3731 : 0 : return NULL;
3732 : 0 : buf = pbuf.buf;
3733 : 0 : buflen = pbuf.len;
3734 : :
3735 [ # # ]: 0 : if (recvlen < 0) {
3736 : 0 : PyBuffer_Release(&pbuf);
3737 : 0 : PyErr_SetString(PyExc_ValueError,
3738 : : "negative buffersize in recv_into");
3739 : 0 : return NULL;
3740 : : }
3741 [ # # ]: 0 : if (recvlen == 0) {
3742 : : /* If nbytes was not specified, use the buffer's length */
3743 : 0 : recvlen = buflen;
3744 : : }
3745 : :
3746 : : /* Check if the buffer is large enough */
3747 [ # # ]: 0 : if (buflen < recvlen) {
3748 : 0 : PyBuffer_Release(&pbuf);
3749 : 0 : PyErr_SetString(PyExc_ValueError,
3750 : : "buffer too small for requested bytes");
3751 : 0 : return NULL;
3752 : : }
3753 : :
3754 : : /* Call the guts */
3755 : 0 : readlen = sock_recv_guts(s, buf, recvlen, flags);
3756 [ # # ]: 0 : if (readlen < 0) {
3757 : : /* Return an error. */
3758 : 0 : PyBuffer_Release(&pbuf);
3759 : 0 : return NULL;
3760 : : }
3761 : :
3762 : 0 : PyBuffer_Release(&pbuf);
3763 : : /* Return the number of bytes read. Note that we do not do anything
3764 : : special here in the case that readlen < recvlen. */
3765 : 0 : return PyLong_FromSsize_t(readlen);
3766 : : }
3767 : :
3768 : : PyDoc_STRVAR(recv_into_doc,
3769 : : "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
3770 : : \n\
3771 : : A version of recv() that stores its data into a buffer rather than creating\n\
3772 : : a new string. Receive up to buffersize bytes from the socket. If buffersize\n\
3773 : : is not specified (or 0), receive up to the size available in the given buffer.\n\
3774 : : \n\
3775 : : See recv() for documentation about the flags.");
3776 : :
3777 : : struct sock_recvfrom {
3778 : : char* cbuf;
3779 : : Py_ssize_t len;
3780 : : int flags;
3781 : : socklen_t *addrlen;
3782 : : sock_addr_t *addrbuf;
3783 : : Py_ssize_t result;
3784 : : };
3785 : :
3786 : : #ifdef HAVE_RECVFROM
3787 : : static int
3788 : 0 : sock_recvfrom_impl(PySocketSockObject *s, void *data)
3789 : : {
3790 : 0 : struct sock_recvfrom *ctx = data;
3791 : :
3792 : 0 : memset(ctx->addrbuf, 0, *ctx->addrlen);
3793 : :
3794 : : #ifdef MS_WINDOWS
3795 : : if (ctx->len > INT_MAX)
3796 : : ctx->len = INT_MAX;
3797 : : ctx->result = recvfrom(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags,
3798 : : SAS2SA(ctx->addrbuf), ctx->addrlen);
3799 : : #else
3800 : 0 : ctx->result = recvfrom(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags,
3801 : 0 : SAS2SA(ctx->addrbuf), ctx->addrlen);
3802 : : #endif
3803 : 0 : return (ctx->result >= 0);
3804 : : }
3805 : :
3806 : :
3807 : : /*
3808 : : * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
3809 : : * into a char buffer. If you have any inc/def ref to do to the objects that
3810 : : * contain the buffer, do it in the caller. This function returns the number
3811 : : * of bytes successfully read. If there was an error, it returns -1. Note
3812 : : * that it is also possible that we return a number of bytes smaller than the
3813 : : * request bytes.
3814 : : *
3815 : : * 'addr' is a return value for the address object. Note that you must decref
3816 : : * it yourself.
3817 : : */
3818 : : static Py_ssize_t
3819 : 0 : sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
3820 : : PyObject** addr)
3821 : : {
3822 : : sock_addr_t addrbuf;
3823 : : socklen_t addrlen;
3824 : : struct sock_recvfrom ctx;
3825 : :
3826 : 0 : *addr = NULL;
3827 : :
3828 [ # # ]: 0 : if (!getsockaddrlen(s, &addrlen))
3829 : 0 : return -1;
3830 : :
3831 : : if (!IS_SELECTABLE(s)) {
3832 : : select_error();
3833 : : return -1;
3834 : : }
3835 : :
3836 : 0 : ctx.cbuf = cbuf;
3837 : 0 : ctx.len = len;
3838 : 0 : ctx.flags = flags;
3839 : 0 : ctx.addrbuf = &addrbuf;
3840 : 0 : ctx.addrlen = &addrlen;
3841 [ # # ]: 0 : if (sock_call(s, 0, sock_recvfrom_impl, &ctx) < 0)
3842 : 0 : return -1;
3843 : :
3844 : 0 : *addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
3845 : : s->sock_proto);
3846 [ # # ]: 0 : if (*addr == NULL)
3847 : 0 : return -1;
3848 : :
3849 : 0 : return ctx.result;
3850 : : }
3851 : :
3852 : : /* s.recvfrom(nbytes [,flags]) method */
3853 : :
3854 : : static PyObject *
3855 : 0 : sock_recvfrom(PySocketSockObject *s, PyObject *args)
3856 : : {
3857 : 0 : PyObject *buf = NULL;
3858 : 0 : PyObject *addr = NULL;
3859 : 0 : PyObject *ret = NULL;
3860 : 0 : int flags = 0;
3861 : : Py_ssize_t recvlen, outlen;
3862 : :
3863 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
3864 : 0 : return NULL;
3865 : :
3866 [ # # ]: 0 : if (recvlen < 0) {
3867 : 0 : PyErr_SetString(PyExc_ValueError,
3868 : : "negative buffersize in recvfrom");
3869 : 0 : return NULL;
3870 : : }
3871 : :
3872 : 0 : buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
3873 [ # # ]: 0 : if (buf == NULL)
3874 : 0 : return NULL;
3875 : :
3876 : 0 : outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
3877 : : recvlen, flags, &addr);
3878 [ # # ]: 0 : if (outlen < 0) {
3879 : 0 : goto finally;
3880 : : }
3881 : :
3882 [ # # ]: 0 : if (outlen != recvlen) {
3883 : : /* We did not read as many bytes as we anticipated, resize the
3884 : : string if possible and be successful. */
3885 [ # # ]: 0 : if (_PyBytes_Resize(&buf, outlen) < 0)
3886 : : /* Oopsy, not so successful after all. */
3887 : 0 : goto finally;
3888 : : }
3889 : :
3890 : 0 : ret = PyTuple_Pack(2, buf, addr);
3891 : :
3892 : 0 : finally:
3893 : 0 : Py_XDECREF(buf);
3894 : 0 : Py_XDECREF(addr);
3895 : 0 : return ret;
3896 : : }
3897 : :
3898 : : PyDoc_STRVAR(recvfrom_doc,
3899 : : "recvfrom(buffersize[, flags]) -> (data, address info)\n\
3900 : : \n\
3901 : : Like recv(buffersize, flags) but also return the sender's address info.");
3902 : :
3903 : :
3904 : : /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
3905 : :
3906 : : static PyObject *
3907 : 0 : sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
3908 : : {
3909 : : static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
3910 : :
3911 : 0 : int flags = 0;
3912 : : Py_buffer pbuf;
3913 : : char *buf;
3914 : 0 : Py_ssize_t readlen, buflen, recvlen = 0;
3915 : :
3916 : 0 : PyObject *addr = NULL;
3917 : :
3918 [ # # ]: 0 : if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
3919 : : kwlist, &pbuf,
3920 : : &recvlen, &flags))
3921 : 0 : return NULL;
3922 : 0 : buf = pbuf.buf;
3923 : 0 : buflen = pbuf.len;
3924 : :
3925 [ # # ]: 0 : if (recvlen < 0) {
3926 : 0 : PyBuffer_Release(&pbuf);
3927 : 0 : PyErr_SetString(PyExc_ValueError,
3928 : : "negative buffersize in recvfrom_into");
3929 : 0 : return NULL;
3930 : : }
3931 [ # # ]: 0 : if (recvlen == 0) {
3932 : : /* If nbytes was not specified, use the buffer's length */
3933 : 0 : recvlen = buflen;
3934 [ # # ]: 0 : } else if (recvlen > buflen) {
3935 : 0 : PyBuffer_Release(&pbuf);
3936 : 0 : PyErr_SetString(PyExc_ValueError,
3937 : : "nbytes is greater than the length of the buffer");
3938 : 0 : return NULL;
3939 : : }
3940 : :
3941 : 0 : readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
3942 [ # # ]: 0 : if (readlen < 0) {
3943 : 0 : PyBuffer_Release(&pbuf);
3944 : : /* Return an error */
3945 : 0 : Py_XDECREF(addr);
3946 : 0 : return NULL;
3947 : : }
3948 : :
3949 : 0 : PyBuffer_Release(&pbuf);
3950 : : /* Return the number of bytes read and the address. Note that we do
3951 : : not do anything special here in the case that readlen < recvlen. */
3952 : 0 : return Py_BuildValue("nN", readlen, addr);
3953 : : }
3954 : :
3955 : : PyDoc_STRVAR(recvfrom_into_doc,
3956 : : "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
3957 : : \n\
3958 : : Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
3959 : : #endif
3960 : :
3961 : : /* The sendmsg() and recvmsg[_into]() methods require a working
3962 : : CMSG_LEN(). See the comment near get_CMSG_LEN(). */
3963 : : #ifdef CMSG_LEN
3964 : : struct sock_recvmsg {
3965 : : struct msghdr *msg;
3966 : : int flags;
3967 : : ssize_t result;
3968 : : };
3969 : :
3970 : : static int
3971 : 0 : sock_recvmsg_impl(PySocketSockObject *s, void *data)
3972 : : {
3973 : 0 : struct sock_recvmsg *ctx = data;
3974 : :
3975 : 0 : ctx->result = recvmsg(s->sock_fd, ctx->msg, ctx->flags);
3976 : 0 : return (ctx->result >= 0);
3977 : : }
3978 : :
3979 : : /*
3980 : : * Call recvmsg() with the supplied iovec structures, flags, and
3981 : : * ancillary data buffer size (controllen). Returns the tuple return
3982 : : * value for recvmsg() or recvmsg_into(), with the first item provided
3983 : : * by the supplied makeval() function. makeval() will be called with
3984 : : * the length read and makeval_data as arguments, and must return a
3985 : : * new reference (which will be decrefed if there is a subsequent
3986 : : * error). On error, closes any file descriptors received via
3987 : : * SCM_RIGHTS.
3988 : : */
3989 : : static PyObject *
3990 : 0 : sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
3991 : : int flags, Py_ssize_t controllen,
3992 : : PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
3993 : : {
3994 : : sock_addr_t addrbuf;
3995 : : socklen_t addrbuflen;
3996 : 0 : struct msghdr msg = {0};
3997 : 0 : PyObject *cmsg_list = NULL, *retval = NULL;
3998 : 0 : void *controlbuf = NULL;
3999 : : struct cmsghdr *cmsgh;
4000 : 0 : size_t cmsgdatalen = 0;
4001 : : int cmsg_status;
4002 : : struct sock_recvmsg ctx;
4003 : :
4004 : : /* XXX: POSIX says that msg_name and msg_namelen "shall be
4005 : : ignored" when the socket is connected (Linux fills them in
4006 : : anyway for AF_UNIX sockets at least). Normally msg_namelen
4007 : : seems to be set to 0 if there's no address, but try to
4008 : : initialize msg_name to something that won't be mistaken for a
4009 : : real address if that doesn't happen. */
4010 [ # # ]: 0 : if (!getsockaddrlen(s, &addrbuflen))
4011 : 0 : return NULL;
4012 : 0 : memset(&addrbuf, 0, addrbuflen);
4013 : 0 : SAS2SA(&addrbuf)->sa_family = AF_UNSPEC;
4014 : :
4015 [ # # # # ]: 0 : if (controllen < 0 || controllen > SOCKLEN_T_LIMIT) {
4016 : 0 : PyErr_SetString(PyExc_ValueError,
4017 : : "invalid ancillary data buffer length");
4018 : 0 : return NULL;
4019 : : }
4020 [ # # # # ]: 0 : if (controllen > 0 && (controlbuf = PyMem_Malloc(controllen)) == NULL)
4021 : 0 : return PyErr_NoMemory();
4022 : :
4023 : : /* Make the system call. */
4024 : : if (!IS_SELECTABLE(s)) {
4025 : : select_error();
4026 : : goto finally;
4027 : : }
4028 : :
4029 : 0 : msg.msg_name = SAS2SA(&addrbuf);
4030 : 0 : msg.msg_namelen = addrbuflen;
4031 : 0 : msg.msg_iov = iov;
4032 : 0 : msg.msg_iovlen = iovlen;
4033 : 0 : msg.msg_control = controlbuf;
4034 : 0 : msg.msg_controllen = controllen;
4035 : :
4036 : 0 : ctx.msg = &msg;
4037 : 0 : ctx.flags = flags;
4038 [ # # ]: 0 : if (sock_call(s, 0, sock_recvmsg_impl, &ctx) < 0)
4039 : 0 : goto finally;
4040 : :
4041 : : /* Make list of (level, type, data) tuples from control messages. */
4042 [ # # ]: 0 : if ((cmsg_list = PyList_New(0)) == NULL)
4043 : 0 : goto err_closefds;
4044 : : /* Check for empty ancillary data as old CMSG_FIRSTHDR()
4045 : : implementations didn't do so. */
4046 [ # # # # : 0 : for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
# # ]
4047 : 0 : cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
4048 : : PyObject *bytes, *tuple;
4049 : : int tmp;
4050 : :
4051 : 0 : cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
4052 [ # # ]: 0 : if (cmsg_status != 0) {
4053 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_RuntimeWarning,
4054 : : "received malformed or improperly-truncated "
4055 : : "ancillary data", 1) == -1)
4056 : 0 : goto err_closefds;
4057 : : }
4058 [ # # ]: 0 : if (cmsg_status < 0)
4059 : 0 : break;
4060 [ # # ]: 0 : if (cmsgdatalen > PY_SSIZE_T_MAX) {
4061 : 0 : PyErr_SetString(PyExc_OSError, "control message too long");
4062 : 0 : goto err_closefds;
4063 : : }
4064 : :
4065 : 0 : bytes = PyBytes_FromStringAndSize((char *)CMSG_DATA(cmsgh),
4066 : : cmsgdatalen);
4067 : 0 : tuple = Py_BuildValue("iiN", (int)cmsgh->cmsg_level,
4068 : : (int)cmsgh->cmsg_type, bytes);
4069 [ # # ]: 0 : if (tuple == NULL)
4070 : 0 : goto err_closefds;
4071 : 0 : tmp = PyList_Append(cmsg_list, tuple);
4072 : 0 : Py_DECREF(tuple);
4073 [ # # ]: 0 : if (tmp != 0)
4074 : 0 : goto err_closefds;
4075 : :
4076 [ # # ]: 0 : if (cmsg_status != 0)
4077 : 0 : break;
4078 : : }
4079 : :
4080 : 0 : retval = Py_BuildValue("NOiN",
4081 : : (*makeval)(ctx.result, makeval_data),
4082 : : cmsg_list,
4083 : : (int)msg.msg_flags,
4084 : : makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
4085 : 0 : ((msg.msg_namelen > addrbuflen) ?
4086 : 0 : addrbuflen : msg.msg_namelen),
4087 : : s->sock_proto));
4088 [ # # ]: 0 : if (retval == NULL)
4089 : 0 : goto err_closefds;
4090 : :
4091 : 0 : finally:
4092 : 0 : Py_XDECREF(cmsg_list);
4093 : 0 : PyMem_Free(controlbuf);
4094 : 0 : return retval;
4095 : :
4096 : 0 : err_closefds:
4097 : : #ifdef SCM_RIGHTS
4098 : : /* Close all descriptors coming from SCM_RIGHTS, so they don't leak. */
4099 [ # # # # : 0 : for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
# # ]
4100 : 0 : cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
4101 : 0 : cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
4102 [ # # ]: 0 : if (cmsg_status < 0)
4103 : 0 : break;
4104 [ # # ]: 0 : if (cmsgh->cmsg_level == SOL_SOCKET &&
4105 [ # # ]: 0 : cmsgh->cmsg_type == SCM_RIGHTS) {
4106 : : size_t numfds;
4107 : : int *fdp;
4108 : :
4109 : 0 : numfds = cmsgdatalen / sizeof(int);
4110 : 0 : fdp = (int *)CMSG_DATA(cmsgh);
4111 [ # # ]: 0 : while (numfds-- > 0)
4112 : 0 : close(*fdp++);
4113 : : }
4114 [ # # ]: 0 : if (cmsg_status != 0)
4115 : 0 : break;
4116 : : }
4117 : : #endif /* SCM_RIGHTS */
4118 : 0 : goto finally;
4119 : : }
4120 : :
4121 : :
4122 : : static PyObject *
4123 : 0 : makeval_recvmsg(ssize_t received, void *data)
4124 : : {
4125 : 0 : PyObject **buf = data;
4126 : :
4127 [ # # ]: 0 : if (received < PyBytes_GET_SIZE(*buf))
4128 : 0 : _PyBytes_Resize(buf, received);
4129 : 0 : return Py_XNewRef(*buf);
4130 : : }
4131 : :
4132 : : /* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */
4133 : :
4134 : : static PyObject *
4135 : 0 : sock_recvmsg(PySocketSockObject *s, PyObject *args)
4136 : : {
4137 : 0 : Py_ssize_t bufsize, ancbufsize = 0;
4138 : 0 : int flags = 0;
4139 : : struct iovec iov;
4140 : 0 : PyObject *buf = NULL, *retval = NULL;
4141 : :
4142 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "n|ni:recvmsg", &bufsize, &ancbufsize, &flags))
4143 : 0 : return NULL;
4144 : :
4145 [ # # ]: 0 : if (bufsize < 0) {
4146 : 0 : PyErr_SetString(PyExc_ValueError, "negative buffer size in recvmsg()");
4147 : 0 : return NULL;
4148 : : }
4149 [ # # ]: 0 : if ((buf = PyBytes_FromStringAndSize(NULL, bufsize)) == NULL)
4150 : 0 : return NULL;
4151 : 0 : iov.iov_base = PyBytes_AS_STRING(buf);
4152 : 0 : iov.iov_len = bufsize;
4153 : :
4154 : : /* Note that we're passing a pointer to *our pointer* to the bytes
4155 : : object here (&buf); makeval_recvmsg() may incref the object, or
4156 : : deallocate it and set our pointer to NULL. */
4157 : 0 : retval = sock_recvmsg_guts(s, &iov, 1, flags, ancbufsize,
4158 : : &makeval_recvmsg, &buf);
4159 : 0 : Py_XDECREF(buf);
4160 : 0 : return retval;
4161 : : }
4162 : :
4163 : : PyDoc_STRVAR(recvmsg_doc,
4164 : : "recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
4165 : : \n\
4166 : : Receive normal data (up to bufsize bytes) and ancillary data from the\n\
4167 : : socket. The ancbufsize argument sets the size in bytes of the\n\
4168 : : internal buffer used to receive the ancillary data; it defaults to 0,\n\
4169 : : meaning that no ancillary data will be received. Appropriate buffer\n\
4170 : : sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
4171 : : CMSG_LEN(), and items which do not fit into the buffer might be\n\
4172 : : truncated or discarded. The flags argument defaults to 0 and has the\n\
4173 : : same meaning as for recv().\n\
4174 : : \n\
4175 : : The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
4176 : : The data item is a bytes object holding the non-ancillary data\n\
4177 : : received. The ancdata item is a list of zero or more tuples\n\
4178 : : (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
4179 : : (control messages) received: cmsg_level and cmsg_type are integers\n\
4180 : : specifying the protocol level and protocol-specific type respectively,\n\
4181 : : and cmsg_data is a bytes object holding the associated data. The\n\
4182 : : msg_flags item is the bitwise OR of various flags indicating\n\
4183 : : conditions on the received message; see your system documentation for\n\
4184 : : details. If the receiving socket is unconnected, address is the\n\
4185 : : address of the sending socket, if available; otherwise, its value is\n\
4186 : : unspecified.\n\
4187 : : \n\
4188 : : If recvmsg() raises an exception after the system call returns, it\n\
4189 : : will first attempt to close any file descriptors received via the\n\
4190 : : SCM_RIGHTS mechanism.");
4191 : :
4192 : :
4193 : : static PyObject *
4194 : 0 : makeval_recvmsg_into(ssize_t received, void *data)
4195 : : {
4196 : 0 : return PyLong_FromSsize_t(received);
4197 : : }
4198 : :
4199 : : /* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */
4200 : :
4201 : : static PyObject *
4202 : 0 : sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
4203 : : {
4204 : 0 : Py_ssize_t ancbufsize = 0;
4205 : 0 : int flags = 0;
4206 : 0 : struct iovec *iovs = NULL;
4207 : 0 : Py_ssize_t i, nitems, nbufs = 0;
4208 : 0 : Py_buffer *bufs = NULL;
4209 : 0 : PyObject *buffers_arg, *fast, *retval = NULL;
4210 : :
4211 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O|ni:recvmsg_into",
4212 : : &buffers_arg, &ancbufsize, &flags))
4213 : 0 : return NULL;
4214 : :
4215 [ # # ]: 0 : if ((fast = PySequence_Fast(buffers_arg,
4216 : : "recvmsg_into() argument 1 must be an "
4217 : : "iterable")) == NULL)
4218 : 0 : return NULL;
4219 [ # # ]: 0 : nitems = PySequence_Fast_GET_SIZE(fast);
4220 [ # # ]: 0 : if (nitems > INT_MAX) {
4221 : 0 : PyErr_SetString(PyExc_OSError, "recvmsg_into() argument 1 is too long");
4222 : 0 : goto finally;
4223 : : }
4224 : :
4225 : : /* Fill in an iovec for each item, and save the Py_buffer
4226 : : structs to release afterwards. */
4227 [ # # # # : 0 : if (nitems > 0 && ((iovs = PyMem_New(struct iovec, nitems)) == NULL ||
# # ]
4228 [ # # # # ]: 0 : (bufs = PyMem_New(Py_buffer, nitems)) == NULL)) {
4229 : 0 : PyErr_NoMemory();
4230 : 0 : goto finally;
4231 : : }
4232 [ # # ]: 0 : for (; nbufs < nitems; nbufs++) {
4233 [ # # # # ]: 0 : if (!PyArg_Parse(PySequence_Fast_GET_ITEM(fast, nbufs),
4234 : : "w*;recvmsg_into() argument 1 must be an iterable "
4235 : : "of single-segment read-write buffers",
4236 : 0 : &bufs[nbufs]))
4237 : 0 : goto finally;
4238 : 0 : iovs[nbufs].iov_base = bufs[nbufs].buf;
4239 : 0 : iovs[nbufs].iov_len = bufs[nbufs].len;
4240 : : }
4241 : :
4242 : 0 : retval = sock_recvmsg_guts(s, iovs, nitems, flags, ancbufsize,
4243 : : &makeval_recvmsg_into, NULL);
4244 : 0 : finally:
4245 [ # # ]: 0 : for (i = 0; i < nbufs; i++)
4246 : 0 : PyBuffer_Release(&bufs[i]);
4247 : 0 : PyMem_Free(bufs);
4248 : 0 : PyMem_Free(iovs);
4249 : 0 : Py_DECREF(fast);
4250 : 0 : return retval;
4251 : : }
4252 : :
4253 : : PyDoc_STRVAR(recvmsg_into_doc,
4254 : : "recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
4255 : : \n\
4256 : : Receive normal data and ancillary data from the socket, scattering the\n\
4257 : : non-ancillary data into a series of buffers. The buffers argument\n\
4258 : : must be an iterable of objects that export writable buffers\n\
4259 : : (e.g. bytearray objects); these will be filled with successive chunks\n\
4260 : : of the non-ancillary data until it has all been written or there are\n\
4261 : : no more buffers. The ancbufsize argument sets the size in bytes of\n\
4262 : : the internal buffer used to receive the ancillary data; it defaults to\n\
4263 : : 0, meaning that no ancillary data will be received. Appropriate\n\
4264 : : buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
4265 : : or CMSG_LEN(), and items which do not fit into the buffer might be\n\
4266 : : truncated or discarded. The flags argument defaults to 0 and has the\n\
4267 : : same meaning as for recv().\n\
4268 : : \n\
4269 : : The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
4270 : : The nbytes item is the total number of bytes of non-ancillary data\n\
4271 : : written into the buffers. The ancdata item is a list of zero or more\n\
4272 : : tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
4273 : : data (control messages) received: cmsg_level and cmsg_type are\n\
4274 : : integers specifying the protocol level and protocol-specific type\n\
4275 : : respectively, and cmsg_data is a bytes object holding the associated\n\
4276 : : data. The msg_flags item is the bitwise OR of various flags\n\
4277 : : indicating conditions on the received message; see your system\n\
4278 : : documentation for details. If the receiving socket is unconnected,\n\
4279 : : address is the address of the sending socket, if available; otherwise,\n\
4280 : : its value is unspecified.\n\
4281 : : \n\
4282 : : If recvmsg_into() raises an exception after the system call returns,\n\
4283 : : it will first attempt to close any file descriptors received via the\n\
4284 : : SCM_RIGHTS mechanism.");
4285 : : #endif /* CMSG_LEN */
4286 : :
4287 : :
4288 : : struct sock_send {
4289 : : char *buf;
4290 : : Py_ssize_t len;
4291 : : int flags;
4292 : : Py_ssize_t result;
4293 : : };
4294 : :
4295 : : static int
4296 : 0 : sock_send_impl(PySocketSockObject *s, void *data)
4297 : : {
4298 : 0 : struct sock_send *ctx = data;
4299 : :
4300 : : #ifdef MS_WINDOWS
4301 : : if (ctx->len > INT_MAX)
4302 : : ctx->len = INT_MAX;
4303 : : ctx->result = send(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags);
4304 : : #else
4305 : 0 : ctx->result = send(s->sock_fd, ctx->buf, ctx->len, ctx->flags);
4306 : : #endif
4307 : 0 : return (ctx->result >= 0);
4308 : : }
4309 : :
4310 : : /* s.send(data [,flags]) method */
4311 : :
4312 : : static PyObject *
4313 : 0 : sock_send(PySocketSockObject *s, PyObject *args)
4314 : : {
4315 : 0 : int flags = 0;
4316 : : Py_buffer pbuf;
4317 : : struct sock_send ctx;
4318 : :
4319 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
4320 : 0 : return NULL;
4321 : :
4322 : : if (!IS_SELECTABLE(s)) {
4323 : : PyBuffer_Release(&pbuf);
4324 : : return select_error();
4325 : : }
4326 : 0 : ctx.buf = pbuf.buf;
4327 : 0 : ctx.len = pbuf.len;
4328 : 0 : ctx.flags = flags;
4329 [ # # ]: 0 : if (sock_call(s, 1, sock_send_impl, &ctx) < 0) {
4330 : 0 : PyBuffer_Release(&pbuf);
4331 : 0 : return NULL;
4332 : : }
4333 : 0 : PyBuffer_Release(&pbuf);
4334 : :
4335 : 0 : return PyLong_FromSsize_t(ctx.result);
4336 : : }
4337 : :
4338 : : PyDoc_STRVAR(send_doc,
4339 : : "send(data[, flags]) -> count\n\
4340 : : \n\
4341 : : Send a data string to the socket. For the optional flags\n\
4342 : : argument, see the Unix manual. Return the number of bytes\n\
4343 : : sent; this may be less than len(data) if the network is busy.");
4344 : :
4345 : :
4346 : : /* s.sendall(data [,flags]) method */
4347 : :
4348 : : static PyObject *
4349 : 0 : sock_sendall(PySocketSockObject *s, PyObject *args)
4350 : : {
4351 : : char *buf;
4352 : : Py_ssize_t len, n;
4353 : 0 : int flags = 0;
4354 : : Py_buffer pbuf;
4355 : : struct sock_send ctx;
4356 : 0 : int has_timeout = (s->sock_timeout > 0);
4357 : 0 : _PyTime_t timeout = s->sock_timeout;
4358 : 0 : _PyTime_t deadline = 0;
4359 : 0 : int deadline_initialized = 0;
4360 : 0 : PyObject *res = NULL;
4361 : :
4362 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
4363 : 0 : return NULL;
4364 : 0 : buf = pbuf.buf;
4365 : 0 : len = pbuf.len;
4366 : :
4367 : : if (!IS_SELECTABLE(s)) {
4368 : : PyBuffer_Release(&pbuf);
4369 : : return select_error();
4370 : : }
4371 : :
4372 : : do {
4373 [ # # ]: 0 : if (has_timeout) {
4374 [ # # ]: 0 : if (deadline_initialized) {
4375 : : /* recompute the timeout */
4376 : 0 : timeout = _PyDeadline_Get(deadline);
4377 : : }
4378 : : else {
4379 : 0 : deadline_initialized = 1;
4380 : 0 : deadline = _PyDeadline_Init(timeout);
4381 : : }
4382 : :
4383 [ # # ]: 0 : if (timeout <= 0) {
4384 : 0 : PyErr_SetString(PyExc_TimeoutError, "timed out");
4385 : 0 : goto done;
4386 : : }
4387 : : }
4388 : :
4389 : 0 : ctx.buf = buf;
4390 : 0 : ctx.len = len;
4391 : 0 : ctx.flags = flags;
4392 [ # # ]: 0 : if (sock_call_ex(s, 1, sock_send_impl, &ctx, 0, NULL, timeout) < 0)
4393 : 0 : goto done;
4394 : 0 : n = ctx.result;
4395 : : assert(n >= 0);
4396 : :
4397 : 0 : buf += n;
4398 : 0 : len -= n;
4399 : :
4400 : : /* We must run our signal handlers before looping again.
4401 : : send() can return a successful partial write when it is
4402 : : interrupted, so we can't restrict ourselves to EINTR. */
4403 [ # # ]: 0 : if (PyErr_CheckSignals())
4404 : 0 : goto done;
4405 [ # # ]: 0 : } while (len > 0);
4406 : 0 : PyBuffer_Release(&pbuf);
4407 : :
4408 : 0 : res = Py_NewRef(Py_None);
4409 : :
4410 : 0 : done:
4411 : 0 : PyBuffer_Release(&pbuf);
4412 : 0 : return res;
4413 : : }
4414 : :
4415 : : PyDoc_STRVAR(sendall_doc,
4416 : : "sendall(data[, flags])\n\
4417 : : \n\
4418 : : Send a data string to the socket. For the optional flags\n\
4419 : : argument, see the Unix manual. This calls send() repeatedly\n\
4420 : : until all data is sent. If an error occurs, it's impossible\n\
4421 : : to tell how much data has been sent.");
4422 : :
4423 : :
4424 : : #ifdef HAVE_SENDTO
4425 : : struct sock_sendto {
4426 : : char *buf;
4427 : : Py_ssize_t len;
4428 : : int flags;
4429 : : int addrlen;
4430 : : sock_addr_t *addrbuf;
4431 : : Py_ssize_t result;
4432 : : };
4433 : :
4434 : : static int
4435 : 0 : sock_sendto_impl(PySocketSockObject *s, void *data)
4436 : : {
4437 : 0 : struct sock_sendto *ctx = data;
4438 : :
4439 : : #ifdef MS_WINDOWS
4440 : : if (ctx->len > INT_MAX)
4441 : : ctx->len = INT_MAX;
4442 : : ctx->result = sendto(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags,
4443 : : SAS2SA(ctx->addrbuf), ctx->addrlen);
4444 : : #else
4445 : 0 : ctx->result = sendto(s->sock_fd, ctx->buf, ctx->len, ctx->flags,
4446 : 0 : SAS2SA(ctx->addrbuf), ctx->addrlen);
4447 : : #endif
4448 : 0 : return (ctx->result >= 0);
4449 : : }
4450 : :
4451 : : /* s.sendto(data, [flags,] sockaddr) method */
4452 : :
4453 : : static PyObject *
4454 : 0 : sock_sendto(PySocketSockObject *s, PyObject *args)
4455 : : {
4456 : : Py_buffer pbuf;
4457 : : PyObject *addro;
4458 : : Py_ssize_t arglen;
4459 : : sock_addr_t addrbuf;
4460 : : int addrlen, flags;
4461 : : struct sock_sendto ctx;
4462 : :
4463 : 0 : flags = 0;
4464 : 0 : arglen = PyTuple_Size(args);
4465 [ # # # ]: 0 : switch (arglen) {
4466 : 0 : case 2:
4467 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
4468 : 0 : return NULL;
4469 : : }
4470 : 0 : break;
4471 : 0 : case 3:
4472 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "y*iO:sendto",
4473 : : &pbuf, &flags, &addro)) {
4474 : 0 : return NULL;
4475 : : }
4476 : 0 : break;
4477 : 0 : default:
4478 : 0 : PyErr_Format(PyExc_TypeError,
4479 : : "sendto() takes 2 or 3 arguments (%zd given)",
4480 : : arglen);
4481 : 0 : return NULL;
4482 : : }
4483 : :
4484 : : if (!IS_SELECTABLE(s)) {
4485 : : PyBuffer_Release(&pbuf);
4486 : : return select_error();
4487 : : }
4488 : :
4489 [ # # ]: 0 : if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "sendto")) {
4490 : 0 : PyBuffer_Release(&pbuf);
4491 : 0 : return NULL;
4492 : : }
4493 : :
4494 [ # # ]: 0 : if (PySys_Audit("socket.sendto", "OO", s, addro) < 0) {
4495 : 0 : return NULL;
4496 : : }
4497 : :
4498 : 0 : ctx.buf = pbuf.buf;
4499 : 0 : ctx.len = pbuf.len;
4500 : 0 : ctx.flags = flags;
4501 : 0 : ctx.addrlen = addrlen;
4502 : 0 : ctx.addrbuf = &addrbuf;
4503 [ # # ]: 0 : if (sock_call(s, 1, sock_sendto_impl, &ctx) < 0) {
4504 : 0 : PyBuffer_Release(&pbuf);
4505 : 0 : return NULL;
4506 : : }
4507 : 0 : PyBuffer_Release(&pbuf);
4508 : :
4509 : 0 : return PyLong_FromSsize_t(ctx.result);
4510 : : }
4511 : :
4512 : : PyDoc_STRVAR(sendto_doc,
4513 : : "sendto(data[, flags], address) -> count\n\
4514 : : \n\
4515 : : Like send(data, flags) but allows specifying the destination address.\n\
4516 : : For IP sockets, the address is a pair (hostaddr, port).");
4517 : : #endif
4518 : :
4519 : :
4520 : : /* The sendmsg() and recvmsg[_into]() methods require a working
4521 : : CMSG_LEN(). See the comment near get_CMSG_LEN(). */
4522 : : #ifdef CMSG_LEN
4523 : : struct sock_sendmsg {
4524 : : struct msghdr *msg;
4525 : : int flags;
4526 : : ssize_t result;
4527 : : };
4528 : :
4529 : : static int
4530 : 0 : sock_sendmsg_iovec(PySocketSockObject *s, PyObject *data_arg,
4531 : : struct msghdr *msg,
4532 : : Py_buffer **databufsout, Py_ssize_t *ndatabufsout) {
4533 : 0 : Py_ssize_t ndataparts, ndatabufs = 0;
4534 : 0 : int result = -1;
4535 : 0 : struct iovec *iovs = NULL;
4536 : 0 : PyObject *data_fast = NULL;
4537 : 0 : Py_buffer *databufs = NULL;
4538 : :
4539 : : /* Fill in an iovec for each message part, and save the Py_buffer
4540 : : structs to release afterwards. */
4541 : 0 : data_fast = PySequence_Fast(data_arg,
4542 : : "sendmsg() argument 1 must be an "
4543 : : "iterable");
4544 [ # # ]: 0 : if (data_fast == NULL) {
4545 : 0 : goto finally;
4546 : : }
4547 : :
4548 [ # # ]: 0 : ndataparts = PySequence_Fast_GET_SIZE(data_fast);
4549 [ # # ]: 0 : if (ndataparts > INT_MAX) {
4550 : 0 : PyErr_SetString(PyExc_OSError, "sendmsg() argument 1 is too long");
4551 : 0 : goto finally;
4552 : : }
4553 : :
4554 : 0 : msg->msg_iovlen = ndataparts;
4555 [ # # ]: 0 : if (ndataparts > 0) {
4556 [ # # ]: 0 : iovs = PyMem_New(struct iovec, ndataparts);
4557 [ # # ]: 0 : if (iovs == NULL) {
4558 : 0 : PyErr_NoMemory();
4559 : 0 : goto finally;
4560 : : }
4561 : 0 : msg->msg_iov = iovs;
4562 : :
4563 [ # # ]: 0 : databufs = PyMem_New(Py_buffer, ndataparts);
4564 [ # # ]: 0 : if (databufs == NULL) {
4565 : 0 : PyErr_NoMemory();
4566 : 0 : goto finally;
4567 : : }
4568 : : }
4569 [ # # ]: 0 : for (; ndatabufs < ndataparts; ndatabufs++) {
4570 [ # # # # ]: 0 : if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, ndatabufs),
4571 : : "y*;sendmsg() argument 1 must be an iterable of "
4572 : : "bytes-like objects",
4573 : 0 : &databufs[ndatabufs]))
4574 : 0 : goto finally;
4575 : 0 : iovs[ndatabufs].iov_base = databufs[ndatabufs].buf;
4576 : 0 : iovs[ndatabufs].iov_len = databufs[ndatabufs].len;
4577 : : }
4578 : 0 : result = 0;
4579 : 0 : finally:
4580 : 0 : *databufsout = databufs;
4581 : 0 : *ndatabufsout = ndatabufs;
4582 : 0 : Py_XDECREF(data_fast);
4583 : 0 : return result;
4584 : : }
4585 : :
4586 : : static int
4587 : 0 : sock_sendmsg_impl(PySocketSockObject *s, void *data)
4588 : : {
4589 : 0 : struct sock_sendmsg *ctx = data;
4590 : :
4591 : 0 : ctx->result = sendmsg(s->sock_fd, ctx->msg, ctx->flags);
4592 : 0 : return (ctx->result >= 0);
4593 : : }
4594 : :
4595 : : /* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */
4596 : :
4597 : : static PyObject *
4598 : 0 : sock_sendmsg(PySocketSockObject *s, PyObject *args)
4599 : : {
4600 : 0 : Py_ssize_t i, ndatabufs = 0, ncmsgs, ncmsgbufs = 0;
4601 : 0 : Py_buffer *databufs = NULL;
4602 : : sock_addr_t addrbuf;
4603 : : struct msghdr msg;
4604 : : struct cmsginfo {
4605 : : int level;
4606 : : int type;
4607 : : Py_buffer data;
4608 : 0 : } *cmsgs = NULL;
4609 : 0 : void *controlbuf = NULL;
4610 : : size_t controllen, controllen_last;
4611 : 0 : int addrlen, flags = 0;
4612 : 0 : PyObject *data_arg, *cmsg_arg = NULL, *addr_arg = NULL,
4613 : 0 : *cmsg_fast = NULL, *retval = NULL;
4614 : : struct sock_sendmsg ctx;
4615 : :
4616 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O|OiO:sendmsg",
4617 : : &data_arg, &cmsg_arg, &flags, &addr_arg)) {
4618 : 0 : return NULL;
4619 : : }
4620 : :
4621 : 0 : memset(&msg, 0, sizeof(msg));
4622 : :
4623 : : /* Parse destination address. */
4624 [ # # # # ]: 0 : if (addr_arg != NULL && addr_arg != Py_None) {
4625 [ # # ]: 0 : if (!getsockaddrarg(s, addr_arg, &addrbuf, &addrlen,
4626 : : "sendmsg"))
4627 : : {
4628 : 0 : goto finally;
4629 : : }
4630 [ # # ]: 0 : if (PySys_Audit("socket.sendmsg", "OO", s, addr_arg) < 0) {
4631 : 0 : return NULL;
4632 : : }
4633 : 0 : msg.msg_name = &addrbuf;
4634 : 0 : msg.msg_namelen = addrlen;
4635 : : } else {
4636 [ # # ]: 0 : if (PySys_Audit("socket.sendmsg", "OO", s, Py_None) < 0) {
4637 : 0 : return NULL;
4638 : : }
4639 : : }
4640 : :
4641 : : /* Fill in an iovec for each message part, and save the Py_buffer
4642 : : structs to release afterwards. */
4643 [ # # ]: 0 : if (sock_sendmsg_iovec(s, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4644 : 0 : goto finally;
4645 : : }
4646 : :
4647 [ # # ]: 0 : if (cmsg_arg == NULL)
4648 : 0 : ncmsgs = 0;
4649 : : else {
4650 [ # # ]: 0 : if ((cmsg_fast = PySequence_Fast(cmsg_arg,
4651 : : "sendmsg() argument 2 must be an "
4652 : : "iterable")) == NULL)
4653 : 0 : goto finally;
4654 [ # # ]: 0 : ncmsgs = PySequence_Fast_GET_SIZE(cmsg_fast);
4655 : : }
4656 : :
4657 : : #ifndef CMSG_SPACE
4658 : : if (ncmsgs > 1) {
4659 : : PyErr_SetString(PyExc_OSError,
4660 : : "sending multiple control messages is not supported "
4661 : : "on this system");
4662 : : goto finally;
4663 : : }
4664 : : #endif
4665 : : /* Save level, type and Py_buffer for each control message,
4666 : : and calculate total size. */
4667 [ # # # # : 0 : if (ncmsgs > 0 && (cmsgs = PyMem_New(struct cmsginfo, ncmsgs)) == NULL) {
# # ]
4668 : 0 : PyErr_NoMemory();
4669 : 0 : goto finally;
4670 : : }
4671 : 0 : controllen = controllen_last = 0;
4672 [ # # ]: 0 : while (ncmsgbufs < ncmsgs) {
4673 : : size_t bufsize, space;
4674 : :
4675 [ # # # # ]: 0 : if (!PyArg_Parse(PySequence_Fast_GET_ITEM(cmsg_fast, ncmsgbufs),
4676 : : "(iiy*):[sendmsg() ancillary data items]",
4677 : 0 : &cmsgs[ncmsgbufs].level,
4678 : 0 : &cmsgs[ncmsgbufs].type,
4679 : 0 : &cmsgs[ncmsgbufs].data))
4680 : 0 : goto finally;
4681 : 0 : bufsize = cmsgs[ncmsgbufs++].data.len;
4682 : :
4683 : : #ifdef CMSG_SPACE
4684 [ # # ]: 0 : if (!get_CMSG_SPACE(bufsize, &space)) {
4685 : : #else
4686 : : if (!get_CMSG_LEN(bufsize, &space)) {
4687 : : #endif
4688 : 0 : PyErr_SetString(PyExc_OSError, "ancillary data item too large");
4689 : 0 : goto finally;
4690 : : }
4691 : 0 : controllen += space;
4692 [ # # # # ]: 0 : if (controllen > SOCKLEN_T_LIMIT || controllen < controllen_last) {
4693 : 0 : PyErr_SetString(PyExc_OSError, "too much ancillary data");
4694 : 0 : goto finally;
4695 : : }
4696 : 0 : controllen_last = controllen;
4697 : : }
4698 : :
4699 : : /* Construct ancillary data block from control message info. */
4700 [ # # ]: 0 : if (ncmsgbufs > 0) {
4701 : 0 : struct cmsghdr *cmsgh = NULL;
4702 : :
4703 : 0 : controlbuf = PyMem_Malloc(controllen);
4704 [ # # ]: 0 : if (controlbuf == NULL) {
4705 : 0 : PyErr_NoMemory();
4706 : 0 : goto finally;
4707 : : }
4708 : 0 : msg.msg_control = controlbuf;
4709 : :
4710 : 0 : msg.msg_controllen = controllen;
4711 : :
4712 : : /* Need to zero out the buffer as a workaround for glibc's
4713 : : CMSG_NXTHDR() implementation. After getting the pointer to
4714 : : the next header, it checks its (uninitialized) cmsg_len
4715 : : member to see if the "message" fits in the buffer, and
4716 : : returns NULL if it doesn't. Zero-filling the buffer
4717 : : ensures that this doesn't happen. */
4718 : 0 : memset(controlbuf, 0, controllen);
4719 : :
4720 [ # # ]: 0 : for (i = 0; i < ncmsgbufs; i++) {
4721 : 0 : size_t msg_len, data_len = cmsgs[i].data.len;
4722 : 0 : int enough_space = 0;
4723 : :
4724 [ # # # # ]: 0 : cmsgh = (i == 0) ? CMSG_FIRSTHDR(&msg) : CMSG_NXTHDR(&msg, cmsgh);
4725 [ # # ]: 0 : if (cmsgh == NULL) {
4726 [ # # ]: 0 : PyErr_Format(PyExc_RuntimeError,
4727 : : "unexpected NULL result from %s()",
4728 : : (i == 0) ? "CMSG_FIRSTHDR" : "CMSG_NXTHDR");
4729 : 0 : goto finally;
4730 : : }
4731 [ # # ]: 0 : if (!get_CMSG_LEN(data_len, &msg_len)) {
4732 : 0 : PyErr_SetString(PyExc_RuntimeError,
4733 : : "item size out of range for CMSG_LEN()");
4734 : 0 : goto finally;
4735 : : }
4736 [ # # ]: 0 : if (cmsg_min_space(&msg, cmsgh, msg_len)) {
4737 : : size_t space;
4738 : :
4739 : 0 : cmsgh->cmsg_len = msg_len;
4740 [ # # ]: 0 : if (get_cmsg_data_space(&msg, cmsgh, &space))
4741 : 0 : enough_space = (space >= data_len);
4742 : : }
4743 [ # # ]: 0 : if (!enough_space) {
4744 : 0 : PyErr_SetString(PyExc_RuntimeError,
4745 : : "ancillary data does not fit in calculated "
4746 : : "space");
4747 : 0 : goto finally;
4748 : : }
4749 : 0 : cmsgh->cmsg_level = cmsgs[i].level;
4750 : 0 : cmsgh->cmsg_type = cmsgs[i].type;
4751 : 0 : memcpy(CMSG_DATA(cmsgh), cmsgs[i].data.buf, data_len);
4752 : : }
4753 : : }
4754 : :
4755 : : /* Make the system call. */
4756 : : if (!IS_SELECTABLE(s)) {
4757 : : select_error();
4758 : : goto finally;
4759 : : }
4760 : :
4761 : 0 : ctx.msg = &msg;
4762 : 0 : ctx.flags = flags;
4763 [ # # ]: 0 : if (sock_call(s, 1, sock_sendmsg_impl, &ctx) < 0)
4764 : 0 : goto finally;
4765 : :
4766 : 0 : retval = PyLong_FromSsize_t(ctx.result);
4767 : :
4768 : 0 : finally:
4769 : 0 : PyMem_Free(controlbuf);
4770 [ # # ]: 0 : for (i = 0; i < ncmsgbufs; i++)
4771 : 0 : PyBuffer_Release(&cmsgs[i].data);
4772 : 0 : PyMem_Free(cmsgs);
4773 : 0 : Py_XDECREF(cmsg_fast);
4774 : 0 : PyMem_Free(msg.msg_iov);
4775 [ # # ]: 0 : for (i = 0; i < ndatabufs; i++) {
4776 : 0 : PyBuffer_Release(&databufs[i]);
4777 : : }
4778 : 0 : PyMem_Free(databufs);
4779 : 0 : return retval;
4780 : : }
4781 : :
4782 : : PyDoc_STRVAR(sendmsg_doc,
4783 : : "sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
4784 : : \n\
4785 : : Send normal and ancillary data to the socket, gathering the\n\
4786 : : non-ancillary data from a series of buffers and concatenating it into\n\
4787 : : a single message. The buffers argument specifies the non-ancillary\n\
4788 : : data as an iterable of bytes-like objects (e.g. bytes objects).\n\
4789 : : The ancdata argument specifies the ancillary data (control messages)\n\
4790 : : as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
4791 : : cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
4792 : : protocol level and protocol-specific type respectively, and cmsg_data\n\
4793 : : is a bytes-like object holding the associated data. The flags\n\
4794 : : argument defaults to 0 and has the same meaning as for send(). If\n\
4795 : : address is supplied and not None, it sets a destination address for\n\
4796 : : the message. The return value is the number of bytes of non-ancillary\n\
4797 : : data sent.");
4798 : : #endif /* CMSG_LEN */
4799 : :
4800 : : #ifdef HAVE_SOCKADDR_ALG
4801 : : static PyObject*
4802 : 0 : sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds)
4803 : : {
4804 : 0 : PyObject *retval = NULL;
4805 : :
4806 : 0 : Py_ssize_t i, ndatabufs = 0;
4807 : 0 : Py_buffer *databufs = NULL;
4808 : 0 : PyObject *data_arg = NULL;
4809 : :
4810 : 0 : Py_buffer iv = {NULL, NULL};
4811 : :
4812 : 0 : PyObject *opobj = NULL;
4813 : 0 : int op = -1;
4814 : :
4815 : 0 : PyObject *assoclenobj = NULL;
4816 : 0 : int assoclen = -1;
4817 : :
4818 : : unsigned int *uiptr;
4819 : 0 : int flags = 0;
4820 : :
4821 : : struct msghdr msg;
4822 : 0 : struct cmsghdr *header = NULL;
4823 : 0 : struct af_alg_iv *alg_iv = NULL;
4824 : : struct sock_sendmsg ctx;
4825 : : Py_ssize_t controllen;
4826 : 0 : void *controlbuf = NULL;
4827 : : static char *keywords[] = {"msg", "op", "iv", "assoclen", "flags", 0};
4828 : :
4829 [ # # ]: 0 : if (self->sock_family != AF_ALG) {
4830 : 0 : PyErr_SetString(PyExc_OSError,
4831 : : "algset is only supported for AF_ALG");
4832 : 0 : return NULL;
4833 : : }
4834 : :
4835 [ # # ]: 0 : if (!PyArg_ParseTupleAndKeywords(args, kwds,
4836 : : "|O$O!y*O!i:sendmsg_afalg", keywords,
4837 : : &data_arg,
4838 : : &PyLong_Type, &opobj, &iv,
4839 : : &PyLong_Type, &assoclenobj, &flags)) {
4840 : 0 : return NULL;
4841 : : }
4842 : :
4843 : 0 : memset(&msg, 0, sizeof(msg));
4844 : :
4845 : : /* op is a required, keyword-only argument >= 0 */
4846 [ # # ]: 0 : if (opobj != NULL) {
4847 : 0 : op = _PyLong_AsInt(opobj);
4848 : : }
4849 [ # # ]: 0 : if (op < 0) {
4850 : : /* override exception from _PyLong_AsInt() */
4851 : 0 : PyErr_SetString(PyExc_TypeError,
4852 : : "Invalid or missing argument 'op'");
4853 : 0 : goto finally;
4854 : : }
4855 : : /* assoclen is optional but must be >= 0 */
4856 [ # # ]: 0 : if (assoclenobj != NULL) {
4857 : 0 : assoclen = _PyLong_AsInt(assoclenobj);
4858 [ # # # # ]: 0 : if (assoclen == -1 && PyErr_Occurred()) {
4859 : 0 : goto finally;
4860 : : }
4861 [ # # ]: 0 : if (assoclen < 0) {
4862 : 0 : PyErr_SetString(PyExc_TypeError,
4863 : : "assoclen must be positive");
4864 : 0 : goto finally;
4865 : : }
4866 : : }
4867 : :
4868 : 0 : controllen = CMSG_SPACE(4);
4869 [ # # ]: 0 : if (iv.buf != NULL) {
4870 : 0 : controllen += CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4871 : : }
4872 [ # # ]: 0 : if (assoclen >= 0) {
4873 : 0 : controllen += CMSG_SPACE(4);
4874 : : }
4875 : :
4876 : 0 : controlbuf = PyMem_Malloc(controllen);
4877 [ # # ]: 0 : if (controlbuf == NULL) {
4878 : 0 : PyErr_NoMemory();
4879 : 0 : goto finally;
4880 : : }
4881 : 0 : memset(controlbuf, 0, controllen);
4882 : :
4883 : 0 : msg.msg_controllen = controllen;
4884 : 0 : msg.msg_control = controlbuf;
4885 : :
4886 : : /* Fill in an iovec for each message part, and save the Py_buffer
4887 : : structs to release afterwards. */
4888 [ # # ]: 0 : if (data_arg != NULL) {
4889 [ # # ]: 0 : if (sock_sendmsg_iovec(self, data_arg, &msg, &databufs, &ndatabufs) == -1) {
4890 : 0 : goto finally;
4891 : : }
4892 : : }
4893 : :
4894 : : /* set operation to encrypt or decrypt */
4895 [ # # ]: 0 : header = CMSG_FIRSTHDR(&msg);
4896 [ # # ]: 0 : if (header == NULL) {
4897 : 0 : PyErr_SetString(PyExc_RuntimeError,
4898 : : "unexpected NULL result from CMSG_FIRSTHDR");
4899 : 0 : goto finally;
4900 : : }
4901 : 0 : header->cmsg_level = SOL_ALG;
4902 : 0 : header->cmsg_type = ALG_SET_OP;
4903 : 0 : header->cmsg_len = CMSG_LEN(4);
4904 : 0 : uiptr = (void*)CMSG_DATA(header);
4905 : 0 : *uiptr = (unsigned int)op;
4906 : :
4907 : : /* set initialization vector */
4908 [ # # ]: 0 : if (iv.buf != NULL) {
4909 : 0 : header = CMSG_NXTHDR(&msg, header);
4910 [ # # ]: 0 : if (header == NULL) {
4911 : 0 : PyErr_SetString(PyExc_RuntimeError,
4912 : : "unexpected NULL result from CMSG_NXTHDR(iv)");
4913 : 0 : goto finally;
4914 : : }
4915 : 0 : header->cmsg_level = SOL_ALG;
4916 : 0 : header->cmsg_type = ALG_SET_IV;
4917 : 0 : header->cmsg_len = CMSG_SPACE(sizeof(*alg_iv) + iv.len);
4918 : 0 : alg_iv = (void*)CMSG_DATA(header);
4919 : 0 : alg_iv->ivlen = iv.len;
4920 : 0 : memcpy(alg_iv->iv, iv.buf, iv.len);
4921 : : }
4922 : :
4923 : : /* set length of associated data for AEAD */
4924 [ # # ]: 0 : if (assoclen >= 0) {
4925 : 0 : header = CMSG_NXTHDR(&msg, header);
4926 [ # # ]: 0 : if (header == NULL) {
4927 : 0 : PyErr_SetString(PyExc_RuntimeError,
4928 : : "unexpected NULL result from CMSG_NXTHDR(assoc)");
4929 : 0 : goto finally;
4930 : : }
4931 : 0 : header->cmsg_level = SOL_ALG;
4932 : 0 : header->cmsg_type = ALG_SET_AEAD_ASSOCLEN;
4933 : 0 : header->cmsg_len = CMSG_LEN(4);
4934 : 0 : uiptr = (void*)CMSG_DATA(header);
4935 : 0 : *uiptr = (unsigned int)assoclen;
4936 : : }
4937 : :
4938 : 0 : ctx.msg = &msg;
4939 : 0 : ctx.flags = flags;
4940 [ # # ]: 0 : if (sock_call(self, 1, sock_sendmsg_impl, &ctx) < 0) {
4941 : 0 : goto finally;
4942 : : }
4943 : :
4944 : 0 : retval = PyLong_FromSsize_t(ctx.result);
4945 : :
4946 : 0 : finally:
4947 : 0 : PyMem_Free(controlbuf);
4948 [ # # ]: 0 : if (iv.buf != NULL) {
4949 : 0 : PyBuffer_Release(&iv);
4950 : : }
4951 : 0 : PyMem_Free(msg.msg_iov);
4952 [ # # ]: 0 : for (i = 0; i < ndatabufs; i++) {
4953 : 0 : PyBuffer_Release(&databufs[i]);
4954 : : }
4955 : 0 : PyMem_Free(databufs);
4956 : 0 : return retval;
4957 : : }
4958 : :
4959 : : PyDoc_STRVAR(sendmsg_afalg_doc,
4960 : : "sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])\n\
4961 : : \n\
4962 : : Set operation mode, IV and length of associated data for an AF_ALG\n\
4963 : : operation socket.");
4964 : : #endif
4965 : :
4966 : : #ifdef HAVE_SHUTDOWN
4967 : : /* s.shutdown(how) method */
4968 : :
4969 : : static PyObject *
4970 : 0 : sock_shutdown(PySocketSockObject *s, PyObject *arg)
4971 : : {
4972 : : int how;
4973 : : int res;
4974 : :
4975 : 0 : how = _PyLong_AsInt(arg);
4976 [ # # # # ]: 0 : if (how == -1 && PyErr_Occurred())
4977 : 0 : return NULL;
4978 : 0 : Py_BEGIN_ALLOW_THREADS
4979 : 0 : res = shutdown(s->sock_fd, how);
4980 : 0 : Py_END_ALLOW_THREADS
4981 [ # # ]: 0 : if (res < 0)
4982 : 0 : return s->errorhandler();
4983 : 0 : Py_RETURN_NONE;
4984 : : }
4985 : :
4986 : : PyDoc_STRVAR(shutdown_doc,
4987 : : "shutdown(flag)\n\
4988 : : \n\
4989 : : Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
4990 : : of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
4991 : : #endif
4992 : :
4993 : : #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
4994 : : static PyObject*
4995 : : sock_ioctl(PySocketSockObject *s, PyObject *arg)
4996 : : {
4997 : : unsigned long cmd = SIO_RCVALL;
4998 : : PyObject *argO;
4999 : : DWORD recv;
5000 : :
5001 : : if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
5002 : : return NULL;
5003 : :
5004 : : switch (cmd) {
5005 : : case SIO_RCVALL: {
5006 : : unsigned int option = RCVALL_ON;
5007 : : if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
5008 : : return NULL;
5009 : : if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
5010 : : NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5011 : : return set_error();
5012 : : }
5013 : : return PyLong_FromUnsignedLong(recv); }
5014 : : case SIO_KEEPALIVE_VALS: {
5015 : : struct tcp_keepalive ka;
5016 : : if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
5017 : : &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
5018 : : return NULL;
5019 : : if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
5020 : : NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5021 : : return set_error();
5022 : : }
5023 : : return PyLong_FromUnsignedLong(recv); }
5024 : : #if defined(SIO_LOOPBACK_FAST_PATH)
5025 : : case SIO_LOOPBACK_FAST_PATH: {
5026 : : unsigned int option;
5027 : : if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
5028 : : return NULL;
5029 : : if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
5030 : : NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
5031 : : return set_error();
5032 : : }
5033 : : return PyLong_FromUnsignedLong(recv); }
5034 : : #endif
5035 : : default:
5036 : : PyErr_Format(PyExc_ValueError, "invalid ioctl command %lu", cmd);
5037 : : return NULL;
5038 : : }
5039 : : }
5040 : : PyDoc_STRVAR(sock_ioctl_doc,
5041 : : "ioctl(cmd, option) -> long\n\
5042 : : \n\
5043 : : Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
5044 : : SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
5045 : : SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).\n\
5046 : : SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default");
5047 : : #endif
5048 : :
5049 : : #if defined(MS_WINDOWS)
5050 : : static PyObject*
5051 : : sock_share(PySocketSockObject *s, PyObject *arg)
5052 : : {
5053 : : WSAPROTOCOL_INFOW info;
5054 : : DWORD processId;
5055 : : int result;
5056 : :
5057 : : if (!PyArg_ParseTuple(arg, "I", &processId))
5058 : : return NULL;
5059 : :
5060 : : Py_BEGIN_ALLOW_THREADS
5061 : : result = WSADuplicateSocketW(s->sock_fd, processId, &info);
5062 : : Py_END_ALLOW_THREADS
5063 : : if (result == SOCKET_ERROR)
5064 : : return set_error();
5065 : : return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
5066 : : }
5067 : : PyDoc_STRVAR(sock_share_doc,
5068 : : "share(process_id) -> bytes\n\
5069 : : \n\
5070 : : Share the socket with another process. The target process id\n\
5071 : : must be provided and the resulting bytes object passed to the target\n\
5072 : : process. There the shared socket can be instantiated by calling\n\
5073 : : socket.fromshare().");
5074 : :
5075 : :
5076 : : #endif
5077 : :
5078 : : /* List of methods for socket objects */
5079 : :
5080 : : static PyMethodDef sock_methods[] = {
5081 : : #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
5082 : : {"_accept", (PyCFunction)sock_accept, METH_NOARGS,
5083 : : accept_doc},
5084 : : #endif
5085 : : #ifdef HAVE_BIND
5086 : : {"bind", (PyCFunction)sock_bind, METH_O,
5087 : : bind_doc},
5088 : : #endif
5089 : : {"close", (PyCFunction)sock_close, METH_NOARGS,
5090 : : sock_close_doc},
5091 : : #ifdef HAVE_CONNECT
5092 : : {"connect", (PyCFunction)sock_connect, METH_O,
5093 : : connect_doc},
5094 : : {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
5095 : : connect_ex_doc},
5096 : : #endif
5097 : : {"detach", (PyCFunction)sock_detach, METH_NOARGS,
5098 : : detach_doc},
5099 : : {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
5100 : : fileno_doc},
5101 : : #ifdef HAVE_GETPEERNAME
5102 : : {"getpeername", (PyCFunction)sock_getpeername,
5103 : : METH_NOARGS, getpeername_doc},
5104 : : #endif
5105 : : #ifdef HAVE_GETSOCKNAME
5106 : : {"getsockname", (PyCFunction)sock_getsockname,
5107 : : METH_NOARGS, getsockname_doc},
5108 : : #endif
5109 : : {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
5110 : : getsockopt_doc},
5111 : : #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
5112 : : {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
5113 : : sock_ioctl_doc},
5114 : : #endif
5115 : : #if defined(MS_WINDOWS)
5116 : : {"share", (PyCFunction)sock_share, METH_VARARGS,
5117 : : sock_share_doc},
5118 : : #endif
5119 : : #ifdef HAVE_LISTEN
5120 : : {"listen", (PyCFunction)sock_listen, METH_VARARGS,
5121 : : listen_doc},
5122 : : #endif
5123 : : {"recv", (PyCFunction)sock_recv, METH_VARARGS,
5124 : : recv_doc},
5125 : : {"recv_into", _PyCFunction_CAST(sock_recv_into), METH_VARARGS | METH_KEYWORDS,
5126 : : recv_into_doc},
5127 : : #ifdef HAVE_RECVFROM
5128 : : {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
5129 : : recvfrom_doc},
5130 : : {"recvfrom_into", _PyCFunction_CAST(sock_recvfrom_into), METH_VARARGS | METH_KEYWORDS,
5131 : : recvfrom_into_doc},
5132 : : #endif
5133 : : {"send", (PyCFunction)sock_send, METH_VARARGS,
5134 : : send_doc},
5135 : : {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
5136 : : sendall_doc},
5137 : : #ifdef HAVE_SENDTO
5138 : : {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
5139 : : sendto_doc},
5140 : : #endif
5141 : : {"setblocking", (PyCFunction)sock_setblocking, METH_O,
5142 : : setblocking_doc},
5143 : : {"getblocking", (PyCFunction)sock_getblocking, METH_NOARGS,
5144 : : getblocking_doc},
5145 : : {"settimeout", (PyCFunction)sock_settimeout, METH_O,
5146 : : settimeout_doc},
5147 : : {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
5148 : : gettimeout_doc},
5149 : : #ifdef HAVE_SETSOCKOPT
5150 : : {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
5151 : : setsockopt_doc},
5152 : : #endif
5153 : : #ifdef HAVE_SHUTDOWN
5154 : : {"shutdown", (PyCFunction)sock_shutdown, METH_O,
5155 : : shutdown_doc},
5156 : : #endif
5157 : : #ifdef CMSG_LEN
5158 : : {"recvmsg", (PyCFunction)sock_recvmsg, METH_VARARGS,
5159 : : recvmsg_doc},
5160 : : {"recvmsg_into", (PyCFunction)sock_recvmsg_into, METH_VARARGS,
5161 : : recvmsg_into_doc,},
5162 : : {"sendmsg", (PyCFunction)sock_sendmsg, METH_VARARGS,
5163 : : sendmsg_doc},
5164 : : #endif
5165 : : #ifdef HAVE_SOCKADDR_ALG
5166 : : {"sendmsg_afalg", _PyCFunction_CAST(sock_sendmsg_afalg), METH_VARARGS | METH_KEYWORDS,
5167 : : sendmsg_afalg_doc},
5168 : : #endif
5169 : : {NULL, NULL} /* sentinel */
5170 : : };
5171 : :
5172 : : /* SockObject members */
5173 : : static PyMemberDef sock_memberlist[] = {
5174 : : {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
5175 : : {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
5176 : : {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
5177 : : {0},
5178 : : };
5179 : :
5180 : : static PyGetSetDef sock_getsetlist[] = {
5181 : : {"timeout", (getter)sock_gettimeout, NULL, PyDoc_STR("the socket timeout")},
5182 : : {NULL} /* sentinel */
5183 : : };
5184 : :
5185 : : /* Deallocate a socket object in response to the last Py_DECREF().
5186 : : First close the file description. */
5187 : :
5188 : : static void
5189 : 0 : sock_finalize(PySocketSockObject *s)
5190 : : {
5191 : : SOCKET_T fd;
5192 : :
5193 : : /* Save the current exception, if any. */
5194 : 0 : PyObject *exc = PyErr_GetRaisedException();
5195 : :
5196 [ # # ]: 0 : if (s->sock_fd != INVALID_SOCKET) {
5197 [ # # ]: 0 : if (PyErr_ResourceWarning((PyObject *)s, 1, "unclosed %R", s)) {
5198 : : /* Spurious errors can appear at shutdown */
5199 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_Warning)) {
5200 : 0 : PyErr_WriteUnraisable((PyObject *)s);
5201 : : }
5202 : : }
5203 : :
5204 : : /* Only close the socket *after* logging the ResourceWarning warning
5205 : : to allow the logger to call socket methods like
5206 : : socket.getsockname(). If the socket is closed before, socket
5207 : : methods fails with the EBADF error. */
5208 : 0 : fd = s->sock_fd;
5209 : 0 : s->sock_fd = INVALID_SOCKET;
5210 : :
5211 : : /* We do not want to retry upon EINTR: see sock_close() */
5212 : 0 : Py_BEGIN_ALLOW_THREADS
5213 : 0 : (void) SOCKETCLOSE(fd);
5214 : 0 : Py_END_ALLOW_THREADS
5215 : : }
5216 : :
5217 : : /* Restore the saved exception. */
5218 : 0 : PyErr_SetRaisedException(exc);
5219 : 0 : }
5220 : :
5221 : : static void
5222 : 0 : sock_dealloc(PySocketSockObject *s)
5223 : : {
5224 [ # # ]: 0 : if (PyObject_CallFinalizerFromDealloc((PyObject *)s) < 0)
5225 : 0 : return;
5226 : :
5227 : 0 : Py_TYPE(s)->tp_free((PyObject *)s);
5228 : : }
5229 : :
5230 : :
5231 : : static PyObject *
5232 : 0 : sock_repr(PySocketSockObject *s)
5233 : : {
5234 : : long sock_fd;
5235 : : /* On Windows, this test is needed because SOCKET_T is unsigned */
5236 [ # # ]: 0 : if (s->sock_fd == INVALID_SOCKET) {
5237 : 0 : sock_fd = -1;
5238 : : }
5239 : : #if SIZEOF_SOCKET_T > SIZEOF_LONG
5240 : : else if (s->sock_fd > LONG_MAX) {
5241 : : /* this can occur on Win64, and actually there is a special
5242 : : ugly printf formatter for decimal pointer length integer
5243 : : printing, only bother if necessary*/
5244 : : PyErr_SetString(PyExc_OverflowError,
5245 : : "no printf formatter to display "
5246 : : "the socket descriptor in decimal");
5247 : : return NULL;
5248 : : }
5249 : : #endif
5250 : : else
5251 : 0 : sock_fd = (long)s->sock_fd;
5252 : 0 : return PyUnicode_FromFormat(
5253 : : "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
5254 : : sock_fd, s->sock_family,
5255 : : s->sock_type,
5256 : : s->sock_proto);
5257 : : }
5258 : :
5259 : :
5260 : : /* Create a new, uninitialized socket object. */
5261 : :
5262 : : static PyObject *
5263 : 0 : sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
5264 : : {
5265 : : PyObject *new;
5266 : :
5267 : 0 : new = type->tp_alloc(type, 0);
5268 [ # # ]: 0 : if (new != NULL) {
5269 : 0 : ((PySocketSockObject *)new)->sock_fd = INVALID_SOCKET;
5270 : 0 : ((PySocketSockObject *)new)->sock_timeout = _PyTime_FromSeconds(-1);
5271 : 0 : ((PySocketSockObject *)new)->errorhandler = &set_error;
5272 : : }
5273 : 0 : return new;
5274 : : }
5275 : :
5276 : :
5277 : : /* Initialize a new socket object. */
5278 : :
5279 : : #ifdef SOCK_CLOEXEC
5280 : : /* socket() and socketpair() fail with EINVAL on Linux kernel older
5281 : : * than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */
5282 : : static int sock_cloexec_works = -1;
5283 : : #endif
5284 : :
5285 : : /*ARGSUSED*/
5286 : :
5287 : : #ifndef HAVE_SOCKET
5288 : : #define socket stub_socket
5289 : : static int
5290 : : socket(int domain, int type, int protocol)
5291 : : {
5292 : : errno = ENOTSUP;
5293 : : return INVALID_SOCKET;
5294 : : }
5295 : : #endif
5296 : :
5297 : : /*[clinic input]
5298 : : _socket.socket.__init__ as sock_initobj
5299 : : family: int = -1
5300 : : type: int = -1
5301 : : proto: int = -1
5302 : : fileno as fdobj: object = NULL
5303 : : [clinic start generated code]*/
5304 : :
5305 : : static int
5306 : 0 : sock_initobj_impl(PySocketSockObject *self, int family, int type, int proto,
5307 : : PyObject *fdobj)
5308 : : /*[clinic end generated code: output=d114d026b9a9a810 input=04cfc32953f5cc25]*/
5309 : : {
5310 : :
5311 : 0 : SOCKET_T fd = INVALID_SOCKET;
5312 : :
5313 : : #ifndef MS_WINDOWS
5314 : : #ifdef SOCK_CLOEXEC
5315 : 0 : int *atomic_flag_works = &sock_cloexec_works;
5316 : : #else
5317 : : int *atomic_flag_works = NULL;
5318 : : #endif
5319 : : #endif
5320 : :
5321 : : #ifdef MS_WINDOWS
5322 : : /* In this case, we don't use the family, type and proto args */
5323 : : if (fdobj == NULL || fdobj == Py_None)
5324 : : #endif
5325 : : {
5326 [ # # ]: 0 : if (PySys_Audit("socket.__new__", "Oiii",
5327 : : self, family, type, proto) < 0) {
5328 : 0 : return -1;
5329 : : }
5330 : : }
5331 : :
5332 [ # # # # ]: 0 : if (fdobj != NULL && fdobj != Py_None) {
5333 : : #ifdef MS_WINDOWS
5334 : : /* recreate a socket that was duplicated */
5335 : : if (PyBytes_Check(fdobj)) {
5336 : : WSAPROTOCOL_INFOW info;
5337 : : if (PyBytes_GET_SIZE(fdobj) != sizeof(info)) {
5338 : : PyErr_Format(PyExc_ValueError,
5339 : : "socket descriptor string has wrong size, "
5340 : : "should be %zu bytes.", sizeof(info));
5341 : : return -1;
5342 : : }
5343 : : memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
5344 : :
5345 : : if (PySys_Audit("socket.__new__", "Oiii", self,
5346 : : info.iAddressFamily, info.iSocketType,
5347 : : info.iProtocol) < 0) {
5348 : : return -1;
5349 : : }
5350 : :
5351 : : Py_BEGIN_ALLOW_THREADS
5352 : : fd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
5353 : : FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
5354 : : Py_END_ALLOW_THREADS
5355 : : if (fd == INVALID_SOCKET) {
5356 : : set_error();
5357 : : return -1;
5358 : : }
5359 : :
5360 : : if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0)) {
5361 : : closesocket(fd);
5362 : : PyErr_SetFromWindowsErr(0);
5363 : : return -1;
5364 : : }
5365 : :
5366 : : family = info.iAddressFamily;
5367 : : type = info.iSocketType;
5368 : : proto = info.iProtocol;
5369 : : }
5370 : : else
5371 : : #endif
5372 : 0 : {
5373 : 0 : fd = PyLong_AsSocket_t(fdobj);
5374 [ # # # # ]: 0 : if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
5375 : 0 : return -1;
5376 : : #ifdef MS_WINDOWS
5377 : : if (fd == INVALID_SOCKET) {
5378 : : #else
5379 [ # # ]: 0 : if (fd < 0) {
5380 : : #endif
5381 : 0 : PyErr_SetString(PyExc_ValueError, "negative file descriptor");
5382 : 0 : return -1;
5383 : : }
5384 : :
5385 : : /* validate that passed file descriptor is valid and a socket. */
5386 : : sock_addr_t addrbuf;
5387 : 0 : socklen_t addrlen = sizeof(sock_addr_t);
5388 : :
5389 : 0 : memset(&addrbuf, 0, addrlen);
5390 : : #ifdef HAVE_GETSOCKNAME
5391 [ # # ]: 0 : if (getsockname(fd, SAS2SA(&addrbuf), &addrlen) == 0) {
5392 [ # # ]: 0 : if (family == -1) {
5393 : 0 : family = SAS2SA(&addrbuf)->sa_family;
5394 : : }
5395 : : } else {
5396 : : #ifdef MS_WINDOWS
5397 : : /* getsockname() on an unbound socket is an error on Windows.
5398 : : Invalid descriptor and not a socket is same error code.
5399 : : Error out if family must be resolved, or bad descriptor. */
5400 : : if (family == -1 || CHECK_ERRNO(ENOTSOCK)) {
5401 : : #else
5402 : : /* getsockname() is not supported for SOL_ALG on Linux. */
5403 [ # # # # : 0 : if (family == -1 || CHECK_ERRNO(EBADF) || CHECK_ERRNO(ENOTSOCK)) {
# # ]
5404 : : #endif
5405 : 0 : set_error();
5406 : 0 : return -1;
5407 : : }
5408 : : }
5409 : : #endif // HAVE_GETSOCKNAME
5410 : : #ifdef SO_TYPE
5411 [ # # ]: 0 : if (type == -1) {
5412 : : int tmp;
5413 : 0 : socklen_t slen = sizeof(tmp);
5414 [ # # ]: 0 : if (getsockopt(fd, SOL_SOCKET, SO_TYPE,
5415 : : (void *)&tmp, &slen) == 0)
5416 : : {
5417 : 0 : type = tmp;
5418 : : } else {
5419 : 0 : set_error();
5420 : 0 : return -1;
5421 : : }
5422 : : }
5423 : : #else
5424 : : type = SOCK_STREAM;
5425 : : #endif
5426 : : #ifdef SO_PROTOCOL
5427 [ # # ]: 0 : if (proto == -1) {
5428 : : int tmp;
5429 : 0 : socklen_t slen = sizeof(tmp);
5430 [ # # ]: 0 : if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL,
5431 : : (void *)&tmp, &slen) == 0)
5432 : : {
5433 : 0 : proto = tmp;
5434 : : } else {
5435 : 0 : set_error();
5436 : 0 : return -1;
5437 : : }
5438 : : }
5439 : : #else
5440 : : proto = 0;
5441 : : #endif
5442 : : }
5443 : : }
5444 : : else {
5445 : : /* No fd, default to AF_INET and SOCK_STREAM */
5446 [ # # ]: 0 : if (family == -1) {
5447 : 0 : family = AF_INET;
5448 : : }
5449 [ # # ]: 0 : if (type == -1) {
5450 : 0 : type = SOCK_STREAM;
5451 : : }
5452 [ # # ]: 0 : if (proto == -1) {
5453 : 0 : proto = 0;
5454 : : }
5455 : : #ifdef MS_WINDOWS
5456 : : Py_BEGIN_ALLOW_THREADS
5457 : : fd = WSASocketW(family, type, proto,
5458 : : NULL, 0,
5459 : : WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
5460 : : Py_END_ALLOW_THREADS
5461 : :
5462 : : if (fd == INVALID_SOCKET) {
5463 : : set_error();
5464 : : return -1;
5465 : : }
5466 : : #else
5467 : : /* UNIX */
5468 : 0 : Py_BEGIN_ALLOW_THREADS
5469 : : #ifdef SOCK_CLOEXEC
5470 [ # # ]: 0 : if (sock_cloexec_works != 0) {
5471 : 0 : fd = socket(family, type | SOCK_CLOEXEC, proto);
5472 [ # # ]: 0 : if (sock_cloexec_works == -1) {
5473 [ # # ]: 0 : if (fd >= 0) {
5474 : 0 : sock_cloexec_works = 1;
5475 : : }
5476 [ # # ]: 0 : else if (errno == EINVAL) {
5477 : : /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
5478 : 0 : sock_cloexec_works = 0;
5479 : 0 : fd = socket(family, type, proto);
5480 : : }
5481 : : }
5482 : : }
5483 : : else
5484 : : #endif
5485 : : {
5486 : 0 : fd = socket(family, type, proto);
5487 : : }
5488 : 0 : Py_END_ALLOW_THREADS
5489 : :
5490 [ # # ]: 0 : if (fd == INVALID_SOCKET) {
5491 : 0 : set_error();
5492 : 0 : return -1;
5493 : : }
5494 : :
5495 [ # # ]: 0 : if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
5496 : 0 : SOCKETCLOSE(fd);
5497 : 0 : return -1;
5498 : : }
5499 : : #endif
5500 : : }
5501 [ # # ]: 0 : if (init_sockobject(self, fd, family, type, proto) == -1) {
5502 : 0 : SOCKETCLOSE(fd);
5503 : 0 : return -1;
5504 : : }
5505 : :
5506 : 0 : return 0;
5507 : :
5508 : : }
5509 : :
5510 : :
5511 : : /* Type object for socket objects. */
5512 : :
5513 : : static PyTypeObject sock_type = {
5514 : : PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
5515 : : "_socket.socket", /* tp_name */
5516 : : sizeof(PySocketSockObject), /* tp_basicsize */
5517 : : 0, /* tp_itemsize */
5518 : : (destructor)sock_dealloc, /* tp_dealloc */
5519 : : 0, /* tp_vectorcall_offset */
5520 : : 0, /* tp_getattr */
5521 : : 0, /* tp_setattr */
5522 : : 0, /* tp_as_async */
5523 : : (reprfunc)sock_repr, /* tp_repr */
5524 : : 0, /* tp_as_number */
5525 : : 0, /* tp_as_sequence */
5526 : : 0, /* tp_as_mapping */
5527 : : 0, /* tp_hash */
5528 : : 0, /* tp_call */
5529 : : 0, /* tp_str */
5530 : : PyObject_GenericGetAttr, /* tp_getattro */
5531 : : 0, /* tp_setattro */
5532 : : 0, /* tp_as_buffer */
5533 : : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5534 : : sock_doc, /* tp_doc */
5535 : : 0, /* tp_traverse */
5536 : : 0, /* tp_clear */
5537 : : 0, /* tp_richcompare */
5538 : : 0, /* tp_weaklistoffset */
5539 : : 0, /* tp_iter */
5540 : : 0, /* tp_iternext */
5541 : : sock_methods, /* tp_methods */
5542 : : sock_memberlist, /* tp_members */
5543 : : sock_getsetlist, /* tp_getset */
5544 : : 0, /* tp_base */
5545 : : 0, /* tp_dict */
5546 : : 0, /* tp_descr_get */
5547 : : 0, /* tp_descr_set */
5548 : : 0, /* tp_dictoffset */
5549 : : sock_initobj, /* tp_init */
5550 : : PyType_GenericAlloc, /* tp_alloc */
5551 : : sock_new, /* tp_new */
5552 : : PyObject_Del, /* tp_free */
5553 : : 0, /* tp_is_gc */
5554 : : 0, /* tp_bases */
5555 : : 0, /* tp_mro */
5556 : : 0, /* tp_cache */
5557 : : 0, /* tp_subclasses */
5558 : : 0, /* tp_weaklist */
5559 : : 0, /* tp_del */
5560 : : 0, /* tp_version_tag */
5561 : : (destructor)sock_finalize, /* tp_finalize */
5562 : : };
5563 : :
5564 : :
5565 : : #ifdef HAVE_GETHOSTNAME
5566 : : /* Python interface to gethostname(). */
5567 : :
5568 : : /*ARGSUSED*/
5569 : : static PyObject *
5570 : 0 : socket_gethostname(PyObject *self, PyObject *unused)
5571 : : {
5572 [ # # ]: 0 : if (PySys_Audit("socket.gethostname", NULL) < 0) {
5573 : 0 : return NULL;
5574 : : }
5575 : :
5576 : : #ifdef MS_WINDOWS
5577 : : /* Don't use winsock's gethostname, as this returns the ANSI
5578 : : version of the hostname, whereas we need a Unicode string.
5579 : : Otherwise, gethostname apparently also returns the DNS name. */
5580 : : wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
5581 : : DWORD size = Py_ARRAY_LENGTH(buf);
5582 : : wchar_t *name;
5583 : : PyObject *result;
5584 : :
5585 : : if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
5586 : : return PyUnicode_FromWideChar(buf, size);
5587 : :
5588 : : if (GetLastError() != ERROR_MORE_DATA)
5589 : : return PyErr_SetFromWindowsErr(0);
5590 : :
5591 : : if (size == 0)
5592 : : return PyUnicode_New(0, 0);
5593 : :
5594 : : /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
5595 : : names */
5596 : : name = PyMem_New(wchar_t, size);
5597 : : if (!name) {
5598 : : PyErr_NoMemory();
5599 : : return NULL;
5600 : : }
5601 : : if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
5602 : : name,
5603 : : &size))
5604 : : {
5605 : : PyMem_Free(name);
5606 : : return PyErr_SetFromWindowsErr(0);
5607 : : }
5608 : :
5609 : : result = PyUnicode_FromWideChar(name, size);
5610 : : PyMem_Free(name);
5611 : : return result;
5612 : : #else
5613 : : char buf[1024];
5614 : : int res;
5615 : 0 : Py_BEGIN_ALLOW_THREADS
5616 : 0 : res = gethostname(buf, (int) sizeof buf - 1);
5617 : 0 : Py_END_ALLOW_THREADS
5618 [ # # ]: 0 : if (res < 0)
5619 : 0 : return set_error();
5620 : 0 : buf[sizeof buf - 1] = '\0';
5621 : 0 : return PyUnicode_DecodeFSDefault(buf);
5622 : : #endif
5623 : : }
5624 : :
5625 : : PyDoc_STRVAR(gethostname_doc,
5626 : : "gethostname() -> string\n\
5627 : : \n\
5628 : : Return the current host name.");
5629 : : #endif
5630 : :
5631 : : #ifdef HAVE_SETHOSTNAME
5632 : : PyDoc_STRVAR(sethostname_doc,
5633 : : "sethostname(name)\n\n\
5634 : : Sets the hostname to name.");
5635 : :
5636 : : static PyObject *
5637 : 0 : socket_sethostname(PyObject *self, PyObject *args)
5638 : : {
5639 : : PyObject *hnobj;
5640 : : Py_buffer buf;
5641 : 0 : int res, flag = 0;
5642 : :
5643 : : #ifdef _AIX
5644 : : /* issue #18259, not declared in any useful header file */
5645 : : extern int sethostname(const char *, size_t);
5646 : : #endif
5647 : :
5648 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "S:sethostname", &hnobj)) {
5649 : 0 : PyErr_Clear();
5650 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O&:sethostname",
5651 : : PyUnicode_FSConverter, &hnobj))
5652 : 0 : return NULL;
5653 : 0 : flag = 1;
5654 : : }
5655 : :
5656 [ # # ]: 0 : if (PySys_Audit("socket.sethostname", "(O)", hnobj) < 0) {
5657 : 0 : return NULL;
5658 : : }
5659 : :
5660 : 0 : res = PyObject_GetBuffer(hnobj, &buf, PyBUF_SIMPLE);
5661 [ # # ]: 0 : if (!res) {
5662 : 0 : res = sethostname(buf.buf, buf.len);
5663 : 0 : PyBuffer_Release(&buf);
5664 : : }
5665 [ # # ]: 0 : if (flag)
5666 : 0 : Py_DECREF(hnobj);
5667 [ # # ]: 0 : if (res)
5668 : 0 : return set_error();
5669 : 0 : Py_RETURN_NONE;
5670 : : }
5671 : : #endif
5672 : :
5673 : : #ifdef HAVE_GETADDRINFO
5674 : : /* Python interface to gethostbyname(name). */
5675 : :
5676 : : /*ARGSUSED*/
5677 : : static PyObject *
5678 : 0 : socket_gethostbyname(PyObject *self, PyObject *args)
5679 : : {
5680 : : char *name;
5681 : : struct sockaddr_in addrbuf;
5682 : 0 : PyObject *ret = NULL;
5683 : :
5684 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
5685 : 0 : return NULL;
5686 [ # # ]: 0 : if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5687 : 0 : goto finally;
5688 : : }
5689 [ # # ]: 0 : if (setipaddr(name, (struct sockaddr *)&addrbuf, sizeof(addrbuf), AF_INET) < 0)
5690 : 0 : goto finally;
5691 : 0 : ret = make_ipv4_addr(&addrbuf);
5692 : 0 : finally:
5693 : 0 : PyMem_Free(name);
5694 : 0 : return ret;
5695 : : }
5696 : :
5697 : : PyDoc_STRVAR(gethostbyname_doc,
5698 : : "gethostbyname(host) -> address\n\
5699 : : \n\
5700 : : Return the IP address (a string of the form '255.255.255.255') for a host.");
5701 : : #endif
5702 : :
5703 : :
5704 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
5705 : : static PyObject*
5706 : 0 : sock_decode_hostname(const char *name)
5707 : : {
5708 : : #ifdef MS_WINDOWS
5709 : : /* Issue #26227: gethostbyaddr() returns a string encoded
5710 : : * to the ANSI code page */
5711 : : return PyUnicode_DecodeMBCS(name, strlen(name), "surrogatepass");
5712 : : #else
5713 : : /* Decode from UTF-8 */
5714 : 0 : return PyUnicode_FromString(name);
5715 : : #endif
5716 : : }
5717 : :
5718 : : /* Convenience function common to gethostbyname_ex and gethostbyaddr */
5719 : :
5720 : : static PyObject *
5721 : 0 : gethost_common(struct hostent *h, struct sockaddr *addr, size_t alen, int af)
5722 : : {
5723 : : char **pch;
5724 : 0 : PyObject *rtn_tuple = (PyObject *)NULL;
5725 : 0 : PyObject *name_list = (PyObject *)NULL;
5726 : 0 : PyObject *addr_list = (PyObject *)NULL;
5727 : : PyObject *tmp;
5728 : : PyObject *name;
5729 : :
5730 [ # # ]: 0 : if (h == NULL) {
5731 : : /* Let's get real error message to return */
5732 : 0 : set_herror(h_errno);
5733 : 0 : return NULL;
5734 : : }
5735 : :
5736 [ # # ]: 0 : if (h->h_addrtype != af) {
5737 : : /* Let's get real error message to return */
5738 : 0 : errno = EAFNOSUPPORT;
5739 : 0 : PyErr_SetFromErrno(PyExc_OSError);
5740 : 0 : return NULL;
5741 : : }
5742 : :
5743 [ # # # ]: 0 : switch (af) {
5744 : :
5745 : 0 : case AF_INET:
5746 [ # # ]: 0 : if (alen < sizeof(struct sockaddr_in))
5747 : 0 : return NULL;
5748 : 0 : break;
5749 : :
5750 : : #ifdef ENABLE_IPV6
5751 : 0 : case AF_INET6:
5752 [ # # ]: 0 : if (alen < sizeof(struct sockaddr_in6))
5753 : 0 : return NULL;
5754 : 0 : break;
5755 : : #endif
5756 : :
5757 : : }
5758 : :
5759 [ # # ]: 0 : if ((name_list = PyList_New(0)) == NULL)
5760 : 0 : goto err;
5761 : :
5762 [ # # ]: 0 : if ((addr_list = PyList_New(0)) == NULL)
5763 : 0 : goto err;
5764 : :
5765 : : /* SF #1511317: h_aliases can be NULL */
5766 [ # # ]: 0 : if (h->h_aliases) {
5767 [ # # ]: 0 : for (pch = h->h_aliases; *pch != NULL; pch++) {
5768 : : int status;
5769 : 0 : tmp = PyUnicode_FromString(*pch);
5770 [ # # ]: 0 : if (tmp == NULL)
5771 : 0 : goto err;
5772 : :
5773 : 0 : status = PyList_Append(name_list, tmp);
5774 : 0 : Py_DECREF(tmp);
5775 : :
5776 [ # # ]: 0 : if (status)
5777 : 0 : goto err;
5778 : : }
5779 : : }
5780 : :
5781 [ # # ]: 0 : for (pch = h->h_addr_list; *pch != NULL; pch++) {
5782 : : int status;
5783 : :
5784 [ # # # ]: 0 : switch (af) {
5785 : :
5786 : 0 : case AF_INET:
5787 : : {
5788 : : struct sockaddr_in sin;
5789 : 0 : memset(&sin, 0, sizeof(sin));
5790 : 0 : sin.sin_family = af;
5791 : : #ifdef HAVE_SOCKADDR_SA_LEN
5792 : : sin.sin_len = sizeof(sin);
5793 : : #endif
5794 : 0 : memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
5795 : 0 : tmp = make_ipv4_addr(&sin);
5796 : :
5797 [ # # # # ]: 0 : if (pch == h->h_addr_list && alen >= sizeof(sin))
5798 : 0 : memcpy((char *) addr, &sin, sizeof(sin));
5799 : 0 : break;
5800 : : }
5801 : :
5802 : : #ifdef ENABLE_IPV6
5803 : 0 : case AF_INET6:
5804 : : {
5805 : : struct sockaddr_in6 sin6;
5806 : 0 : memset(&sin6, 0, sizeof(sin6));
5807 : 0 : sin6.sin6_family = af;
5808 : : #ifdef HAVE_SOCKADDR_SA_LEN
5809 : : sin6.sin6_len = sizeof(sin6);
5810 : : #endif
5811 : 0 : memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
5812 : 0 : tmp = make_ipv6_addr(&sin6);
5813 : :
5814 [ # # # # ]: 0 : if (pch == h->h_addr_list && alen >= sizeof(sin6))
5815 : 0 : memcpy((char *) addr, &sin6, sizeof(sin6));
5816 : 0 : break;
5817 : : }
5818 : : #endif
5819 : :
5820 : 0 : default: /* can't happen */
5821 : 0 : PyErr_SetString(PyExc_OSError,
5822 : : "unsupported address family");
5823 : 0 : return NULL;
5824 : : }
5825 : :
5826 [ # # ]: 0 : if (tmp == NULL)
5827 : 0 : goto err;
5828 : :
5829 : 0 : status = PyList_Append(addr_list, tmp);
5830 : 0 : Py_DECREF(tmp);
5831 : :
5832 [ # # ]: 0 : if (status)
5833 : 0 : goto err;
5834 : : }
5835 : :
5836 : 0 : name = sock_decode_hostname(h->h_name);
5837 [ # # ]: 0 : if (name == NULL)
5838 : 0 : goto err;
5839 : 0 : rtn_tuple = Py_BuildValue("NOO", name, name_list, addr_list);
5840 : :
5841 : 0 : err:
5842 : 0 : Py_XDECREF(name_list);
5843 : 0 : Py_XDECREF(addr_list);
5844 : 0 : return rtn_tuple;
5845 : : }
5846 : : #endif
5847 : :
5848 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
5849 : : /* Python interface to gethostbyname_ex(name). */
5850 : :
5851 : : /*ARGSUSED*/
5852 : : static PyObject *
5853 : 0 : socket_gethostbyname_ex(PyObject *self, PyObject *args)
5854 : : {
5855 : : char *name;
5856 : : struct hostent *h;
5857 : : sock_addr_t addr;
5858 : : struct sockaddr *sa;
5859 : 0 : PyObject *ret = NULL;
5860 : : #ifdef HAVE_GETHOSTBYNAME_R
5861 : : struct hostent hp_allocated;
5862 : : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5863 : : struct hostent_data data;
5864 : : #else
5865 : : char buf[16384];
5866 : 0 : int buf_len = (sizeof buf) - 1;
5867 : : int errnop;
5868 : : #endif
5869 : : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5870 : : int result;
5871 : : #endif
5872 : : #endif /* HAVE_GETHOSTBYNAME_R */
5873 : :
5874 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
5875 : 0 : return NULL;
5876 [ # # ]: 0 : if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
5877 : 0 : goto finally;
5878 : : }
5879 [ # # ]: 0 : if (setipaddr(name, SAS2SA(&addr), sizeof(addr), AF_INET) < 0)
5880 : 0 : goto finally;
5881 : 0 : Py_BEGIN_ALLOW_THREADS
5882 : : #ifdef HAVE_GETHOSTBYNAME_R
5883 : : #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
5884 : 0 : gethostbyname_r(name, &hp_allocated, buf, buf_len,
5885 : : &h, &errnop);
5886 : : #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
5887 : : h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
5888 : : #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
5889 : : memset((void *) &data, '\0', sizeof(data));
5890 : : result = gethostbyname_r(name, &hp_allocated, &data);
5891 : : h = (result != 0) ? NULL : &hp_allocated;
5892 : : #endif
5893 : : #else /* not HAVE_GETHOSTBYNAME_R */
5894 : : #ifdef USE_GETHOSTBYNAME_LOCK
5895 : : PyThread_acquire_lock(netdb_lock, 1);
5896 : : #endif
5897 : : SUPPRESS_DEPRECATED_CALL
5898 : : h = gethostbyname(name);
5899 : : #endif /* HAVE_GETHOSTBYNAME_R */
5900 : 0 : Py_END_ALLOW_THREADS
5901 : : /* Some C libraries would require addr.__ss_family instead of
5902 : : addr.ss_family.
5903 : : Therefore, we cast the sockaddr_storage into sockaddr to
5904 : : access sa_family. */
5905 : 0 : sa = SAS2SA(&addr);
5906 : 0 : ret = gethost_common(h, SAS2SA(&addr), sizeof(addr),
5907 : 0 : sa->sa_family);
5908 : : #ifdef USE_GETHOSTBYNAME_LOCK
5909 : : PyThread_release_lock(netdb_lock);
5910 : : #endif
5911 : 0 : finally:
5912 : 0 : PyMem_Free(name);
5913 : 0 : return ret;
5914 : : }
5915 : :
5916 : : PyDoc_STRVAR(ghbn_ex_doc,
5917 : : "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
5918 : : \n\
5919 : : Return the true host name, a list of aliases, and a list of IP addresses,\n\
5920 : : for a host. The host argument is a string giving a host name or IP number.");
5921 : : #endif
5922 : :
5923 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
5924 : : /* Python interface to gethostbyaddr(IP). */
5925 : :
5926 : : /*ARGSUSED*/
5927 : : static PyObject *
5928 : 0 : socket_gethostbyaddr(PyObject *self, PyObject *args)
5929 : : {
5930 : : sock_addr_t addr;
5931 : 0 : struct sockaddr *sa = SAS2SA(&addr);
5932 : : char *ip_num;
5933 : : struct hostent *h;
5934 : 0 : PyObject *ret = NULL;
5935 : : #ifdef HAVE_GETHOSTBYNAME_R
5936 : : struct hostent hp_allocated;
5937 : : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5938 : : struct hostent_data data;
5939 : : #else
5940 : : /* glibcs up to 2.10 assume that the buf argument to
5941 : : gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
5942 : : does not ensure. The attribute below instructs the compiler
5943 : : to maintain this alignment. */
5944 : : char buf[16384] Py_ALIGNED(8);
5945 : 0 : int buf_len = (sizeof buf) - 1;
5946 : : int errnop;
5947 : : #endif
5948 : : #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
5949 : : int result;
5950 : : #endif
5951 : : #endif /* HAVE_GETHOSTBYNAME_R */
5952 : : const char *ap;
5953 : : int al;
5954 : : int af;
5955 : :
5956 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
5957 : 0 : return NULL;
5958 [ # # ]: 0 : if (PySys_Audit("socket.gethostbyaddr", "O", args) < 0) {
5959 : 0 : goto finally;
5960 : : }
5961 : 0 : af = AF_UNSPEC;
5962 [ # # ]: 0 : if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
5963 : 0 : goto finally;
5964 : 0 : af = sa->sa_family;
5965 : 0 : ap = NULL;
5966 : : /* al = 0; */
5967 [ # # # ]: 0 : switch (af) {
5968 : 0 : case AF_INET:
5969 : 0 : ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
5970 : 0 : al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
5971 : 0 : break;
5972 : : #ifdef ENABLE_IPV6
5973 : 0 : case AF_INET6:
5974 : 0 : ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
5975 : 0 : al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
5976 : 0 : break;
5977 : : #endif
5978 : 0 : default:
5979 : 0 : PyErr_SetString(PyExc_OSError, "unsupported address family");
5980 : 0 : goto finally;
5981 : : }
5982 : 0 : Py_BEGIN_ALLOW_THREADS
5983 : : #ifdef HAVE_GETHOSTBYNAME_R
5984 : : #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
5985 : 0 : gethostbyaddr_r(ap, al, af,
5986 : : &hp_allocated, buf, buf_len,
5987 : : &h, &errnop);
5988 : : #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
5989 : : h = gethostbyaddr_r(ap, al, af,
5990 : : &hp_allocated, buf, buf_len, &errnop);
5991 : : #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
5992 : : memset((void *) &data, '\0', sizeof(data));
5993 : : result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
5994 : : h = (result != 0) ? NULL : &hp_allocated;
5995 : : #endif
5996 : : #else /* not HAVE_GETHOSTBYNAME_R */
5997 : : #ifdef USE_GETHOSTBYNAME_LOCK
5998 : : PyThread_acquire_lock(netdb_lock, 1);
5999 : : #endif
6000 : : SUPPRESS_DEPRECATED_CALL
6001 : : h = gethostbyaddr(ap, al, af);
6002 : : #endif /* HAVE_GETHOSTBYNAME_R */
6003 : 0 : Py_END_ALLOW_THREADS
6004 : 0 : ret = gethost_common(h, SAS2SA(&addr), sizeof(addr), af);
6005 : : #ifdef USE_GETHOSTBYNAME_LOCK
6006 : : PyThread_release_lock(netdb_lock);
6007 : : #endif
6008 : 0 : finally:
6009 : 0 : PyMem_Free(ip_num);
6010 : 0 : return ret;
6011 : : }
6012 : :
6013 : : PyDoc_STRVAR(gethostbyaddr_doc,
6014 : : "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
6015 : : \n\
6016 : : Return the true host name, a list of aliases, and a list of IP addresses,\n\
6017 : : for a host. The host argument is a string giving a host name or IP number.");
6018 : : #endif
6019 : :
6020 : : #ifdef HAVE_GETSERVBYNAME
6021 : : /* Python interface to getservbyname(name).
6022 : : This only returns the port number, since the other info is already
6023 : : known or not useful (like the list of aliases). */
6024 : :
6025 : : /*ARGSUSED*/
6026 : : static PyObject *
6027 : 0 : socket_getservbyname(PyObject *self, PyObject *args)
6028 : : {
6029 : 0 : const char *name, *proto=NULL;
6030 : : struct servent *sp;
6031 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
6032 : 0 : return NULL;
6033 : :
6034 [ # # ]: 0 : if (PySys_Audit("socket.getservbyname", "ss", name, proto) < 0) {
6035 : 0 : return NULL;
6036 : : }
6037 : :
6038 : 0 : Py_BEGIN_ALLOW_THREADS
6039 : 0 : sp = getservbyname(name, proto);
6040 : 0 : Py_END_ALLOW_THREADS
6041 [ # # ]: 0 : if (sp == NULL) {
6042 : 0 : PyErr_SetString(PyExc_OSError, "service/proto not found");
6043 : 0 : return NULL;
6044 : : }
6045 : 0 : return PyLong_FromLong((long) ntohs(sp->s_port));
6046 : : }
6047 : :
6048 : : PyDoc_STRVAR(getservbyname_doc,
6049 : : "getservbyname(servicename[, protocolname]) -> integer\n\
6050 : : \n\
6051 : : Return a port number from a service name and protocol name.\n\
6052 : : The optional protocol name, if given, should be 'tcp' or 'udp',\n\
6053 : : otherwise any protocol will match.");
6054 : : #endif
6055 : :
6056 : : #ifdef HAVE_GETSERVBYPORT
6057 : : /* Python interface to getservbyport(port).
6058 : : This only returns the service name, since the other info is already
6059 : : known or not useful (like the list of aliases). */
6060 : :
6061 : : /*ARGSUSED*/
6062 : : static PyObject *
6063 : 0 : socket_getservbyport(PyObject *self, PyObject *args)
6064 : : {
6065 : : int port;
6066 : 0 : const char *proto=NULL;
6067 : : struct servent *sp;
6068 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
6069 : 0 : return NULL;
6070 [ # # # # ]: 0 : if (port < 0 || port > 0xffff) {
6071 : 0 : PyErr_SetString(
6072 : : PyExc_OverflowError,
6073 : : "getservbyport: port must be 0-65535.");
6074 : 0 : return NULL;
6075 : : }
6076 : :
6077 [ # # ]: 0 : if (PySys_Audit("socket.getservbyport", "is", port, proto) < 0) {
6078 : 0 : return NULL;
6079 : : }
6080 : :
6081 : 0 : Py_BEGIN_ALLOW_THREADS
6082 : 0 : sp = getservbyport(htons((short)port), proto);
6083 : 0 : Py_END_ALLOW_THREADS
6084 [ # # ]: 0 : if (sp == NULL) {
6085 : 0 : PyErr_SetString(PyExc_OSError, "port/proto not found");
6086 : 0 : return NULL;
6087 : : }
6088 : 0 : return PyUnicode_FromString(sp->s_name);
6089 : : }
6090 : :
6091 : : PyDoc_STRVAR(getservbyport_doc,
6092 : : "getservbyport(port[, protocolname]) -> string\n\
6093 : : \n\
6094 : : Return the service name from a port number and protocol name.\n\
6095 : : The optional protocol name, if given, should be 'tcp' or 'udp',\n\
6096 : : otherwise any protocol will match.");
6097 : : #endif
6098 : :
6099 : : #ifdef HAVE_GETPROTOBYNAME
6100 : : /* Python interface to getprotobyname(name).
6101 : : This only returns the protocol number, since the other info is
6102 : : already known or not useful (like the list of aliases). */
6103 : :
6104 : : /*ARGSUSED*/
6105 : : static PyObject *
6106 : 0 : socket_getprotobyname(PyObject *self, PyObject *args)
6107 : : {
6108 : : const char *name;
6109 : : struct protoent *sp;
6110 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
6111 : 0 : return NULL;
6112 : 0 : Py_BEGIN_ALLOW_THREADS
6113 : 0 : sp = getprotobyname(name);
6114 : 0 : Py_END_ALLOW_THREADS
6115 [ # # ]: 0 : if (sp == NULL) {
6116 : 0 : PyErr_SetString(PyExc_OSError, "protocol not found");
6117 : 0 : return NULL;
6118 : : }
6119 : 0 : return PyLong_FromLong((long) sp->p_proto);
6120 : : }
6121 : :
6122 : : PyDoc_STRVAR(getprotobyname_doc,
6123 : : "getprotobyname(name) -> integer\n\
6124 : : \n\
6125 : : Return the protocol number for the named protocol. (Rarely used.)");
6126 : : #endif
6127 : :
6128 : : static PyObject *
6129 : 0 : socket_close(PyObject *self, PyObject *fdobj)
6130 : : {
6131 : : SOCKET_T fd;
6132 : : int res;
6133 : :
6134 : 0 : fd = PyLong_AsSocket_t(fdobj);
6135 [ # # # # ]: 0 : if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
6136 : 0 : return NULL;
6137 : 0 : Py_BEGIN_ALLOW_THREADS
6138 : 0 : res = SOCKETCLOSE(fd);
6139 : 0 : Py_END_ALLOW_THREADS
6140 : : /* bpo-30319: The peer can already have closed the connection.
6141 : : Python ignores ECONNRESET on close(). */
6142 [ # # # # ]: 0 : if (res < 0 && !CHECK_ERRNO(ECONNRESET)) {
6143 : 0 : return set_error();
6144 : : }
6145 : 0 : Py_RETURN_NONE;
6146 : : }
6147 : :
6148 : : PyDoc_STRVAR(close_doc,
6149 : : "close(integer) -> None\n\
6150 : : \n\
6151 : : Close an integer socket file descriptor. This is like os.close(), but for\n\
6152 : : sockets; on some platforms os.close() won't work for socket file descriptors.");
6153 : :
6154 : : #ifndef NO_DUP
6155 : : /* dup() function for socket fds */
6156 : :
6157 : : static PyObject *
6158 : 0 : socket_dup(PyObject *self, PyObject *fdobj)
6159 : : {
6160 : : SOCKET_T fd, newfd;
6161 : : PyObject *newfdobj;
6162 : : #ifdef MS_WINDOWS
6163 : : WSAPROTOCOL_INFOW info;
6164 : : #endif
6165 : :
6166 : 0 : fd = PyLong_AsSocket_t(fdobj);
6167 [ # # # # ]: 0 : if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) {
6168 : 0 : return NULL;
6169 : : }
6170 : :
6171 : : #ifdef MS_WINDOWS
6172 : : if (WSADuplicateSocketW(fd, GetCurrentProcessId(), &info))
6173 : : return set_error();
6174 : :
6175 : : newfd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
6176 : : FROM_PROTOCOL_INFO,
6177 : : &info, 0, WSA_FLAG_OVERLAPPED);
6178 : : if (newfd == INVALID_SOCKET) {
6179 : : return set_error();
6180 : : }
6181 : :
6182 : : if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
6183 : : closesocket(newfd);
6184 : : PyErr_SetFromWindowsErr(0);
6185 : : return NULL;
6186 : : }
6187 : : #else
6188 : : /* On UNIX, dup can be used to duplicate the file descriptor of a socket */
6189 : 0 : newfd = _Py_dup(fd);
6190 [ # # ]: 0 : if (newfd == INVALID_SOCKET) {
6191 : 0 : return NULL;
6192 : : }
6193 : : #endif
6194 : :
6195 : 0 : newfdobj = PyLong_FromSocket_t(newfd);
6196 [ # # ]: 0 : if (newfdobj == NULL) {
6197 : 0 : SOCKETCLOSE(newfd);
6198 : : }
6199 : 0 : return newfdobj;
6200 : : }
6201 : :
6202 : : PyDoc_STRVAR(dup_doc,
6203 : : "dup(integer) -> integer\n\
6204 : : \n\
6205 : : Duplicate an integer socket file descriptor. This is like os.dup(), but for\n\
6206 : : sockets; on some platforms os.dup() won't work for socket file descriptors.");
6207 : : #endif
6208 : :
6209 : :
6210 : : #ifdef HAVE_SOCKETPAIR
6211 : : /* Create a pair of sockets using the socketpair() function.
6212 : : Arguments as for socket() except the default family is AF_UNIX if
6213 : : defined on the platform; otherwise, the default is AF_INET. */
6214 : :
6215 : : /*ARGSUSED*/
6216 : : static PyObject *
6217 : 0 : socket_socketpair(PyObject *self, PyObject *args)
6218 : : {
6219 : 0 : PySocketSockObject *s0 = NULL, *s1 = NULL;
6220 : : SOCKET_T sv[2];
6221 : 0 : int family, type = SOCK_STREAM, proto = 0;
6222 : 0 : PyObject *res = NULL;
6223 : : #ifdef SOCK_CLOEXEC
6224 : 0 : int *atomic_flag_works = &sock_cloexec_works;
6225 : : #else
6226 : : int *atomic_flag_works = NULL;
6227 : : #endif
6228 : : int ret;
6229 : :
6230 : : #if defined(AF_UNIX)
6231 : 0 : family = AF_UNIX;
6232 : : #else
6233 : : family = AF_INET;
6234 : : #endif
6235 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "|iii:socketpair",
6236 : : &family, &type, &proto))
6237 : 0 : return NULL;
6238 : :
6239 : : /* Create a pair of socket fds */
6240 : 0 : Py_BEGIN_ALLOW_THREADS
6241 : : #ifdef SOCK_CLOEXEC
6242 [ # # ]: 0 : if (sock_cloexec_works != 0) {
6243 : 0 : ret = socketpair(family, type | SOCK_CLOEXEC, proto, sv);
6244 [ # # ]: 0 : if (sock_cloexec_works == -1) {
6245 [ # # ]: 0 : if (ret >= 0) {
6246 : 0 : sock_cloexec_works = 1;
6247 : : }
6248 [ # # ]: 0 : else if (errno == EINVAL) {
6249 : : /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
6250 : 0 : sock_cloexec_works = 0;
6251 : 0 : ret = socketpair(family, type, proto, sv);
6252 : : }
6253 : : }
6254 : : }
6255 : : else
6256 : : #endif
6257 : : {
6258 : 0 : ret = socketpair(family, type, proto, sv);
6259 : : }
6260 : 0 : Py_END_ALLOW_THREADS
6261 : :
6262 [ # # ]: 0 : if (ret < 0)
6263 : 0 : return set_error();
6264 : :
6265 [ # # ]: 0 : if (_Py_set_inheritable(sv[0], 0, atomic_flag_works) < 0)
6266 : 0 : goto finally;
6267 [ # # ]: 0 : if (_Py_set_inheritable(sv[1], 0, atomic_flag_works) < 0)
6268 : 0 : goto finally;
6269 : :
6270 : 0 : s0 = new_sockobject(sv[0], family, type, proto);
6271 [ # # ]: 0 : if (s0 == NULL)
6272 : 0 : goto finally;
6273 : 0 : s1 = new_sockobject(sv[1], family, type, proto);
6274 [ # # ]: 0 : if (s1 == NULL)
6275 : 0 : goto finally;
6276 : 0 : res = PyTuple_Pack(2, s0, s1);
6277 : :
6278 : 0 : finally:
6279 [ # # ]: 0 : if (res == NULL) {
6280 [ # # ]: 0 : if (s0 == NULL)
6281 : 0 : SOCKETCLOSE(sv[0]);
6282 [ # # ]: 0 : if (s1 == NULL)
6283 : 0 : SOCKETCLOSE(sv[1]);
6284 : : }
6285 : 0 : Py_XDECREF(s0);
6286 : 0 : Py_XDECREF(s1);
6287 : 0 : return res;
6288 : : }
6289 : :
6290 : : PyDoc_STRVAR(socketpair_doc,
6291 : : "socketpair([family[, type [, proto]]]) -> (socket object, socket object)\n\
6292 : : \n\
6293 : : Create a pair of socket objects from the sockets returned by the platform\n\
6294 : : socketpair() function.\n\
6295 : : The arguments are the same as for socket() except the default family is\n\
6296 : : AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
6297 : :
6298 : : #endif /* HAVE_SOCKETPAIR */
6299 : :
6300 : :
6301 : : static PyObject *
6302 : 0 : socket_ntohs(PyObject *self, PyObject *args)
6303 : : {
6304 : : int x;
6305 : :
6306 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "i:ntohs", &x)) {
6307 : 0 : return NULL;
6308 : : }
6309 [ # # ]: 0 : if (x < 0) {
6310 : 0 : PyErr_SetString(PyExc_OverflowError,
6311 : : "ntohs: can't convert negative Python int to C "
6312 : : "16-bit unsigned integer");
6313 : 0 : return NULL;
6314 : : }
6315 [ # # ]: 0 : if (x > 0xffff) {
6316 : 0 : PyErr_SetString(PyExc_OverflowError,
6317 : : "ntohs: Python int too large to convert to C "
6318 : : "16-bit unsigned integer");
6319 : 0 : return NULL;
6320 : : }
6321 : 0 : return PyLong_FromUnsignedLong(ntohs((unsigned short)x));
6322 : : }
6323 : :
6324 : : PyDoc_STRVAR(ntohs_doc,
6325 : : "ntohs(integer) -> integer\n\
6326 : : \n\
6327 : : Convert a 16-bit unsigned integer from network to host byte order.");
6328 : :
6329 : :
6330 : : static PyObject *
6331 : 0 : socket_ntohl(PyObject *self, PyObject *arg)
6332 : : {
6333 : : unsigned long x;
6334 : :
6335 [ # # ]: 0 : if (PyLong_Check(arg)) {
6336 : 0 : x = PyLong_AsUnsignedLong(arg);
6337 [ # # # # ]: 0 : if (x == (unsigned long) -1 && PyErr_Occurred())
6338 : 0 : return NULL;
6339 : : #if SIZEOF_LONG > 4
6340 : : {
6341 : : unsigned long y;
6342 : : /* only want the trailing 32 bits */
6343 : 0 : y = x & 0xFFFFFFFFUL;
6344 [ # # ]: 0 : if (y ^ x)
6345 : 0 : return PyErr_Format(PyExc_OverflowError,
6346 : : "int larger than 32 bits");
6347 : 0 : x = y;
6348 : : }
6349 : : #endif
6350 : : }
6351 : : else
6352 : 0 : return PyErr_Format(PyExc_TypeError,
6353 : : "expected int, %s found",
6354 : 0 : Py_TYPE(arg)->tp_name);
6355 : 0 : return PyLong_FromUnsignedLong(ntohl(x));
6356 : : }
6357 : :
6358 : : PyDoc_STRVAR(ntohl_doc,
6359 : : "ntohl(integer) -> integer\n\
6360 : : \n\
6361 : : Convert a 32-bit integer from network to host byte order.");
6362 : :
6363 : :
6364 : : static PyObject *
6365 : 0 : socket_htons(PyObject *self, PyObject *args)
6366 : : {
6367 : : int x;
6368 : :
6369 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "i:htons", &x)) {
6370 : 0 : return NULL;
6371 : : }
6372 [ # # ]: 0 : if (x < 0) {
6373 : 0 : PyErr_SetString(PyExc_OverflowError,
6374 : : "htons: can't convert negative Python int to C "
6375 : : "16-bit unsigned integer");
6376 : 0 : return NULL;
6377 : : }
6378 [ # # ]: 0 : if (x > 0xffff) {
6379 : 0 : PyErr_SetString(PyExc_OverflowError,
6380 : : "htons: Python int too large to convert to C "
6381 : : "16-bit unsigned integer");
6382 : 0 : return NULL;
6383 : : }
6384 : 0 : return PyLong_FromUnsignedLong(htons((unsigned short)x));
6385 : : }
6386 : :
6387 : : PyDoc_STRVAR(htons_doc,
6388 : : "htons(integer) -> integer\n\
6389 : : \n\
6390 : : Convert a 16-bit unsigned integer from host to network byte order.");
6391 : :
6392 : :
6393 : : static PyObject *
6394 : 0 : socket_htonl(PyObject *self, PyObject *arg)
6395 : : {
6396 : : unsigned long x;
6397 : :
6398 [ # # ]: 0 : if (PyLong_Check(arg)) {
6399 : 0 : x = PyLong_AsUnsignedLong(arg);
6400 [ # # # # ]: 0 : if (x == (unsigned long) -1 && PyErr_Occurred())
6401 : 0 : return NULL;
6402 : : #if SIZEOF_LONG > 4
6403 : : {
6404 : : unsigned long y;
6405 : : /* only want the trailing 32 bits */
6406 : 0 : y = x & 0xFFFFFFFFUL;
6407 [ # # ]: 0 : if (y ^ x)
6408 : 0 : return PyErr_Format(PyExc_OverflowError,
6409 : : "int larger than 32 bits");
6410 : 0 : x = y;
6411 : : }
6412 : : #endif
6413 : : }
6414 : : else
6415 : 0 : return PyErr_Format(PyExc_TypeError,
6416 : : "expected int, %s found",
6417 : 0 : Py_TYPE(arg)->tp_name);
6418 : 0 : return PyLong_FromUnsignedLong(htonl((unsigned long)x));
6419 : : }
6420 : :
6421 : : PyDoc_STRVAR(htonl_doc,
6422 : : "htonl(integer) -> integer\n\
6423 : : \n\
6424 : : Convert a 32-bit integer from host to network byte order.");
6425 : :
6426 : : /* socket.inet_aton() and socket.inet_ntoa() functions. */
6427 : :
6428 : : PyDoc_STRVAR(inet_aton_doc,
6429 : : "inet_aton(string) -> bytes giving packed 32-bit IP representation\n\
6430 : : \n\
6431 : : Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
6432 : : binary format used in low-level network functions.");
6433 : :
6434 : : static PyObject*
6435 : 0 : socket_inet_aton(PyObject *self, PyObject *args)
6436 : : {
6437 : : #ifdef HAVE_INET_ATON
6438 : : struct in_addr buf;
6439 : : #endif
6440 : :
6441 : : #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6442 : : #if (SIZEOF_INT != 4)
6443 : : #error "Not sure if in_addr_t exists and int is not 32-bits."
6444 : : #endif
6445 : : /* Have to use inet_addr() instead */
6446 : : unsigned int packed_addr;
6447 : : #endif
6448 : : const char *ip_addr;
6449 : :
6450 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
6451 : 0 : return NULL;
6452 : :
6453 : :
6454 : : #ifdef HAVE_INET_ATON
6455 : :
6456 : : #ifdef USE_INET_ATON_WEAKLINK
6457 : : if (inet_aton != NULL) {
6458 : : #endif
6459 [ # # ]: 0 : if (inet_aton(ip_addr, &buf))
6460 : 0 : return PyBytes_FromStringAndSize((char *)(&buf),
6461 : : sizeof(buf));
6462 : :
6463 : 0 : PyErr_SetString(PyExc_OSError,
6464 : : "illegal IP address string passed to inet_aton");
6465 : 0 : return NULL;
6466 : :
6467 : : #ifdef USE_INET_ATON_WEAKLINK
6468 : : } else {
6469 : : #endif
6470 : :
6471 : : #endif
6472 : :
6473 : : #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
6474 : :
6475 : : /* special-case this address as inet_addr might return INADDR_NONE
6476 : : * for this */
6477 : : if (strcmp(ip_addr, "255.255.255.255") == 0) {
6478 : : packed_addr = INADDR_BROADCAST;
6479 : : } else {
6480 : :
6481 : : SUPPRESS_DEPRECATED_CALL
6482 : : packed_addr = inet_addr(ip_addr);
6483 : :
6484 : : if (packed_addr == INADDR_NONE) { /* invalid address */
6485 : : PyErr_SetString(PyExc_OSError,
6486 : : "illegal IP address string passed to inet_aton");
6487 : : return NULL;
6488 : : }
6489 : : }
6490 : : return PyBytes_FromStringAndSize((char *) &packed_addr,
6491 : : sizeof(packed_addr));
6492 : :
6493 : : #ifdef USE_INET_ATON_WEAKLINK
6494 : : }
6495 : : #endif
6496 : :
6497 : : #endif
6498 : : }
6499 : :
6500 : : #ifdef HAVE_INET_NTOA
6501 : : PyDoc_STRVAR(inet_ntoa_doc,
6502 : : "inet_ntoa(packed_ip) -> ip_address_string\n\
6503 : : \n\
6504 : : Convert an IP address from 32-bit packed binary format to string format");
6505 : :
6506 : : static PyObject*
6507 : 0 : socket_inet_ntoa(PyObject *self, PyObject *args)
6508 : : {
6509 : : Py_buffer packed_ip;
6510 : : struct in_addr packed_addr;
6511 : :
6512 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "y*:inet_ntoa", &packed_ip)) {
6513 : 0 : return NULL;
6514 : : }
6515 : :
6516 [ # # ]: 0 : if (packed_ip.len != sizeof(packed_addr)) {
6517 : 0 : PyErr_SetString(PyExc_OSError,
6518 : : "packed IP wrong length for inet_ntoa");
6519 : 0 : PyBuffer_Release(&packed_ip);
6520 : 0 : return NULL;
6521 : : }
6522 : :
6523 : 0 : memcpy(&packed_addr, packed_ip.buf, packed_ip.len);
6524 : 0 : PyBuffer_Release(&packed_ip);
6525 : :
6526 : : SUPPRESS_DEPRECATED_CALL
6527 : 0 : return PyUnicode_FromString(inet_ntoa(packed_addr));
6528 : : }
6529 : : #endif // HAVE_INET_NTOA
6530 : :
6531 : : #ifdef HAVE_INET_PTON
6532 : :
6533 : : PyDoc_STRVAR(inet_pton_doc,
6534 : : "inet_pton(af, ip) -> packed IP address string\n\
6535 : : \n\
6536 : : Convert an IP address from string format to a packed string suitable\n\
6537 : : for use with low-level network functions.");
6538 : :
6539 : : static PyObject *
6540 : 0 : socket_inet_pton(PyObject *self, PyObject *args)
6541 : : {
6542 : : int af;
6543 : : const char* ip;
6544 : : int retval;
6545 : : #ifdef ENABLE_IPV6
6546 : : char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
6547 : : #else
6548 : : char packed[sizeof(struct in_addr)];
6549 : : #endif
6550 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
6551 : 0 : return NULL;
6552 : : }
6553 : :
6554 : : #if !defined(ENABLE_IPV6) && defined(AF_INET6)
6555 : : if(af == AF_INET6) {
6556 : : PyErr_SetString(PyExc_OSError,
6557 : : "can't use AF_INET6, IPv6 is disabled");
6558 : : return NULL;
6559 : : }
6560 : : #endif
6561 : :
6562 : 0 : retval = inet_pton(af, ip, packed);
6563 [ # # ]: 0 : if (retval < 0) {
6564 : 0 : PyErr_SetFromErrno(PyExc_OSError);
6565 : 0 : return NULL;
6566 [ # # ]: 0 : } else if (retval == 0) {
6567 : 0 : PyErr_SetString(PyExc_OSError,
6568 : : "illegal IP address string passed to inet_pton");
6569 : 0 : return NULL;
6570 [ # # ]: 0 : } else if (af == AF_INET) {
6571 : 0 : return PyBytes_FromStringAndSize(packed,
6572 : : sizeof(struct in_addr));
6573 : : #ifdef ENABLE_IPV6
6574 [ # # ]: 0 : } else if (af == AF_INET6) {
6575 : 0 : return PyBytes_FromStringAndSize(packed,
6576 : : sizeof(struct in6_addr));
6577 : : #endif
6578 : : } else {
6579 : 0 : PyErr_SetString(PyExc_OSError, "unknown address family");
6580 : 0 : return NULL;
6581 : : }
6582 : : }
6583 : :
6584 : : PyDoc_STRVAR(inet_ntop_doc,
6585 : : "inet_ntop(af, packed_ip) -> string formatted IP address\n\
6586 : : \n\
6587 : : Convert a packed IP address of the given family to string format.");
6588 : :
6589 : : static PyObject *
6590 : 0 : socket_inet_ntop(PyObject *self, PyObject *args)
6591 : : {
6592 : : int af;
6593 : : Py_buffer packed_ip;
6594 : : const char* retval;
6595 : : #ifdef ENABLE_IPV6
6596 : : char ip[Py_MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
6597 : : #else
6598 : : char ip[INET_ADDRSTRLEN];
6599 : : #endif
6600 : :
6601 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "iy*:inet_ntop", &af, &packed_ip)) {
6602 : 0 : return NULL;
6603 : : }
6604 : :
6605 [ # # ]: 0 : if (af == AF_INET) {
6606 [ # # ]: 0 : if (packed_ip.len != sizeof(struct in_addr)) {
6607 : 0 : PyErr_SetString(PyExc_ValueError,
6608 : : "invalid length of packed IP address string");
6609 : 0 : PyBuffer_Release(&packed_ip);
6610 : 0 : return NULL;
6611 : : }
6612 : : #ifdef ENABLE_IPV6
6613 [ # # ]: 0 : } else if (af == AF_INET6) {
6614 [ # # ]: 0 : if (packed_ip.len != sizeof(struct in6_addr)) {
6615 : 0 : PyErr_SetString(PyExc_ValueError,
6616 : : "invalid length of packed IP address string");
6617 : 0 : PyBuffer_Release(&packed_ip);
6618 : 0 : return NULL;
6619 : : }
6620 : : #endif
6621 : : } else {
6622 : 0 : PyErr_Format(PyExc_ValueError,
6623 : : "unknown address family %d", af);
6624 : 0 : PyBuffer_Release(&packed_ip);
6625 : 0 : return NULL;
6626 : : }
6627 : :
6628 : : /* inet_ntop guarantee NUL-termination of resulting string. */
6629 : 0 : retval = inet_ntop(af, packed_ip.buf, ip, sizeof(ip));
6630 : 0 : PyBuffer_Release(&packed_ip);
6631 [ # # ]: 0 : if (!retval) {
6632 : 0 : PyErr_SetFromErrno(PyExc_OSError);
6633 : 0 : return NULL;
6634 : : } else {
6635 : 0 : return PyUnicode_FromString(retval);
6636 : : }
6637 : : }
6638 : :
6639 : : #endif /* HAVE_INET_PTON */
6640 : :
6641 : : #ifdef HAVE_GETADDRINFO
6642 : : /* Python interface to getaddrinfo(host, port). */
6643 : :
6644 : : /*ARGSUSED*/
6645 : : static PyObject *
6646 : 0 : socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
6647 : : {
6648 : : static char* kwnames[] = {"host", "port", "family", "type", "proto",
6649 : : "flags", 0};
6650 : : struct addrinfo hints, *res;
6651 : 0 : struct addrinfo *res0 = NULL;
6652 : 0 : PyObject *hobj = NULL;
6653 : 0 : PyObject *pobj = (PyObject *)NULL;
6654 : 0 : PyObject *pstr = NULL;
6655 : : const char *hptr, *pptr;
6656 : : int family, socktype, protocol, flags;
6657 : : int error;
6658 : 0 : PyObject *all = (PyObject *)NULL;
6659 : 0 : PyObject *idna = NULL;
6660 : :
6661 : 0 : socktype = protocol = flags = 0;
6662 : 0 : family = AF_UNSPEC;
6663 [ # # ]: 0 : if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo",
6664 : : kwnames, &hobj, &pobj, &family, &socktype,
6665 : : &protocol, &flags)) {
6666 : 0 : return NULL;
6667 : : }
6668 [ # # ]: 0 : if (hobj == Py_None) {
6669 : 0 : hptr = NULL;
6670 [ # # ]: 0 : } else if (PyUnicode_Check(hobj)) {
6671 : 0 : idna = PyUnicode_AsEncodedString(hobj, "idna", NULL);
6672 [ # # ]: 0 : if (!idna)
6673 : 0 : return NULL;
6674 : : assert(PyBytes_Check(idna));
6675 : 0 : hptr = PyBytes_AS_STRING(idna);
6676 [ # # ]: 0 : } else if (PyBytes_Check(hobj)) {
6677 : 0 : hptr = PyBytes_AsString(hobj);
6678 : : } else {
6679 : 0 : PyErr_SetString(PyExc_TypeError,
6680 : : "getaddrinfo() argument 1 must be string or None");
6681 : 0 : return NULL;
6682 : : }
6683 [ # # ]: 0 : if (PyLong_CheckExact(pobj)) {
6684 : 0 : pstr = PyObject_Str(pobj);
6685 [ # # ]: 0 : if (pstr == NULL)
6686 : 0 : goto err;
6687 : : assert(PyUnicode_Check(pstr));
6688 : 0 : pptr = PyUnicode_AsUTF8(pstr);
6689 [ # # ]: 0 : if (pptr == NULL)
6690 : 0 : goto err;
6691 [ # # ]: 0 : } else if (PyUnicode_Check(pobj)) {
6692 : 0 : pptr = PyUnicode_AsUTF8(pobj);
6693 [ # # ]: 0 : if (pptr == NULL)
6694 : 0 : goto err;
6695 [ # # ]: 0 : } else if (PyBytes_Check(pobj)) {
6696 : 0 : pptr = PyBytes_AS_STRING(pobj);
6697 [ # # ]: 0 : } else if (pobj == Py_None) {
6698 : 0 : pptr = (char *)NULL;
6699 : : } else {
6700 : 0 : PyErr_SetString(PyExc_OSError, "Int or String expected");
6701 : 0 : goto err;
6702 : : }
6703 : : #if defined(__APPLE__) && defined(AI_NUMERICSERV)
6704 : : if ((flags & AI_NUMERICSERV) && (pptr == NULL || (pptr[0] == '0' && pptr[1] == 0))) {
6705 : : /* On OSX up to at least OSX 10.8 getaddrinfo crashes
6706 : : * if AI_NUMERICSERV is set and the servname is NULL or "0".
6707 : : * This workaround avoids a segfault in libsystem.
6708 : : */
6709 : : pptr = "00";
6710 : : }
6711 : : #endif
6712 : :
6713 [ # # ]: 0 : if (PySys_Audit("socket.getaddrinfo", "OOiii",
6714 : : hobj, pobj, family, socktype, protocol) < 0) {
6715 : 0 : return NULL;
6716 : : }
6717 : :
6718 : 0 : memset(&hints, 0, sizeof(hints));
6719 : 0 : hints.ai_family = family;
6720 : 0 : hints.ai_socktype = socktype;
6721 : 0 : hints.ai_protocol = protocol;
6722 : 0 : hints.ai_flags = flags;
6723 : 0 : Py_BEGIN_ALLOW_THREADS
6724 : 0 : error = getaddrinfo(hptr, pptr, &hints, &res0);
6725 : 0 : Py_END_ALLOW_THREADS
6726 [ # # ]: 0 : if (error) {
6727 : 0 : res0 = NULL; // gh-100795
6728 : 0 : set_gaierror(error);
6729 : 0 : goto err;
6730 : : }
6731 : :
6732 : 0 : all = PyList_New(0);
6733 [ # # ]: 0 : if (all == NULL)
6734 : 0 : goto err;
6735 [ # # ]: 0 : for (res = res0; res; res = res->ai_next) {
6736 : : PyObject *single;
6737 : : PyObject *addr =
6738 : 0 : makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
6739 [ # # ]: 0 : if (addr == NULL)
6740 : 0 : goto err;
6741 : 0 : single = Py_BuildValue("iiisO", res->ai_family,
6742 : : res->ai_socktype, res->ai_protocol,
6743 [ # # ]: 0 : res->ai_canonname ? res->ai_canonname : "",
6744 : : addr);
6745 : 0 : Py_DECREF(addr);
6746 [ # # ]: 0 : if (single == NULL)
6747 : 0 : goto err;
6748 : :
6749 [ # # ]: 0 : if (PyList_Append(all, single)) {
6750 : 0 : Py_DECREF(single);
6751 : 0 : goto err;
6752 : : }
6753 : 0 : Py_DECREF(single);
6754 : : }
6755 : 0 : Py_XDECREF(idna);
6756 : 0 : Py_XDECREF(pstr);
6757 [ # # ]: 0 : if (res0)
6758 : 0 : freeaddrinfo(res0);
6759 : 0 : return all;
6760 : 0 : err:
6761 : 0 : Py_XDECREF(all);
6762 : 0 : Py_XDECREF(idna);
6763 : 0 : Py_XDECREF(pstr);
6764 [ # # ]: 0 : if (res0)
6765 : 0 : freeaddrinfo(res0);
6766 : 0 : return (PyObject *)NULL;
6767 : : }
6768 : :
6769 : : PyDoc_STRVAR(getaddrinfo_doc,
6770 : : "getaddrinfo(host, port [, family, type, proto, flags])\n\
6771 : : -> list of (family, type, proto, canonname, sockaddr)\n\
6772 : : \n\
6773 : : Resolve host and port into addrinfo struct.");
6774 : : #endif // HAVE_GETADDRINFO
6775 : :
6776 : : #ifdef HAVE_GETNAMEINFO
6777 : : /* Python interface to getnameinfo(sa, flags). */
6778 : :
6779 : : /*ARGSUSED*/
6780 : : static PyObject *
6781 : 0 : socket_getnameinfo(PyObject *self, PyObject *args)
6782 : : {
6783 : 0 : PyObject *sa = (PyObject *)NULL;
6784 : : int flags;
6785 : : const char *hostp;
6786 : : int port;
6787 : : unsigned int flowinfo, scope_id;
6788 : : char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
6789 : 0 : struct addrinfo hints, *res = NULL;
6790 : : int error;
6791 : 0 : PyObject *ret = (PyObject *)NULL;
6792 : : PyObject *name;
6793 : :
6794 : 0 : flags = flowinfo = scope_id = 0;
6795 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
6796 : 0 : return NULL;
6797 [ # # ]: 0 : if (!PyTuple_Check(sa)) {
6798 : 0 : PyErr_SetString(PyExc_TypeError,
6799 : : "getnameinfo() argument 1 must be a tuple");
6800 : 0 : return NULL;
6801 : : }
6802 [ # # ]: 0 : if (!PyArg_ParseTuple(sa, "si|II;getnameinfo(): illegal sockaddr argument",
6803 : : &hostp, &port, &flowinfo, &scope_id))
6804 : : {
6805 : 0 : return NULL;
6806 : : }
6807 [ # # ]: 0 : if (flowinfo > 0xfffff) {
6808 : 0 : PyErr_SetString(PyExc_OverflowError,
6809 : : "getnameinfo(): flowinfo must be 0-1048575.");
6810 : 0 : return NULL;
6811 : : }
6812 : :
6813 [ # # ]: 0 : if (PySys_Audit("socket.getnameinfo", "(O)", sa) < 0) {
6814 : 0 : return NULL;
6815 : : }
6816 : :
6817 : 0 : PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
6818 : 0 : memset(&hints, 0, sizeof(hints));
6819 : 0 : hints.ai_family = AF_UNSPEC;
6820 : 0 : hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
6821 : 0 : hints.ai_flags = AI_NUMERICHOST; /* don't do any name resolution */
6822 : 0 : Py_BEGIN_ALLOW_THREADS
6823 : 0 : error = getaddrinfo(hostp, pbuf, &hints, &res);
6824 : 0 : Py_END_ALLOW_THREADS
6825 [ # # ]: 0 : if (error) {
6826 : 0 : res = NULL; // gh-100795
6827 : 0 : set_gaierror(error);
6828 : 0 : goto fail;
6829 : : }
6830 [ # # ]: 0 : if (res->ai_next) {
6831 : 0 : PyErr_SetString(PyExc_OSError,
6832 : : "sockaddr resolved to multiple addresses");
6833 : 0 : goto fail;
6834 : : }
6835 [ # # # ]: 0 : switch (res->ai_family) {
6836 : 0 : case AF_INET:
6837 : : {
6838 [ # # ]: 0 : if (PyTuple_GET_SIZE(sa) != 2) {
6839 : 0 : PyErr_SetString(PyExc_OSError,
6840 : : "IPv4 sockaddr must be 2 tuple");
6841 : 0 : goto fail;
6842 : : }
6843 : 0 : break;
6844 : : }
6845 : : #ifdef ENABLE_IPV6
6846 : 0 : case AF_INET6:
6847 : : {
6848 : : struct sockaddr_in6 *sin6;
6849 : 0 : sin6 = (struct sockaddr_in6 *)res->ai_addr;
6850 : 0 : sin6->sin6_flowinfo = htonl(flowinfo);
6851 : 0 : sin6->sin6_scope_id = scope_id;
6852 : 0 : break;
6853 : : }
6854 : : #endif
6855 : : }
6856 : 0 : error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
6857 : : hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
6858 [ # # ]: 0 : if (error) {
6859 : 0 : set_gaierror(error);
6860 : 0 : goto fail;
6861 : : }
6862 : :
6863 : 0 : name = sock_decode_hostname(hbuf);
6864 [ # # ]: 0 : if (name == NULL)
6865 : 0 : goto fail;
6866 : 0 : ret = Py_BuildValue("Ns", name, pbuf);
6867 : :
6868 : 0 : fail:
6869 [ # # ]: 0 : if (res)
6870 : 0 : freeaddrinfo(res);
6871 : 0 : return ret;
6872 : : }
6873 : :
6874 : : PyDoc_STRVAR(getnameinfo_doc,
6875 : : "getnameinfo(sockaddr, flags) --> (host, port)\n\
6876 : : \n\
6877 : : Get host and port for a sockaddr.");
6878 : : #endif // HAVE_GETNAMEINFO
6879 : :
6880 : : /* Python API to getting and setting the default timeout value. */
6881 : :
6882 : : static PyObject *
6883 : 0 : socket_getdefaulttimeout(PyObject *self, PyObject *Py_UNUSED(ignored))
6884 : : {
6885 [ # # ]: 0 : if (defaulttimeout < 0) {
6886 : 0 : Py_RETURN_NONE;
6887 : : }
6888 : : else {
6889 : 0 : double seconds = _PyTime_AsSecondsDouble(defaulttimeout);
6890 : 0 : return PyFloat_FromDouble(seconds);
6891 : : }
6892 : : }
6893 : :
6894 : : PyDoc_STRVAR(getdefaulttimeout_doc,
6895 : : "getdefaulttimeout() -> timeout\n\
6896 : : \n\
6897 : : Returns the default timeout in seconds (float) for new socket objects.\n\
6898 : : A value of None indicates that new socket objects have no timeout.\n\
6899 : : When the socket module is first imported, the default is None.");
6900 : :
6901 : : static PyObject *
6902 : 0 : socket_setdefaulttimeout(PyObject *self, PyObject *arg)
6903 : : {
6904 : : _PyTime_t timeout;
6905 : :
6906 [ # # ]: 0 : if (socket_parse_timeout(&timeout, arg) < 0)
6907 : 0 : return NULL;
6908 : :
6909 : 0 : defaulttimeout = timeout;
6910 : :
6911 : 0 : Py_RETURN_NONE;
6912 : : }
6913 : :
6914 : : PyDoc_STRVAR(setdefaulttimeout_doc,
6915 : : "setdefaulttimeout(timeout)\n\
6916 : : \n\
6917 : : Set the default timeout in seconds (float) for new socket objects.\n\
6918 : : A value of None indicates that new socket objects have no timeout.\n\
6919 : : When the socket module is first imported, the default is None.");
6920 : :
6921 : : #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
6922 : : /* Python API for getting interface indices and names */
6923 : :
6924 : : static PyObject *
6925 : 0 : socket_if_nameindex(PyObject *self, PyObject *arg)
6926 : : {
6927 : 0 : PyObject *list = PyList_New(0);
6928 [ # # ]: 0 : if (list == NULL) {
6929 : 0 : return NULL;
6930 : : }
6931 : : #ifdef MS_WINDOWS
6932 : : PMIB_IF_TABLE2 tbl;
6933 : : int ret;
6934 : : if ((ret = GetIfTable2Ex(MibIfTableRaw, &tbl)) != NO_ERROR) {
6935 : : Py_DECREF(list);
6936 : : // ret is used instead of GetLastError()
6937 : : return PyErr_SetFromWindowsErr(ret);
6938 : : }
6939 : : for (ULONG i = 0; i < tbl->NumEntries; ++i) {
6940 : : MIB_IF_ROW2 r = tbl->Table[i];
6941 : : WCHAR buf[NDIS_IF_MAX_STRING_SIZE + 1];
6942 : : if ((ret = ConvertInterfaceLuidToNameW(&r.InterfaceLuid, buf,
6943 : : Py_ARRAY_LENGTH(buf)))) {
6944 : : Py_DECREF(list);
6945 : : FreeMibTable(tbl);
6946 : : // ret is used instead of GetLastError()
6947 : : return PyErr_SetFromWindowsErr(ret);
6948 : : }
6949 : : PyObject *tuple = Py_BuildValue("Iu", r.InterfaceIndex, buf);
6950 : : if (tuple == NULL || PyList_Append(list, tuple) == -1) {
6951 : : Py_XDECREF(tuple);
6952 : : Py_DECREF(list);
6953 : : FreeMibTable(tbl);
6954 : : return NULL;
6955 : : }
6956 : : Py_DECREF(tuple);
6957 : : }
6958 : : FreeMibTable(tbl);
6959 : : return list;
6960 : : #else
6961 : : int i;
6962 : : struct if_nameindex *ni;
6963 : :
6964 : 0 : ni = if_nameindex();
6965 [ # # ]: 0 : if (ni == NULL) {
6966 : 0 : Py_DECREF(list);
6967 : 0 : PyErr_SetFromErrno(PyExc_OSError);
6968 : 0 : return NULL;
6969 : : }
6970 : :
6971 : : #ifdef _Py_MEMORY_SANITIZER
6972 : : __msan_unpoison(ni, sizeof(ni));
6973 : : __msan_unpoison(&ni[0], sizeof(ni[0]));
6974 : : #endif
6975 [ # # # # ]: 0 : for (i = 0; ni[i].if_index != 0 && i < INT_MAX; i++) {
6976 : : #ifdef _Py_MEMORY_SANITIZER
6977 : : /* This one isn't the end sentinel, the next one must exist. */
6978 : : __msan_unpoison(&ni[i+1], sizeof(ni[0]));
6979 : : /* Otherwise Py_BuildValue internals are flagged by MSan when
6980 : : they access the not-msan-tracked if_name string data. */
6981 : : {
6982 : : char *to_sanitize = ni[i].if_name;
6983 : : do {
6984 : : __msan_unpoison(to_sanitize, 1);
6985 : : } while (*to_sanitize++ != '\0');
6986 : : }
6987 : : #endif
6988 : 0 : PyObject *ni_tuple = Py_BuildValue("IO&",
6989 : 0 : ni[i].if_index, PyUnicode_DecodeFSDefault, ni[i].if_name);
6990 : :
6991 [ # # # # ]: 0 : if (ni_tuple == NULL || PyList_Append(list, ni_tuple) == -1) {
6992 : 0 : Py_XDECREF(ni_tuple);
6993 : 0 : Py_DECREF(list);
6994 : 0 : if_freenameindex(ni);
6995 : 0 : return NULL;
6996 : : }
6997 : 0 : Py_DECREF(ni_tuple);
6998 : : }
6999 : :
7000 : 0 : if_freenameindex(ni);
7001 : 0 : return list;
7002 : : #endif
7003 : : }
7004 : :
7005 : : PyDoc_STRVAR(if_nameindex_doc,
7006 : : "if_nameindex()\n\
7007 : : \n\
7008 : : Returns a list of network interface information (index, name) tuples.");
7009 : :
7010 : : static PyObject *
7011 : 0 : socket_if_nametoindex(PyObject *self, PyObject *args)
7012 : : {
7013 : : PyObject *oname;
7014 : : #ifdef MS_WINDOWS
7015 : : NET_IFINDEX index;
7016 : : #else
7017 : : unsigned long index;
7018 : : #endif
7019 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "O&:if_nametoindex",
7020 : : PyUnicode_FSConverter, &oname))
7021 : 0 : return NULL;
7022 : :
7023 : 0 : index = if_nametoindex(PyBytes_AS_STRING(oname));
7024 : 0 : Py_DECREF(oname);
7025 [ # # ]: 0 : if (index == 0) {
7026 : : /* if_nametoindex() doesn't set errno */
7027 : 0 : PyErr_SetString(PyExc_OSError, "no interface with this name");
7028 : 0 : return NULL;
7029 : : }
7030 : :
7031 : 0 : return PyLong_FromUnsignedLong(index);
7032 : : }
7033 : :
7034 : : PyDoc_STRVAR(if_nametoindex_doc,
7035 : : "if_nametoindex(if_name)\n\
7036 : : \n\
7037 : : Returns the interface index corresponding to the interface name if_name.");
7038 : :
7039 : : static PyObject *
7040 : 0 : socket_if_indextoname(PyObject *self, PyObject *arg)
7041 : : {
7042 : : #ifdef MS_WINDOWS
7043 : : NET_IFINDEX index;
7044 : : #else
7045 : : unsigned long index;
7046 : : #endif
7047 : : char name[IF_NAMESIZE + 1];
7048 : :
7049 : 0 : index = PyLong_AsUnsignedLong(arg);
7050 [ # # ]: 0 : if (index == (unsigned long) -1)
7051 : 0 : return NULL;
7052 : :
7053 [ # # ]: 0 : if (if_indextoname(index, name) == NULL) {
7054 : 0 : PyErr_SetFromErrno(PyExc_OSError);
7055 : 0 : return NULL;
7056 : : }
7057 : :
7058 : 0 : return PyUnicode_DecodeFSDefault(name);
7059 : : }
7060 : :
7061 : : PyDoc_STRVAR(if_indextoname_doc,
7062 : : "if_indextoname(if_index)\n\
7063 : : \n\
7064 : : Returns the interface name corresponding to the interface index if_index.");
7065 : :
7066 : : #endif // defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
7067 : :
7068 : :
7069 : : #ifdef CMSG_LEN
7070 : : /* Python interface to CMSG_LEN(length). */
7071 : :
7072 : : static PyObject *
7073 : 0 : socket_CMSG_LEN(PyObject *self, PyObject *args)
7074 : : {
7075 : : Py_ssize_t length;
7076 : : size_t result;
7077 : :
7078 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "n:CMSG_LEN", &length))
7079 : 0 : return NULL;
7080 [ # # # # ]: 0 : if (length < 0 || !get_CMSG_LEN(length, &result)) {
7081 : 0 : PyErr_Format(PyExc_OverflowError, "CMSG_LEN() argument out of range");
7082 : 0 : return NULL;
7083 : : }
7084 : 0 : return PyLong_FromSize_t(result);
7085 : : }
7086 : :
7087 : : PyDoc_STRVAR(CMSG_LEN_doc,
7088 : : "CMSG_LEN(length) -> control message length\n\
7089 : : \n\
7090 : : Return the total length, without trailing padding, of an ancillary\n\
7091 : : data item with associated data of the given length. This value can\n\
7092 : : often be used as the buffer size for recvmsg() to receive a single\n\
7093 : : item of ancillary data, but RFC 3542 requires portable applications to\n\
7094 : : use CMSG_SPACE() and thus include space for padding, even when the\n\
7095 : : item will be the last in the buffer. Raises OverflowError if length\n\
7096 : : is outside the permissible range of values.");
7097 : :
7098 : :
7099 : : #ifdef CMSG_SPACE
7100 : : /* Python interface to CMSG_SPACE(length). */
7101 : :
7102 : : static PyObject *
7103 : 0 : socket_CMSG_SPACE(PyObject *self, PyObject *args)
7104 : : {
7105 : : Py_ssize_t length;
7106 : : size_t result;
7107 : :
7108 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "n:CMSG_SPACE", &length))
7109 : 0 : return NULL;
7110 [ # # # # ]: 0 : if (length < 0 || !get_CMSG_SPACE(length, &result)) {
7111 : 0 : PyErr_SetString(PyExc_OverflowError,
7112 : : "CMSG_SPACE() argument out of range");
7113 : 0 : return NULL;
7114 : : }
7115 : 0 : return PyLong_FromSize_t(result);
7116 : : }
7117 : :
7118 : : PyDoc_STRVAR(CMSG_SPACE_doc,
7119 : : "CMSG_SPACE(length) -> buffer size\n\
7120 : : \n\
7121 : : Return the buffer size needed for recvmsg() to receive an ancillary\n\
7122 : : data item with associated data of the given length, along with any\n\
7123 : : trailing padding. The buffer space needed to receive multiple items\n\
7124 : : is the sum of the CMSG_SPACE() values for their associated data\n\
7125 : : lengths. Raises OverflowError if length is outside the permissible\n\
7126 : : range of values.");
7127 : : #endif /* CMSG_SPACE */
7128 : : #endif /* CMSG_LEN */
7129 : :
7130 : :
7131 : : /* List of functions exported by this module. */
7132 : :
7133 : : static PyMethodDef socket_methods[] = {
7134 : : #ifdef HAVE_GETADDRINFO
7135 : : {"gethostbyname", socket_gethostbyname,
7136 : : METH_VARARGS, gethostbyname_doc},
7137 : : #endif
7138 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
7139 : : {"gethostbyname_ex", socket_gethostbyname_ex,
7140 : : METH_VARARGS, ghbn_ex_doc},
7141 : : #endif
7142 : : #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
7143 : : {"gethostbyaddr", socket_gethostbyaddr,
7144 : : METH_VARARGS, gethostbyaddr_doc},
7145 : : #endif
7146 : : #ifdef HAVE_GETHOSTNAME
7147 : : {"gethostname", socket_gethostname,
7148 : : METH_NOARGS, gethostname_doc},
7149 : : #endif
7150 : : #ifdef HAVE_SETHOSTNAME
7151 : : {"sethostname", socket_sethostname,
7152 : : METH_VARARGS, sethostname_doc},
7153 : : #endif
7154 : : #ifdef HAVE_GETSERVBYNAME
7155 : : {"getservbyname", socket_getservbyname,
7156 : : METH_VARARGS, getservbyname_doc},
7157 : : #endif
7158 : : #ifdef HAVE_GETSERVBYPORT
7159 : : {"getservbyport", socket_getservbyport,
7160 : : METH_VARARGS, getservbyport_doc},
7161 : : #endif
7162 : : #ifdef HAVE_GETPROTOBYNAME
7163 : : {"getprotobyname", socket_getprotobyname,
7164 : : METH_VARARGS, getprotobyname_doc},
7165 : : #endif
7166 : : {"close", socket_close,
7167 : : METH_O, close_doc},
7168 : : #ifndef NO_DUP
7169 : : {"dup", socket_dup,
7170 : : METH_O, dup_doc},
7171 : : #endif
7172 : : #ifdef HAVE_SOCKETPAIR
7173 : : {"socketpair", socket_socketpair,
7174 : : METH_VARARGS, socketpair_doc},
7175 : : #endif
7176 : : {"ntohs", socket_ntohs,
7177 : : METH_VARARGS, ntohs_doc},
7178 : : {"ntohl", socket_ntohl,
7179 : : METH_O, ntohl_doc},
7180 : : {"htons", socket_htons,
7181 : : METH_VARARGS, htons_doc},
7182 : : {"htonl", socket_htonl,
7183 : : METH_O, htonl_doc},
7184 : : {"inet_aton", socket_inet_aton,
7185 : : METH_VARARGS, inet_aton_doc},
7186 : : #ifdef HAVE_INET_NTOA
7187 : : {"inet_ntoa", socket_inet_ntoa,
7188 : : METH_VARARGS, inet_ntoa_doc},
7189 : : #endif
7190 : : #ifdef HAVE_INET_PTON
7191 : : {"inet_pton", socket_inet_pton,
7192 : : METH_VARARGS, inet_pton_doc},
7193 : : {"inet_ntop", socket_inet_ntop,
7194 : : METH_VARARGS, inet_ntop_doc},
7195 : : #endif
7196 : : #ifdef HAVE_GETADDRINFO
7197 : : {"getaddrinfo", _PyCFunction_CAST(socket_getaddrinfo),
7198 : : METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
7199 : : #endif
7200 : : #ifdef HAVE_GETNAMEINFO
7201 : : {"getnameinfo", socket_getnameinfo,
7202 : : METH_VARARGS, getnameinfo_doc},
7203 : : #endif
7204 : : {"getdefaulttimeout", socket_getdefaulttimeout,
7205 : : METH_NOARGS, getdefaulttimeout_doc},
7206 : : {"setdefaulttimeout", socket_setdefaulttimeout,
7207 : : METH_O, setdefaulttimeout_doc},
7208 : : #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
7209 : : {"if_nameindex", socket_if_nameindex,
7210 : : METH_NOARGS, if_nameindex_doc},
7211 : : {"if_nametoindex", socket_if_nametoindex,
7212 : : METH_VARARGS, if_nametoindex_doc},
7213 : : {"if_indextoname", socket_if_indextoname,
7214 : : METH_O, if_indextoname_doc},
7215 : : #endif
7216 : : #ifdef CMSG_LEN
7217 : : {"CMSG_LEN", socket_CMSG_LEN,
7218 : : METH_VARARGS, CMSG_LEN_doc},
7219 : : #ifdef CMSG_SPACE
7220 : : {"CMSG_SPACE", socket_CMSG_SPACE,
7221 : : METH_VARARGS, CMSG_SPACE_doc},
7222 : : #endif
7223 : : #endif
7224 : : {NULL, NULL} /* Sentinel */
7225 : : };
7226 : :
7227 : :
7228 : : #ifdef MS_WINDOWS
7229 : : #define OS_INIT_DEFINED
7230 : :
7231 : : /* Additional initialization and cleanup for Windows */
7232 : :
7233 : : static void
7234 : : os_cleanup(void)
7235 : : {
7236 : : WSACleanup();
7237 : : }
7238 : :
7239 : : static int
7240 : : os_init(void)
7241 : : {
7242 : : WSADATA WSAData;
7243 : : int ret;
7244 : : ret = WSAStartup(0x0101, &WSAData);
7245 : : switch (ret) {
7246 : : case 0: /* No error */
7247 : : Py_AtExit(os_cleanup);
7248 : : return 1; /* Success */
7249 : : case WSASYSNOTREADY:
7250 : : PyErr_SetString(PyExc_ImportError,
7251 : : "WSAStartup failed: network not ready");
7252 : : break;
7253 : : case WSAVERNOTSUPPORTED:
7254 : : case WSAEINVAL:
7255 : : PyErr_SetString(
7256 : : PyExc_ImportError,
7257 : : "WSAStartup failed: requested version not supported");
7258 : : break;
7259 : : default:
7260 : : PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
7261 : : break;
7262 : : }
7263 : : return 0; /* Failure */
7264 : : }
7265 : :
7266 : : #endif /* MS_WINDOWS */
7267 : :
7268 : :
7269 : :
7270 : : #ifndef OS_INIT_DEFINED
7271 : : static int
7272 : 1 : os_init(void)
7273 : : {
7274 : 1 : return 1; /* Success */
7275 : : }
7276 : : #endif
7277 : :
7278 : : static void
7279 : 1 : sock_free_api(PySocketModule_APIObject *capi)
7280 : : {
7281 : 1 : Py_DECREF(capi->Sock_Type);
7282 : 1 : Py_DECREF(capi->error);
7283 : 1 : Py_DECREF(capi->timeout_error);
7284 : 1 : PyMem_Free(capi);
7285 : 1 : }
7286 : :
7287 : : static void
7288 : 1 : sock_destroy_api(PyObject *capsule)
7289 : : {
7290 : 1 : void *capi = PyCapsule_GetPointer(capsule, PySocket_CAPSULE_NAME);
7291 : 1 : sock_free_api(capi);
7292 : 1 : }
7293 : :
7294 : : static PySocketModule_APIObject *
7295 : 1 : sock_get_api(void)
7296 : : {
7297 : 1 : PySocketModule_APIObject *capi = PyMem_Malloc(sizeof(PySocketModule_APIObject));
7298 [ - + ]: 1 : if (capi == NULL) {
7299 : 0 : PyErr_NoMemory();
7300 : 0 : return NULL;
7301 : : }
7302 : :
7303 : 1 : capi->Sock_Type = (PyTypeObject *)Py_NewRef(&sock_type);
7304 : 1 : capi->error = Py_NewRef(PyExc_OSError);
7305 : 1 : capi->timeout_error = Py_NewRef(PyExc_TimeoutError);
7306 : 1 : return capi;
7307 : : }
7308 : :
7309 : :
7310 : : /* Initialize the _socket module.
7311 : :
7312 : : This module is actually called "_socket", and there's a wrapper
7313 : : "socket.py" which implements some additional functionality.
7314 : : The import of "_socket" may fail with an ImportError exception if
7315 : : os-specific initialization fails. On Windows, this does WINSOCK
7316 : : initialization. When WINSOCK is initialized successfully, a call to
7317 : : WSACleanup() is scheduled to be made at exit time.
7318 : : */
7319 : :
7320 : : PyDoc_STRVAR(socket_doc,
7321 : : "Implementation module for socket operations.\n\
7322 : : \n\
7323 : : See the socket module for documentation.");
7324 : :
7325 : : static struct PyModuleDef socketmodule = {
7326 : : PyModuleDef_HEAD_INIT,
7327 : : PySocket_MODULE_NAME,
7328 : : socket_doc,
7329 : : -1,
7330 : : socket_methods,
7331 : : NULL,
7332 : : NULL,
7333 : : NULL,
7334 : : NULL
7335 : : };
7336 : :
7337 : : PyMODINIT_FUNC
7338 : 1 : PyInit__socket(void)
7339 : : {
7340 : : PyObject *m, *has_ipv6;
7341 : :
7342 [ - + ]: 1 : if (!os_init())
7343 : 0 : return NULL;
7344 : :
7345 : 1 : Py_SET_TYPE(&sock_type, &PyType_Type);
7346 : 1 : m = PyModule_Create(&socketmodule);
7347 [ - + ]: 1 : if (m == NULL)
7348 : 0 : return NULL;
7349 : :
7350 : 1 : PyModule_AddObject(m, "error", Py_NewRef(PyExc_OSError));
7351 : 1 : socket_herror = PyErr_NewException("socket.herror",
7352 : : PyExc_OSError, NULL);
7353 [ - + ]: 1 : if (socket_herror == NULL)
7354 : 0 : return NULL;
7355 : 1 : PyModule_AddObject(m, "herror", Py_NewRef(socket_herror));
7356 : 1 : socket_gaierror = PyErr_NewException("socket.gaierror", PyExc_OSError,
7357 : : NULL);
7358 [ - + ]: 1 : if (socket_gaierror == NULL)
7359 : 0 : return NULL;
7360 : 1 : PyModule_AddObject(m, "gaierror", Py_NewRef(socket_gaierror));
7361 : 1 : PyModule_AddObjectRef(m, "timeout", PyExc_TimeoutError);
7362 : :
7363 [ - + ]: 1 : if (PyModule_AddObject(m, "SocketType", Py_NewRef(&sock_type)) != 0)
7364 : 0 : return NULL;
7365 [ - + ]: 1 : if (PyModule_AddObject(m, "socket", Py_NewRef(&sock_type)) != 0)
7366 : 0 : return NULL;
7367 : :
7368 : : #ifdef ENABLE_IPV6
7369 : 1 : has_ipv6 = Py_True;
7370 : : #else
7371 : : has_ipv6 = Py_False;
7372 : : #endif
7373 : 1 : PyModule_AddObject(m, "has_ipv6", Py_NewRef(has_ipv6));
7374 : :
7375 : : /* Export C API */
7376 : 1 : PySocketModule_APIObject *capi = sock_get_api();
7377 [ - + ]: 1 : if (capi == NULL) {
7378 : 0 : Py_DECREF(m);
7379 : 0 : return NULL;
7380 : : }
7381 : 1 : PyObject *capsule = PyCapsule_New(capi,
7382 : : PySocket_CAPSULE_NAME,
7383 : : sock_destroy_api);
7384 [ - + ]: 1 : if (capsule == NULL) {
7385 : 0 : sock_free_api(capi);
7386 : 0 : Py_DECREF(m);
7387 : 0 : return NULL;
7388 : : }
7389 [ - + ]: 1 : if (PyModule_AddObject(m, PySocket_CAPI_NAME, capsule) < 0) {
7390 : 0 : Py_DECREF(capsule);
7391 : 0 : Py_DECREF(m);
7392 : 0 : return NULL;
7393 : : }
7394 : :
7395 : : /* Address families (we only support AF_INET and AF_UNIX) */
7396 : : #ifdef AF_UNSPEC
7397 : 1 : PyModule_AddIntMacro(m, AF_UNSPEC);
7398 : : #endif
7399 : 1 : PyModule_AddIntMacro(m, AF_INET);
7400 : : #if defined(AF_UNIX)
7401 : 1 : PyModule_AddIntMacro(m, AF_UNIX);
7402 : : #endif /* AF_UNIX */
7403 : : #ifdef AF_AX25
7404 : : /* Amateur Radio AX.25 */
7405 : 1 : PyModule_AddIntMacro(m, AF_AX25);
7406 : : #endif
7407 : : #ifdef AF_IPX
7408 : 1 : PyModule_AddIntMacro(m, AF_IPX); /* Novell IPX */
7409 : : #endif
7410 : : #ifdef AF_APPLETALK
7411 : : /* Appletalk DDP */
7412 : 1 : PyModule_AddIntMacro(m, AF_APPLETALK);
7413 : : #endif
7414 : : #ifdef AF_NETROM
7415 : : /* Amateur radio NetROM */
7416 : 1 : PyModule_AddIntMacro(m, AF_NETROM);
7417 : : #endif
7418 : : #ifdef AF_BRIDGE
7419 : : /* Multiprotocol bridge */
7420 : 1 : PyModule_AddIntMacro(m, AF_BRIDGE);
7421 : : #endif
7422 : : #ifdef AF_ATMPVC
7423 : : /* ATM PVCs */
7424 : 1 : PyModule_AddIntMacro(m, AF_ATMPVC);
7425 : : #endif
7426 : : #ifdef AF_AAL5
7427 : : /* Reserved for Werner's ATM */
7428 : : PyModule_AddIntMacro(m, AF_AAL5);
7429 : : #endif
7430 : : #ifdef HAVE_SOCKADDR_ALG
7431 : 1 : PyModule_AddIntMacro(m, AF_ALG); /* Linux crypto */
7432 : : #endif
7433 : : #ifdef AF_X25
7434 : : /* Reserved for X.25 project */
7435 : 1 : PyModule_AddIntMacro(m, AF_X25);
7436 : : #endif
7437 : : #ifdef AF_INET6
7438 : 1 : PyModule_AddIntMacro(m, AF_INET6); /* IP version 6 */
7439 : : #endif
7440 : : #ifdef AF_ROSE
7441 : : /* Amateur Radio X.25 PLP */
7442 : 1 : PyModule_AddIntMacro(m, AF_ROSE);
7443 : : #endif
7444 : : #ifdef AF_DECnet
7445 : : /* Reserved for DECnet project */
7446 : 1 : PyModule_AddIntMacro(m, AF_DECnet);
7447 : : #endif
7448 : : #ifdef AF_NETBEUI
7449 : : /* Reserved for 802.2LLC project */
7450 : 1 : PyModule_AddIntMacro(m, AF_NETBEUI);
7451 : : #endif
7452 : : #ifdef AF_SECURITY
7453 : : /* Security callback pseudo AF */
7454 : 1 : PyModule_AddIntMacro(m, AF_SECURITY);
7455 : : #endif
7456 : : #ifdef AF_KEY
7457 : : /* PF_KEY key management API */
7458 : 1 : PyModule_AddIntMacro(m, AF_KEY);
7459 : : #endif
7460 : : #ifdef AF_NETLINK
7461 : : /* */
7462 : 1 : PyModule_AddIntMacro(m, AF_NETLINK);
7463 : 1 : PyModule_AddIntMacro(m, NETLINK_ROUTE);
7464 : : #ifdef NETLINK_SKIP
7465 : : PyModule_AddIntMacro(m, NETLINK_SKIP);
7466 : : #endif
7467 : : #ifdef NETLINK_W1
7468 : : PyModule_AddIntMacro(m, NETLINK_W1);
7469 : : #endif
7470 : 1 : PyModule_AddIntMacro(m, NETLINK_USERSOCK);
7471 : 1 : PyModule_AddIntMacro(m, NETLINK_FIREWALL);
7472 : : #ifdef NETLINK_TCPDIAG
7473 : : PyModule_AddIntMacro(m, NETLINK_TCPDIAG);
7474 : : #endif
7475 : : #ifdef NETLINK_NFLOG
7476 : 1 : PyModule_AddIntMacro(m, NETLINK_NFLOG);
7477 : : #endif
7478 : : #ifdef NETLINK_XFRM
7479 : 1 : PyModule_AddIntMacro(m, NETLINK_XFRM);
7480 : : #endif
7481 : : #ifdef NETLINK_ARPD
7482 : : PyModule_AddIntMacro(m, NETLINK_ARPD);
7483 : : #endif
7484 : : #ifdef NETLINK_ROUTE6
7485 : : PyModule_AddIntMacro(m, NETLINK_ROUTE6);
7486 : : #endif
7487 : 1 : PyModule_AddIntMacro(m, NETLINK_IP6_FW);
7488 : : #ifdef NETLINK_DNRTMSG
7489 : 1 : PyModule_AddIntMacro(m, NETLINK_DNRTMSG);
7490 : : #endif
7491 : : #ifdef NETLINK_TAPBASE
7492 : : PyModule_AddIntMacro(m, NETLINK_TAPBASE);
7493 : : #endif
7494 : : #ifdef NETLINK_CRYPTO
7495 : 1 : PyModule_AddIntMacro(m, NETLINK_CRYPTO);
7496 : : #endif
7497 : : #endif /* AF_NETLINK */
7498 : :
7499 : : #ifdef AF_QIPCRTR
7500 : : /* Qualcomm IPCROUTER */
7501 : 1 : PyModule_AddIntMacro(m, AF_QIPCRTR);
7502 : : #endif
7503 : :
7504 : : #ifdef AF_VSOCK
7505 : 1 : PyModule_AddIntConstant(m, "AF_VSOCK", AF_VSOCK);
7506 : 1 : PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_SIZE", 0);
7507 : 1 : PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_MIN_SIZE", 1);
7508 : 1 : PyModule_AddIntConstant(m, "SO_VM_SOCKETS_BUFFER_MAX_SIZE", 2);
7509 : 1 : PyModule_AddIntConstant(m, "VMADDR_CID_ANY", 0xffffffff);
7510 : 1 : PyModule_AddIntConstant(m, "VMADDR_PORT_ANY", 0xffffffff);
7511 : 1 : PyModule_AddIntConstant(m, "VMADDR_CID_HOST", 2);
7512 : 1 : PyModule_AddIntConstant(m, "VM_SOCKETS_INVALID_VERSION", 0xffffffff);
7513 : 1 : PyModule_AddIntConstant(m, "IOCTL_VM_SOCKETS_GET_LOCAL_CID", _IO(7, 0xb9));
7514 : : #endif
7515 : :
7516 : : #ifdef AF_ROUTE
7517 : : /* Alias to emulate 4.4BSD */
7518 : 1 : PyModule_AddIntMacro(m, AF_ROUTE);
7519 : : #endif
7520 : : #ifdef AF_LINK
7521 : : PyModule_AddIntMacro(m, AF_LINK);
7522 : : #endif
7523 : : #ifdef AF_ASH
7524 : : /* Ash */
7525 : 1 : PyModule_AddIntMacro(m, AF_ASH);
7526 : : #endif
7527 : : #ifdef AF_ECONET
7528 : : /* Acorn Econet */
7529 : 1 : PyModule_AddIntMacro(m, AF_ECONET);
7530 : : #endif
7531 : : #ifdef AF_ATMSVC
7532 : : /* ATM SVCs */
7533 : 1 : PyModule_AddIntMacro(m, AF_ATMSVC);
7534 : : #endif
7535 : : #ifdef AF_SNA
7536 : : /* Linux SNA Project (nutters!) */
7537 : 1 : PyModule_AddIntMacro(m, AF_SNA);
7538 : : #endif
7539 : : #ifdef AF_IRDA
7540 : : /* IRDA sockets */
7541 : 1 : PyModule_AddIntMacro(m, AF_IRDA);
7542 : : #endif
7543 : : #ifdef AF_PPPOX
7544 : : /* PPPoX sockets */
7545 : 1 : PyModule_AddIntMacro(m, AF_PPPOX);
7546 : : #endif
7547 : : #ifdef AF_WANPIPE
7548 : : /* Wanpipe API Sockets */
7549 : 1 : PyModule_AddIntMacro(m, AF_WANPIPE);
7550 : : #endif
7551 : : #ifdef AF_LLC
7552 : : /* Linux LLC */
7553 : 1 : PyModule_AddIntMacro(m, AF_LLC);
7554 : : #endif
7555 : : #ifdef HAVE_AF_HYPERV
7556 : : /* Hyper-V sockets */
7557 : : PyModule_AddIntMacro(m, AF_HYPERV);
7558 : :
7559 : : /* for proto */
7560 : : PyModule_AddIntMacro(m, HV_PROTOCOL_RAW);
7561 : :
7562 : : /* for setsockopt() */
7563 : : PyModule_AddIntMacro(m, HVSOCKET_CONNECT_TIMEOUT);
7564 : : PyModule_AddIntMacro(m, HVSOCKET_CONNECT_TIMEOUT_MAX);
7565 : : PyModule_AddIntMacro(m, HVSOCKET_CONNECTED_SUSPEND);
7566 : : PyModule_AddIntMacro(m, HVSOCKET_ADDRESS_FLAG_PASSTHRU);
7567 : :
7568 : : /* for bind() or connect() */
7569 : : PyModule_AddStringConstant(m, "HV_GUID_ZERO", "00000000-0000-0000-0000-000000000000");
7570 : : PyModule_AddStringConstant(m, "HV_GUID_WILDCARD", "00000000-0000-0000-0000-000000000000");
7571 : : PyModule_AddStringConstant(m, "HV_GUID_BROADCAST", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
7572 : : PyModule_AddStringConstant(m, "HV_GUID_CHILDREN", "90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD");
7573 : : PyModule_AddStringConstant(m, "HV_GUID_LOOPBACK", "E0E16197-DD56-4A10-9195-5EE7A155A838");
7574 : : PyModule_AddStringConstant(m, "HV_GUID_PARENT", "A42E7CDA-D03F-480C-9CC2-A4DE20ABB878");
7575 : : #endif /* HAVE_AF_HYPERV */
7576 : :
7577 : : #ifdef USE_BLUETOOTH
7578 : : PyModule_AddIntMacro(m, AF_BLUETOOTH);
7579 : : #ifdef BTPROTO_L2CAP
7580 : : PyModule_AddIntMacro(m, BTPROTO_L2CAP);
7581 : : #endif /* BTPROTO_L2CAP */
7582 : : #ifdef BTPROTO_HCI
7583 : : PyModule_AddIntMacro(m, BTPROTO_HCI);
7584 : : PyModule_AddIntMacro(m, SOL_HCI);
7585 : : #if !defined(__NetBSD__) && !defined(__DragonFly__)
7586 : : PyModule_AddIntMacro(m, HCI_FILTER);
7587 : : #if !defined(__FreeBSD__)
7588 : : PyModule_AddIntMacro(m, HCI_TIME_STAMP);
7589 : : PyModule_AddIntMacro(m, HCI_DATA_DIR);
7590 : : #endif /* !__FreeBSD__ */
7591 : : #endif /* !__NetBSD__ && !__DragonFly__ */
7592 : : #endif /* BTPROTO_HCI */
7593 : : #ifdef BTPROTO_RFCOMM
7594 : : PyModule_AddIntMacro(m, BTPROTO_RFCOMM);
7595 : : #endif /* BTPROTO_RFCOMM */
7596 : : PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
7597 : : PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
7598 : : #ifdef BTPROTO_SCO
7599 : : PyModule_AddIntMacro(m, BTPROTO_SCO);
7600 : : #endif /* BTPROTO_SCO */
7601 : : #endif /* USE_BLUETOOTH */
7602 : :
7603 : : #ifdef AF_CAN
7604 : : /* Controller Area Network */
7605 : 1 : PyModule_AddIntMacro(m, AF_CAN);
7606 : : #endif
7607 : : #ifdef PF_CAN
7608 : : /* Controller Area Network */
7609 : 1 : PyModule_AddIntMacro(m, PF_CAN);
7610 : : #endif
7611 : :
7612 : : /* Reliable Datagram Sockets */
7613 : : #ifdef AF_RDS
7614 : 1 : PyModule_AddIntMacro(m, AF_RDS);
7615 : : #endif
7616 : : #ifdef PF_RDS
7617 : 1 : PyModule_AddIntMacro(m, PF_RDS);
7618 : : #endif
7619 : :
7620 : : /* Kernel event messages */
7621 : : #ifdef PF_SYSTEM
7622 : : PyModule_AddIntMacro(m, PF_SYSTEM);
7623 : : #endif
7624 : : #ifdef AF_SYSTEM
7625 : : PyModule_AddIntMacro(m, AF_SYSTEM);
7626 : : #endif
7627 : :
7628 : : #ifdef AF_PACKET
7629 : 1 : PyModule_AddIntMacro(m, AF_PACKET);
7630 : : #endif
7631 : : #ifdef PF_PACKET
7632 : 1 : PyModule_AddIntMacro(m, PF_PACKET);
7633 : : #endif
7634 : : #ifdef PACKET_HOST
7635 : 1 : PyModule_AddIntMacro(m, PACKET_HOST);
7636 : : #endif
7637 : : #ifdef PACKET_BROADCAST
7638 : 1 : PyModule_AddIntMacro(m, PACKET_BROADCAST);
7639 : : #endif
7640 : : #ifdef PACKET_MULTICAST
7641 : 1 : PyModule_AddIntMacro(m, PACKET_MULTICAST);
7642 : : #endif
7643 : : #ifdef PACKET_OTHERHOST
7644 : 1 : PyModule_AddIntMacro(m, PACKET_OTHERHOST);
7645 : : #endif
7646 : : #ifdef PACKET_OUTGOING
7647 : 1 : PyModule_AddIntMacro(m, PACKET_OUTGOING);
7648 : : #endif
7649 : : #ifdef PACKET_LOOPBACK
7650 : 1 : PyModule_AddIntMacro(m, PACKET_LOOPBACK);
7651 : : #endif
7652 : : #ifdef PACKET_FASTROUTE
7653 : 1 : PyModule_AddIntMacro(m, PACKET_FASTROUTE);
7654 : : #endif
7655 : :
7656 : : #ifdef HAVE_LINUX_TIPC_H
7657 : 1 : PyModule_AddIntMacro(m, AF_TIPC);
7658 : :
7659 : : /* for addresses */
7660 : 1 : PyModule_AddIntMacro(m, TIPC_ADDR_NAMESEQ);
7661 : 1 : PyModule_AddIntMacro(m, TIPC_ADDR_NAME);
7662 : 1 : PyModule_AddIntMacro(m, TIPC_ADDR_ID);
7663 : :
7664 : 1 : PyModule_AddIntMacro(m, TIPC_ZONE_SCOPE);
7665 : 1 : PyModule_AddIntMacro(m, TIPC_CLUSTER_SCOPE);
7666 : 1 : PyModule_AddIntMacro(m, TIPC_NODE_SCOPE);
7667 : :
7668 : : /* for setsockopt() */
7669 : 1 : PyModule_AddIntMacro(m, SOL_TIPC);
7670 : 1 : PyModule_AddIntMacro(m, TIPC_IMPORTANCE);
7671 : 1 : PyModule_AddIntMacro(m, TIPC_SRC_DROPPABLE);
7672 : 1 : PyModule_AddIntMacro(m, TIPC_DEST_DROPPABLE);
7673 : 1 : PyModule_AddIntMacro(m, TIPC_CONN_TIMEOUT);
7674 : :
7675 : 1 : PyModule_AddIntMacro(m, TIPC_LOW_IMPORTANCE);
7676 : 1 : PyModule_AddIntMacro(m, TIPC_MEDIUM_IMPORTANCE);
7677 : 1 : PyModule_AddIntMacro(m, TIPC_HIGH_IMPORTANCE);
7678 : 1 : PyModule_AddIntMacro(m, TIPC_CRITICAL_IMPORTANCE);
7679 : :
7680 : : /* for subscriptions */
7681 : 1 : PyModule_AddIntMacro(m, TIPC_SUB_PORTS);
7682 : 1 : PyModule_AddIntMacro(m, TIPC_SUB_SERVICE);
7683 : : #ifdef TIPC_SUB_CANCEL
7684 : : /* doesn't seem to be available everywhere */
7685 : 1 : PyModule_AddIntMacro(m, TIPC_SUB_CANCEL);
7686 : : #endif
7687 : 1 : PyModule_AddIntMacro(m, TIPC_WAIT_FOREVER);
7688 : 1 : PyModule_AddIntMacro(m, TIPC_PUBLISHED);
7689 : 1 : PyModule_AddIntMacro(m, TIPC_WITHDRAWN);
7690 : 1 : PyModule_AddIntMacro(m, TIPC_SUBSCR_TIMEOUT);
7691 : 1 : PyModule_AddIntMacro(m, TIPC_CFG_SRV);
7692 : 1 : PyModule_AddIntMacro(m, TIPC_TOP_SRV);
7693 : : #endif
7694 : :
7695 : : #ifdef HAVE_SOCKADDR_ALG
7696 : : /* Socket options */
7697 : 1 : PyModule_AddIntMacro(m, ALG_SET_KEY);
7698 : 1 : PyModule_AddIntMacro(m, ALG_SET_IV);
7699 : 1 : PyModule_AddIntMacro(m, ALG_SET_OP);
7700 : 1 : PyModule_AddIntMacro(m, ALG_SET_AEAD_ASSOCLEN);
7701 : 1 : PyModule_AddIntMacro(m, ALG_SET_AEAD_AUTHSIZE);
7702 : 1 : PyModule_AddIntMacro(m, ALG_SET_PUBKEY);
7703 : :
7704 : : /* Operations */
7705 : 1 : PyModule_AddIntMacro(m, ALG_OP_DECRYPT);
7706 : 1 : PyModule_AddIntMacro(m, ALG_OP_ENCRYPT);
7707 : 1 : PyModule_AddIntMacro(m, ALG_OP_SIGN);
7708 : 1 : PyModule_AddIntMacro(m, ALG_OP_VERIFY);
7709 : : #endif
7710 : :
7711 : : /* IEEE 802.3 protocol numbers required for a standard TCP/IP network stack */
7712 : : #ifdef ETHERTYPE_ARP
7713 : 1 : PyModule_AddIntMacro(m, ETHERTYPE_ARP);
7714 : : #endif
7715 : : #ifdef ETHERTYPE_IP
7716 : 1 : PyModule_AddIntMacro(m, ETHERTYPE_IP);
7717 : : #endif
7718 : : #ifdef ETHERTYPE_IPV6
7719 : 1 : PyModule_AddIntMacro(m, ETHERTYPE_IPV6);
7720 : : #endif
7721 : : #ifdef ETHERTYPE_VLAN
7722 : 1 : PyModule_AddIntMacro(m, ETHERTYPE_VLAN);
7723 : : #endif
7724 : :
7725 : : /* Linux pseudo-protocol for sniffing every packet */
7726 : : #ifdef ETH_P_ALL
7727 : 1 : PyModule_AddIntMacro(m, ETH_P_ALL);
7728 : : #endif
7729 : :
7730 : : /* Socket types */
7731 : 1 : PyModule_AddIntMacro(m, SOCK_STREAM);
7732 : 1 : PyModule_AddIntMacro(m, SOCK_DGRAM);
7733 : : /* We have incomplete socket support. */
7734 : : #ifdef SOCK_RAW
7735 : : /* SOCK_RAW is marked as optional in the POSIX specification */
7736 : 1 : PyModule_AddIntMacro(m, SOCK_RAW);
7737 : : #endif
7738 : : #ifdef SOCK_SEQPACKET
7739 : 1 : PyModule_AddIntMacro(m, SOCK_SEQPACKET);
7740 : : #endif
7741 : : #if defined(SOCK_RDM)
7742 : 1 : PyModule_AddIntMacro(m, SOCK_RDM);
7743 : : #endif
7744 : : #ifdef SOCK_CLOEXEC
7745 : 1 : PyModule_AddIntMacro(m, SOCK_CLOEXEC);
7746 : : #endif
7747 : : #ifdef SOCK_NONBLOCK
7748 : 1 : PyModule_AddIntMacro(m, SOCK_NONBLOCK);
7749 : : #endif
7750 : :
7751 : : #ifdef SO_DEBUG
7752 : 1 : PyModule_AddIntMacro(m, SO_DEBUG);
7753 : : #endif
7754 : : #ifdef SO_ACCEPTCONN
7755 : 1 : PyModule_AddIntMacro(m, SO_ACCEPTCONN);
7756 : : #endif
7757 : : #ifdef SO_REUSEADDR
7758 : 1 : PyModule_AddIntMacro(m, SO_REUSEADDR);
7759 : : #endif
7760 : : #ifdef SO_EXCLUSIVEADDRUSE
7761 : : PyModule_AddIntMacro(m, SO_EXCLUSIVEADDRUSE);
7762 : : #endif
7763 : : #ifdef SO_INCOMING_CPU
7764 : 1 : PyModule_AddIntMacro(m, SO_INCOMING_CPU);
7765 : : #endif
7766 : :
7767 : : #ifdef SO_KEEPALIVE
7768 : 1 : PyModule_AddIntMacro(m, SO_KEEPALIVE);
7769 : : #endif
7770 : : #ifdef SO_DONTROUTE
7771 : 1 : PyModule_AddIntMacro(m, SO_DONTROUTE);
7772 : : #endif
7773 : : #ifdef SO_BROADCAST
7774 : 1 : PyModule_AddIntMacro(m, SO_BROADCAST);
7775 : : #endif
7776 : : #ifdef SO_USELOOPBACK
7777 : : PyModule_AddIntMacro(m, SO_USELOOPBACK);
7778 : : #endif
7779 : : #ifdef SO_LINGER
7780 : 1 : PyModule_AddIntMacro(m, SO_LINGER);
7781 : : #endif
7782 : : #ifdef SO_OOBINLINE
7783 : 1 : PyModule_AddIntMacro(m, SO_OOBINLINE);
7784 : : #endif
7785 : : #ifndef __GNU__
7786 : : #ifdef SO_REUSEPORT
7787 : 1 : PyModule_AddIntMacro(m, SO_REUSEPORT);
7788 : : #endif
7789 : : #endif
7790 : : #ifdef SO_SNDBUF
7791 : 1 : PyModule_AddIntMacro(m, SO_SNDBUF);
7792 : : #endif
7793 : : #ifdef SO_RCVBUF
7794 : 1 : PyModule_AddIntMacro(m, SO_RCVBUF);
7795 : : #endif
7796 : : #ifdef SO_SNDLOWAT
7797 : 1 : PyModule_AddIntMacro(m, SO_SNDLOWAT);
7798 : : #endif
7799 : : #ifdef SO_RCVLOWAT
7800 : 1 : PyModule_AddIntMacro(m, SO_RCVLOWAT);
7801 : : #endif
7802 : : #ifdef SO_SNDTIMEO
7803 : 1 : PyModule_AddIntMacro(m, SO_SNDTIMEO);
7804 : : #endif
7805 : : #ifdef SO_RCVTIMEO
7806 : 1 : PyModule_AddIntMacro(m, SO_RCVTIMEO);
7807 : : #endif
7808 : : #ifdef SO_ERROR
7809 : 1 : PyModule_AddIntMacro(m, SO_ERROR);
7810 : : #endif
7811 : : #ifdef SO_TYPE
7812 : 1 : PyModule_AddIntMacro(m, SO_TYPE);
7813 : : #endif
7814 : : #ifdef SO_SETFIB
7815 : : PyModule_AddIntMacro(m, SO_SETFIB);
7816 : : #endif
7817 : : #ifdef SO_PASSCRED
7818 : 1 : PyModule_AddIntMacro(m, SO_PASSCRED);
7819 : : #endif
7820 : : #ifdef SO_PEERCRED
7821 : 1 : PyModule_AddIntMacro(m, SO_PEERCRED);
7822 : : #endif
7823 : : #ifdef LOCAL_PEERCRED
7824 : : PyModule_AddIntMacro(m, LOCAL_PEERCRED);
7825 : : #endif
7826 : : #ifdef SO_PASSSEC
7827 : 1 : PyModule_AddIntMacro(m, SO_PASSSEC);
7828 : : #endif
7829 : : #ifdef SO_PEERSEC
7830 : 1 : PyModule_AddIntMacro(m, SO_PEERSEC);
7831 : : #endif
7832 : : #ifdef SO_BINDTODEVICE
7833 : 1 : PyModule_AddIntMacro(m, SO_BINDTODEVICE);
7834 : : #endif
7835 : : #ifdef SO_PRIORITY
7836 : 1 : PyModule_AddIntMacro(m, SO_PRIORITY);
7837 : : #endif
7838 : : #ifdef SO_MARK
7839 : 1 : PyModule_AddIntMacro(m, SO_MARK);
7840 : : #endif
7841 : : #ifdef SO_USER_COOKIE
7842 : : PyModule_AddIntMacro(m, SO_USER_COOKIE);
7843 : : #endif
7844 : : #ifdef SO_RTABLE
7845 : : PyModule_AddIntMacro(m, SO_RTABLE);
7846 : : #endif
7847 : : #ifdef SO_DOMAIN
7848 : 1 : PyModule_AddIntMacro(m, SO_DOMAIN);
7849 : : #endif
7850 : : #ifdef SO_PROTOCOL
7851 : 1 : PyModule_AddIntMacro(m, SO_PROTOCOL);
7852 : : #endif
7853 : : #ifdef LOCAL_CREDS
7854 : : PyModule_AddIntMacro(m, LOCAL_CREDS);
7855 : : #endif
7856 : : #ifdef LOCAL_CREDS_PERSISTENT
7857 : : PyModule_AddIntMacro(m, LOCAL_CREDS_PERSISTENT);
7858 : : #endif
7859 : :
7860 : : /* Maximum number of connections for "listen" */
7861 : : #ifdef SOMAXCONN
7862 : 1 : PyModule_AddIntMacro(m, SOMAXCONN);
7863 : : #else
7864 : : PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
7865 : : #endif
7866 : :
7867 : : /* Ancillary message types */
7868 : : #ifdef SCM_RIGHTS
7869 : 1 : PyModule_AddIntMacro(m, SCM_RIGHTS);
7870 : : #endif
7871 : : #ifdef SCM_CREDENTIALS
7872 : 1 : PyModule_AddIntMacro(m, SCM_CREDENTIALS);
7873 : : #endif
7874 : : #ifdef SCM_CREDS
7875 : : PyModule_AddIntMacro(m, SCM_CREDS);
7876 : : #endif
7877 : : #ifdef SCM_CREDS2
7878 : : PyModule_AddIntMacro(m, SCM_CREDS2);
7879 : : #endif
7880 : :
7881 : : /* Flags for send, recv */
7882 : : #ifdef MSG_OOB
7883 : 1 : PyModule_AddIntMacro(m, MSG_OOB);
7884 : : #endif
7885 : : #ifdef MSG_PEEK
7886 : 1 : PyModule_AddIntMacro(m, MSG_PEEK);
7887 : : #endif
7888 : : #ifdef MSG_DONTROUTE
7889 : 1 : PyModule_AddIntMacro(m, MSG_DONTROUTE);
7890 : : #endif
7891 : : #ifdef MSG_DONTWAIT
7892 : 1 : PyModule_AddIntMacro(m, MSG_DONTWAIT);
7893 : : #endif
7894 : : #ifdef MSG_EOR
7895 : 1 : PyModule_AddIntMacro(m, MSG_EOR);
7896 : : #endif
7897 : : #ifdef MSG_TRUNC
7898 : : // workaround for https://github.com/WebAssembly/wasi-libc/issues/305
7899 : : #if defined(__wasi__) && !defined(__WASI_RIFLAGS_RECV_DATA_TRUNCATED)
7900 : : # define __WASI_RIFLAGS_RECV_DATA_TRUNCATED 2
7901 : : #endif
7902 : 1 : PyModule_AddIntMacro(m, MSG_TRUNC);
7903 : : #endif
7904 : : #ifdef MSG_CTRUNC
7905 : 1 : PyModule_AddIntMacro(m, MSG_CTRUNC);
7906 : : #endif
7907 : : #ifdef MSG_WAITALL
7908 : 1 : PyModule_AddIntMacro(m, MSG_WAITALL);
7909 : : #endif
7910 : : #ifdef MSG_BTAG
7911 : : PyModule_AddIntMacro(m, MSG_BTAG);
7912 : : #endif
7913 : : #ifdef MSG_ETAG
7914 : : PyModule_AddIntMacro(m, MSG_ETAG);
7915 : : #endif
7916 : : #ifdef MSG_NOSIGNAL
7917 : 1 : PyModule_AddIntMacro(m, MSG_NOSIGNAL);
7918 : : #endif
7919 : : #ifdef MSG_NOTIFICATION
7920 : : PyModule_AddIntMacro(m, MSG_NOTIFICATION);
7921 : : #endif
7922 : : #ifdef MSG_CMSG_CLOEXEC
7923 : 1 : PyModule_AddIntMacro(m, MSG_CMSG_CLOEXEC);
7924 : : #endif
7925 : : #ifdef MSG_ERRQUEUE
7926 : 1 : PyModule_AddIntMacro(m, MSG_ERRQUEUE);
7927 : : #endif
7928 : : #ifdef MSG_CONFIRM
7929 : 1 : PyModule_AddIntMacro(m, MSG_CONFIRM);
7930 : : #endif
7931 : : #ifdef MSG_MORE
7932 : 1 : PyModule_AddIntMacro(m, MSG_MORE);
7933 : : #endif
7934 : : #ifdef MSG_EOF
7935 : : PyModule_AddIntMacro(m, MSG_EOF);
7936 : : #endif
7937 : : #ifdef MSG_BCAST
7938 : : PyModule_AddIntMacro(m, MSG_BCAST);
7939 : : #endif
7940 : : #ifdef MSG_MCAST
7941 : : PyModule_AddIntMacro(m, MSG_MCAST);
7942 : : #endif
7943 : : #ifdef MSG_FASTOPEN
7944 : 1 : PyModule_AddIntMacro(m, MSG_FASTOPEN);
7945 : : #endif
7946 : :
7947 : : /* Protocol level and numbers, usable for [gs]etsockopt */
7948 : : #ifdef SOL_SOCKET
7949 : 1 : PyModule_AddIntMacro(m, SOL_SOCKET);
7950 : : #endif
7951 : : #ifdef SOL_IP
7952 : 1 : PyModule_AddIntMacro(m, SOL_IP);
7953 : : #else
7954 : : PyModule_AddIntConstant(m, "SOL_IP", 0);
7955 : : #endif
7956 : : #ifdef SOL_IPX
7957 : : PyModule_AddIntMacro(m, SOL_IPX);
7958 : : #endif
7959 : : #ifdef SOL_AX25
7960 : : PyModule_AddIntMacro(m, SOL_AX25);
7961 : : #endif
7962 : : #ifdef SOL_ATALK
7963 : : PyModule_AddIntMacro(m, SOL_ATALK);
7964 : : #endif
7965 : : #ifdef SOL_NETROM
7966 : : PyModule_AddIntMacro(m, SOL_NETROM);
7967 : : #endif
7968 : : #ifdef SOL_ROSE
7969 : : PyModule_AddIntMacro(m, SOL_ROSE);
7970 : : #endif
7971 : : #ifdef SOL_TCP
7972 : 1 : PyModule_AddIntMacro(m, SOL_TCP);
7973 : : #else
7974 : : PyModule_AddIntConstant(m, "SOL_TCP", 6);
7975 : : #endif
7976 : : #ifdef SOL_UDP
7977 : : PyModule_AddIntMacro(m, SOL_UDP);
7978 : : #else
7979 : 1 : PyModule_AddIntConstant(m, "SOL_UDP", 17);
7980 : : #endif
7981 : : #ifdef SOL_CAN_BASE
7982 : 1 : PyModule_AddIntMacro(m, SOL_CAN_BASE);
7983 : : #endif
7984 : : #ifdef SOL_CAN_RAW
7985 : 1 : PyModule_AddIntMacro(m, SOL_CAN_RAW);
7986 : 1 : PyModule_AddIntMacro(m, CAN_RAW);
7987 : : #endif
7988 : : #if defined(HAVE_LINUX_CAN_H) || defined(HAVE_NETCAN_CAN_H)
7989 : 1 : PyModule_AddIntMacro(m, CAN_EFF_FLAG);
7990 : 1 : PyModule_AddIntMacro(m, CAN_RTR_FLAG);
7991 : 1 : PyModule_AddIntMacro(m, CAN_ERR_FLAG);
7992 : :
7993 : 1 : PyModule_AddIntMacro(m, CAN_SFF_MASK);
7994 : 1 : PyModule_AddIntMacro(m, CAN_EFF_MASK);
7995 : 1 : PyModule_AddIntMacro(m, CAN_ERR_MASK);
7996 : : #ifdef CAN_ISOTP
7997 : 1 : PyModule_AddIntMacro(m, CAN_ISOTP);
7998 : : #endif
7999 : : #ifdef CAN_J1939
8000 : 1 : PyModule_AddIntMacro(m, CAN_J1939);
8001 : : #endif
8002 : : #endif
8003 : : #if defined(HAVE_LINUX_CAN_RAW_H) || defined(HAVE_NETCAN_CAN_H)
8004 : 1 : PyModule_AddIntMacro(m, CAN_RAW_FILTER);
8005 : : #ifdef CAN_RAW_ERR_FILTER
8006 : : PyModule_AddIntMacro(m, CAN_RAW_ERR_FILTER);
8007 : : #endif
8008 : 1 : PyModule_AddIntMacro(m, CAN_RAW_LOOPBACK);
8009 : 1 : PyModule_AddIntMacro(m, CAN_RAW_RECV_OWN_MSGS);
8010 : : #endif
8011 : : #ifdef HAVE_LINUX_CAN_RAW_FD_FRAMES
8012 : 1 : PyModule_AddIntMacro(m, CAN_RAW_FD_FRAMES);
8013 : : #endif
8014 : : #ifdef HAVE_LINUX_CAN_RAW_JOIN_FILTERS
8015 : 1 : PyModule_AddIntMacro(m, CAN_RAW_JOIN_FILTERS);
8016 : : #endif
8017 : : #ifdef HAVE_LINUX_CAN_BCM_H
8018 : 1 : PyModule_AddIntMacro(m, CAN_BCM);
8019 : :
8020 : : /* BCM opcodes */
8021 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_SETUP", TX_SETUP);
8022 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_DELETE", TX_DELETE);
8023 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_READ", TX_READ);
8024 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_SEND", TX_SEND);
8025 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_SETUP", RX_SETUP);
8026 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_DELETE", RX_DELETE);
8027 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_READ", RX_READ);
8028 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_STATUS", TX_STATUS);
8029 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_EXPIRED", TX_EXPIRED);
8030 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_STATUS", RX_STATUS);
8031 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_TIMEOUT", RX_TIMEOUT);
8032 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_CHANGED", RX_CHANGED);
8033 : :
8034 : : /* BCM flags */
8035 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_SETTIMER", SETTIMER);
8036 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_STARTTIMER", STARTTIMER);
8037 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_COUNTEVT", TX_COUNTEVT);
8038 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_ANNOUNCE", TX_ANNOUNCE);
8039 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_CP_CAN_ID", TX_CP_CAN_ID);
8040 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_FILTER_ID", RX_FILTER_ID);
8041 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_CHECK_DLC", RX_CHECK_DLC);
8042 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_NO_AUTOTIMER", RX_NO_AUTOTIMER);
8043 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_ANNOUNCE_RESUME", RX_ANNOUNCE_RESUME);
8044 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_TX_RESET_MULTI_IDX", TX_RESET_MULTI_IDX);
8045 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_RX_RTR_FRAME", RX_RTR_FRAME);
8046 : : #ifdef CAN_FD_FRAME
8047 : : /* CAN_FD_FRAME was only introduced in the 4.8.x kernel series */
8048 : 1 : PyModule_AddIntConstant(m, "CAN_BCM_CAN_FD_FRAME", CAN_FD_FRAME);
8049 : : #endif
8050 : : #endif
8051 : : #ifdef HAVE_LINUX_CAN_J1939_H
8052 : 1 : PyModule_AddIntMacro(m, J1939_MAX_UNICAST_ADDR);
8053 : 1 : PyModule_AddIntMacro(m, J1939_IDLE_ADDR);
8054 : 1 : PyModule_AddIntMacro(m, J1939_NO_ADDR);
8055 : 1 : PyModule_AddIntMacro(m, J1939_NO_NAME);
8056 : 1 : PyModule_AddIntMacro(m, J1939_PGN_REQUEST);
8057 : 1 : PyModule_AddIntMacro(m, J1939_PGN_ADDRESS_CLAIMED);
8058 : 1 : PyModule_AddIntMacro(m, J1939_PGN_ADDRESS_COMMANDED);
8059 : 1 : PyModule_AddIntMacro(m, J1939_PGN_PDU1_MAX);
8060 : 1 : PyModule_AddIntMacro(m, J1939_PGN_MAX);
8061 : 1 : PyModule_AddIntMacro(m, J1939_NO_PGN);
8062 : :
8063 : : /* J1939 socket options */
8064 : 1 : PyModule_AddIntMacro(m, SO_J1939_FILTER);
8065 : 1 : PyModule_AddIntMacro(m, SO_J1939_PROMISC);
8066 : 1 : PyModule_AddIntMacro(m, SO_J1939_SEND_PRIO);
8067 : 1 : PyModule_AddIntMacro(m, SO_J1939_ERRQUEUE);
8068 : :
8069 : 1 : PyModule_AddIntMacro(m, SCM_J1939_DEST_ADDR);
8070 : 1 : PyModule_AddIntMacro(m, SCM_J1939_DEST_NAME);
8071 : 1 : PyModule_AddIntMacro(m, SCM_J1939_PRIO);
8072 : 1 : PyModule_AddIntMacro(m, SCM_J1939_ERRQUEUE);
8073 : :
8074 : 1 : PyModule_AddIntMacro(m, J1939_NLA_PAD);
8075 : 1 : PyModule_AddIntMacro(m, J1939_NLA_BYTES_ACKED);
8076 : :
8077 : 1 : PyModule_AddIntMacro(m, J1939_EE_INFO_NONE);
8078 : 1 : PyModule_AddIntMacro(m, J1939_EE_INFO_TX_ABORT);
8079 : :
8080 : 1 : PyModule_AddIntMacro(m, J1939_FILTER_MAX);
8081 : : #endif
8082 : : #ifdef SOL_RDS
8083 : 1 : PyModule_AddIntMacro(m, SOL_RDS);
8084 : : #endif
8085 : : #ifdef HAVE_SOCKADDR_ALG
8086 : 1 : PyModule_AddIntMacro(m, SOL_ALG);
8087 : : #endif
8088 : : #ifdef RDS_CANCEL_SENT_TO
8089 : : PyModule_AddIntMacro(m, RDS_CANCEL_SENT_TO);
8090 : : #endif
8091 : : #ifdef RDS_GET_MR
8092 : : PyModule_AddIntMacro(m, RDS_GET_MR);
8093 : : #endif
8094 : : #ifdef RDS_FREE_MR
8095 : : PyModule_AddIntMacro(m, RDS_FREE_MR);
8096 : : #endif
8097 : : #ifdef RDS_RECVERR
8098 : : PyModule_AddIntMacro(m, RDS_RECVERR);
8099 : : #endif
8100 : : #ifdef RDS_CONG_MONITOR
8101 : : PyModule_AddIntMacro(m, RDS_CONG_MONITOR);
8102 : : #endif
8103 : : #ifdef RDS_GET_MR_FOR_DEST
8104 : : PyModule_AddIntMacro(m, RDS_GET_MR_FOR_DEST);
8105 : : #endif
8106 : : #ifdef IPPROTO_IP
8107 : 1 : PyModule_AddIntMacro(m, IPPROTO_IP);
8108 : : #else
8109 : : PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
8110 : : #endif
8111 : : #ifdef IPPROTO_HOPOPTS
8112 : 1 : PyModule_AddIntMacro(m, IPPROTO_HOPOPTS);
8113 : : #endif
8114 : : #ifdef IPPROTO_ICMP
8115 : 1 : PyModule_AddIntMacro(m, IPPROTO_ICMP);
8116 : : #else
8117 : : PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
8118 : : #endif
8119 : : #ifdef IPPROTO_IGMP
8120 : 1 : PyModule_AddIntMacro(m, IPPROTO_IGMP);
8121 : : #endif
8122 : : #ifdef IPPROTO_GGP
8123 : : PyModule_AddIntMacro(m, IPPROTO_GGP);
8124 : : #endif
8125 : : #ifdef IPPROTO_IPV4
8126 : : PyModule_AddIntMacro(m, IPPROTO_IPV4);
8127 : : #endif
8128 : : #ifdef IPPROTO_IPV6
8129 : 1 : PyModule_AddIntMacro(m, IPPROTO_IPV6);
8130 : : #endif
8131 : : #ifdef IPPROTO_IPIP
8132 : 1 : PyModule_AddIntMacro(m, IPPROTO_IPIP);
8133 : : #endif
8134 : : #ifdef IPPROTO_TCP
8135 : 1 : PyModule_AddIntMacro(m, IPPROTO_TCP);
8136 : : #else
8137 : : PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
8138 : : #endif
8139 : : #ifdef IPPROTO_EGP
8140 : 1 : PyModule_AddIntMacro(m, IPPROTO_EGP);
8141 : : #endif
8142 : : #ifdef IPPROTO_PUP
8143 : 1 : PyModule_AddIntMacro(m, IPPROTO_PUP);
8144 : : #endif
8145 : : #ifdef IPPROTO_UDP
8146 : 1 : PyModule_AddIntMacro(m, IPPROTO_UDP);
8147 : : #else
8148 : : PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
8149 : : #endif
8150 : : #ifdef IPPROTO_UDPLITE
8151 : 1 : PyModule_AddIntMacro(m, IPPROTO_UDPLITE);
8152 : : #ifndef UDPLITE_SEND_CSCOV
8153 : : #define UDPLITE_SEND_CSCOV 10
8154 : : #endif
8155 : 1 : PyModule_AddIntMacro(m, UDPLITE_SEND_CSCOV);
8156 : : #ifndef UDPLITE_RECV_CSCOV
8157 : : #define UDPLITE_RECV_CSCOV 11
8158 : : #endif
8159 : 1 : PyModule_AddIntMacro(m, UDPLITE_RECV_CSCOV);
8160 : : #endif
8161 : : #ifdef IPPROTO_IDP
8162 : 1 : PyModule_AddIntMacro(m, IPPROTO_IDP);
8163 : : #endif
8164 : : #ifdef IPPROTO_HELLO
8165 : : PyModule_AddIntMacro(m, IPPROTO_HELLO);
8166 : : #endif
8167 : : #ifdef IPPROTO_ND
8168 : : PyModule_AddIntMacro(m, IPPROTO_ND);
8169 : : #endif
8170 : : #ifdef IPPROTO_TP
8171 : 1 : PyModule_AddIntMacro(m, IPPROTO_TP);
8172 : : #endif
8173 : : #ifdef IPPROTO_ROUTING
8174 : 1 : PyModule_AddIntMacro(m, IPPROTO_ROUTING);
8175 : : #endif
8176 : : #ifdef IPPROTO_FRAGMENT
8177 : 1 : PyModule_AddIntMacro(m, IPPROTO_FRAGMENT);
8178 : : #endif
8179 : : #ifdef IPPROTO_RSVP
8180 : 1 : PyModule_AddIntMacro(m, IPPROTO_RSVP);
8181 : : #endif
8182 : : #ifdef IPPROTO_GRE
8183 : 1 : PyModule_AddIntMacro(m, IPPROTO_GRE);
8184 : : #endif
8185 : : #ifdef IPPROTO_ESP
8186 : 1 : PyModule_AddIntMacro(m, IPPROTO_ESP);
8187 : : #endif
8188 : : #ifdef IPPROTO_AH
8189 : 1 : PyModule_AddIntMacro(m, IPPROTO_AH);
8190 : : #endif
8191 : : #ifdef IPPROTO_MOBILE
8192 : : PyModule_AddIntMacro(m, IPPROTO_MOBILE);
8193 : : #endif
8194 : : #ifdef IPPROTO_ICMPV6
8195 : 1 : PyModule_AddIntMacro(m, IPPROTO_ICMPV6);
8196 : : #endif
8197 : : #ifdef IPPROTO_NONE
8198 : 1 : PyModule_AddIntMacro(m, IPPROTO_NONE);
8199 : : #endif
8200 : : #ifdef IPPROTO_DSTOPTS
8201 : 1 : PyModule_AddIntMacro(m, IPPROTO_DSTOPTS);
8202 : : #endif
8203 : : #ifdef IPPROTO_XTP
8204 : : PyModule_AddIntMacro(m, IPPROTO_XTP);
8205 : : #endif
8206 : : #ifdef IPPROTO_EON
8207 : : PyModule_AddIntMacro(m, IPPROTO_EON);
8208 : : #endif
8209 : : #ifdef IPPROTO_PIM
8210 : 1 : PyModule_AddIntMacro(m, IPPROTO_PIM);
8211 : : #endif
8212 : : #ifdef IPPROTO_IPCOMP
8213 : : PyModule_AddIntMacro(m, IPPROTO_IPCOMP);
8214 : : #endif
8215 : : #ifdef IPPROTO_VRRP
8216 : : PyModule_AddIntMacro(m, IPPROTO_VRRP);
8217 : : #endif
8218 : : #ifdef IPPROTO_SCTP
8219 : 1 : PyModule_AddIntMacro(m, IPPROTO_SCTP);
8220 : : #endif
8221 : : #ifdef IPPROTO_BIP
8222 : : PyModule_AddIntMacro(m, IPPROTO_BIP);
8223 : : #endif
8224 : : #ifdef IPPROTO_MPTCP
8225 : : PyModule_AddIntMacro(m, IPPROTO_MPTCP);
8226 : : #endif
8227 : : /**/
8228 : : #ifdef IPPROTO_RAW
8229 : 1 : PyModule_AddIntMacro(m, IPPROTO_RAW);
8230 : : #else
8231 : : PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
8232 : : #endif
8233 : : #ifdef IPPROTO_MAX
8234 : : PyModule_AddIntMacro(m, IPPROTO_MAX);
8235 : : #endif
8236 : :
8237 : : #ifdef MS_WINDOWS
8238 : : PyModule_AddIntMacro(m, IPPROTO_ICLFXBM);
8239 : : PyModule_AddIntMacro(m, IPPROTO_ST);
8240 : : PyModule_AddIntMacro(m, IPPROTO_CBT);
8241 : : PyModule_AddIntMacro(m, IPPROTO_IGP);
8242 : : PyModule_AddIntMacro(m, IPPROTO_RDP);
8243 : : PyModule_AddIntMacro(m, IPPROTO_PGM);
8244 : : PyModule_AddIntMacro(m, IPPROTO_L2TP);
8245 : : PyModule_AddIntMacro(m, IPPROTO_SCTP);
8246 : : #endif
8247 : :
8248 : : #ifdef SYSPROTO_CONTROL
8249 : : PyModule_AddIntMacro(m, SYSPROTO_CONTROL);
8250 : : #endif
8251 : :
8252 : : /* Some port configuration */
8253 : : #ifdef IPPORT_RESERVED
8254 : 1 : PyModule_AddIntMacro(m, IPPORT_RESERVED);
8255 : : #else
8256 : : PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
8257 : : #endif
8258 : : #ifdef IPPORT_USERRESERVED
8259 : : PyModule_AddIntMacro(m, IPPORT_USERRESERVED);
8260 : : #else
8261 : 1 : PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
8262 : : #endif
8263 : :
8264 : : /* Some reserved IP v.4 addresses */
8265 : : #ifdef INADDR_ANY
8266 : 1 : PyModule_AddIntMacro(m, INADDR_ANY);
8267 : : #else
8268 : : PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
8269 : : #endif
8270 : : #ifdef INADDR_BROADCAST
8271 : 1 : PyModule_AddIntMacro(m, INADDR_BROADCAST);
8272 : : #else
8273 : : PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
8274 : : #endif
8275 : : #ifdef INADDR_LOOPBACK
8276 : 1 : PyModule_AddIntMacro(m, INADDR_LOOPBACK);
8277 : : #else
8278 : : PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
8279 : : #endif
8280 : : #ifdef INADDR_UNSPEC_GROUP
8281 : 1 : PyModule_AddIntMacro(m, INADDR_UNSPEC_GROUP);
8282 : : #else
8283 : : PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
8284 : : #endif
8285 : : #ifdef INADDR_ALLHOSTS_GROUP
8286 : 1 : PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
8287 : : INADDR_ALLHOSTS_GROUP);
8288 : : #else
8289 : : PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
8290 : : #endif
8291 : : #ifdef INADDR_MAX_LOCAL_GROUP
8292 : 1 : PyModule_AddIntMacro(m, INADDR_MAX_LOCAL_GROUP);
8293 : : #else
8294 : : PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
8295 : : #endif
8296 : : #ifdef INADDR_NONE
8297 : 1 : PyModule_AddIntMacro(m, INADDR_NONE);
8298 : : #else
8299 : : PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
8300 : : #endif
8301 : :
8302 : : /* IPv4 [gs]etsockopt options */
8303 : : #ifdef IP_OPTIONS
8304 : 1 : PyModule_AddIntMacro(m, IP_OPTIONS);
8305 : : #endif
8306 : : #ifdef IP_HDRINCL
8307 : 1 : PyModule_AddIntMacro(m, IP_HDRINCL);
8308 : : #endif
8309 : : #ifdef IP_TOS
8310 : 1 : PyModule_AddIntMacro(m, IP_TOS);
8311 : : #endif
8312 : : #ifdef IP_TTL
8313 : 1 : PyModule_AddIntMacro(m, IP_TTL);
8314 : : #endif
8315 : : #ifdef IP_RECVOPTS
8316 : 1 : PyModule_AddIntMacro(m, IP_RECVOPTS);
8317 : : #endif
8318 : : #ifdef IP_RECVRETOPTS
8319 : 1 : PyModule_AddIntMacro(m, IP_RECVRETOPTS);
8320 : : #endif
8321 : : #ifdef IP_RECVTOS
8322 : 1 : PyModule_AddIntMacro(m, IP_RECVTOS);
8323 : : #endif
8324 : : #ifdef IP_RECVDSTADDR
8325 : : PyModule_AddIntMacro(m, IP_RECVDSTADDR);
8326 : : #endif
8327 : : #ifdef IP_RETOPTS
8328 : 1 : PyModule_AddIntMacro(m, IP_RETOPTS);
8329 : : #endif
8330 : : #ifdef IP_MULTICAST_IF
8331 : 1 : PyModule_AddIntMacro(m, IP_MULTICAST_IF);
8332 : : #endif
8333 : : #ifdef IP_MULTICAST_TTL
8334 : 1 : PyModule_AddIntMacro(m, IP_MULTICAST_TTL);
8335 : : #endif
8336 : : #ifdef IP_MULTICAST_LOOP
8337 : 1 : PyModule_AddIntMacro(m, IP_MULTICAST_LOOP);
8338 : : #endif
8339 : : #ifdef IP_ADD_MEMBERSHIP
8340 : 1 : PyModule_AddIntMacro(m, IP_ADD_MEMBERSHIP);
8341 : : #endif
8342 : : #ifdef IP_DROP_MEMBERSHIP
8343 : 1 : PyModule_AddIntMacro(m, IP_DROP_MEMBERSHIP);
8344 : : #endif
8345 : : #ifdef IP_DEFAULT_MULTICAST_TTL
8346 : 1 : PyModule_AddIntMacro(m, IP_DEFAULT_MULTICAST_TTL);
8347 : : #endif
8348 : : #ifdef IP_DEFAULT_MULTICAST_LOOP
8349 : 1 : PyModule_AddIntMacro(m, IP_DEFAULT_MULTICAST_LOOP);
8350 : : #endif
8351 : : #ifdef IP_MAX_MEMBERSHIPS
8352 : 1 : PyModule_AddIntMacro(m, IP_MAX_MEMBERSHIPS);
8353 : : #endif
8354 : : #ifdef IP_TRANSPARENT
8355 : 1 : PyModule_AddIntMacro(m, IP_TRANSPARENT);
8356 : : #endif
8357 : : #ifdef IP_PKTINFO
8358 : 1 : PyModule_AddIntMacro(m, IP_PKTINFO);
8359 : : #endif
8360 : : #ifdef IP_BIND_ADDRESS_NO_PORT
8361 : 1 : PyModule_AddIntMacro(m, IP_BIND_ADDRESS_NO_PORT);
8362 : : #endif
8363 : :
8364 : : /* IPv6 [gs]etsockopt options, defined in RFC2553 */
8365 : : #ifdef IPV6_JOIN_GROUP
8366 : 1 : PyModule_AddIntMacro(m, IPV6_JOIN_GROUP);
8367 : : #endif
8368 : : #ifdef IPV6_LEAVE_GROUP
8369 : 1 : PyModule_AddIntMacro(m, IPV6_LEAVE_GROUP);
8370 : : #endif
8371 : : #ifdef IPV6_MULTICAST_HOPS
8372 : 1 : PyModule_AddIntMacro(m, IPV6_MULTICAST_HOPS);
8373 : : #endif
8374 : : #ifdef IPV6_MULTICAST_IF
8375 : 1 : PyModule_AddIntMacro(m, IPV6_MULTICAST_IF);
8376 : : #endif
8377 : : #ifdef IPV6_MULTICAST_LOOP
8378 : 1 : PyModule_AddIntMacro(m, IPV6_MULTICAST_LOOP);
8379 : : #endif
8380 : : #ifdef IPV6_UNICAST_HOPS
8381 : 1 : PyModule_AddIntMacro(m, IPV6_UNICAST_HOPS);
8382 : : #endif
8383 : : /* Additional IPV6 socket options, defined in RFC 3493 */
8384 : : #ifdef IPV6_V6ONLY
8385 : 1 : PyModule_AddIntMacro(m, IPV6_V6ONLY);
8386 : : #endif
8387 : : /* Advanced IPV6 socket options, from RFC 3542 */
8388 : : #ifdef IPV6_CHECKSUM
8389 : 1 : PyModule_AddIntMacro(m, IPV6_CHECKSUM);
8390 : : #endif
8391 : : #ifdef IPV6_DONTFRAG
8392 : 1 : PyModule_AddIntMacro(m, IPV6_DONTFRAG);
8393 : : #endif
8394 : : #ifdef IPV6_DSTOPTS
8395 : 1 : PyModule_AddIntMacro(m, IPV6_DSTOPTS);
8396 : : #endif
8397 : : #ifdef IPV6_HOPLIMIT
8398 : 1 : PyModule_AddIntMacro(m, IPV6_HOPLIMIT);
8399 : : #endif
8400 : : #ifdef IPV6_HOPOPTS
8401 : 1 : PyModule_AddIntMacro(m, IPV6_HOPOPTS);
8402 : : #endif
8403 : : #ifdef IPV6_NEXTHOP
8404 : 1 : PyModule_AddIntMacro(m, IPV6_NEXTHOP);
8405 : : #endif
8406 : : #ifdef IPV6_PATHMTU
8407 : 1 : PyModule_AddIntMacro(m, IPV6_PATHMTU);
8408 : : #endif
8409 : : #ifdef IPV6_PKTINFO
8410 : 1 : PyModule_AddIntMacro(m, IPV6_PKTINFO);
8411 : : #endif
8412 : : #ifdef IPV6_RECVDSTOPTS
8413 : 1 : PyModule_AddIntMacro(m, IPV6_RECVDSTOPTS);
8414 : : #endif
8415 : : #ifdef IPV6_RECVHOPLIMIT
8416 : 1 : PyModule_AddIntMacro(m, IPV6_RECVHOPLIMIT);
8417 : : #endif
8418 : : #ifdef IPV6_RECVHOPOPTS
8419 : 1 : PyModule_AddIntMacro(m, IPV6_RECVHOPOPTS);
8420 : : #endif
8421 : : #ifdef IPV6_RECVPKTINFO
8422 : 1 : PyModule_AddIntMacro(m, IPV6_RECVPKTINFO);
8423 : : #endif
8424 : : #ifdef IPV6_RECVRTHDR
8425 : 1 : PyModule_AddIntMacro(m, IPV6_RECVRTHDR);
8426 : : #endif
8427 : : #ifdef IPV6_RECVTCLASS
8428 : 1 : PyModule_AddIntMacro(m, IPV6_RECVTCLASS);
8429 : : #endif
8430 : : #ifdef IPV6_RTHDR
8431 : 1 : PyModule_AddIntMacro(m, IPV6_RTHDR);
8432 : : #endif
8433 : : #ifdef IPV6_RTHDRDSTOPTS
8434 : 1 : PyModule_AddIntMacro(m, IPV6_RTHDRDSTOPTS);
8435 : : #endif
8436 : : #ifdef IPV6_RTHDR_TYPE_0
8437 : 1 : PyModule_AddIntMacro(m, IPV6_RTHDR_TYPE_0);
8438 : : #endif
8439 : : #ifdef IPV6_RECVPATHMTU
8440 : 1 : PyModule_AddIntMacro(m, IPV6_RECVPATHMTU);
8441 : : #endif
8442 : : #ifdef IPV6_TCLASS
8443 : 1 : PyModule_AddIntMacro(m, IPV6_TCLASS);
8444 : : #endif
8445 : : #ifdef IPV6_USE_MIN_MTU
8446 : : PyModule_AddIntMacro(m, IPV6_USE_MIN_MTU);
8447 : : #endif
8448 : :
8449 : : /* TCP options */
8450 : : #ifdef TCP_NODELAY
8451 : 1 : PyModule_AddIntMacro(m, TCP_NODELAY);
8452 : : #endif
8453 : : #ifdef TCP_MAXSEG
8454 : 1 : PyModule_AddIntMacro(m, TCP_MAXSEG);
8455 : : #endif
8456 : : #ifdef TCP_CORK
8457 : 1 : PyModule_AddIntMacro(m, TCP_CORK);
8458 : : #endif
8459 : : #ifdef TCP_KEEPIDLE
8460 : 1 : PyModule_AddIntMacro(m, TCP_KEEPIDLE);
8461 : : #endif
8462 : : /* TCP_KEEPALIVE is OSX's TCP_KEEPIDLE equivalent */
8463 : : #if defined(__APPLE__) && defined(TCP_KEEPALIVE)
8464 : : PyModule_AddIntMacro(m, TCP_KEEPALIVE);
8465 : : #endif
8466 : : #ifdef TCP_KEEPINTVL
8467 : 1 : PyModule_AddIntMacro(m, TCP_KEEPINTVL);
8468 : : #endif
8469 : : #ifdef TCP_KEEPCNT
8470 : 1 : PyModule_AddIntMacro(m, TCP_KEEPCNT);
8471 : : #endif
8472 : : #ifdef TCP_SYNCNT
8473 : 1 : PyModule_AddIntMacro(m, TCP_SYNCNT);
8474 : : #endif
8475 : : #ifdef TCP_LINGER2
8476 : 1 : PyModule_AddIntMacro(m, TCP_LINGER2);
8477 : : #endif
8478 : : #ifdef TCP_DEFER_ACCEPT
8479 : 1 : PyModule_AddIntMacro(m, TCP_DEFER_ACCEPT);
8480 : : #endif
8481 : : #ifdef TCP_WINDOW_CLAMP
8482 : 1 : PyModule_AddIntMacro(m, TCP_WINDOW_CLAMP);
8483 : : #endif
8484 : : #ifdef TCP_INFO
8485 : 1 : PyModule_AddIntMacro(m, TCP_INFO);
8486 : : #endif
8487 : : #ifdef TCP_CONNECTION_INFO
8488 : : PyModule_AddIntMacro(m, TCP_CONNECTION_INFO);
8489 : : #endif
8490 : : #ifdef TCP_QUICKACK
8491 : 1 : PyModule_AddIntMacro(m, TCP_QUICKACK);
8492 : : #endif
8493 : : #ifdef TCP_CONGESTION
8494 : 1 : PyModule_AddIntMacro(m, TCP_CONGESTION);
8495 : : #endif
8496 : : #ifdef TCP_MD5SIG
8497 : 1 : PyModule_AddIntMacro(m, TCP_MD5SIG);
8498 : : #endif
8499 : : #ifdef TCP_THIN_LINEAR_TIMEOUTS
8500 : 1 : PyModule_AddIntMacro(m, TCP_THIN_LINEAR_TIMEOUTS);
8501 : : #endif
8502 : : #ifdef TCP_THIN_DUPACK
8503 : 1 : PyModule_AddIntMacro(m, TCP_THIN_DUPACK);
8504 : : #endif
8505 : : #ifdef TCP_USER_TIMEOUT
8506 : 1 : PyModule_AddIntMacro(m, TCP_USER_TIMEOUT);
8507 : : #endif
8508 : : #ifdef TCP_REPAIR
8509 : 1 : PyModule_AddIntMacro(m, TCP_REPAIR);
8510 : : #endif
8511 : : #ifdef TCP_REPAIR_QUEUE
8512 : 1 : PyModule_AddIntMacro(m, TCP_REPAIR_QUEUE);
8513 : : #endif
8514 : : #ifdef TCP_QUEUE_SEQ
8515 : 1 : PyModule_AddIntMacro(m, TCP_QUEUE_SEQ);
8516 : : #endif
8517 : : #ifdef TCP_REPAIR_OPTIONS
8518 : 1 : PyModule_AddIntMacro(m, TCP_REPAIR_OPTIONS);
8519 : : #endif
8520 : : #ifdef TCP_FASTOPEN
8521 : 1 : PyModule_AddIntMacro(m, TCP_FASTOPEN);
8522 : : #endif
8523 : : #ifdef TCP_TIMESTAMP
8524 : 1 : PyModule_AddIntMacro(m, TCP_TIMESTAMP);
8525 : : #endif
8526 : : #ifdef TCP_NOTSENT_LOWAT
8527 : 1 : PyModule_AddIntMacro(m, TCP_NOTSENT_LOWAT);
8528 : : #endif
8529 : : #ifdef TCP_CC_INFO
8530 : 1 : PyModule_AddIntMacro(m, TCP_CC_INFO);
8531 : : #endif
8532 : : #ifdef TCP_SAVE_SYN
8533 : 1 : PyModule_AddIntMacro(m, TCP_SAVE_SYN);
8534 : : #endif
8535 : : #ifdef TCP_SAVED_SYN
8536 : 1 : PyModule_AddIntMacro(m, TCP_SAVED_SYN);
8537 : : #endif
8538 : : #ifdef TCP_REPAIR_WINDOW
8539 : 1 : PyModule_AddIntMacro(m, TCP_REPAIR_WINDOW);
8540 : : #endif
8541 : : #ifdef TCP_FASTOPEN_CONNECT
8542 : 1 : PyModule_AddIntMacro(m, TCP_FASTOPEN_CONNECT);
8543 : : #endif
8544 : : #ifdef TCP_ULP
8545 : 1 : PyModule_AddIntMacro(m, TCP_ULP);
8546 : : #endif
8547 : : #ifdef TCP_MD5SIG_EXT
8548 : 1 : PyModule_AddIntMacro(m, TCP_MD5SIG_EXT);
8549 : : #endif
8550 : : #ifdef TCP_FASTOPEN_KEY
8551 : 1 : PyModule_AddIntMacro(m, TCP_FASTOPEN_KEY);
8552 : : #endif
8553 : : #ifdef TCP_FASTOPEN_NO_COOKIE
8554 : 1 : PyModule_AddIntMacro(m, TCP_FASTOPEN_NO_COOKIE);
8555 : : #endif
8556 : : #ifdef TCP_ZEROCOPY_RECEIVE
8557 : 1 : PyModule_AddIntMacro(m, TCP_ZEROCOPY_RECEIVE);
8558 : : #endif
8559 : : #ifdef TCP_INQ
8560 : 1 : PyModule_AddIntMacro(m, TCP_INQ);
8561 : : #endif
8562 : : #ifdef TCP_TX_DELAY
8563 : 1 : PyModule_AddIntMacro(m, TCP_TX_DELAY);
8564 : : #endif
8565 : :
8566 : : /* IPX options */
8567 : : #ifdef IPX_TYPE
8568 : : PyModule_AddIntMacro(m, IPX_TYPE);
8569 : : #endif
8570 : :
8571 : : /* Reliable Datagram Sockets */
8572 : : #ifdef RDS_CMSG_RDMA_ARGS
8573 : : PyModule_AddIntMacro(m, RDS_CMSG_RDMA_ARGS);
8574 : : #endif
8575 : : #ifdef RDS_CMSG_RDMA_DEST
8576 : : PyModule_AddIntMacro(m, RDS_CMSG_RDMA_DEST);
8577 : : #endif
8578 : : #ifdef RDS_CMSG_RDMA_MAP
8579 : : PyModule_AddIntMacro(m, RDS_CMSG_RDMA_MAP);
8580 : : #endif
8581 : : #ifdef RDS_CMSG_RDMA_STATUS
8582 : : PyModule_AddIntMacro(m, RDS_CMSG_RDMA_STATUS);
8583 : : #endif
8584 : : #ifdef RDS_CMSG_RDMA_UPDATE
8585 : : PyModule_AddIntMacro(m, RDS_CMSG_RDMA_UPDATE);
8586 : : #endif
8587 : : #ifdef RDS_RDMA_READWRITE
8588 : : PyModule_AddIntMacro(m, RDS_RDMA_READWRITE);
8589 : : #endif
8590 : : #ifdef RDS_RDMA_FENCE
8591 : : PyModule_AddIntMacro(m, RDS_RDMA_FENCE);
8592 : : #endif
8593 : : #ifdef RDS_RDMA_INVALIDATE
8594 : : PyModule_AddIntMacro(m, RDS_RDMA_INVALIDATE);
8595 : : #endif
8596 : : #ifdef RDS_RDMA_USE_ONCE
8597 : : PyModule_AddIntMacro(m, RDS_RDMA_USE_ONCE);
8598 : : #endif
8599 : : #ifdef RDS_RDMA_DONTWAIT
8600 : : PyModule_AddIntMacro(m, RDS_RDMA_DONTWAIT);
8601 : : #endif
8602 : : #ifdef RDS_RDMA_NOTIFY_ME
8603 : : PyModule_AddIntMacro(m, RDS_RDMA_NOTIFY_ME);
8604 : : #endif
8605 : : #ifdef RDS_RDMA_SILENT
8606 : : PyModule_AddIntMacro(m, RDS_RDMA_SILENT);
8607 : : #endif
8608 : :
8609 : : /* get{addr,name}info parameters */
8610 : : #ifdef EAI_ADDRFAMILY
8611 : 1 : PyModule_AddIntMacro(m, EAI_ADDRFAMILY);
8612 : : #endif
8613 : : #ifdef EAI_AGAIN
8614 : 1 : PyModule_AddIntMacro(m, EAI_AGAIN);
8615 : : #endif
8616 : : #ifdef EAI_BADFLAGS
8617 : 1 : PyModule_AddIntMacro(m, EAI_BADFLAGS);
8618 : : #endif
8619 : : #ifdef EAI_FAIL
8620 : 1 : PyModule_AddIntMacro(m, EAI_FAIL);
8621 : : #endif
8622 : : #ifdef EAI_FAMILY
8623 : 1 : PyModule_AddIntMacro(m, EAI_FAMILY);
8624 : : #endif
8625 : : #ifdef EAI_MEMORY
8626 : 1 : PyModule_AddIntMacro(m, EAI_MEMORY);
8627 : : #endif
8628 : : #ifdef EAI_NODATA
8629 : 1 : PyModule_AddIntMacro(m, EAI_NODATA);
8630 : : #endif
8631 : : #ifdef EAI_NONAME
8632 : 1 : PyModule_AddIntMacro(m, EAI_NONAME);
8633 : : #endif
8634 : : #ifdef EAI_OVERFLOW
8635 : 1 : PyModule_AddIntMacro(m, EAI_OVERFLOW);
8636 : : #endif
8637 : : #ifdef EAI_SERVICE
8638 : 1 : PyModule_AddIntMacro(m, EAI_SERVICE);
8639 : : #endif
8640 : : #ifdef EAI_SOCKTYPE
8641 : 1 : PyModule_AddIntMacro(m, EAI_SOCKTYPE);
8642 : : #endif
8643 : : #ifdef EAI_SYSTEM
8644 : 1 : PyModule_AddIntMacro(m, EAI_SYSTEM);
8645 : : #endif
8646 : : #ifdef EAI_BADHINTS
8647 : : PyModule_AddIntMacro(m, EAI_BADHINTS);
8648 : : #endif
8649 : : #ifdef EAI_PROTOCOL
8650 : : PyModule_AddIntMacro(m, EAI_PROTOCOL);
8651 : : #endif
8652 : : #ifdef EAI_MAX
8653 : : PyModule_AddIntMacro(m, EAI_MAX);
8654 : : #endif
8655 : : #ifdef AI_PASSIVE
8656 : 1 : PyModule_AddIntMacro(m, AI_PASSIVE);
8657 : : #endif
8658 : : #ifdef AI_CANONNAME
8659 : 1 : PyModule_AddIntMacro(m, AI_CANONNAME);
8660 : : #endif
8661 : : #ifdef AI_NUMERICHOST
8662 : 1 : PyModule_AddIntMacro(m, AI_NUMERICHOST);
8663 : : #endif
8664 : : #ifdef AI_NUMERICSERV
8665 : 1 : PyModule_AddIntMacro(m, AI_NUMERICSERV);
8666 : : #endif
8667 : : #ifdef AI_MASK
8668 : : PyModule_AddIntMacro(m, AI_MASK);
8669 : : #endif
8670 : : #ifdef AI_ALL
8671 : 1 : PyModule_AddIntMacro(m, AI_ALL);
8672 : : #endif
8673 : : #ifdef AI_V4MAPPED_CFG
8674 : : PyModule_AddIntMacro(m, AI_V4MAPPED_CFG);
8675 : : #endif
8676 : : #ifdef AI_ADDRCONFIG
8677 : 1 : PyModule_AddIntMacro(m, AI_ADDRCONFIG);
8678 : : #endif
8679 : : #ifdef AI_V4MAPPED
8680 : 1 : PyModule_AddIntMacro(m, AI_V4MAPPED);
8681 : : #endif
8682 : : #ifdef AI_DEFAULT
8683 : : PyModule_AddIntMacro(m, AI_DEFAULT);
8684 : : #endif
8685 : : #ifdef NI_MAXHOST
8686 : 1 : PyModule_AddIntMacro(m, NI_MAXHOST);
8687 : : #endif
8688 : : #ifdef NI_MAXSERV
8689 : 1 : PyModule_AddIntMacro(m, NI_MAXSERV);
8690 : : #endif
8691 : : #ifdef NI_NOFQDN
8692 : 1 : PyModule_AddIntMacro(m, NI_NOFQDN);
8693 : : #endif
8694 : : #ifdef NI_NUMERICHOST
8695 : 1 : PyModule_AddIntMacro(m, NI_NUMERICHOST);
8696 : : #endif
8697 : : #ifdef NI_NAMEREQD
8698 : 1 : PyModule_AddIntMacro(m, NI_NAMEREQD);
8699 : : #endif
8700 : : #ifdef NI_NUMERICSERV
8701 : 1 : PyModule_AddIntMacro(m, NI_NUMERICSERV);
8702 : : #endif
8703 : : #ifdef NI_DGRAM
8704 : 1 : PyModule_AddIntMacro(m, NI_DGRAM);
8705 : : #endif
8706 : :
8707 : : /* shutdown() parameters */
8708 : : #ifdef SHUT_RD
8709 : 1 : PyModule_AddIntMacro(m, SHUT_RD);
8710 : : #elif defined(SD_RECEIVE)
8711 : : PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
8712 : : #else
8713 : : PyModule_AddIntConstant(m, "SHUT_RD", 0);
8714 : : #endif
8715 : : #ifdef SHUT_WR
8716 : 1 : PyModule_AddIntMacro(m, SHUT_WR);
8717 : : #elif defined(SD_SEND)
8718 : : PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
8719 : : #else
8720 : : PyModule_AddIntConstant(m, "SHUT_WR", 1);
8721 : : #endif
8722 : : #ifdef SHUT_RDWR
8723 : 1 : PyModule_AddIntMacro(m, SHUT_RDWR);
8724 : : #elif defined(SD_BOTH)
8725 : : PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
8726 : : #else
8727 : : PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
8728 : : #endif
8729 : :
8730 : : #ifdef SIO_RCVALL
8731 : : {
8732 : : DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS,
8733 : : #if defined(SIO_LOOPBACK_FAST_PATH)
8734 : : SIO_LOOPBACK_FAST_PATH
8735 : : #endif
8736 : : };
8737 : : const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS",
8738 : : #if defined(SIO_LOOPBACK_FAST_PATH)
8739 : : "SIO_LOOPBACK_FAST_PATH"
8740 : : #endif
8741 : : };
8742 : : int i;
8743 : : for(i = 0; i<Py_ARRAY_LENGTH(codes); ++i) {
8744 : : PyObject *tmp;
8745 : : tmp = PyLong_FromUnsignedLong(codes[i]);
8746 : : if (tmp == NULL)
8747 : : return NULL;
8748 : : PyModule_AddObject(m, names[i], tmp);
8749 : : }
8750 : : }
8751 : : PyModule_AddIntMacro(m, RCVALL_OFF);
8752 : : PyModule_AddIntMacro(m, RCVALL_ON);
8753 : : PyModule_AddIntMacro(m, RCVALL_SOCKETLEVELONLY);
8754 : : #ifdef RCVALL_IPLEVEL
8755 : : PyModule_AddIntMacro(m, RCVALL_IPLEVEL);
8756 : : #endif
8757 : : #ifdef RCVALL_MAX
8758 : : PyModule_AddIntMacro(m, RCVALL_MAX);
8759 : : #endif
8760 : : #endif /* _MSTCPIP_ */
8761 : :
8762 : : /* Initialize gethostbyname lock */
8763 : : #if defined(USE_GETHOSTBYNAME_LOCK)
8764 : : netdb_lock = PyThread_allocate_lock();
8765 : : #endif
8766 : :
8767 : : #ifdef MS_WINDOWS
8768 : : /* remove some flags on older version Windows during run-time */
8769 : : if (remove_unusable_flags(m) < 0) {
8770 : : Py_DECREF(m);
8771 : : return NULL;
8772 : : }
8773 : : #endif
8774 : :
8775 : 1 : return m;
8776 : : }
|