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