Skip to content

Bugfixes and Improvements #23

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 10 additions & 7 deletions src/clamd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ def _init_socket(self):
"""
try:
self.clamd_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.clamd_socket.connect((self.host, self.port))
# Set timeout prior to connecting to ensure that an initial
# connection timeout will respect the setting regardless of OS.
# https://docs.python.org/3/library/socket.html#timeouts-and-the-connect-method
self.clamd_socket.settimeout(self.timeout)
self.clamd_socket.connect((self.host, self.port))

except socket.error:
e = sys.exc_info()[1]
Expand Down Expand Up @@ -166,11 +169,13 @@ def _file_system_scan(self, command, file):
finally:
self._close_socket()

def instream(self, buff):
def instream(self, buff, max_chunk_size=1024):
"""
Scan a buffer

buff filelikeobj: buffer to scan
max_chunk_size int: Maximum size of chunk to send to clamd in bytes
MUST be < StreamMaxLength in /etc/clamav/clamd.conf

return:
- (dict): {filename1: ("virusname", "status")}
Expand All @@ -184,15 +189,13 @@ def instream(self, buff):
self._init_socket()
self._send_command('INSTREAM')

max_chunk_size = 1024 # MUST be < StreamMaxLength in /etc/clamav/clamd.conf

chunk = buff.read(max_chunk_size)
while chunk:
size = struct.pack(b'!L', len(chunk))
self.clamd_socket.send(size + chunk)
self.clamd_socket.sendall(size + chunk)
chunk = buff.read(max_chunk_size)

self.clamd_socket.send(struct.pack(b'!L', 0))
self.clamd_socket.sendall(struct.pack(b'!L', 0))

result = self._recv_response()

Expand Down Expand Up @@ -231,7 +234,7 @@ def _send_command(self, cmd, *args):
concat_args = ' ' + ' '.join(args)

cmd = 'n{cmd}{args}\n'.format(cmd=cmd, args=concat_args).encode('utf-8')
self.clamd_socket.send(cmd)
self.clamd_socket.sendall(cmd)

def _recv_response(self):
"""
Expand Down