rewrite done

This commit is contained in:
2020-05-12 18:13:42 -04:00
parent 262a2be385
commit bb4055c87f
6 changed files with 63 additions and 323 deletions

View File

@@ -2,4 +2,3 @@ from . import args
from . import config
from . import logger
from . import tunnelbroker
from . import main

View File

@@ -10,14 +10,15 @@ def parseArgs():
help = ('If specified, use the RFC1918 IP address assigned to this machine instead of the WAN '
'IP (necessary if this machine is behind NAT)'))
args.add_argument('-c', '--config',
dest = 'conf',
default = '~/.config/he_tunnelbroker.ini',
help = ('The path to the config. '
'Default: ~/.config/he_tunnelbroker.ini'))
dest = 'conf_xml',
default = '~/.config/he_tunnelbroker.xml',
help = ('The path to the config. See example.tunnelbroker.xml'
'Default: ~/.config/he_tunnelbroker.xml'))
args.add_argument('-t', '--tunnel-id',
dest = 'tun_id',
type = int,
help = ('The tunnel profile ID/name to use in -c/--config. '
'Default is to use the first one found.'))
'Default is to use the first one found'))
args.add_argument('-u', '--no-update',
dest = 'update',
action = 'store_false',

View File

@@ -1,24 +0,0 @@
import logging
##
from . import args
from . import tunnelbroker
logger = logging.getLogger()
def main():
_args = args.parseArgs().parse_args()
logger.debug('Invoked with args: {0}'.format(vars(_args)))
tb = tunnelbroker.TunnelBroker(**vars(_args))
if _args.oper == 'start':
tb.start()
elif _args.oper == 'stop':
tb.stop()
elif _args.oper == 'update':
tb.update(oneshot = True)
return(None)
if __name__ == '__main__':
main()

View File

@@ -4,6 +4,7 @@ import socket
logger = logging.getLogger()
##
import requests
import requests.auth
from pyroute2 import IPRoute
##
from . import config
@@ -13,6 +14,8 @@ class TunnelBroker(object):
url_ip = 'https://ipv4.clientinfo.square-r00t.net/'
params_ip = {'raw': '1'}
url_api = 'https://ipv4.tunnelbroker.net/nic/update'
# def_rt = 'default'
def_rt = '::192.88.99.1'
def __init__(self, conf_xml, tun_id = None, wan_ip = True, update = True, *args, **kwargs):
self.conf_file = os.path.abspath(os.path.expanduser(conf_xml))
@@ -111,8 +114,7 @@ class TunnelBroker(object):
ipr.close()
raise e
try:
# ipr.route('add', dst = 'default', oif = self.iface_idx, family = socket.AF_INET6)
ipr.route('add', dst = '::192.88.99.1', oif = self.iface_idx, family = socket.AF_INET6)
ipr.route('add', dst = self.def_rt, oif = self.iface_idx, family = socket.AF_INET6)
logger.debug('Added default route for link {0}.'.format(self.iface_name))
except Exception as e:
logger.error(('Could not add default IPv6 route on link {0}: {1}').format(self.iface_name, e))
@@ -122,5 +124,50 @@ class TunnelBroker(object):
return(None)
def stop(self):
ipr = IPRoute()
try:
self.iface_idx = ipr.link_lookup(ifname = self.iface_name)[0]
logger.debug('Found link {0} at index {1}.'.format(self.iface_name, self.iface_idx))
except Exception as e:
ipr.close()
logger.error('Could not set iface_idx for link {0}: {1}'.format(self.iface_name, e))
raise e
try:
ipr.route('del', dst = self.def_rt, oif = self.iface_idx, family = socket.AF_INET6)
logger.debug('Removed default route for link {0}.'.format(self.iface_name))
except Exception as e:
logger.error(('Could not remove default IPv6 route on link {0}: '
'{1} (continuing anyways)').format(self.iface_name, e))
try:
ipr.link('set', index = self.iface_idx, state = 'down')
except Exception as e:
logger.error('Could not bring down link {0}: {1} (continuing anyways)'.format(self.iface_name, e))
try:
ipr.link('del', index = self.iface_idx)
logger.debug('Deleted link {0}.'.format(self.iface_name))
except Exception as e:
logger.error('Could not delete link {0}: {1}'.format(self.iface_name, e))
ipr.close()
raise e
ipr.close()
return(None)
def update(self):
def update(self, oneshot = False):
self._get_my_ip()
auth_handler = requests.auth.HTTPBasicAuth(self.tun.creds.user, self.tun.creds.key)
logger.debug('Set auth handler.')
logger.debug('Requesting IP update at provider.')
req = requests.get(self.url_api,
params = {'hostname': str(self.tun.id),
'myip': self.my_ip},
auth = auth_handler)
if not req.ok:
logger.error('Could not update IP at provider. Request returned {0}.'.format(req.status_code))
raise RuntimeError('Could not update client IP in tunnel')
status = req.content.decode('utf-8').split()[0].strip()
if status.lower() not in ('good', 'nochg'):
logger.error('Returned following failure message: {0}'.format(req.content.decode('utf-8')))
raise RuntimeError('Client IP update returned failure')
else:
logger.debug('Returned success message: {0}'.format(req.content.decode('utf-8')))
return(None)