Skip to content
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

Backward compatibility with Python 2.4-3.4 (server) #56

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions sshuttle/assembler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
content = z.decompress(stdin.read(nbytes))

module = imp.new_module(name)
parent, _, parent_name = name.rpartition(".")
if parent != "":
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)

code = compile(content, name, "exec")
Expand Down
13 changes: 12 additions & 1 deletion sshuttle/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@
logprefix = ''
verbose = 0

if sys.version_info[0] == 3:
binary_type = bytes

def b(s):
return s.encode("latin-1")
else:
binary_type = str

def b(s):
return s

def log(s):
global logprefix
Expand Down Expand Up @@ -70,7 +80,8 @@ def islocal(ip, family):
try:
try:
sock.bind((ip, 0))
except socket.error as e:
except socket.error:
_, e = sys.exc_info()[:2]
if e.args[0] == errno.EADDRNOTAVAIL:
return False # not a local IP
else:
Expand Down
23 changes: 14 additions & 9 deletions sshuttle/hostwatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import subprocess as ssubprocess
import sshuttle.helpers as helpers
from sshuttle.helpers import log, debug1, debug2, debug3
from sshuttle.helpers import b, log, debug1, debug2, debug3

POLL_TIME = 60 * 15
NETSTAT_POLL_TIME = 30
Expand All @@ -22,7 +22,8 @@
queue = {}
try:
null = open('/dev/null', 'wb')
except IOError as e:
except IOError:
_, e = sys.exc_info()[:2]
log('warning: %s\n' % e)
null = os.popen("sh -c 'while read x; do :; done'", 'wb', 4096)

Expand All @@ -36,9 +37,9 @@ def write_host_cache():
try:
f = open(tmpname, 'wb')
for name, ip in sorted(hostnames.items()):
f.write('%s,%s\n' % (name, ip))
f.write(b('%s,%s\n' % (name, ip)))
f.close()
os.chmod(tmpname, 0o600)
os.chmod(tmpname, 384) # 600 in octal, 'rw-------'
os.rename(tmpname, CACHEFILE)
finally:
try:
Expand All @@ -50,7 +51,8 @@ def write_host_cache():
def read_host_cache():
try:
f = open(CACHEFILE)
except IOError as e:
except IOError:
_, e = sys.exc_info()[:2]
if e.errno == errno.ENOENT:
return
else:
Expand Down Expand Up @@ -122,9 +124,10 @@ def _check_netstat():
argv = ['netstat', '-n']
try:
p = ssubprocess.Popen(argv, stdout=ssubprocess.PIPE, stderr=null)
content = p.stdout.read()
content = p.stdout.read().decode("ASCII")
p.wait()
except OSError as e:
except OSError:
_, e = sys.exc_info()[:2]
log('%r failed: %r\n' % (argv, e))
return

Expand All @@ -144,7 +147,8 @@ def _check_smb(hostname):
p = ssubprocess.Popen(argv, stdout=ssubprocess.PIPE, stderr=null)
lines = p.stdout.readlines()
p.wait()
except OSError as e:
except OSError:
_, e = sys.exc_info()[:2]
log('%r failed: %r\n' % (argv, e))
_smb_ok = False
return
Expand Down Expand Up @@ -201,7 +205,8 @@ def _check_nmb(hostname, is_workgroup, is_master):
p = ssubprocess.Popen(argv, stdout=ssubprocess.PIPE, stderr=null)
lines = p.stdout.readlines()
rv = p.wait()
except OSError as e:
except OSError:
_, e = sys.exc_info()[:2]
log('%r failed: %r\n' % (argv, e))
_nmb_ok = False
return
Expand Down
44 changes: 24 additions & 20 deletions sshuttle/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,26 @@
import sshuttle.hostwatch as hostwatch
import subprocess as ssubprocess
from sshuttle.ssnet import Handler, Proxy, Mux, MuxWrapper
from sshuttle.helpers import log, debug1, debug2, debug3, Fatal, \
from sshuttle.helpers import b, log, debug1, debug2, debug3, Fatal, \
resolvconf_random_nameserver


