From 711cf3f2d3b01eabea6f3c6af2d5967b6687112f Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Sun, 23 Sep 2018 20:47:27 -0500 Subject: [PATCH] work on sockets --- onionr/communicator2.py | 7 +++--- onionr/core.py | 4 +++ onionr/onionrchat.py | 29 ++++++++++++++-------- onionr/onionrsockets.py | 54 ++++++++++++++++++++++++++--------------- requirements.txt | 1 + 5 files changed, 63 insertions(+), 32 deletions(-) diff --git a/onionr/communicator2.py b/onionr/communicator2.py index 3cf69513..24f64c09 100755 --- a/onionr/communicator2.py +++ b/onionr/communicator2.py @@ -80,9 +80,7 @@ class OnionrCommunicatorDaemon: #self.daemonTools = onionrdaemontools.DaemonTools(self) self.daemonTools = onionrdaemontools.DaemonTools(self) - # Active sockets for direct connections - self.sockets = {} - self.socketExchange = {} # Socket ID exchange + self._chat = onionrchat.OnionrChat(self) if debug or developmentMode: OnionrCommunicatorTimers(self, self.heartbeat, 10) @@ -112,6 +110,9 @@ class OnionrCommunicatorDaemon: self.socketServer.start() self.socketClient = onionrsockets.OnionrSocketClient(self._core) + # Loads chat messages into memory + threading.Thread(target=self._chat.chatHandler).start() + # Main daemon loop, mainly for calling timers, don't do any complex operations here to avoid locking try: while not self.shutdown: diff --git a/onionr/core.py b/onionr/core.py index 17036e30..ac1c4902 100644 --- a/onionr/core.py +++ b/onionr/core.py @@ -50,8 +50,12 @@ class Core: self.dbCreate = dbcreator.DBCreator(self) self.forwardKeysFile = 'data/forward-keys.db' + # Socket data, defined here because of multithreading constraints with gevent self.killSockets = False self.startSocket = {} + self.socketServerConnData = {} + self.socketReasons = {} + self.socketServerResponseData = {} self.usageFile = 'data/disk-usage.txt' self.config = config diff --git a/onionr/onionrchat.py b/onionr/onionrchat.py index 33981d41..6d8fafa6 100644 --- a/onionr/onionrchat.py +++ b/onionr/onionrchat.py @@ -18,14 +18,23 @@ along with this program. If not, see . ''' import logger, time -class OnionrChat: - def __init__(self, communicatorInst, socketID): - self.communicator = communicatorInst - self.socket = self.communicator.sockets[socketID] - while True: - time.sleep(2) - logger.info('Chat: got %s' % (self.socket.getReadData(),)) - time.sleep(1) - self.socket.addSendData('rekt') - return \ No newline at end of file +class OnionrChat: + def __init__(self, communicatorInst): + '''OnionrChat uses onionrsockets (handled by the communicator) to exchange direct chat messages''' + self.communicator = communicatorInst + self._core = self.communicator._core + self._utils = self._core._utils + + self.chats = {} # {'peer': {'date': date, message': message}} + + def chatHandler(self): + while not self.communicator.shutdown: + for peer in self._core.socketServerConnData: + try: + assert self._core.socketReasons[peer] == "chat" + except (AssertionError, KeyError) as e: + continue + else: + self.chats[peer] = {'date': self._core.socketServerConnData[peer]['date'], 'data': self._core.socketServerConnData[peer]['data']} + logger.info("CHAT MESSAGE RECIEVED: %s" % self.chats[peer]['data']) \ No newline at end of file diff --git a/onionr/onionrsockets.py b/onionr/onionrsockets.py index 4d16ea7b..72bdbe38 100644 --- a/onionr/onionrsockets.py +++ b/onionr/onionrsockets.py @@ -27,12 +27,16 @@ from flask import request, Response, abort import flask class OnionrSocketServer: def __init__(self, coreInst): - app = flask.Flask(__name__) - self.sockets = {} # pubkey: tor address - self.connPool = {} - - self.bindPort = 1337 self._core = coreInst + app = flask.Flask(__name__) + self._core.socketServerConnData = {} + self.bindPort = 0 + + self.sockets = {} + + while self.bindPort < 1024: + self.bindPort = secrets.randbelow(65535) + self.responseData = {} threading.Thread(target=self.detectShutdown).start() @@ -45,15 +49,27 @@ class OnionrSocketServer: def acceptConn(self): data = request.form['data'] data = self._core._utils.bytesTorStr(data) - - if request.host in self.connPool: - self.connPool[request.host].append(data) + data = {'date': self._core._utils.getEpoch(), 'data': data} + myPeer = '' + retData = '' + for peer in self.sockets: + if self.sockets[peer] == request.host: + myPeer = peer + break else: - self.connPool[request.host] = [data] + return "" - retData = self.responseData[request.host] + if request.host in self.sockets: + self._core.socketServerConnData[myPeer].append(data) + else: + self._core.socketServerConnData[myPeer] = [data] - self.responseData[request.host] = '' + try: + retData = self._core.socketServerResponseData[myPeer] + except KeyError: + pass + + self._core.socketServerConnData[myPeer] = '' return retData @@ -66,6 +82,7 @@ class OnionrSocketServer: else: logger.info('%s socket started with %s' % (self._core.startSocket['reason'], self._core.startSocket['peer'])) self._core.startSocket = {} + time.sleep(1) def detectShutdown(self): while not self._core.killSockets: @@ -73,11 +90,11 @@ class OnionrSocketServer: logger.info('Killing socket server') self.http_server.stop() - def setResponseData(self, host, data): - self.responseData[host] = data - def addSocket(self, peer, reason=''): bindPort = 1337 + + assert len(reason) <= 12 + with stem.control.Controller.from_port(port=config.get('tor.controlPort')) as controller: controller.authenticate(config.get('tor.controlpassword')) @@ -86,8 +103,8 @@ class OnionrSocketServer: self.responseData[socket.service_id] = '' - self._core.insertBlock(str(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', asymPee=peer, meta={'reason': reason}) + self._core.socketReasons[peer] = reason return class OnionrSocketClient: @@ -95,7 +112,6 @@ class OnionrSocketClient: self.sockets = {} # pubkey: tor address self.connPool = {} self.sendData = {} - self.bindPort = 1337 self._core = coreInst self.response = '' self.request = '' @@ -117,7 +133,7 @@ class OnionrSocketClient: address = '' if address != '': self.sockets[peer] = address - data = '' + data = 'hey' while not self.killSocket: try: data = self.sendData[peer] @@ -126,7 +142,7 @@ class OnionrSocketClient: else: self.sendData[peer] = '' postData = {'data': data} - self.connPool[peer] = self._core._utils.doPostRequest('http://' + address + '/dc/', data=postData) + self.connPool[peer] = {'date': self._core._utils.getEpoch(), 'data': self._core._utils.doPostRequest('http://' + address + '/dc/', data=postData)} def getResponse(self, peer): retData = '' diff --git a/requirements.txt b/requirements.txt index 69322e22..05797aed 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,3 +8,4 @@ simple_crypt==4.1.7 Flask==1.0.2 PySocks==1.6.8 stem==1.6.0 +ntfy==2.6.0