1 | n/a | # Wrapper module for _socket, providing some additional facilities |
---|
2 | n/a | # implemented in Python. |
---|
3 | n/a | |
---|
4 | n/a | """\ |
---|
5 | n/a | This module provides socket operations and some related functions. |
---|
6 | n/a | On Unix, it supports IP (Internet Protocol) and Unix domain sockets. |
---|
7 | n/a | On other systems, it only supports IP. Functions specific for a |
---|
8 | n/a | socket are available as methods of the socket object. |
---|
9 | n/a | |
---|
10 | n/a | Functions: |
---|
11 | n/a | |
---|
12 | n/a | socket() -- create a new socket object |
---|
13 | n/a | socketpair() -- create a pair of new socket objects [*] |
---|
14 | n/a | fromfd() -- create a socket object from an open file descriptor [*] |
---|
15 | n/a | fromshare() -- create a socket object from data received from socket.share() [*] |
---|
16 | n/a | gethostname() -- return the current hostname |
---|
17 | n/a | gethostbyname() -- map a hostname to its IP number |
---|
18 | n/a | gethostbyaddr() -- map an IP number or hostname to DNS info |
---|
19 | n/a | getservbyname() -- map a service name and a protocol name to a port number |
---|
20 | n/a | getprotobyname() -- map a protocol name (e.g. 'tcp') to a number |
---|
21 | n/a | ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order |
---|
22 | n/a | htons(), htonl() -- convert 16, 32 bit int from host to network byte order |
---|
23 | n/a | inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format |
---|
24 | n/a | inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) |
---|
25 | n/a | socket.getdefaulttimeout() -- get the default timeout value |
---|
26 | n/a | socket.setdefaulttimeout() -- set the default timeout value |
---|
27 | n/a | create_connection() -- connects to an address, with an optional timeout and |
---|
28 | n/a | optional source address. |
---|
29 | n/a | |
---|
30 | n/a | [*] not available on all platforms! |
---|
31 | n/a | |
---|
32 | n/a | Special objects: |
---|
33 | n/a | |
---|
34 | n/a | SocketType -- type object for socket objects |
---|
35 | n/a | error -- exception raised for I/O errors |
---|
36 | n/a | has_ipv6 -- boolean value indicating if IPv6 is supported |
---|
37 | n/a | |
---|
38 | n/a | IntEnum constants: |
---|
39 | n/a | |
---|
40 | n/a | AF_INET, AF_UNIX -- socket domains (first argument to socket() call) |
---|
41 | n/a | SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) |
---|
42 | n/a | |
---|
43 | n/a | Integer constants: |
---|
44 | n/a | |
---|
45 | n/a | Many other constants may be defined; these may be used in calls to |
---|
46 | n/a | the setsockopt() and getsockopt() methods. |
---|
47 | n/a | """ |
---|
48 | n/a | |
---|
49 | n/a | import _socket |
---|
50 | n/a | from _socket import * |
---|
51 | n/a | |
---|
52 | n/a | import os, sys, io, selectors |
---|
53 | n/a | from enum import IntEnum, IntFlag |
---|
54 | n/a | |
---|
55 | n/a | try: |
---|
56 | n/a | import errno |
---|
57 | n/a | except ImportError: |
---|
58 | n/a | errno = None |
---|
59 | n/a | EBADF = getattr(errno, 'EBADF', 9) |
---|
60 | n/a | EAGAIN = getattr(errno, 'EAGAIN', 11) |
---|
61 | n/a | EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11) |
---|
62 | n/a | |
---|
63 | n/a | __all__ = ["fromfd", "getfqdn", "create_connection", |
---|
64 | n/a | "AddressFamily", "SocketKind"] |
---|
65 | n/a | __all__.extend(os._get_exports_list(_socket)) |
---|
66 | n/a | |
---|
67 | n/a | # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for |
---|
68 | n/a | # nicer string representations. |
---|
69 | n/a | # Note that _socket only knows about the integer values. The public interface |
---|
70 | n/a | # in this module understands the enums and translates them back from integers |
---|
71 | n/a | # where needed (e.g. .family property of a socket object). |
---|
72 | n/a | |
---|
73 | n/a | IntEnum._convert( |
---|
74 | n/a | 'AddressFamily', |
---|
75 | n/a | __name__, |
---|
76 | n/a | lambda C: C.isupper() and C.startswith('AF_')) |
---|
77 | n/a | |
---|
78 | n/a | IntEnum._convert( |
---|
79 | n/a | 'SocketKind', |
---|
80 | n/a | __name__, |
---|
81 | n/a | lambda C: C.isupper() and C.startswith('SOCK_')) |
---|
82 | n/a | |
---|
83 | n/a | IntFlag._convert( |
---|
84 | n/a | 'MsgFlag', |
---|
85 | n/a | __name__, |
---|
86 | n/a | lambda C: C.isupper() and C.startswith('MSG_')) |
---|
87 | n/a | |
---|
88 | n/a | IntFlag._convert( |
---|
89 | n/a | 'AddressInfo', |
---|
90 | n/a | __name__, |
---|
91 | n/a | lambda C: C.isupper() and C.startswith('AI_')) |
---|
92 | n/a | |
---|
93 | n/a | _LOCALHOST = '127.0.0.1' |
---|
94 | n/a | _LOCALHOST_V6 = '::1' |
---|
95 | n/a | |
---|
96 | n/a | |
---|
97 | n/a | def _intenum_converter(value, enum_klass): |
---|
98 | n/a | """Convert a numeric family value to an IntEnum member. |
---|
99 | n/a | |
---|
100 | n/a | If it's not a known member, return the numeric value itself. |
---|
101 | n/a | """ |
---|
102 | n/a | try: |
---|
103 | n/a | return enum_klass(value) |
---|
104 | n/a | except ValueError: |
---|
105 | n/a | return value |
---|
106 | n/a | |
---|
107 | n/a | _realsocket = socket |
---|
108 | n/a | |
---|
109 | n/a | # WSA error codes |
---|
110 | n/a | if sys.platform.lower().startswith("win"): |
---|
111 | n/a | errorTab = {} |
---|
112 | n/a | errorTab[10004] = "The operation was interrupted." |
---|
113 | n/a | errorTab[10009] = "A bad file handle was passed." |
---|
114 | n/a | errorTab[10013] = "Permission denied." |
---|
115 | n/a | errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT |
---|
116 | n/a | errorTab[10022] = "An invalid operation was attempted." |
---|
117 | n/a | errorTab[10035] = "The socket operation would block" |
---|
118 | n/a | errorTab[10036] = "A blocking operation is already in progress." |
---|
119 | n/a | errorTab[10048] = "The network address is in use." |
---|
120 | n/a | errorTab[10054] = "The connection has been reset." |
---|
121 | n/a | errorTab[10058] = "The network has been shut down." |
---|
122 | n/a | errorTab[10060] = "The operation timed out." |
---|
123 | n/a | errorTab[10061] = "Connection refused." |
---|
124 | n/a | errorTab[10063] = "The name is too long." |
---|
125 | n/a | errorTab[10064] = "The host is down." |
---|
126 | n/a | errorTab[10065] = "The host is unreachable." |
---|
127 | n/a | __all__.append("errorTab") |
---|
128 | n/a | |
---|
129 | n/a | |
---|
130 | n/a | class _GiveupOnSendfile(Exception): pass |
---|
131 | n/a | |
---|
132 | n/a | |
---|
133 | n/a | class socket(_socket.socket): |
---|
134 | n/a | |
---|
135 | n/a | """A subclass of _socket.socket adding the makefile() method.""" |
---|
136 | n/a | |
---|
137 | n/a | __slots__ = ["__weakref__", "_io_refs", "_closed"] |
---|
138 | n/a | |
---|
139 | n/a | def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): |
---|
140 | n/a | # For user code address family and type values are IntEnum members, but |
---|
141 | n/a | # for the underlying _socket.socket they're just integers. The |
---|
142 | n/a | # constructor of _socket.socket converts the given argument to an |
---|
143 | n/a | # integer automatically. |
---|
144 | n/a | _socket.socket.__init__(self, family, type, proto, fileno) |
---|
145 | n/a | self._io_refs = 0 |
---|
146 | n/a | self._closed = False |
---|
147 | n/a | |
---|
148 | n/a | def __enter__(self): |
---|
149 | n/a | return self |
---|
150 | n/a | |
---|
151 | n/a | def __exit__(self, *args): |
---|
152 | n/a | if not self._closed: |
---|
153 | n/a | self.close() |
---|
154 | n/a | |
---|
155 | n/a | def __repr__(self): |
---|
156 | n/a | """Wrap __repr__() to reveal the real class name and socket |
---|
157 | n/a | address(es). |
---|
158 | n/a | """ |
---|
159 | n/a | closed = getattr(self, '_closed', False) |
---|
160 | n/a | s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \ |
---|
161 | n/a | % (self.__class__.__module__, |
---|
162 | n/a | self.__class__.__qualname__, |
---|
163 | n/a | " [closed]" if closed else "", |
---|
164 | n/a | self.fileno(), |
---|
165 | n/a | self.family, |
---|
166 | n/a | self.type, |
---|
167 | n/a | self.proto) |
---|
168 | n/a | if not closed: |
---|
169 | n/a | try: |
---|
170 | n/a | laddr = self.getsockname() |
---|
171 | n/a | if laddr: |
---|
172 | n/a | s += ", laddr=%s" % str(laddr) |
---|
173 | n/a | except error: |
---|
174 | n/a | pass |
---|
175 | n/a | try: |
---|
176 | n/a | raddr = self.getpeername() |
---|
177 | n/a | if raddr: |
---|
178 | n/a | s += ", raddr=%s" % str(raddr) |
---|
179 | n/a | except error: |
---|
180 | n/a | pass |
---|
181 | n/a | s += '>' |
---|
182 | n/a | return s |
---|
183 | n/a | |
---|
184 | n/a | def __getstate__(self): |
---|
185 | n/a | raise TypeError("Cannot serialize socket object") |
---|
186 | n/a | |
---|
187 | n/a | def dup(self): |
---|
188 | n/a | """dup() -> socket object |
---|
189 | n/a | |
---|
190 | n/a | Duplicate the socket. Return a new socket object connected to the same |
---|
191 | n/a | system resource. The new socket is non-inheritable. |
---|
192 | n/a | """ |
---|
193 | n/a | fd = dup(self.fileno()) |
---|
194 | n/a | sock = self.__class__(self.family, self.type, self.proto, fileno=fd) |
---|
195 | n/a | sock.settimeout(self.gettimeout()) |
---|
196 | n/a | return sock |
---|
197 | n/a | |
---|
198 | n/a | def accept(self): |
---|
199 | n/a | """accept() -> (socket object, address info) |
---|
200 | n/a | |
---|
201 | n/a | Wait for an incoming connection. Return a new socket |
---|
202 | n/a | representing the connection, and the address of the client. |
---|
203 | n/a | For IP sockets, the address info is a pair (hostaddr, port). |
---|
204 | n/a | """ |
---|
205 | n/a | fd, addr = self._accept() |
---|
206 | n/a | # If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the |
---|
207 | n/a | # new socket. We do not currently allow passing SOCK_NONBLOCK to |
---|
208 | n/a | # accept4, so the returned socket is always blocking. |
---|
209 | n/a | type = self.type & ~globals().get("SOCK_NONBLOCK", 0) |
---|
210 | n/a | sock = socket(self.family, type, self.proto, fileno=fd) |
---|
211 | n/a | # Issue #7995: if no default timeout is set and the listening |
---|
212 | n/a | # socket had a (non-zero) timeout, force the new socket in blocking |
---|
213 | n/a | # mode to override platform-specific socket flags inheritance. |
---|
214 | n/a | if getdefaulttimeout() is None and self.gettimeout(): |
---|
215 | n/a | sock.setblocking(True) |
---|
216 | n/a | return sock, addr |
---|
217 | n/a | |
---|
218 | n/a | def makefile(self, mode="r", buffering=None, *, |
---|
219 | n/a | encoding=None, errors=None, newline=None): |
---|
220 | n/a | """makefile(...) -> an I/O stream connected to the socket |
---|
221 | n/a | |
---|
222 | n/a | The arguments are as for io.open() after the filename, except the only |
---|
223 | n/a | supported mode values are 'r' (default), 'w' and 'b'. |
---|
224 | n/a | """ |
---|
225 | n/a | # XXX refactor to share code? |
---|
226 | n/a | if not set(mode) <= {"r", "w", "b"}: |
---|
227 | n/a | raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) |
---|
228 | n/a | writing = "w" in mode |
---|
229 | n/a | reading = "r" in mode or not writing |
---|
230 | n/a | assert reading or writing |
---|
231 | n/a | binary = "b" in mode |
---|
232 | n/a | rawmode = "" |
---|
233 | n/a | if reading: |
---|
234 | n/a | rawmode += "r" |
---|
235 | n/a | if writing: |
---|
236 | n/a | rawmode += "w" |
---|
237 | n/a | raw = SocketIO(self, rawmode) |
---|
238 | n/a | self._io_refs += 1 |
---|
239 | n/a | if buffering is None: |
---|
240 | n/a | buffering = -1 |
---|
241 | n/a | if buffering < 0: |
---|
242 | n/a | buffering = io.DEFAULT_BUFFER_SIZE |
---|
243 | n/a | if buffering == 0: |
---|
244 | n/a | if not binary: |
---|
245 | n/a | raise ValueError("unbuffered streams must be binary") |
---|
246 | n/a | return raw |
---|
247 | n/a | if reading and writing: |
---|
248 | n/a | buffer = io.BufferedRWPair(raw, raw, buffering) |
---|
249 | n/a | elif reading: |
---|
250 | n/a | buffer = io.BufferedReader(raw, buffering) |
---|
251 | n/a | else: |
---|
252 | n/a | assert writing |
---|
253 | n/a | buffer = io.BufferedWriter(raw, buffering) |
---|
254 | n/a | if binary: |
---|
255 | n/a | return buffer |
---|
256 | n/a | text = io.TextIOWrapper(buffer, encoding, errors, newline) |
---|
257 | n/a | text.mode = mode |
---|
258 | n/a | return text |
---|
259 | n/a | |
---|
260 | n/a | if hasattr(os, 'sendfile'): |
---|
261 | n/a | |
---|
262 | n/a | def _sendfile_use_sendfile(self, file, offset=0, count=None): |
---|
263 | n/a | self._check_sendfile_params(file, offset, count) |
---|
264 | n/a | sockno = self.fileno() |
---|
265 | n/a | try: |
---|
266 | n/a | fileno = file.fileno() |
---|
267 | n/a | except (AttributeError, io.UnsupportedOperation) as err: |
---|
268 | n/a | raise _GiveupOnSendfile(err) # not a regular file |
---|
269 | n/a | try: |
---|
270 | n/a | fsize = os.fstat(fileno).st_size |
---|
271 | n/a | except OSError as err: |
---|
272 | n/a | raise _GiveupOnSendfile(err) # not a regular file |
---|
273 | n/a | if not fsize: |
---|
274 | n/a | return 0 # empty file |
---|
275 | n/a | blocksize = fsize if not count else count |
---|
276 | n/a | |
---|
277 | n/a | timeout = self.gettimeout() |
---|
278 | n/a | if timeout == 0: |
---|
279 | n/a | raise ValueError("non-blocking sockets are not supported") |
---|
280 | n/a | # poll/select have the advantage of not requiring any |
---|
281 | n/a | # extra file descriptor, contrarily to epoll/kqueue |
---|
282 | n/a | # (also, they require a single syscall). |
---|
283 | n/a | if hasattr(selectors, 'PollSelector'): |
---|
284 | n/a | selector = selectors.PollSelector() |
---|
285 | n/a | else: |
---|
286 | n/a | selector = selectors.SelectSelector() |
---|
287 | n/a | selector.register(sockno, selectors.EVENT_WRITE) |
---|
288 | n/a | |
---|
289 | n/a | total_sent = 0 |
---|
290 | n/a | # localize variable access to minimize overhead |
---|
291 | n/a | selector_select = selector.select |
---|
292 | n/a | os_sendfile = os.sendfile |
---|
293 | n/a | try: |
---|
294 | n/a | while True: |
---|
295 | n/a | if timeout and not selector_select(timeout): |
---|
296 | n/a | raise _socket.timeout('timed out') |
---|
297 | n/a | if count: |
---|
298 | n/a | blocksize = count - total_sent |
---|
299 | n/a | if blocksize <= 0: |
---|
300 | n/a | break |
---|
301 | n/a | try: |
---|
302 | n/a | sent = os_sendfile(sockno, fileno, offset, blocksize) |
---|
303 | n/a | except BlockingIOError: |
---|
304 | n/a | if not timeout: |
---|
305 | n/a | # Block until the socket is ready to send some |
---|
306 | n/a | # data; avoids hogging CPU resources. |
---|
307 | n/a | selector_select() |
---|
308 | n/a | continue |
---|
309 | n/a | except OSError as err: |
---|
310 | n/a | if total_sent == 0: |
---|
311 | n/a | # We can get here for different reasons, the main |
---|
312 | n/a | # one being 'file' is not a regular mmap(2)-like |
---|
313 | n/a | # file, in which case we'll fall back on using |
---|
314 | n/a | # plain send(). |
---|
315 | n/a | raise _GiveupOnSendfile(err) |
---|
316 | n/a | raise err from None |
---|
317 | n/a | else: |
---|
318 | n/a | if sent == 0: |
---|
319 | n/a | break # EOF |
---|
320 | n/a | offset += sent |
---|
321 | n/a | total_sent += sent |
---|
322 | n/a | return total_sent |
---|
323 | n/a | finally: |
---|
324 | n/a | if total_sent > 0 and hasattr(file, 'seek'): |
---|
325 | n/a | file.seek(offset) |
---|
326 | n/a | else: |
---|
327 | n/a | def _sendfile_use_sendfile(self, file, offset=0, count=None): |
---|
328 | n/a | raise _GiveupOnSendfile( |
---|
329 | n/a | "os.sendfile() not available on this platform") |
---|
330 | n/a | |
---|
331 | n/a | def _sendfile_use_send(self, file, offset=0, count=None): |
---|
332 | n/a | self._check_sendfile_params(file, offset, count) |
---|
333 | n/a | if self.gettimeout() == 0: |
---|
334 | n/a | raise ValueError("non-blocking sockets are not supported") |
---|
335 | n/a | if offset: |
---|
336 | n/a | file.seek(offset) |
---|
337 | n/a | blocksize = min(count, 8192) if count else 8192 |
---|
338 | n/a | total_sent = 0 |
---|
339 | n/a | # localize variable access to minimize overhead |
---|
340 | n/a | file_read = file.read |
---|
341 | n/a | sock_send = self.send |
---|
342 | n/a | try: |
---|
343 | n/a | while True: |
---|
344 | n/a | if count: |
---|
345 | n/a | blocksize = min(count - total_sent, blocksize) |
---|
346 | n/a | if blocksize <= 0: |
---|
347 | n/a | break |
---|
348 | n/a | data = memoryview(file_read(blocksize)) |
---|
349 | n/a | if not data: |
---|
350 | n/a | break # EOF |
---|
351 | n/a | while True: |
---|
352 | n/a | try: |
---|
353 | n/a | sent = sock_send(data) |
---|
354 | n/a | except BlockingIOError: |
---|
355 | n/a | continue |
---|
356 | n/a | else: |
---|
357 | n/a | total_sent += sent |
---|
358 | n/a | if sent < len(data): |
---|
359 | n/a | data = data[sent:] |
---|
360 | n/a | else: |
---|
361 | n/a | break |
---|
362 | n/a | return total_sent |
---|
363 | n/a | finally: |
---|
364 | n/a | if total_sent > 0 and hasattr(file, 'seek'): |
---|
365 | n/a | file.seek(offset + total_sent) |
---|
366 | n/a | |
---|
367 | n/a | def _check_sendfile_params(self, file, offset, count): |
---|
368 | n/a | if 'b' not in getattr(file, 'mode', 'b'): |
---|
369 | n/a | raise ValueError("file should be opened in binary mode") |
---|
370 | n/a | if not self.type & SOCK_STREAM: |
---|
371 | n/a | raise ValueError("only SOCK_STREAM type sockets are supported") |
---|
372 | n/a | if count is not None: |
---|
373 | n/a | if not isinstance(count, int): |
---|
374 | n/a | raise TypeError( |
---|
375 | n/a | "count must be a positive integer (got {!r})".format(count)) |
---|
376 | n/a | if count <= 0: |
---|
377 | n/a | raise ValueError( |
---|
378 | n/a | "count must be a positive integer (got {!r})".format(count)) |
---|
379 | n/a | |
---|
380 | n/a | def sendfile(self, file, offset=0, count=None): |
---|
381 | n/a | """sendfile(file[, offset[, count]]) -> sent |
---|
382 | n/a | |
---|
383 | n/a | Send a file until EOF is reached by using high-performance |
---|
384 | n/a | os.sendfile() and return the total number of bytes which |
---|
385 | n/a | were sent. |
---|
386 | n/a | *file* must be a regular file object opened in binary mode. |
---|
387 | n/a | If os.sendfile() is not available (e.g. Windows) or file is |
---|
388 | n/a | not a regular file socket.send() will be used instead. |
---|
389 | n/a | *offset* tells from where to start reading the file. |
---|
390 | n/a | If specified, *count* is the total number of bytes to transmit |
---|
391 | n/a | as opposed to sending the file until EOF is reached. |
---|
392 | n/a | File position is updated on return or also in case of error in |
---|
393 | n/a | which case file.tell() can be used to figure out the number of |
---|
394 | n/a | bytes which were sent. |
---|
395 | n/a | The socket must be of SOCK_STREAM type. |
---|
396 | n/a | Non-blocking sockets are not supported. |
---|
397 | n/a | """ |
---|
398 | n/a | try: |
---|
399 | n/a | return self._sendfile_use_sendfile(file, offset, count) |
---|
400 | n/a | except _GiveupOnSendfile: |
---|
401 | n/a | return self._sendfile_use_send(file, offset, count) |
---|
402 | n/a | |
---|
403 | n/a | def _decref_socketios(self): |
---|
404 | n/a | if self._io_refs > 0: |
---|
405 | n/a | self._io_refs -= 1 |
---|
406 | n/a | if self._closed: |
---|
407 | n/a | self.close() |
---|
408 | n/a | |
---|
409 | n/a | def _real_close(self, _ss=_socket.socket): |
---|
410 | n/a | # This function should not reference any globals. See issue #808164. |
---|
411 | n/a | _ss.close(self) |
---|
412 | n/a | |
---|
413 | n/a | def close(self): |
---|
414 | n/a | # This function should not reference any globals. See issue #808164. |
---|
415 | n/a | self._closed = True |
---|
416 | n/a | if self._io_refs <= 0: |
---|
417 | n/a | self._real_close() |
---|
418 | n/a | |
---|
419 | n/a | def detach(self): |
---|
420 | n/a | """detach() -> file descriptor |
---|
421 | n/a | |
---|
422 | n/a | Close the socket object without closing the underlying file descriptor. |
---|
423 | n/a | The object cannot be used after this call, but the file descriptor |
---|
424 | n/a | can be reused for other purposes. The file descriptor is returned. |
---|
425 | n/a | """ |
---|
426 | n/a | self._closed = True |
---|
427 | n/a | return super().detach() |
---|
428 | n/a | |
---|
429 | n/a | @property |
---|
430 | n/a | def family(self): |
---|
431 | n/a | """Read-only access to the address family for this socket. |
---|
432 | n/a | """ |
---|
433 | n/a | return _intenum_converter(super().family, AddressFamily) |
---|
434 | n/a | |
---|
435 | n/a | @property |
---|
436 | n/a | def type(self): |
---|
437 | n/a | """Read-only access to the socket type. |
---|
438 | n/a | """ |
---|
439 | n/a | return _intenum_converter(super().type, SocketKind) |
---|
440 | n/a | |
---|
441 | n/a | if os.name == 'nt': |
---|
442 | n/a | def get_inheritable(self): |
---|
443 | n/a | return os.get_handle_inheritable(self.fileno()) |
---|
444 | n/a | def set_inheritable(self, inheritable): |
---|
445 | n/a | os.set_handle_inheritable(self.fileno(), inheritable) |
---|
446 | n/a | else: |
---|
447 | n/a | def get_inheritable(self): |
---|
448 | n/a | return os.get_inheritable(self.fileno()) |
---|
449 | n/a | def set_inheritable(self, inheritable): |
---|
450 | n/a | os.set_inheritable(self.fileno(), inheritable) |
---|
451 | n/a | get_inheritable.__doc__ = "Get the inheritable flag of the socket" |
---|
452 | n/a | set_inheritable.__doc__ = "Set the inheritable flag of the socket" |
---|
453 | n/a | |
---|
454 | n/a | def fromfd(fd, family, type, proto=0): |
---|
455 | n/a | """ fromfd(fd, family, type[, proto]) -> socket object |
---|
456 | n/a | |
---|
457 | n/a | Create a socket object from a duplicate of the given file |
---|
458 | n/a | descriptor. The remaining arguments are the same as for socket(). |
---|
459 | n/a | """ |
---|
460 | n/a | nfd = dup(fd) |
---|
461 | n/a | return socket(family, type, proto, nfd) |
---|
462 | n/a | |
---|
463 | n/a | if hasattr(_socket.socket, "share"): |
---|
464 | n/a | def fromshare(info): |
---|
465 | n/a | """ fromshare(info) -> socket object |
---|
466 | n/a | |
---|
467 | n/a | Create a socket object from the bytes object returned by |
---|
468 | n/a | socket.share(pid). |
---|
469 | n/a | """ |
---|
470 | n/a | return socket(0, 0, 0, info) |
---|
471 | n/a | __all__.append("fromshare") |
---|
472 | n/a | |
---|
473 | n/a | if hasattr(_socket, "socketpair"): |
---|
474 | n/a | |
---|
475 | n/a | def socketpair(family=None, type=SOCK_STREAM, proto=0): |
---|
476 | n/a | """socketpair([family[, type[, proto]]]) -> (socket object, socket object) |
---|
477 | n/a | |
---|
478 | n/a | Create a pair of socket objects from the sockets returned by the platform |
---|
479 | n/a | socketpair() function. |
---|
480 | n/a | The arguments are the same as for socket() except the default family is |
---|
481 | n/a | AF_UNIX if defined on the platform; otherwise, the default is AF_INET. |
---|
482 | n/a | """ |
---|
483 | n/a | if family is None: |
---|
484 | n/a | try: |
---|
485 | n/a | family = AF_UNIX |
---|
486 | n/a | except NameError: |
---|
487 | n/a | family = AF_INET |
---|
488 | n/a | a, b = _socket.socketpair(family, type, proto) |
---|
489 | n/a | a = socket(family, type, proto, a.detach()) |
---|
490 | n/a | b = socket(family, type, proto, b.detach()) |
---|
491 | n/a | return a, b |
---|
492 | n/a | |
---|
493 | n/a | else: |
---|
494 | n/a | |
---|
495 | n/a | # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain. |
---|
496 | n/a | def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0): |
---|
497 | n/a | if family == AF_INET: |
---|
498 | n/a | host = _LOCALHOST |
---|
499 | n/a | elif family == AF_INET6: |
---|
500 | n/a | host = _LOCALHOST_V6 |
---|
501 | n/a | else: |
---|
502 | n/a | raise ValueError("Only AF_INET and AF_INET6 socket address families " |
---|
503 | n/a | "are supported") |
---|
504 | n/a | if type != SOCK_STREAM: |
---|
505 | n/a | raise ValueError("Only SOCK_STREAM socket type is supported") |
---|
506 | n/a | if proto != 0: |
---|
507 | n/a | raise ValueError("Only protocol zero is supported") |
---|
508 | n/a | |
---|
509 | n/a | # We create a connected TCP socket. Note the trick with |
---|
510 | n/a | # setblocking(False) that prevents us from having to create a thread. |
---|
511 | n/a | lsock = socket(family, type, proto) |
---|
512 | n/a | try: |
---|
513 | n/a | lsock.bind((host, 0)) |
---|
514 | n/a | lsock.listen() |
---|
515 | n/a | # On IPv6, ignore flow_info and scope_id |
---|
516 | n/a | addr, port = lsock.getsockname()[:2] |
---|
517 | n/a | csock = socket(family, type, proto) |
---|
518 | n/a | try: |
---|
519 | n/a | csock.setblocking(False) |
---|
520 | n/a | try: |
---|
521 | n/a | csock.connect((addr, port)) |
---|
522 | n/a | except (BlockingIOError, InterruptedError): |
---|
523 | n/a | pass |
---|
524 | n/a | csock.setblocking(True) |
---|
525 | n/a | ssock, _ = lsock.accept() |
---|
526 | n/a | except: |
---|
527 | n/a | csock.close() |
---|
528 | n/a | raise |
---|
529 | n/a | finally: |
---|
530 | n/a | lsock.close() |
---|
531 | n/a | return (ssock, csock) |
---|
532 | n/a | __all__.append("socketpair") |
---|
533 | n/a | |
---|
534 | n/a | socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object) |
---|
535 | n/a | Create a pair of socket objects from the sockets returned by the platform |
---|
536 | n/a | socketpair() function. |
---|
537 | n/a | The arguments are the same as for socket() except the default family is AF_UNIX |
---|
538 | n/a | if defined on the platform; otherwise, the default is AF_INET. |
---|
539 | n/a | """ |
---|
540 | n/a | |
---|
541 | n/a | _blocking_errnos = { EAGAIN, EWOULDBLOCK } |
---|
542 | n/a | |
---|
543 | n/a | class SocketIO(io.RawIOBase): |
---|
544 | n/a | |
---|
545 | n/a | """Raw I/O implementation for stream sockets. |
---|
546 | n/a | |
---|
547 | n/a | This class supports the makefile() method on sockets. It provides |
---|
548 | n/a | the raw I/O interface on top of a socket object. |
---|
549 | n/a | """ |
---|
550 | n/a | |
---|
551 | n/a | # One might wonder why not let FileIO do the job instead. There are two |
---|
552 | n/a | # main reasons why FileIO is not adapted: |
---|
553 | n/a | # - it wouldn't work under Windows (where you can't used read() and |
---|
554 | n/a | # write() on a socket handle) |
---|
555 | n/a | # - it wouldn't work with socket timeouts (FileIO would ignore the |
---|
556 | n/a | # timeout and consider the socket non-blocking) |
---|
557 | n/a | |
---|
558 | n/a | # XXX More docs |
---|
559 | n/a | |
---|
560 | n/a | def __init__(self, sock, mode): |
---|
561 | n/a | if mode not in ("r", "w", "rw", "rb", "wb", "rwb"): |
---|
562 | n/a | raise ValueError("invalid mode: %r" % mode) |
---|
563 | n/a | io.RawIOBase.__init__(self) |
---|
564 | n/a | self._sock = sock |
---|
565 | n/a | if "b" not in mode: |
---|
566 | n/a | mode += "b" |
---|
567 | n/a | self._mode = mode |
---|
568 | n/a | self._reading = "r" in mode |
---|
569 | n/a | self._writing = "w" in mode |
---|
570 | n/a | self._timeout_occurred = False |
---|
571 | n/a | |
---|
572 | n/a | def readinto(self, b): |
---|
573 | n/a | """Read up to len(b) bytes into the writable buffer *b* and return |
---|
574 | n/a | the number of bytes read. If the socket is non-blocking and no bytes |
---|
575 | n/a | are available, None is returned. |
---|
576 | n/a | |
---|
577 | n/a | If *b* is non-empty, a 0 return value indicates that the connection |
---|
578 | n/a | was shutdown at the other end. |
---|
579 | n/a | """ |
---|
580 | n/a | self._checkClosed() |
---|
581 | n/a | self._checkReadable() |
---|
582 | n/a | if self._timeout_occurred: |
---|
583 | n/a | raise OSError("cannot read from timed out object") |
---|
584 | n/a | while True: |
---|
585 | n/a | try: |
---|
586 | n/a | return self._sock.recv_into(b) |
---|
587 | n/a | except timeout: |
---|
588 | n/a | self._timeout_occurred = True |
---|
589 | n/a | raise |
---|
590 | n/a | except error as e: |
---|
591 | n/a | if e.args[0] in _blocking_errnos: |
---|
592 | n/a | return None |
---|
593 | n/a | raise |
---|
594 | n/a | |
---|
595 | n/a | def write(self, b): |
---|
596 | n/a | """Write the given bytes or bytearray object *b* to the socket |
---|
597 | n/a | and return the number of bytes written. This can be less than |
---|
598 | n/a | len(b) if not all data could be written. If the socket is |
---|
599 | n/a | non-blocking and no bytes could be written None is returned. |
---|
600 | n/a | """ |
---|
601 | n/a | self._checkClosed() |
---|
602 | n/a | self._checkWritable() |
---|
603 | n/a | try: |
---|
604 | n/a | return self._sock.send(b) |
---|
605 | n/a | except error as e: |
---|
606 | n/a | # XXX what about EINTR? |
---|
607 | n/a | if e.args[0] in _blocking_errnos: |
---|
608 | n/a | return None |
---|
609 | n/a | raise |
---|
610 | n/a | |
---|
611 | n/a | def readable(self): |
---|
612 | n/a | """True if the SocketIO is open for reading. |
---|
613 | n/a | """ |
---|
614 | n/a | if self.closed: |
---|
615 | n/a | raise ValueError("I/O operation on closed socket.") |
---|
616 | n/a | return self._reading |
---|
617 | n/a | |
---|
618 | n/a | def writable(self): |
---|
619 | n/a | """True if the SocketIO is open for writing. |
---|
620 | n/a | """ |
---|
621 | n/a | if self.closed: |
---|
622 | n/a | raise ValueError("I/O operation on closed socket.") |
---|
623 | n/a | return self._writing |
---|
624 | n/a | |
---|
625 | n/a | def seekable(self): |
---|
626 | n/a | """True if the SocketIO is open for seeking. |
---|
627 | n/a | """ |
---|
628 | n/a | if self.closed: |
---|
629 | n/a | raise ValueError("I/O operation on closed socket.") |
---|
630 | n/a | return super().seekable() |
---|
631 | n/a | |
---|
632 | n/a | def fileno(self): |
---|
633 | n/a | """Return the file descriptor of the underlying socket. |
---|
634 | n/a | """ |
---|
635 | n/a | self._checkClosed() |
---|
636 | n/a | return self._sock.fileno() |
---|
637 | n/a | |
---|
638 | n/a | @property |
---|
639 | n/a | def name(self): |
---|
640 | n/a | if not self.closed: |
---|
641 | n/a | return self.fileno() |
---|
642 | n/a | else: |
---|
643 | n/a | return -1 |
---|
644 | n/a | |
---|
645 | n/a | @property |
---|
646 | n/a | def mode(self): |
---|
647 | n/a | return self._mode |
---|
648 | n/a | |
---|
649 | n/a | def close(self): |
---|
650 | n/a | """Close the SocketIO object. This doesn't close the underlying |
---|
651 | n/a | socket, except if all references to it have disappeared. |
---|
652 | n/a | """ |
---|
653 | n/a | if self.closed: |
---|
654 | n/a | return |
---|
655 | n/a | io.RawIOBase.close(self) |
---|
656 | n/a | self._sock._decref_socketios() |
---|
657 | n/a | self._sock = None |
---|
658 | n/a | |
---|
659 | n/a | |
---|
660 | n/a | def getfqdn(name=''): |
---|
661 | n/a | """Get fully qualified domain name from name. |
---|
662 | n/a | |
---|
663 | n/a | An empty argument is interpreted as meaning the local host. |
---|
664 | n/a | |
---|
665 | n/a | First the hostname returned by gethostbyaddr() is checked, then |
---|
666 | n/a | possibly existing aliases. In case no FQDN is available, hostname |
---|
667 | n/a | from gethostname() is returned. |
---|
668 | n/a | """ |
---|
669 | n/a | name = name.strip() |
---|
670 | n/a | if not name or name == '0.0.0.0': |
---|
671 | n/a | name = gethostname() |
---|
672 | n/a | try: |
---|
673 | n/a | hostname, aliases, ipaddrs = gethostbyaddr(name) |
---|
674 | n/a | except error: |
---|
675 | n/a | pass |
---|
676 | n/a | else: |
---|
677 | n/a | aliases.insert(0, hostname) |
---|
678 | n/a | for name in aliases: |
---|
679 | n/a | if '.' in name: |
---|
680 | n/a | break |
---|
681 | n/a | else: |
---|
682 | n/a | name = hostname |
---|
683 | n/a | return name |
---|
684 | n/a | |
---|
685 | n/a | |
---|
686 | n/a | _GLOBAL_DEFAULT_TIMEOUT = object() |
---|
687 | n/a | |
---|
688 | n/a | def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, |
---|
689 | n/a | source_address=None): |
---|
690 | n/a | """Connect to *address* and return the socket object. |
---|
691 | n/a | |
---|
692 | n/a | Convenience function. Connect to *address* (a 2-tuple ``(host, |
---|
693 | n/a | port)``) and return the socket object. Passing the optional |
---|
694 | n/a | *timeout* parameter will set the timeout on the socket instance |
---|
695 | n/a | before attempting to connect. If no *timeout* is supplied, the |
---|
696 | n/a | global default timeout setting returned by :func:`getdefaulttimeout` |
---|
697 | n/a | is used. If *source_address* is set it must be a tuple of (host, port) |
---|
698 | n/a | for the socket to bind as a source address before making the connection. |
---|
699 | n/a | A host of '' or port 0 tells the OS to use the default. |
---|
700 | n/a | """ |
---|
701 | n/a | |
---|
702 | n/a | host, port = address |
---|
703 | n/a | err = None |
---|
704 | n/a | for res in getaddrinfo(host, port, 0, SOCK_STREAM): |
---|
705 | n/a | af, socktype, proto, canonname, sa = res |
---|
706 | n/a | sock = None |
---|
707 | n/a | try: |
---|
708 | n/a | sock = socket(af, socktype, proto) |
---|
709 | n/a | if timeout is not _GLOBAL_DEFAULT_TIMEOUT: |
---|
710 | n/a | sock.settimeout(timeout) |
---|
711 | n/a | if source_address: |
---|
712 | n/a | sock.bind(source_address) |
---|
713 | n/a | sock.connect(sa) |
---|
714 | n/a | return sock |
---|
715 | n/a | |
---|
716 | n/a | except error as _: |
---|
717 | n/a | err = _ |
---|
718 | n/a | if sock is not None: |
---|
719 | n/a | sock.close() |
---|
720 | n/a | |
---|
721 | n/a | if err is not None: |
---|
722 | n/a | raise err |
---|
723 | n/a | else: |
---|
724 | n/a | raise error("getaddrinfo returns an empty list") |
---|
725 | n/a | |
---|
726 | n/a | def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): |
---|
727 | n/a | """Resolve host and port into list of address info entries. |
---|
728 | n/a | |
---|
729 | n/a | Translate the host/port argument into a sequence of 5-tuples that contain |
---|
730 | n/a | all the necessary arguments for creating a socket connected to that service. |
---|
731 | n/a | host is a domain name, a string representation of an IPv4/v6 address or |
---|
732 | n/a | None. port is a string service name such as 'http', a numeric port number or |
---|
733 | n/a | None. By passing None as the value of host and port, you can pass NULL to |
---|
734 | n/a | the underlying C API. |
---|
735 | n/a | |
---|
736 | n/a | The family, type and proto arguments can be optionally specified in order to |
---|
737 | n/a | narrow the list of addresses returned. Passing zero as a value for each of |
---|
738 | n/a | these arguments selects the full range of results. |
---|
739 | n/a | """ |
---|
740 | n/a | # We override this function since we want to translate the numeric family |
---|
741 | n/a | # and socket type values to enum constants. |
---|
742 | n/a | addrlist = [] |
---|
743 | n/a | for res in _socket.getaddrinfo(host, port, family, type, proto, flags): |
---|
744 | n/a | af, socktype, proto, canonname, sa = res |
---|
745 | n/a | addrlist.append((_intenum_converter(af, AddressFamily), |
---|
746 | n/a | _intenum_converter(socktype, SocketKind), |
---|
747 | n/a | proto, canonname, sa)) |
---|
748 | n/a | return addrlist |
---|