ยปCore Development>Code coverage>Modules/socketmodule.c

Python code coverage for Modules/socketmodule.c

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