From 10069f99e2161b26306c76e2c6ad0ef012162f12 Mon Sep 17 00:00:00 2001 From: Avery Pennarun Date: Sun, 2 May 2010 01:52:05 -0400 Subject: [PATCH] Clean up SockWrapper.peername stuff. Some fds don't have peernames, and sometimes the peername isn't very helpful, so let's fill it in by hand when appropriate. --- ssh.py | 2 +- ssnet.py | 37 ++++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/ssh.py b/ssh.py index 9056b9b..ef3199e 100644 --- a/ssh.py +++ b/ssh.py @@ -20,7 +20,7 @@ def connect(rhost): cmd = r""" sh -c PATH=%s:'$PATH exec sshuttle --server' """ % (escapedir,) - argv = ['ssh', '-v', rhost, '--', cmd.strip()] + argv = ['ssh', rhost, '--', cmd.strip()] print repr(argv) (s1,s2) = socket.socketpair() def setup(): diff --git a/ssnet.py b/ssnet.py index f4cb5c4..bbc926f 100644 --- a/ssnet.py +++ b/ssnet.py @@ -36,27 +36,35 @@ def _nb_clean(func, *args): def _try_peername(sock): try: - return sock.getpeername() + pn = sock.getpeername() + if pn: + return '%s:%s' % (pn[0], pn[1]) except socket.error, e: if e.args[0] not in (errno.ENOTCONN, errno.ENOTSOCK): raise - else: - return ('0.0.0.0',0) + return 'unknown' class SockWrapper: - def __init__(self, rsock, wsock): + def __init__(self, rsock, wsock, peername=None): + self.exc = None self.rsock = rsock self.wsock = wsock - self.peername = _try_peername(self.rsock) self.shut_read = self.shut_write = False self.buf = [] + self.peername = peername or _try_peername(self.rsock) def __del__(self): log('%r: deleting\n' % self) + if self.exc: + log('%r: error was: %r\n' % (self, self.exc)) def __repr__(self): - return 'SW%r' % (self.peername,) + return 'SW:%s' % (self.peername,) + + def seterr(self, e): + if not self.exc: + self.exc = e def noread(self): if not self.shut_read: @@ -70,15 +78,16 @@ class SockWrapper: self.shut_write = True try: self.wsock.shutdown(socket.SHUT_WR) - except socket.error: - pass + except socket.error, e: + self.seterr(e) def uwrite(self, buf): self.wsock.setblocking(False) try: return _nb_clean(os.write, self.wsock.fileno(), buf) - except OSError: + except OSError, e: # unexpected error... stream is dead + self.seterr(e) self.nowrite() self.noread() return 0 @@ -93,7 +102,8 @@ class SockWrapper: self.rsock.setblocking(False) try: return _nb_clean(os.read, self.rsock.fileno(), 65536) - except OSError: + except OSError, e: + self.seterr(e) return '' # unexpected error... we'll call it EOF def fill(self): @@ -312,11 +322,16 @@ class MuxWrapper(SockWrapper): def connect_dst(ip, port): + log('Connecting to %s:%d\n' % (ip, port)) outsock = socket.socket() outsock.setsockopt(socket.SOL_IP, socket.IP_TTL, 42) + e = None try: outsock.connect((ip,port)) except socket.error, e: if e.args[0] not in [errno.ECONNREFUSED]: raise - return SockWrapper(outsock,outsock) + sw = SockWrapper(outsock, outsock, peername = '%s:%d' % (ip,port)) + if e: + sw.seterr(e) + return sw