Skip to content

Commit

Permalink
source code
Browse files Browse the repository at this point in the history
  • Loading branch information
ab77 committed Mar 20, 2017
1 parent b72a192 commit e0fac58
Show file tree
Hide file tree
Showing 16 changed files with 2,087 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# source code

<TBC>
155 changes: 155 additions & 0 deletions src/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib, requests, json
from inspect import stack
from common import retry
from traceback import print_exc

from config import (DEBUG, TARGET_COUNTRY, API_SECRET, API_HOST, API_VERSION,
AF, PAIRED_DEVICE_GUID, GUID, DEVICE_TYPE, GEOIP_OVERRIDE)


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def get_node_by_country(family=AF):
headers = {'X-Auth-Token': API_SECRET}
country = urllib.quote(TARGET_COUNTRY)

if GEOIP_OVERRIDE:
print 'override:%s' % GEOIP_OVERRIDE
country = GEOIP_OVERRIDE

res = requests.get('%s/api/v%s/node/%s/country/%s' % (API_HOST, API_VERSION,
family, country),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return res.content


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def get_node_by_guid(family=AF, guid=PAIRED_DEVICE_GUID):
if not guid: return None
headers = {'X-Auth-Token': API_SECRET}
res = requests.get('%s/api/v%s/node/%s/guid/%s' % (API_HOST, API_VERSION,
family, guid),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return res.content


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def get_device_env_by_name(guid=None, name=None, default=None):
headers = {'X-Auth-Token': API_SECRET}
res = requests.get('%s/api/v%s/device/%s/env/%s' % (API_HOST, API_VERSION,
guid, name),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code == 200:
return res.content

return default


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def auth_device(guid=None, default=False):
headers = {'X-Auth-Token': API_SECRET}
res = requests.get('%s/api/v%s/device/%s' % (API_HOST, API_VERSION,
guid),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code == 200:
return True

return default


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def get_alpha(country):
if not country: country = TARGET_COUNTRY
country = urllib.quote(country)
headers = {'X-Auth-Token': API_SECRET}
res = requests.get('%s/api/v%s/country/%s' % (API_HOST,
API_VERSION,
country),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return res.content


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def get_guid_by_public_ipaddr(ipaddr=None, family=4):
headers = {'X-Auth-Token': API_SECRET}
res = requests.get('%s/api/v%s/ipaddr/%s/%s' % (API_HOST, API_VERSION,
ipaddr, str(family)),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return res.content


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def put_device(family=AF, data=None):
headers = {'X-Auth-Token': API_SECRET}
res = requests.put('%s/api/v%s/device/%s/%s/%d' % (API_HOST, API_VERSION,
DEVICE_TYPE, GUID, family),
data=json.dumps(data), headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return (res.status_code, res.content)


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def dequeue_speedtest(guid=GUID, data=None):
result = False
headers = {'X-Auth-Token': API_SECRET}
res = requests.head('%s/api/v%s/speedtest/%s' % (API_HOST, API_VERSION, GUID),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code == 204: result = True

return result


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def update_speedtest(guid=GUID, data=None):
headers = {'X-Auth-Token': API_SECRET}
res = requests.patch('%s/api/v%s/speedtest/%s' % (API_HOST, API_VERSION, GUID),
data=json.dumps(data), headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], res)

if res.status_code not in [200]:
raise AssertionError((res.status_code, res.content))

return (res.status_code, res.content)


52 changes: 52 additions & 0 deletions src/as_prefixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env python

import pyasn, os, sys
from traceback import print_exc
from ipaddr import (IPNetwork, IPv4Network, IPv6Network, collapse_address_list)


DEBUG = bool(int(os.getenv('DEBUG', False)))
IPASN_DB = os.getenv('IPASN_DB', 'ipasn_20170201.1600.dat.gz')
DATADIR = os.getenv('DATADIR', '/data')


if __name__ == '__main__':
af = 4
try:
af = int(sys.argv[1])
except Exception:
pass

try:
assert af in [4, 6]
db = pyasn.pyasn('%s/%s' % (DATADIR, IPASN_DB))
assert db
asns = os.getenv('AS_NUMS')
asns = asns.split()
assert asns

except Exception:
if DEBUG: print_exc()
sys.exit(1)

asns = [asn.replace('AS', '') for asn in asns]

nets = list()
collapsed = None
for asn in asns:
try:
result = db.get_as_prefixes(asn)
if result:
for net in result:
if IPNetwork(net).version == 4 and IPNetwork(net).version == af:
nets.append(IPv4Network(net))
if IPNetwork(net).version == 6 and IPNetwork(net).version == af:
nets.append(IPv6Network(net))

collapsed = [str(net) for net in collapse_address_list(nets)]

except Exception:
if DEBUG: print_exc()
pass

if collapsed: print '\n'.join(collapsed)
66 changes: 66 additions & 0 deletions src/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
from inspect import stack
from traceback import print_exc

import vpn, nuitka
from common import retry
from config import (MAX_CONNS, DEBUG, DNS_SUB_DOMAIN, USER_AUTH_ENABLED)


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def authenticate(username=None, password=None):
# user auth disabled completely (anything goes)
if not USER_AUTH_ENABLED:
print '%s: plugin=%s user_auth_enabled=%d username=%s password=%s authenticated' % (stack()[0][3], DNS_SUB_DOMAIN,
USER_AUTH_ENABLED, username, password)
return True

# check number of server connections
conns = 0
try:
conns = vpn.get_server_conns()
except Exception:
pass

if conns > MAX_CONNS:
print '%s: plugin=%s username=%s conns=%s/%s' % (stack()[0][3], DNS_SUB_DOMAIN,
username, conns, MAX_CONNS)
return False

# auth plug-ins
plugin = None
result = False
try:
plugin = __import__('plugin')
except ImportError:
pass

if plugin and 'auth_user' in dir(plugin):
result = plugin.auth_user(username, password)
if result:
print '%s: plugin=%s user_auth_enabled=%d username=%s password=%s authenticated' % (stack()[0][3], DNS_SUB_DOMAIN,
USER_AUTH_ENABLED, username, password)
return True

print '%s: plugin=%s user_auth_enabled=%d username=%s password=%s authentication failed' % (stack()[0][3], DNS_SUB_DOMAIN,
USER_AUTH_ENABLED, username, password)
return False


if __name__ == '__main__':
result = False
try:
username = os.getenv('username')
passwd = os.getenv('password')
result = authenticate(username=username, password=passwd)
except Exception as e:
print repr(e)
if DEBUG: print_exc()
pass

if result: sys.exit(0)

sys.exit(1)
49 changes: 49 additions & 0 deletions src/bitcoin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json, requests
from datetime import datetime, timedelta
from inspect import stack
from common import retry
from config import (DEBUG, API_HOST, API_VERSION, API_SECRET, GUID)


@retry(Exception, cdata='method=%s()' % stack()[0][3])
def check_active_bitcoin_payment(guid=GUID):
headers = {'X-Auth-Token': API_SECRET}
result = requests.get('%s/api/v%s/device/%s/env/%s' % (API_HOST, API_VERSION,
guid, 'BITCOIN_LAST_PAYMENT_DATE'),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], result)

last_payment_date = None
if result.status_code in [200]:
last_payment_date = result.content

result = requests.get('%s/api/v%s/device/%s/env/%s' % (API_HOST, API_VERSION,
guid, 'BITCOIN_LAST_PAYMENT_AMOUNT'),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], result)

last_payment_amount = None
if result.status_code in [200]:
last_payment_amount = float(result.content)

result = requests.get('%s/api/v%s/device/%s/env/%s' % (API_HOST, API_VERSION,
guid, 'BITCOIN_DAILY_AMOUNT'),
headers=headers)

if DEBUG: print '%s: %s' % (stack()[0][3], result)

btc_price = None
if result.status_code in [200]:
btc_price = float(result.content)

expires = None
if last_payment_date and last_payment_amount and btc_price:
expires = datetime.strptime(last_payment_date, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=last_payment_amount / btc_price)
if datetime.today() <= expires: return True

return False
44 changes: 44 additions & 0 deletions src/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, importlib
from inspect import stack

import nuitka
from common import retry
from config import (DEBUG, DNS_SUB_DOMAIN)


if __name__ == '__main__':
try:
op = sys.argv[1]
except IndexError:
pass
sys.exit(0)

uname = os.getenv('username')
plugin = None
result = False

try:
plugin = __import__('plugin')

except ImportError:
pass
sys.exit(0)

# connect plug-ins
if op == 'connect':
if plugin and 'client_connect' in dir(plugin):
result = plugin.client_connect(uname)
if result:
print 'plugin=%s name=%s connected' % (DNS_SUB_DOMAIN, uname)

# disconnect plug-ins
if op == 'disconnect':
if plugin and 'client_disconnect' in dir(plugin):
result = plugin.client_disconnect(uname)
if result:
print 'plugin=%s name=%s disconnected' % (DNS_SUB_DOMAIN, uname)

sys.exit(0)
Loading

0 comments on commit e0fac58

Please sign in to comment.