Smarter listenport selection.

Now if we aren't given an explicit port, we always initiate the port search
at 12300 and count upward looking for an available port.

Normally the kernel will assign us a random port, but that's not ideal
in our case because we'd like to use the same port numbers whenever
possible; that avoids piling up crap inside iptables in the (hopefully
unlikely) event that we die without cleaning up correctly.
This commit is contained in:
Avery Pennarun
2010-05-01 21:50:43 -04:00
parent ad459e2918
commit 9f514d7a15
3 changed files with 38 additions and 6 deletions

View File

@ -1,4 +1,4 @@
import struct, socket, select, subprocess
import struct, socket, select, subprocess, errno
from ssnet import SockWrapper, Handler, Proxy
from helpers import *
@ -58,9 +58,28 @@ def main(listenip, remotename, subnets):
log('Starting sshuttle proxy.\n')
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(listenip)
if listenip[1]:
ports = [listenip[1]]
else:
ports = xrange(12300,65536)
last_e = None
bound = False
log('Binding:')
for port in ports:
log(' %d' % port)
try:
listener.bind((listenip[0], port))
bound = True
break
except socket.error, e:
last_e = e
log('\n')
if not bound:
assert(last_e)
raise last_e
listener.listen(10)
log('Listening on %r.\n' % (listener.getsockname(),))
listenip = listener.getsockname()
log('Listening on %r.\n' % (listenip,))
iptables_setup(listenip[1], subnets)