Skip to content

gh-112341: Specify the exact file size if offset is non zero in socket.sendfile #112342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ def _sendfile_use_sendfile(self, file, offset=0, count=None):
if not fsize:
return 0 # empty file
# Truncate to 1GiB to avoid OverflowError, see bpo-38319.
blocksize = min(count or fsize, 2 ** 30)
blocksize = min(count or fsize - offset, 2 ** 30)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if offset >= fsize?

Please add tests for offset == fsize and offset > fsize.

timeout = self.gettimeout()
if timeout == 0:
raise ValueError("non-blocking sockets are not supported")
Expand Down
23 changes: 23 additions & 0 deletions Lib/test/test_socket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
from unittest import mock
from test import support
from test.support import os_helper
from test.support import socket_helper
Expand Down Expand Up @@ -6433,6 +6434,28 @@ class SendfileUsingSendfileTest(SendfileUsingSendTest):
def meth_from_sock(self, sock):
return getattr(sock, "_sendfile_use_sendfile")

def _test_blocksize(self):
address = self.serv.getsockname()
file = open(os_helper.TESTFN, 'rb')
with socket.create_connection(address) as sock, file as file:
meth = self.meth_from_sock(sock)
with mock.patch('os.sendfile', wraps=os.sendfile) as mocked:
sent = meth(file, offset=10)
self.assertEqual(mocked.call_count, 2)
# blocksize is the blocksize argument in first call.
blocksize = mocked.call_args_list[0][0][3]
self.assertEqual(blocksize, self.FILESIZE - 10)
self.assertEqual(sent, self.FILESIZE - 10)
self.assertEqual(file.tell(), self.FILESIZE)

def test_blocksize(self):
# gh-112341: Check whether the blocksize is exactly fsize - offset if
# count is not specified when calling os.sendfile.
conn = self.accept_conn()
data = self.recv_data(conn)
self.assertEqual(len(data), self.FILESIZE - 10)
self.assertEqual(data, self.FILEDATA[10:])


@unittest.skipUnless(HAVE_SOCKET_ALG, 'AF_ALG required')
class LinuxKernelCryptoAPI(unittest.TestCase):
Expand Down