Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: socket.py
# Wrapper module for _socket, providing some additional facilities
[0] Fix | Delete
# implemented in Python.
[1] Fix | Delete
[2] Fix | Delete
"""\
[3] Fix | Delete
This module provides socket operations and some related functions.
[4] Fix | Delete
On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
[5] Fix | Delete
On other systems, it only supports IP. Functions specific for a
[6] Fix | Delete
socket are available as methods of the socket object.
[7] Fix | Delete
[8] Fix | Delete
Functions:
[9] Fix | Delete
[10] Fix | Delete
socket() -- create a new socket object
[11] Fix | Delete
socketpair() -- create a pair of new socket objects [*]
[12] Fix | Delete
fromfd() -- create a socket object from an open file descriptor [*]
[13] Fix | Delete
send_fds() -- Send file descriptor to the socket.
[14] Fix | Delete
recv_fds() -- Recieve file descriptors from the socket.
[15] Fix | Delete
fromshare() -- create a socket object from data received from socket.share() [*]
[16] Fix | Delete
gethostname() -- return the current hostname
[17] Fix | Delete
gethostbyname() -- map a hostname to its IP number
[18] Fix | Delete
gethostbyaddr() -- map an IP number or hostname to DNS info
[19] Fix | Delete
getservbyname() -- map a service name and a protocol name to a port number
[20] Fix | Delete
getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
[21] Fix | Delete
ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
[22] Fix | Delete
htons(), htonl() -- convert 16, 32 bit int from host to network byte order
[23] Fix | Delete
inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
[24] Fix | Delete
inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
[25] Fix | Delete
socket.getdefaulttimeout() -- get the default timeout value
[26] Fix | Delete
socket.setdefaulttimeout() -- set the default timeout value
[27] Fix | Delete
create_connection() -- connects to an address, with an optional timeout and
[28] Fix | Delete
optional source address.
[29] Fix | Delete
[30] Fix | Delete
[*] not available on all platforms!
[31] Fix | Delete
[32] Fix | Delete
Special objects:
[33] Fix | Delete
[34] Fix | Delete
SocketType -- type object for socket objects
[35] Fix | Delete
error -- exception raised for I/O errors
[36] Fix | Delete
has_ipv6 -- boolean value indicating if IPv6 is supported
[37] Fix | Delete
[38] Fix | Delete
IntEnum constants:
[39] Fix | Delete
[40] Fix | Delete
AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
[41] Fix | Delete
SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
[42] Fix | Delete
[43] Fix | Delete
Integer constants:
[44] Fix | Delete
[45] Fix | Delete
Many other constants may be defined; these may be used in calls to
[46] Fix | Delete
the setsockopt() and getsockopt() methods.
[47] Fix | Delete
"""
[48] Fix | Delete
[49] Fix | Delete
import _socket
[50] Fix | Delete
from _socket import *
[51] Fix | Delete
[52] Fix | Delete
import os, sys, io, selectors
[53] Fix | Delete
from enum import IntEnum, IntFlag
[54] Fix | Delete
[55] Fix | Delete
try:
[56] Fix | Delete
import errno
[57] Fix | Delete
except ImportError:
[58] Fix | Delete
errno = None
[59] Fix | Delete
EBADF = getattr(errno, 'EBADF', 9)
[60] Fix | Delete
EAGAIN = getattr(errno, 'EAGAIN', 11)
[61] Fix | Delete
EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
[62] Fix | Delete
[63] Fix | Delete
__all__ = ["fromfd", "getfqdn", "create_connection", "create_server",
[64] Fix | Delete
"has_dualstack_ipv6", "AddressFamily", "SocketKind"]
[65] Fix | Delete
__all__.extend(os._get_exports_list(_socket))
[66] Fix | Delete
[67] Fix | Delete
# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
[68] Fix | Delete
# nicer string representations.
[69] Fix | Delete
# Note that _socket only knows about the integer values. The public interface
[70] Fix | Delete
# in this module understands the enums and translates them back from integers
[71] Fix | Delete
# where needed (e.g. .family property of a socket object).
[72] Fix | Delete
[73] Fix | Delete
IntEnum._convert_(
[74] Fix | Delete
'AddressFamily',
[75] Fix | Delete
__name__,
[76] Fix | Delete
lambda C: C.isupper() and C.startswith('AF_'))
[77] Fix | Delete
[78] Fix | Delete
IntEnum._convert_(
[79] Fix | Delete
'SocketKind',
[80] Fix | Delete
__name__,
[81] Fix | Delete
lambda C: C.isupper() and C.startswith('SOCK_'))
[82] Fix | Delete
[83] Fix | Delete
IntFlag._convert_(
[84] Fix | Delete
'MsgFlag',
[85] Fix | Delete
__name__,
[86] Fix | Delete
lambda C: C.isupper() and C.startswith('MSG_'))
[87] Fix | Delete
[88] Fix | Delete
IntFlag._convert_(
[89] Fix | Delete
'AddressInfo',
[90] Fix | Delete
__name__,
[91] Fix | Delete
lambda C: C.isupper() and C.startswith('AI_'))
[92] Fix | Delete
[93] Fix | Delete
_LOCALHOST = '127.0.0.1'
[94] Fix | Delete
_LOCALHOST_V6 = '::1'
[95] Fix | Delete
[96] Fix | Delete
[97] Fix | Delete
def _intenum_converter(value, enum_klass):
[98] Fix | Delete
"""Convert a numeric family value to an IntEnum member.
[99] Fix | Delete
[100] Fix | Delete
If it's not a known member, return the numeric value itself.
[101] Fix | Delete
"""
[102] Fix | Delete
try:
[103] Fix | Delete
return enum_klass(value)
[104] Fix | Delete
except ValueError:
[105] Fix | Delete
return value
[106] Fix | Delete
[107] Fix | Delete
[108] Fix | Delete
# WSA error codes
[109] Fix | Delete
if sys.platform.lower().startswith("win"):
[110] Fix | Delete
errorTab = {}
[111] Fix | Delete
errorTab[6] = "Specified event object handle is invalid."
[112] Fix | Delete
errorTab[8] = "Insufficient memory available."
[113] Fix | Delete
errorTab[87] = "One or more parameters are invalid."
[114] Fix | Delete
errorTab[995] = "Overlapped operation aborted."
[115] Fix | Delete
errorTab[996] = "Overlapped I/O event object not in signaled state."
[116] Fix | Delete
errorTab[997] = "Overlapped operation will complete later."
[117] Fix | Delete
errorTab[10004] = "The operation was interrupted."
[118] Fix | Delete
errorTab[10009] = "A bad file handle was passed."
[119] Fix | Delete
errorTab[10013] = "Permission denied."
[120] Fix | Delete
errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
[121] Fix | Delete
errorTab[10022] = "An invalid operation was attempted."
[122] Fix | Delete
errorTab[10024] = "Too many open files."
[123] Fix | Delete
errorTab[10035] = "The socket operation would block"
[124] Fix | Delete
errorTab[10036] = "A blocking operation is already in progress."
[125] Fix | Delete
errorTab[10037] = "Operation already in progress."
[126] Fix | Delete
errorTab[10038] = "Socket operation on nonsocket."
[127] Fix | Delete
errorTab[10039] = "Destination address required."
[128] Fix | Delete
errorTab[10040] = "Message too long."
[129] Fix | Delete
errorTab[10041] = "Protocol wrong type for socket."
[130] Fix | Delete
errorTab[10042] = "Bad protocol option."
[131] Fix | Delete
errorTab[10043] = "Protocol not supported."
[132] Fix | Delete
errorTab[10044] = "Socket type not supported."
[133] Fix | Delete
errorTab[10045] = "Operation not supported."
[134] Fix | Delete
errorTab[10046] = "Protocol family not supported."
[135] Fix | Delete
errorTab[10047] = "Address family not supported by protocol family."
[136] Fix | Delete
errorTab[10048] = "The network address is in use."
[137] Fix | Delete
errorTab[10049] = "Cannot assign requested address."
[138] Fix | Delete
errorTab[10050] = "Network is down."
[139] Fix | Delete
errorTab[10051] = "Network is unreachable."
[140] Fix | Delete
errorTab[10052] = "Network dropped connection on reset."
[141] Fix | Delete
errorTab[10053] = "Software caused connection abort."
[142] Fix | Delete
errorTab[10054] = "The connection has been reset."
[143] Fix | Delete
errorTab[10055] = "No buffer space available."
[144] Fix | Delete
errorTab[10056] = "Socket is already connected."
[145] Fix | Delete
errorTab[10057] = "Socket is not connected."
[146] Fix | Delete
errorTab[10058] = "The network has been shut down."
[147] Fix | Delete
errorTab[10059] = "Too many references."
[148] Fix | Delete
errorTab[10060] = "The operation timed out."
[149] Fix | Delete
errorTab[10061] = "Connection refused."
[150] Fix | Delete
errorTab[10062] = "Cannot translate name."
[151] Fix | Delete
errorTab[10063] = "The name is too long."
[152] Fix | Delete
errorTab[10064] = "The host is down."
[153] Fix | Delete
errorTab[10065] = "The host is unreachable."
[154] Fix | Delete
errorTab[10066] = "Directory not empty."
[155] Fix | Delete
errorTab[10067] = "Too many processes."
[156] Fix | Delete
errorTab[10068] = "User quota exceeded."
[157] Fix | Delete
errorTab[10069] = "Disk quota exceeded."
[158] Fix | Delete
errorTab[10070] = "Stale file handle reference."
[159] Fix | Delete
errorTab[10071] = "Item is remote."
[160] Fix | Delete
errorTab[10091] = "Network subsystem is unavailable."
[161] Fix | Delete
errorTab[10092] = "Winsock.dll version out of range."
[162] Fix | Delete
errorTab[10093] = "Successful WSAStartup not yet performed."
[163] Fix | Delete
errorTab[10101] = "Graceful shutdown in progress."
[164] Fix | Delete
errorTab[10102] = "No more results from WSALookupServiceNext."
[165] Fix | Delete
errorTab[10103] = "Call has been canceled."
[166] Fix | Delete
errorTab[10104] = "Procedure call table is invalid."
[167] Fix | Delete
errorTab[10105] = "Service provider is invalid."
[168] Fix | Delete
errorTab[10106] = "Service provider failed to initialize."
[169] Fix | Delete
errorTab[10107] = "System call failure."
[170] Fix | Delete
errorTab[10108] = "Service not found."
[171] Fix | Delete
errorTab[10109] = "Class type not found."
[172] Fix | Delete
errorTab[10110] = "No more results from WSALookupServiceNext."
[173] Fix | Delete
errorTab[10111] = "Call was canceled."
[174] Fix | Delete
errorTab[10112] = "Database query was refused."
[175] Fix | Delete
errorTab[11001] = "Host not found."
[176] Fix | Delete
errorTab[11002] = "Nonauthoritative host not found."
[177] Fix | Delete
errorTab[11003] = "This is a nonrecoverable error."
[178] Fix | Delete
errorTab[11004] = "Valid name, no data record requested type."
[179] Fix | Delete
errorTab[11005] = "QoS receivers."
[180] Fix | Delete
errorTab[11006] = "QoS senders."
[181] Fix | Delete
errorTab[11007] = "No QoS senders."
[182] Fix | Delete
errorTab[11008] = "QoS no receivers."
[183] Fix | Delete
errorTab[11009] = "QoS request confirmed."
[184] Fix | Delete
errorTab[11010] = "QoS admission error."
[185] Fix | Delete
errorTab[11011] = "QoS policy failure."
[186] Fix | Delete
errorTab[11012] = "QoS bad style."
[187] Fix | Delete
errorTab[11013] = "QoS bad object."
[188] Fix | Delete
errorTab[11014] = "QoS traffic control error."
[189] Fix | Delete
errorTab[11015] = "QoS generic error."
[190] Fix | Delete
errorTab[11016] = "QoS service type error."
[191] Fix | Delete
errorTab[11017] = "QoS flowspec error."
[192] Fix | Delete
errorTab[11018] = "Invalid QoS provider buffer."
[193] Fix | Delete
errorTab[11019] = "Invalid QoS filter style."
[194] Fix | Delete
errorTab[11020] = "Invalid QoS filter style."
[195] Fix | Delete
errorTab[11021] = "Incorrect QoS filter count."
[196] Fix | Delete
errorTab[11022] = "Invalid QoS object length."
[197] Fix | Delete
errorTab[11023] = "Incorrect QoS flow count."
[198] Fix | Delete
errorTab[11024] = "Unrecognized QoS object."
[199] Fix | Delete
errorTab[11025] = "Invalid QoS policy object."
[200] Fix | Delete
errorTab[11026] = "Invalid QoS flow descriptor."
[201] Fix | Delete
errorTab[11027] = "Invalid QoS provider-specific flowspec."
[202] Fix | Delete
errorTab[11028] = "Invalid QoS provider-specific filterspec."
[203] Fix | Delete
errorTab[11029] = "Invalid QoS shape discard mode object."
[204] Fix | Delete
errorTab[11030] = "Invalid QoS shaping rate object."
[205] Fix | Delete
errorTab[11031] = "Reserved policy QoS element type."
[206] Fix | Delete
__all__.append("errorTab")
[207] Fix | Delete
[208] Fix | Delete
[209] Fix | Delete
class _GiveupOnSendfile(Exception): pass
[210] Fix | Delete
[211] Fix | Delete
[212] Fix | Delete
class socket(_socket.socket):
[213] Fix | Delete
[214] Fix | Delete
"""A subclass of _socket.socket adding the makefile() method."""
[215] Fix | Delete
[216] Fix | Delete
__slots__ = ["__weakref__", "_io_refs", "_closed"]
[217] Fix | Delete
[218] Fix | Delete
def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
[219] Fix | Delete
# For user code address family and type values are IntEnum members, but
[220] Fix | Delete
# for the underlying _socket.socket they're just integers. The
[221] Fix | Delete
# constructor of _socket.socket converts the given argument to an
[222] Fix | Delete
# integer automatically.
[223] Fix | Delete
if fileno is None:
[224] Fix | Delete
if family == -1:
[225] Fix | Delete
family = AF_INET
[226] Fix | Delete
if type == -1:
[227] Fix | Delete
type = SOCK_STREAM
[228] Fix | Delete
if proto == -1:
[229] Fix | Delete
proto = 0
[230] Fix | Delete
_socket.socket.__init__(self, family, type, proto, fileno)
[231] Fix | Delete
self._io_refs = 0
[232] Fix | Delete
self._closed = False
[233] Fix | Delete
[234] Fix | Delete
def __enter__(self):
[235] Fix | Delete
return self
[236] Fix | Delete
[237] Fix | Delete
def __exit__(self, *args):
[238] Fix | Delete
if not self._closed:
[239] Fix | Delete
self.close()
[240] Fix | Delete
[241] Fix | Delete
def __repr__(self):
[242] Fix | Delete
"""Wrap __repr__() to reveal the real class name and socket
[243] Fix | Delete
address(es).
[244] Fix | Delete
"""
[245] Fix | Delete
closed = getattr(self, '_closed', False)
[246] Fix | Delete
s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
[247] Fix | Delete
% (self.__class__.__module__,
[248] Fix | Delete
self.__class__.__qualname__,
[249] Fix | Delete
" [closed]" if closed else "",
[250] Fix | Delete
self.fileno(),
[251] Fix | Delete
self.family,
[252] Fix | Delete
self.type,
[253] Fix | Delete
self.proto)
[254] Fix | Delete
if not closed:
[255] Fix | Delete
try:
[256] Fix | Delete
laddr = self.getsockname()
[257] Fix | Delete
if laddr:
[258] Fix | Delete
s += ", laddr=%s" % str(laddr)
[259] Fix | Delete
except error:
[260] Fix | Delete
pass
[261] Fix | Delete
try:
[262] Fix | Delete
raddr = self.getpeername()
[263] Fix | Delete
if raddr:
[264] Fix | Delete
s += ", raddr=%s" % str(raddr)
[265] Fix | Delete
except error:
[266] Fix | Delete
pass
[267] Fix | Delete
s += '>'
[268] Fix | Delete
return s
[269] Fix | Delete
[270] Fix | Delete
def __getstate__(self):
[271] Fix | Delete
raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
[272] Fix | Delete
[273] Fix | Delete
def dup(self):
[274] Fix | Delete
"""dup() -> socket object
[275] Fix | Delete
[276] Fix | Delete
Duplicate the socket. Return a new socket object connected to the same
[277] Fix | Delete
system resource. The new socket is non-inheritable.
[278] Fix | Delete
"""
[279] Fix | Delete
fd = dup(self.fileno())
[280] Fix | Delete
sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
[281] Fix | Delete
sock.settimeout(self.gettimeout())
[282] Fix | Delete
return sock
[283] Fix | Delete
[284] Fix | Delete
def accept(self):
[285] Fix | Delete
"""accept() -> (socket object, address info)
[286] Fix | Delete
[287] Fix | Delete
Wait for an incoming connection. Return a new socket
[288] Fix | Delete
representing the connection, and the address of the client.
[289] Fix | Delete
For IP sockets, the address info is a pair (hostaddr, port).
[290] Fix | Delete
"""
[291] Fix | Delete
fd, addr = self._accept()
[292] Fix | Delete
sock = socket(self.family, self.type, self.proto, fileno=fd)
[293] Fix | Delete
# Issue #7995: if no default timeout is set and the listening
[294] Fix | Delete
# socket had a (non-zero) timeout, force the new socket in blocking
[295] Fix | Delete
# mode to override platform-specific socket flags inheritance.
[296] Fix | Delete
if getdefaulttimeout() is None and self.gettimeout():
[297] Fix | Delete
sock.setblocking(True)
[298] Fix | Delete
return sock, addr
[299] Fix | Delete
[300] Fix | Delete
def makefile(self, mode="r", buffering=None, *,
[301] Fix | Delete
encoding=None, errors=None, newline=None):
[302] Fix | Delete
"""makefile(...) -> an I/O stream connected to the socket
[303] Fix | Delete
[304] Fix | Delete
The arguments are as for io.open() after the filename, except the only
[305] Fix | Delete
supported mode values are 'r' (default), 'w' and 'b'.
[306] Fix | Delete
"""
[307] Fix | Delete
# XXX refactor to share code?
[308] Fix | Delete
if not set(mode) <= {"r", "w", "b"}:
[309] Fix | Delete
raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
[310] Fix | Delete
writing = "w" in mode
[311] Fix | Delete
reading = "r" in mode or not writing
[312] Fix | Delete
assert reading or writing
[313] Fix | Delete
binary = "b" in mode
[314] Fix | Delete
rawmode = ""
[315] Fix | Delete
if reading:
[316] Fix | Delete
rawmode += "r"
[317] Fix | Delete
if writing:
[318] Fix | Delete
rawmode += "w"
[319] Fix | Delete
raw = SocketIO(self, rawmode)
[320] Fix | Delete
self._io_refs += 1
[321] Fix | Delete
if buffering is None:
[322] Fix | Delete
buffering = -1
[323] Fix | Delete
if buffering < 0:
[324] Fix | Delete
buffering = io.DEFAULT_BUFFER_SIZE
[325] Fix | Delete
if buffering == 0:
[326] Fix | Delete
if not binary:
[327] Fix | Delete
raise ValueError("unbuffered streams must be binary")
[328] Fix | Delete
return raw
[329] Fix | Delete
if reading and writing:
[330] Fix | Delete
buffer = io.BufferedRWPair(raw, raw, buffering)
[331] Fix | Delete
elif reading:
[332] Fix | Delete
buffer = io.BufferedReader(raw, buffering)
[333] Fix | Delete
else:
[334] Fix | Delete
assert writing
[335] Fix | Delete
buffer = io.BufferedWriter(raw, buffering)
[336] Fix | Delete
if binary:
[337] Fix | Delete
return buffer
[338] Fix | Delete
text = io.TextIOWrapper(buffer, encoding, errors, newline)
[339] Fix | Delete
text.mode = mode
[340] Fix | Delete
return text
[341] Fix | Delete
[342] Fix | Delete
if hasattr(os, 'sendfile'):
[343] Fix | Delete
[344] Fix | Delete
def _sendfile_use_sendfile(self, file, offset=0, count=None):
[345] Fix | Delete
self._check_sendfile_params(file, offset, count)
[346] Fix | Delete
sockno = self.fileno()
[347] Fix | Delete
try:
[348] Fix | Delete
fileno = file.fileno()
[349] Fix | Delete
except (AttributeError, io.UnsupportedOperation) as err:
[350] Fix | Delete
raise _GiveupOnSendfile(err) # not a regular file
[351] Fix | Delete
try:
[352] Fix | Delete
fsize = os.fstat(fileno).st_size
[353] Fix | Delete
except OSError as err:
[354] Fix | Delete
raise _GiveupOnSendfile(err) # not a regular file
[355] Fix | Delete
if not fsize:
[356] Fix | Delete
return 0 # empty file
[357] Fix | Delete
# Truncate to 1GiB to avoid OverflowError, see bpo-38319.
[358] Fix | Delete
blocksize = min(count or fsize, 2 ** 30)
[359] Fix | Delete
timeout = self.gettimeout()
[360] Fix | Delete
if timeout == 0:
[361] Fix | Delete
raise ValueError("non-blocking sockets are not supported")
[362] Fix | Delete
# poll/select have the advantage of not requiring any
[363] Fix | Delete
# extra file descriptor, contrarily to epoll/kqueue
[364] Fix | Delete
# (also, they require a single syscall).
[365] Fix | Delete
if hasattr(selectors, 'PollSelector'):
[366] Fix | Delete
selector = selectors.PollSelector()
[367] Fix | Delete
else:
[368] Fix | Delete
selector = selectors.SelectSelector()
[369] Fix | Delete
selector.register(sockno, selectors.EVENT_WRITE)
[370] Fix | Delete
[371] Fix | Delete
total_sent = 0
[372] Fix | Delete
# localize variable access to minimize overhead
[373] Fix | Delete
selector_select = selector.select
[374] Fix | Delete
os_sendfile = os.sendfile
[375] Fix | Delete
try:
[376] Fix | Delete
while True:
[377] Fix | Delete
if timeout and not selector_select(timeout):
[378] Fix | Delete
raise _socket.timeout('timed out')
[379] Fix | Delete
if count:
[380] Fix | Delete
blocksize = count - total_sent
[381] Fix | Delete
if blocksize <= 0:
[382] Fix | Delete
break
[383] Fix | Delete
try:
[384] Fix | Delete
sent = os_sendfile(sockno, fileno, offset, blocksize)
[385] Fix | Delete
except BlockingIOError:
[386] Fix | Delete
if not timeout:
[387] Fix | Delete
# Block until the socket is ready to send some
[388] Fix | Delete
# data; avoids hogging CPU resources.
[389] Fix | Delete
selector_select()
[390] Fix | Delete
continue
[391] Fix | Delete
except OSError as err:
[392] Fix | Delete
if total_sent == 0:
[393] Fix | Delete
# We can get here for different reasons, the main
[394] Fix | Delete
# one being 'file' is not a regular mmap(2)-like
[395] Fix | Delete
# file, in which case we'll fall back on using
[396] Fix | Delete
# plain send().
[397] Fix | Delete
raise _GiveupOnSendfile(err)
[398] Fix | Delete
raise err from None
[399] Fix | Delete
else:
[400] Fix | Delete
if sent == 0:
[401] Fix | Delete
break # EOF
[402] Fix | Delete
offset += sent
[403] Fix | Delete
total_sent += sent
[404] Fix | Delete
return total_sent
[405] Fix | Delete
finally:
[406] Fix | Delete
if total_sent > 0 and hasattr(file, 'seek'):
[407] Fix | Delete
file.seek(offset)
[408] Fix | Delete
else:
[409] Fix | Delete
def _sendfile_use_sendfile(self, file, offset=0, count=None):
[410] Fix | Delete
raise _GiveupOnSendfile(
[411] Fix | Delete
"os.sendfile() not available on this platform")
[412] Fix | Delete
[413] Fix | Delete
def _sendfile_use_send(self, file, offset=0, count=None):
[414] Fix | Delete
self._check_sendfile_params(file, offset, count)
[415] Fix | Delete
if self.gettimeout() == 0:
[416] Fix | Delete
raise ValueError("non-blocking sockets are not supported")
[417] Fix | Delete
if offset:
[418] Fix | Delete
file.seek(offset)
[419] Fix | Delete
blocksize = min(count, 8192) if count else 8192
[420] Fix | Delete
total_sent = 0
[421] Fix | Delete
# localize variable access to minimize overhead
[422] Fix | Delete
file_read = file.read
[423] Fix | Delete
sock_send = self.send
[424] Fix | Delete
try:
[425] Fix | Delete
while True:
[426] Fix | Delete
if count:
[427] Fix | Delete
blocksize = min(count - total_sent, blocksize)
[428] Fix | Delete
if blocksize <= 0:
[429] Fix | Delete
break
[430] Fix | Delete
data = memoryview(file_read(blocksize))
[431] Fix | Delete
if not data:
[432] Fix | Delete
break # EOF
[433] Fix | Delete
while True:
[434] Fix | Delete
try:
[435] Fix | Delete
sent = sock_send(data)
[436] Fix | Delete
except BlockingIOError:
[437] Fix | Delete
continue
[438] Fix | Delete
else:
[439] Fix | Delete
total_sent += sent
[440] Fix | Delete
if sent < len(data):
[441] Fix | Delete
data = data[sent:]
[442] Fix | Delete
else:
[443] Fix | Delete
break
[444] Fix | Delete
return total_sent
[445] Fix | Delete
finally:
[446] Fix | Delete
if total_sent > 0 and hasattr(file, 'seek'):
[447] Fix | Delete
file.seek(offset + total_sent)
[448] Fix | Delete
[449] Fix | Delete
def _check_sendfile_params(self, file, offset, count):
[450] Fix | Delete
if 'b' not in getattr(file, 'mode', 'b'):
[451] Fix | Delete
raise ValueError("file should be opened in binary mode")
[452] Fix | Delete
if not self.type & SOCK_STREAM:
[453] Fix | Delete
raise ValueError("only SOCK_STREAM type sockets are supported")
[454] Fix | Delete
if count is not None:
[455] Fix | Delete
if not isinstance(count, int):
[456] Fix | Delete
raise TypeError(
[457] Fix | Delete
"count must be a positive integer (got {!r})".format(count))
[458] Fix | Delete
if count <= 0:
[459] Fix | Delete
raise ValueError(
[460] Fix | Delete
"count must be a positive integer (got {!r})".format(count))
[461] Fix | Delete
[462] Fix | Delete
def sendfile(self, file, offset=0, count=None):
[463] Fix | Delete
"""sendfile(file[, offset[, count]]) -> sent
[464] Fix | Delete
[465] Fix | Delete
Send a file until EOF is reached by using high-performance
[466] Fix | Delete
os.sendfile() and return the total number of bytes which
[467] Fix | Delete
were sent.
[468] Fix | Delete
*file* must be a regular file object opened in binary mode.
[469] Fix | Delete
If os.sendfile() is not available (e.g. Windows) or file is
[470] Fix | Delete
not a regular file socket.send() will be used instead.
[471] Fix | Delete
*offset* tells from where to start reading the file.
[472] Fix | Delete
If specified, *count* is the total number of bytes to transmit
[473] Fix | Delete
as opposed to sending the file until EOF is reached.
[474] Fix | Delete
File position is updated on return or also in case of error in
[475] Fix | Delete
which case file.tell() can be used to figure out the number of
[476] Fix | Delete
bytes which were sent.
[477] Fix | Delete
The socket must be of SOCK_STREAM type.
[478] Fix | Delete
Non-blocking sockets are not supported.
[479] Fix | Delete
"""
[480] Fix | Delete
try:
[481] Fix | Delete
return self._sendfile_use_sendfile(file, offset, count)
[482] Fix | Delete
except _GiveupOnSendfile:
[483] Fix | Delete
return self._sendfile_use_send(file, offset, count)
[484] Fix | Delete
[485] Fix | Delete
def _decref_socketios(self):
[486] Fix | Delete
if self._io_refs > 0:
[487] Fix | Delete
self._io_refs -= 1
[488] Fix | Delete
if self._closed:
[489] Fix | Delete
self.close()
[490] Fix | Delete
[491] Fix | Delete
def _real_close(self, _ss=_socket.socket):
[492] Fix | Delete
# This function should not reference any globals. See issue #808164.
[493] Fix | Delete
_ss.close(self)
[494] Fix | Delete
[495] Fix | Delete
def close(self):
[496] Fix | Delete
# This function should not reference any globals. See issue #808164.
[497] Fix | Delete
self._closed = True
[498] Fix | Delete
if self._io_refs <= 0:
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function