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