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