work on sockets

This commit is contained in:
Kevin Froman 2018-09-23 20:47:27 -05:00
parent ad3d7940f5
commit 711cf3f2d3
5 changed files with 63 additions and 32 deletions

View File

@ -80,9 +80,7 @@ class OnionrCommunicatorDaemon:
#self.daemonTools = onionrdaemontools.DaemonTools(self) #self.daemonTools = onionrdaemontools.DaemonTools(self)
self.daemonTools = onionrdaemontools.DaemonTools(self) self.daemonTools = onionrdaemontools.DaemonTools(self)
# Active sockets for direct connections self._chat = onionrchat.OnionrChat(self)
self.sockets = {}
self.socketExchange = {} # Socket ID exchange
if debug or developmentMode: if debug or developmentMode:
OnionrCommunicatorTimers(self, self.heartbeat, 10) OnionrCommunicatorTimers(self, self.heartbeat, 10)
@ -112,6 +110,9 @@ class OnionrCommunicatorDaemon:
self.socketServer.start() self.socketServer.start()
self.socketClient = onionrsockets.OnionrSocketClient(self._core) 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 # Main daemon loop, mainly for calling timers, don't do any complex operations here to avoid locking
try: try:
while not self.shutdown: while not self.shutdown:

View File

@ -50,8 +50,12 @@ class Core:
self.dbCreate = dbcreator.DBCreator(self) self.dbCreate = dbcreator.DBCreator(self)
self.forwardKeysFile = 'data/forward-keys.db' self.forwardKeysFile = 'data/forward-keys.db'
# Socket data, defined here because of multithreading constraints with gevent
self.killSockets = False self.killSockets = False
self.startSocket = {} self.startSocket = {}
self.socketServerConnData = {}
self.socketReasons = {}
self.socketServerResponseData = {}
self.usageFile = 'data/disk-usage.txt' self.usageFile = 'data/disk-usage.txt'
self.config = config self.config = config

View File

@ -18,14 +18,23 @@
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
''' '''
import logger, time import logger, time
class OnionrChat:
def __init__(self, communicatorInst, socketID):
self.communicator = communicatorInst
self.socket = self.communicator.sockets[socketID]
while True: class OnionrChat:
time.sleep(2) def __init__(self, communicatorInst):
logger.info('Chat: got %s' % (self.socket.getReadData(),)) '''OnionrChat uses onionrsockets (handled by the communicator) to exchange direct chat messages'''
time.sleep(1) self.communicator = communicatorInst
self.socket.addSendData('rekt') self._core = self.communicator._core
return 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'])

View File

@ -27,12 +27,16 @@ from flask import request, Response, abort
import flask import flask
class OnionrSocketServer: class OnionrSocketServer:
def __init__(self, coreInst): def __init__(self, coreInst):
app = flask.Flask(__name__)
self.sockets = {} # pubkey: tor address
self.connPool = {}
self.bindPort = 1337
self._core = coreInst 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 = {} self.responseData = {}
threading.Thread(target=self.detectShutdown).start() threading.Thread(target=self.detectShutdown).start()
@ -45,15 +49,27 @@ class OnionrSocketServer:
def acceptConn(self): def acceptConn(self):
data = request.form['data'] data = request.form['data']
data = self._core._utils.bytesTorStr(data) data = self._core._utils.bytesTorStr(data)
data = {'date': self._core._utils.getEpoch(), 'data': data}
if request.host in self.connPool: myPeer = ''
self.connPool[request.host].append(data) retData = ''
for peer in self.sockets:
if self.sockets[peer] == request.host:
myPeer = peer
break
else: 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 return retData
@ -66,6 +82,7 @@ class OnionrSocketServer:
else: else:
logger.info('%s socket started with %s' % (self._core.startSocket['reason'], self._core.startSocket['peer'])) logger.info('%s socket started with %s' % (self._core.startSocket['reason'], self._core.startSocket['peer']))
self._core.startSocket = {} self._core.startSocket = {}
time.sleep(1)
def detectShutdown(self): def detectShutdown(self):
while not self._core.killSockets: while not self._core.killSockets:
@ -73,11 +90,11 @@ class OnionrSocketServer:
logger.info('Killing socket server') logger.info('Killing socket server')
self.http_server.stop() self.http_server.stop()
def setResponseData(self, host, data):
self.responseData[host] = data
def addSocket(self, peer, reason=''): def addSocket(self, peer, reason=''):
bindPort = 1337 bindPort = 1337
assert len(reason) <= 12
with stem.control.Controller.from_port(port=config.get('tor.controlPort')) as controller: with stem.control.Controller.from_port(port=config.get('tor.controlPort')) as controller:
controller.authenticate(config.get('tor.controlpassword')) controller.authenticate(config.get('tor.controlpassword'))
@ -86,8 +103,8 @@ class OnionrSocketServer:
self.responseData[socket.service_id] = '' 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 return
class OnionrSocketClient: class OnionrSocketClient:
@ -95,7 +112,6 @@ class OnionrSocketClient:
self.sockets = {} # pubkey: tor address self.sockets = {} # pubkey: tor address
self.connPool = {} self.connPool = {}
self.sendData = {} self.sendData = {}
self.bindPort = 1337
self._core = coreInst self._core = coreInst
self.response = '' self.response = ''
self.request = '' self.request = ''
@ -117,7 +133,7 @@ class OnionrSocketClient:
address = '' address = ''
if address != '': if address != '':
self.sockets[peer] = address self.sockets[peer] = address
data = '' data = 'hey'
while not self.killSocket: while not self.killSocket:
try: try:
data = self.sendData[peer] data = self.sendData[peer]
@ -126,7 +142,7 @@ class OnionrSocketClient:
else: else:
self.sendData[peer] = '' self.sendData[peer] = ''
postData = {'data': data} 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): def getResponse(self, peer):
retData = '' retData = ''

View File

@ -8,3 +8,4 @@ simple_crypt==4.1.7
Flask==1.0.2 Flask==1.0.2
PySocks==1.6.8 PySocks==1.6.8
stem==1.6.0 stem==1.6.0
ntfy==2.6.0