def _ipmatch(ipstr):
if ipstr == b'default':
ipstr = b'0.0.0.0/0'
m = re.match(b'^(\d+(\.\d+(\.\d+(\.\d+)?)?)?)(?:/(\d+))?$', ipstr)
if ipstr == b('default'):
ipstr = b('0.0.0.0/0')
m = re.match(b('^(\d+(\.\d+(\.\d+(\.\d+)?)?)?)(?:/(\d+))?$'), ipstr)
if m:
g = m.groups()
ips = g[0]
width = int(g[4] or 32)
if g[1] is None:
ips += b'.0.0.0'
ips += b('.0.0.0')
width = min(width, 8)
elif g[2] is None:
ips += b'.0.0'
ips += b('.0.0')
width = min(width, 16)
elif g[3] is None:
ips += b'.0'
ips += b('.0')
width = min(width, 24)
ips = ips.decode("ASCII")
return (struct.unpack('!I', socket.inet_aton(ips))[0], width)
Expand Down Expand Up @@ -63,7 +63,7 @@ def _list_routes():
p = ssubprocess.Popen(argv, stdout=ssubprocess.PIPE)
routes = []
for line in p.stdout:
cols = re.split(b'\s+', line)
cols = re.split(b('\s+'), line)
ipw = _ipmatch(cols[0])
if not ipw:
continue # some lines won't be parseable; never mind
Expand Down Expand Up @@ -149,7 +149,8 @@ def try_send(self):
try:
sock.send(self.request)
self.socks.append(sock)
except socket.error as e:
except socket.error:
_, e = sys.exc_info()[:2]
if e.args[0] in ssnet.NET_ERRS:
# might have been spurious; try again.
# Note: these errors sometimes are reported by recv(),
Expand All @@ -166,7 +167,8 @@ def callback(self, sock):

try:
data = sock.recv(4096)
except socket.error as e:
except socket.error:
_, e = sys.exc_info()[:2]
self.socks.remove(sock)
del self.peers[sock]

Expand Down Expand Up @@ -201,14 +203,16 @@ def send(self, dstip, data):
debug2('UDP: sending to %r port %d\n' % dstip)
try:
self.sock.sendto(data, dstip)
except socket.error as e:
except socket.error:
_, e = sys.exc_info()[:2]
log('UDP send to %r port %d: %s\n' % (dstip[0], dstip[1], e))
return

def callback(self, sock):
try:
data, peer = sock.recvfrom(4096)
except socket.error as e:
except socket.error:
_, e = sys.exc_info()[:2]
log('UDP recv from %r port %d: %s\n' % (peer[0], peer[1], e))
return
debug2('UDP response: %d bytes\n' % len(data))
Expand Down Expand Up @@ -241,26 +245,26 @@ def main(latency_control):
socket.fromfd(sys.stdout.fileno(),
socket.AF_INET, socket.SOCK_STREAM))
handlers.append(mux)
routepkt = b''
routepkt = ''
for r in routes:
routepkt += b'%d,%s,%d\n' % (r[0], r[1].encode("ASCII"), r[2])
mux.send(0, ssnet.CMD_ROUTES, routepkt)
routepkt += '%d,%s,%d\n' % r
mux.send(0, ssnet.CMD_ROUTES, b(routepkt))

hw = Hostwatch()
hw.leftover = ''
hw.leftover = b('')

def hostwatch_ready(sock):
assert(hw.pid)
content = hw.sock.recv(4096)
if content:
lines = (hw.leftover + content).split('\n')
lines = (hw.leftover + content).split(b('\n'))
if lines[-1]:
# no terminating newline: entry isn't complete yet!
hw.leftover = lines.pop()
lines.append('')
else:
hw.leftover = ''
mux.send(0, ssnet.CMD_HOST_LIST, '\n'.join(lines))
hw.leftover = b('')
mux.send(0, ssnet.CMD_HOST_LIST, b('\n').join(lines))
else:
raise Fatal('hostwatch process died')

Expand All @@ -272,7 +276,7 @@ def got_host_req(data):
mux.got_host_req = got_host_req

def new_channel(channel, data):
(family, dstip, dstport) = data.split(b',', 2)
(family, dstip, dstport) = data.split(b(','), 2)
family = int(family)
dstport = int(dstport)
outwrap = ssnet.connect_dst(family, dstip, dstport)
Expand Down