openmedialibrary/oml/localnodes.py

157 lines
5.4 KiB
Python
Raw Normal View History

2014-05-12 12:57:47 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2014-09-02 22:32:44 +00:00
2014-05-17 14:26:59 +00:00
import socket
2014-05-12 12:57:47 +00:00
import netifaces
2016-03-14 13:31:56 +00:00
from zeroconf import (
ServiceBrowser, ServiceInfo, ServiceStateChange, Zeroconf
)
from tornado.ioloop import PeriodicCallback
import settings
2014-05-18 03:01:24 +00:00
import state
from tor_request import get_opener
2014-05-12 12:57:47 +00:00
import logging
2015-11-29 14:56:38 +00:00
logger = logging.getLogger(__name__)
2014-05-17 14:26:59 +00:00
2016-03-14 13:31:56 +00:00
2014-05-12 12:57:47 +00:00
def can_connect(data):
try:
opener = get_opener(data['id'])
headers = {
'User-Agent': settings.USER_AGENT,
'X-Node-Protocol': settings.NODE_PROTOCOL,
'Accept-Encoding': 'gzip',
}
if ':' in data['host']:
url = 'https://[{host}]:{port}'.format(**data)
else:
url = 'https://{host}:{port}'.format(**data)
opener.addheaders = list(zip(headers.keys(), headers.values()))
opener.timeout = 1
r = opener.open(url)
version = r.headers.get('X-Node-Protocol', None)
if version != settings.NODE_PROTOCOL:
logger.debug('version does not match local: %s remote %s (%s)', settings.NODE_PROTOCOL, version, data['id'])
return False
c = r.read()
2014-05-12 12:57:47 +00:00
return True
except:
2015-12-01 10:51:58 +00:00
pass
2016-01-24 09:13:03 +00:00
#logger.debug('failed to connect to local node %s', data, exc_info=True)
2014-05-12 12:57:47 +00:00
return False
def get_broadcast_interfaces():
return list(set(
addr['addr']
for iface in netifaces.interfaces()
for addr in netifaces.ifaddresses(iface).get(socket.AF_INET, [])
if addr.get('netmask') != '255.255.255.255' and addr.get('broadcast')
))
2016-03-14 13:31:56 +00:00
class LocalNodes(dict):
service_type = '_oml._tcp.local.'
local_info = None
local_ips = None
2016-03-14 13:31:56 +00:00
def __init__(self):
if not settings.server.get('localnode_discovery'):
2014-05-14 23:28:49 +00:00
return
2016-03-14 13:31:56 +00:00
self.setup()
self._ip_changed = PeriodicCallback(self._update_if_ip_changed, 60000)
def setup(self):
self.local_ips = get_broadcast_interfaces()
self.zeroconf = {ip: Zeroconf(interfaces=[ip]) for ip in self.local_ips}
2016-03-14 13:31:56 +00:00
self.register_service()
self.browse()
def _update_if_ip_changed(self):
local_ips = get_broadcast_interfaces()
2016-03-14 13:31:56 +00:00
if local_ips != self.local_ips:
self.close()
self.setup()
def browse(self):
self.browser = {
ip: ServiceBrowser(self.zeroconf[ip], self.service_type, handlers=[self.on_service_state_change])
for ip in self.zeroconf
}
2016-03-14 13:31:56 +00:00
def register_service(self):
if self.local_info:
for local_ip, local_info in self.local_info:
self.zeroconf[local_ip].unregister_service(local_info)
2016-03-14 13:31:56 +00:00
self.local_info = None
local_name = socket.gethostname().partition('.')[0] + '.local.'
port = settings.server['node_port']
desc = {
'username': settings.preferences.get('username', 'anonymous')
}
self.local_info = []
for i, local_ip in enumerate(get_broadcast_interfaces()):
if i:
2016-03-26 16:26:19 +00:00
name = '%s-%s [%s].%s' % (desc['username'], i+1, settings.USER_ID, self.service_type)
else:
name = '%s [%s].%s' % (desc['username'], settings.USER_ID, self.service_type)
local_info = ServiceInfo(self.service_type, name,
socket.inet_aton(local_ip), port, 0, 0, desc, local_name)
self.zeroconf[local_ip].register_service(local_info)
self.local_info.append((local_ip, local_info))
2016-03-14 13:31:56 +00:00
def __del__(self):
self.close()
def close(self):
if self.local_info:
for local_ip, local_info in self.local_info:
try:
self.zeroconf[local_ip].unregister_service(local_info)
except:
logger.debug('exception closing zeroconf', exc_info=True)
2016-03-14 13:31:56 +00:00
self.local_info = None
if self.zeroconf:
for local_ip in self.zeroconf:
try:
self.zeroconf[local_ip].close()
except:
logger.debug('exception closing zeroconf', exc_info=True)
2016-03-14 13:31:56 +00:00
self.zeroconf = None
for id in list(self):
self.pop(id, None)
def on_service_state_change(self, zeroconf, service_type, name, state_change):
if not '[' in name:
id = name.split('.')[0]
else:
id = name.split('[')[1].split(']')[0]
2016-03-14 13:31:56 +00:00
if id == settings.USER_ID:
2014-05-24 09:39:45 +00:00
return
2016-03-14 13:31:56 +00:00
if state_change is ServiceStateChange.Added:
info = zeroconf.get_service_info(service_type, name)
if info:
self[id] = {
'id': id,
'host': socket.inet_ntoa(info.address),
'port': info.port
}
if info.properties:
for key, value in info.properties.items():
key = key.decode()
self[id][key] = value.decode()
2016-03-23 19:15:26 +00:00
logger.debug('add: %s', self[id])
2016-03-14 13:31:56 +00:00
if state.tasks:
state.tasks.queue('addlocalinfo', self[id])
elif state_change is ServiceStateChange.Removed:
2016-03-23 19:15:26 +00:00
logger.debug('remove: %s', id)
2016-03-14 13:31:56 +00:00
self.pop(id, None)
if state.tasks:
state.tasks.queue('removelocalinfo', id)
2014-05-24 09:39:45 +00:00
def get(self, user_id):
2016-03-23 19:15:26 +00:00
if user_id in self and can_connect(self[user_id]):
return self[user_id]