openmedialibrary/oml/directory.py

50 lines
1.2 KiB
Python
Raw Normal View History

2014-05-04 17:26:43 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2014-05-17 14:26:59 +00:00
# DHT placeholder
2014-05-16 08:06:11 +00:00
from __future__ import division
2014-05-04 17:26:43 +00:00
2014-05-17 14:26:59 +00:00
import logging
2014-05-04 17:26:43 +00:00
import requests
import ed25519
import json
import settings
2014-05-17 14:26:59 +00:00
logger = logging.getLogger('oml.directory')
2014-05-04 17:26:43 +00:00
base = settings.server['directory_service']
def get(vk):
id = vk.to_ascii(encoding='base64')
url ='%s/%s' % (base, id)
r = requests.get(url)
sig = r.headers.get('X-Ed25519-Signature')
data = r.content
if sig and data:
vk = ed25519.VerifyingKey(id, encoding='base64')
try:
vk.verify(sig, data, encoding='base64')
data = json.loads(data)
except ed25519.BadSignatureError:
2014-05-17 14:26:59 +00:00
logger.debug('invalid signature')
2014-05-04 17:26:43 +00:00
data = None
return data
def put(sk, data):
id = sk.get_verifying_key().to_ascii(encoding='base64')
data = json.dumps(data)
sig = sk.sign(data, encoding='base64')
url ='%s/%s' % (base, id)
headers = {
'X-Ed25519-Signature': sig
}
try:
2014-05-17 00:14:15 +00:00
r = requests.put(url, data, headers=headers, timeout=2)
2014-05-04 17:26:43 +00:00
except:
import traceback
2014-05-17 14:26:59 +00:00
logger.info('directory.put failed: %s', data)
2014-05-04 17:26:43 +00:00
traceback.print_exc()
return False
return r.status_code == 200