Skip to content

Commit 7a2bdb6

Browse files
author
ldx
committed
Fix stdout closing/reopening around save().
The save() callback prints rules to stdout in the extension. Make sure we close and then reopen not just the low-level fd, but the Python file as well around it.
1 parent b210822 commit 7a2bdb6

1 file changed

Lines changed: 22 additions & 16 deletions

File tree

iptc/ip4tc.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import shlex
77
import socket
88
import struct
9+
import sys
910
import weakref
1011

1112
from util import find_library
@@ -296,23 +297,28 @@ def save(self, name):
296297
return self._save(name, self.rule.get_ip())
297298

298299
def _save(self, name, ip):
299-
if self._module and self._module.save:
300-
# redirect C stdout to a pipe and read back the output of m->save
301-
pipes = os.pipe()
302-
saved_out = os.dup(1)
303-
os.dup2(pipes[1], 1)
304-
self._xt.save(self._module, ip, self._ptr)
305-
buf = os.read(pipes[0], 1024)
306-
os.dup2(saved_out, 1)
307-
os.close(pipes[0])
308-
os.close(pipes[1])
309-
os.close(saved_out)
310-
if name:
311-
return self._get_value(buf, name)
312-
else:
313-
return self._get_all_values(buf)
314-
else:
300+
if not self._module or not self._module.save:
315301
return None
302+
# redirect C stdout to a pipe and read back the output of m->save
303+
fd = sys.stdout.fileno()
304+
with os.fdopen(os.dup(fd), 'w') as old_stdout:
305+
try:
306+
pipes = os.pipe()
307+
sys.stdout.close()
308+
os.dup2(pipes[1], fd)
309+
sys.stdout = os.fdopen(fd, 'w')
310+
self._xt.save(self._module, ip, self._ptr)
311+
buf = os.read(pipes[0], 1024)
312+
os.close(pipes[0])
313+
os.close(pipes[1])
314+
if name:
315+
return self._get_value(buf, name)
316+
else:
317+
return self._get_all_values(buf)
318+
finally:
319+
sys.stdout.close()
320+
os.dup2(old_stdout.fileno(), fd)
321+
sys.stdout = os.fdopen(fd, 'w')
316322

317323
def _get_all_values(self, buf):
318324
table = {} # variable -> (value, inverted)

0 commit comments

Comments
 (0)