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