work on sockets

master
Kevin Froman 2018-09-22 23:53:09 -05:00
parent 70e2ccbc0a
commit ad3d7940f5
5 changed files with 52 additions and 27 deletions

View File

@ -108,7 +108,8 @@ class OnionrCommunicatorDaemon:
cleanupTimer.count = (cleanupTimer.frequency - 60) cleanupTimer.count = (cleanupTimer.frequency - 60)
announceTimer.count = (cleanupTimer.frequency - 60) announceTimer.count = (cleanupTimer.frequency - 60)
self.socketServer = onionrsockets.OnionrSocketServer(self._core) self.socketServer = threading.Thread(target=onionrsockets.OnionrSocketServer, args=(self._core,))
self.socketServer.start()
self.socketClient = onionrsockets.OnionrSocketClient(self._core) self.socketClient = onionrsockets.OnionrSocketClient(self._core)
# Main daemon loop, mainly for calling timers, don't do any complex operations here to avoid locking # Main daemon loop, mainly for calling timers, don't do any complex operations here to avoid locking
@ -124,6 +125,7 @@ class OnionrCommunicatorDaemon:
pass pass
logger.info('Goodbye.') logger.info('Goodbye.')
self._core.killSockets = True
self._core._utils.localCommand('shutdown') # shutdown the api self._core._utils.localCommand('shutdown') # shutdown the api
time.sleep(0.5) time.sleep(0.5)
@ -473,9 +475,8 @@ class OnionrCommunicatorDaemon:
elif cmd[0] == 'startSocket': elif cmd[0] == 'startSocket':
# Create our own socket server # Create our own socket server
socketInfo = json.loads(cmd[1]) socketInfo = json.loads(cmd[1])
peer = socketInfo['peer'] socketInfo['id'] = uuid.uuid4()
reason = socketInfo['reason'] self._core.startSocket = socketInfo
threading.Thread(target=self.socketServer.addSocket, args=(peer, reason)).start()
elif cmd[0] == 'addSocket': elif cmd[0] == 'addSocket':
# Socket server was created for us # Socket server was created for us
socketInfo = json.loads(cmd[1]) socketInfo = json.loads(cmd[1])

View File

@ -50,6 +50,9 @@ class Core:
self.dbCreate = dbcreator.DBCreator(self) self.dbCreate = dbcreator.DBCreator(self)
self.forwardKeysFile = 'data/forward-keys.db' self.forwardKeysFile = 'data/forward-keys.db'
self.killSockets = False
self.startSocket = {}
self.usageFile = 'data/disk-usage.txt' self.usageFile = 'data/disk-usage.txt'
self.config = config self.config = config

View File

@ -271,7 +271,11 @@ class Onionr:
''' '''
def startChat(self): def startChat(self):
try:
data = json.dumps({'peer': sys.argv[2], 'reason': 'chat'}) data = json.dumps({'peer': sys.argv[2], 'reason': 'chat'})
except IndexError:
logger.error('Must specify peer to chat with.')
else:
self.onionrCore.daemonQueueAdd('startSocket', data) self.onionrCore.daemonQueueAdd('startSocket', data)
def getCommands(self): def getCommands(self):

View File

@ -20,24 +20,26 @@
import stem.control import stem.control
import threading import threading
import socks, config, uuid import socks, config, uuid
import onionrexceptions, time, requests, onionrblockapi import onionrexceptions, time, requests, onionrblockapi, logger
from dependencies import secrets from dependencies import secrets
from gevent.pywsgi import WSGIServer
from flask import request, Response, abort from flask import request, Response, abort
import flask
class OnionrSocketServer: class OnionrSocketServer:
def __init__(self, coreInst): def __init__(self, coreInst):
app = flask.Flask(__name__)
self.sockets = {} # pubkey: tor address self.sockets = {} # pubkey: tor address
self.connPool = {} self.connPool = {}
self.bindPort = 1337 self.bindPort = 1337
self._core = coreInst self._core = coreInst
self.responseData = {} self.responseData = {}
self.killSocket = False
threading.Thread(target=self.detectShutdown).start()
threading.Thread(target=self.socketStarter).start()
app = flask.Flask(__name__) app = flask.Flask(__name__)
self.http_server = WSGIServer(('127.0.0.1', self.bindPort), app)
http_server = WSGIServer((socket.service_id, bindPort), app) self.http_server.serve_forever()
threading.Thread(target=http_server.serve_forever).start()
@app.route('/dc/', methods=['POST']) @app.route('/dc/', methods=['POST'])
def acceptConn(self): def acceptConn(self):
@ -55,6 +57,22 @@ class OnionrSocketServer:
return retData return retData
def socketStarter(self):
while not self._core.killSockets:
try:
self.addSocket(self._core.startSocket['peer'], reason=self._core.startSocket['reason'])
except KeyError:
pass
else:
logger.info('%s socket started with %s' % (self._core.startSocket['reason'], self._core.startSocket['peer']))
self._core.startSocket = {}
def detectShutdown(self):
while not self._core.killSockets:
time.sleep(5)
logger.info('Killing socket server')
self.http_server.stop()
def setResponseData(self, host, data): def setResponseData(self, host, data):
self.responseData[host] = data self.responseData[host] = data
@ -68,10 +86,8 @@ class OnionrSocketServer:
self.responseData[socket.service_id] = '' self.responseData[socket.service_id] = ''
self._core.insertBlock(uuid.uuid4(), header='socket', sign=True, encryptType='asym', asymPeer=peer, meta={'reason': reason}) self._core.insertBlock(str(uuid.uuid4()), header='socket', sign=True, encryptType='asym', asymPeer=peer, meta={'reason': reason})
while not self.killSocket:
time.sleep(3)
return return
class OnionrSocketClient: class OnionrSocketClient:

View File

@ -593,6 +593,7 @@ class OnionrUtils:
except ValueError as e: except ValueError as e:
logger.debug('Failed to make request', error = e) logger.debug('Failed to make request', error = e)
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
if not 'ConnectTimeoutError' in str(e):
logger.debug('Error: %s' % str(e)) logger.debug('Error: %s' % str(e))
retData = False retData = False
return retData return retData