5656import os
5757import sys
5858from enum import IntEnum , IntFlag
59+ from functools import partial
5960
6061try :
6162 import errno
@@ -122,7 +123,7 @@ def _intenum_converter(value, enum_klass):
122123 10004 : "The operation was interrupted." ,
123124 10009 : "A bad file handle was passed." ,
124125 10013 : "Permission denied." ,
125- 10014 : "A fault occurred on the network?? " ,
126+ 10014 : "An invalid pointer was passed. " ,
126127 10022 : "An invalid operation was attempted." ,
127128 10024 : "Too many open files." ,
128129 10035 : "The socket operation would block." ,
@@ -180,7 +181,7 @@ def _intenum_converter(value, enum_klass):
180181 11001 : "Host not found." ,
181182 11002 : "Nonauthoritative host not found." ,
182183 11003 : "This is a nonrecoverable error." ,
183- 11004 : "Valid name, no data record requested type." ,
184+ 11004 : "Valid name, no data record of requested type." ,
184185 11005 : "QoS receivers." ,
185186 11006 : "QoS senders." ,
186187 11007 : "No QoS senders." ,
@@ -196,7 +197,7 @@ def _intenum_converter(value, enum_klass):
196197 11017 : "QoS flowspec error." ,
197198 11018 : "Invalid QoS provider buffer." ,
198199 11019 : "Invalid QoS filter style." ,
199- 11020 : "Invalid QoS filter style ." ,
200+ 11020 : "Invalid QoS filter type ." ,
200201 11021 : "Incorrect QoS filter count." ,
201202 11022 : "Invalid QoS object length." ,
202203 11023 : "Incorrect QoS flow count." ,
@@ -348,75 +349,83 @@ def makefile(self, mode="r", buffering=None, *,
348349 text .mode = mode
349350 return text
350351
351- if hasattr (os , 'sendfile' ):
352+ def _sendfile_zerocopy (self , zerocopy_func , giveup_exc_type , file ,
353+ offset = 0 , count = None ):
354+ """
355+ Send a file using a zero-copy function.
356+ """
357+ import selectors
352358
353- def _sendfile_use_sendfile (self , file , offset = 0 , count = None ):
354- # Lazy import to improve module import time
355- import selectors
359+ self ._check_sendfile_params (file , offset , count )
360+ sockno = self .fileno ()
361+ try :
362+ fileno = file .fileno ()
363+ except (AttributeError , io .UnsupportedOperation ) as err :
364+ raise giveup_exc_type (err ) # not a regular file
365+ try :
366+ fsize = os .fstat (fileno ).st_size
367+ except OSError as err :
368+ raise giveup_exc_type (err ) # not a regular file
369+ if not fsize :
370+ return 0 # empty file
371+ # Truncate to 1GiB to avoid OverflowError, see bpo-38319.
372+ blocksize = min (count or fsize , 2 ** 30 )
373+ timeout = self .gettimeout ()
374+ if timeout == 0 :
375+ raise ValueError ("non-blocking sockets are not supported" )
376+ # poll/select have the advantage of not requiring any
377+ # extra file descriptor, contrarily to epoll/kqueue
378+ # (also, they require a single syscall).
379+ if hasattr (selectors , 'PollSelector' ):
380+ selector = selectors .PollSelector ()
381+ else :
382+ selector = selectors .SelectSelector ()
383+ selector .register (sockno , selectors .EVENT_WRITE )
356384
357- self ._check_sendfile_params (file , offset , count )
358- sockno = self .fileno ()
359- try :
360- fileno = file .fileno ()
361- except (AttributeError , io .UnsupportedOperation ) as err :
362- raise _GiveupOnSendfile (err ) # not a regular file
363- try :
364- fsize = os .fstat (fileno ).st_size
365- except OSError as err :
366- raise _GiveupOnSendfile (err ) # not a regular file
367- if not fsize :
368- return 0 # empty file
369- # Truncate to 1GiB to avoid OverflowError, see bpo-38319.
370- blocksize = min (count or fsize , 2 ** 30 )
371- timeout = self .gettimeout ()
372- if timeout == 0 :
373- raise ValueError ("non-blocking sockets are not supported" )
374- # poll/select have the advantage of not requiring any
375- # extra file descriptor, contrarily to epoll/kqueue
376- # (also, they require a single syscall).
377- if hasattr (selectors , 'PollSelector' ):
378- selector = selectors .PollSelector ()
379- else :
380- selector = selectors .SelectSelector ()
381- selector .register (sockno , selectors .EVENT_WRITE )
382-
383- total_sent = 0
384- # localize variable access to minimize overhead
385- selector_select = selector .select
386- os_sendfile = os .sendfile
387- try :
388- while True :
389- if timeout and not selector_select (timeout ):
390- raise TimeoutError ('timed out' )
391- if count :
392- blocksize = min (count - total_sent , blocksize )
393- if blocksize <= 0 :
394- break
395- try :
396- sent = os_sendfile (sockno , fileno , offset , blocksize )
397- except BlockingIOError :
398- if not timeout :
399- # Block until the socket is ready to send some
400- # data; avoids hogging CPU resources.
401- selector_select ()
402- continue
403- except OSError as err :
404- if total_sent == 0 :
405- # We can get here for different reasons, the main
406- # one being 'file' is not a regular mmap(2)-like
407- # file, in which case we'll fall back on using
408- # plain send().
409- raise _GiveupOnSendfile (err )
410- raise err from None
411- else :
412- if sent == 0 :
413- break # EOF
414- offset += sent
415- total_sent += sent
416- return total_sent
417- finally :
418- if total_sent > 0 and hasattr (file , 'seek' ):
419- file .seek (offset )
385+ total_sent = 0
386+ # localize variable access to minimize overhead
387+ selector_select = selector .select
388+ try :
389+ while True :
390+ if timeout and not selector_select (timeout ):
391+ raise TimeoutError ('timed out' )
392+ if count :
393+ blocksize = min (count - total_sent , blocksize )
394+ if blocksize <= 0 :
395+ break
396+ try :
397+ sent = zerocopy_func (fileno , offset , blocksize )
398+ except BlockingIOError :
399+ if not timeout :
400+ # Block until the socket is ready to send some
401+ # data; avoids hogging CPU resources.
402+ selector_select ()
403+ continue
404+ except OSError as err :
405+ if total_sent == 0 :
406+ # We can get here for different reasons, the main
407+ # one being 'file' is not a regular mmap(2)-like
408+ # file, in which case we'll fall back on using
409+ # plain send().
410+ raise giveup_exc_type (err )
411+ raise err from None
412+ else :
413+ if sent == 0 :
414+ break # EOF
415+ offset += sent
416+ total_sent += sent
417+ return total_sent
418+ finally :
419+ if total_sent > 0 and hasattr (file , 'seek' ):
420+ file .seek (offset )
421+
422+ if hasattr (os , 'sendfile' ):
423+ def _sendfile_use_sendfile (self , file , offset = 0 , count = None ):
424+ return self ._sendfile_zerocopy (
425+ partial (os .sendfile , self .fileno ()),
426+ _GiveupOnSendfile ,
427+ file , offset , count ,
428+ )
420429 else :
421430 def _sendfile_use_sendfile (self , file , offset = 0 , count = None ):
422431 raise _GiveupOnSendfile (
0 commit comments