Changeset - e7a2c084dcd0
[Not reviewed]
default
0 1 0
Dennis Fink - 10 years ago 2014-12-11 11:31:51
dennis.fink@c3l.lu
Fixed country and added ipv6 support
1 file changed with 11 insertions and 6 deletions:
0 comments (0 inline, 0 general)
ennstatus/api/functions.py
Show inline comments
 

	
 
import re
 
import json
 
import ipaddress
 

	
 
from datetime import datetime
 

	
 
import pygeoip
 

	
 
from flask import current_app
 

	
 
from ennstatus.status.functions import _send_mail
 

	
 

	
 
FINGERPRINT_REGEX = re.compile(r'^[A-Z0-9]{40}$', re.I)
 

	
 
DATE_FORMAT = '%d-%m-%Y %H:%M:%S'
 

	
 
gi4 = pygeoip.GeoIP('/usr/share/GeoIP/GeoIP.dat', pygeoip.MEMORY_CACHE)
 

	
 
gi6 = pygeoip.GeoIP('/usr/share/GeoIP/GeoIPv6.dat', pygeoip.MEMORY_CACHE)
 

	
 
mail_cache = dict()
 

	
 

	
 
def check_bridge(key, server):
 

	
 
    if key not in server:
 
        raise ValueError('%s key not present!\n' % key)
 
    else:
 
        if not isinstance(server[key], bool):
 
            error_message = ('%s has not the right type!'
 
                             ' Needs to be a boolean!\n') % key
 
            raise ValueError(error_message)
 

	
 

	
 
def check_json_format(server):
 

	
 
    for key in ('server_type', 'server_name', 'tor_status', 'fingerprint'):
 
        if key not in server:
 
            raise ValueError('%s key not present!\n' % key)
 

	
 
    if server['server_type'] not in ('Exit', 'Relay', 'Bridge'):
 
        error_message = ('server_type has not the right content!'
 
                         ' is: %s must be one of: Exit, Relay or Bridge\n') \
 
@@ -74,68 +74,73 @@ def check_json_format(server):
 
            address = ipaddress.IPv6Address(server['ip6'])
 
            if any([address.is_private, address.is_multicast,
 
                    address.is_unspecified, address.is_reserved,
 
                    address.is_loopback, address.link_local]):
 
                raise ValueError('ip is not accepted!\n')
 

	
 
        except ipaddress.AddressValueError:
 
            raise ValueError('ip is not the right format!\n')
 

	
 
    return True
 

	
 

	
 
def _send_offline_mail(server_name, last_updated):
 

	
 
    current_app.logger.info('Sending tor status offline mail!')
 
    subject = '[Ennstatus] %s Tor status went offline'
 
    _send_mail(server_name, last_updated, subject)
 
    mail_cache[server_name] = datetime.utcnow()
 

	
 

	
 
def update_server(server, ip):
 

	
 
    server['last_updated'] = datetime.utcnow().strftime(DATE_FORMAT)
 
    server['server_status'] = 'Online'
 
    server['country'] = gi4.country_name_by_addr(ip)
 

	
 
    if ip.version == 4:
 
        server['country'] = gi4.country_name_by_addr(str(ip))
 
    elif ip.verion == 6:
 
        server['country'] = gi6.country_name_by_addr(str(ip))
 

	
 
    server_name = server['server_name']
 

	
 
    if server['server_type'] == 'Bridge':
 
        if 'ip' in server:
 
            del server['ip']
 

	
 
        if 'ip6' in server:
 
            del server['ip6']
 
    else:
 
        for key in ('obfs', 'fteproxy', 'flashproxy', 'meek'):
 
            if key in server:
 
                del server[key]
 

	
 
        if isinstance(ip, ipaddress.IPv4Address):
 
        if ip.version == 4:
 
            if 'ip' not in server:
 
                server['ip'] = ip
 
        elif isinstance(ip, ipaddress.IPv6Address):
 
                server['ip'] = str(ip)
 
        elif ip.version == 6:
 
            if 'ip6' not in server:
 
                server['ip6'] = ip
 
                server['ip6'] = str(ip)
 

	
 
    try:
 
        filename = ''.join(['data/', server_name.lower(), '.json'])
 

	
 
        with open(filename, 'w', encoding='utf-8') as fb:
 
            json.dump(server, fb)
 
    except Exception as e:
 
        return e
 

	
 
    if server['tor_status'] == 'Offline':
 

	
 
        if server_name in mail_cache:
 

	
 
            current_app.logger.debug('Mail cache is %s' % str(mail_cache))
 

	
 
            send_date = mail_cache[server_name]
 
            now = datetime.utcnow()
 
            delta = now - send_date
 

	
 
            if delta.seconds <= 7200:
 
                current_app.logger.debug('Server is in mail cache but not old enough to resend mail')
 
                return server
 
            else:
 
                current_app.logger.debug('Server tor status is offline for more than 7200 seconds')
0 comments (0 inline, 0 general)