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