diff -r e76f1ee05cc8 courier/control.py --- a/courier/control.py Sun Apr 28 14:56:49 2019 -0700 +++ b/courier/control.py Fri Aug 09 12:31:26 2019 +0200 @@ -73,7 +73,7 @@ sender = get_senders_mta(control_paths) if not sender: return None - ipstr = sender.partition('[')[2].partition(']')[0] + ipstr = sender.rpartition('[')[2].partition(']')[0] if not ipstr: return None sender_ip = ipaddress.ip_address(ipstr) diff -r e76f1ee05cc8 courier/xfilter.py --- a/courier/xfilter.py Sun Apr 28 14:56:49 2019 -0700 +++ b/courier/xfilter.py Fri Aug 09 12:31:26 2019 +0200 @@ -26,6 +26,7 @@ import email.generator import courier.control import courier.config +import tempfile class XFilterError(Exception): @@ -86,18 +87,24 @@ return self.control_data def submit(self): - bfo = open(self.body_path, 'r+') - bfo.truncate(0) - g = email.generator.Generator(bfo, mangle_from_=False) - g.flatten(self.message) - # Make sure that the file ends with a newline, or courier - # will choke on the new message file. - bfo.seek(0, 2) - bfo.seek(bfo.tell() - 1, 0) - if bfo.read(1) != '\n': - bfo.seek(0, 2) - bfo.write('\n') - bfo.close() + with tempfile.TemporaryFile(mode='w+b', prefix='pythonfilter') as tmp: + g = email.generator.BytesGenerator(tmp, mangle_from_=False) + g.flatten(self.message) + # Make sure that the file ends with a newline, or courier + # will choke on the new message file. + tmp.seek(0, 2) + tmp.seek(tmp.tell() - 1, 0) + if tmp.read(1).decode('ascii') != '\n': + tmp.seek(0, 2) + tmp.write('\n'.encode('ascii')) + tmp.seek(0) + with open(self.body_path, 'r+b') as bfo: + bfo.truncate(0) + while True: + data = tmp.read(4096) + if not data: + break + bfo.write(data) return '' # Deprecated names preserved for compatibility with older releases