Onionr/onionr/api.py

149 lines
5.2 KiB
Python
Raw Normal View History

2017-12-26 07:25:29 +00:00
'''
2018-11-04 16:06:24 +00:00
Onionr - P2P Anonymous Storage Network
This file handles all incoming http requests to the client, using Flask
'''
'''
2017-12-26 07:25:29 +00:00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
2017-12-27 05:00:02 +00:00
import flask
from flask import request, Response, abort, send_from_directory
from gevent.pywsgi import WSGIServer
2018-08-04 03:47:56 +00:00
import sys, random, threading, hmac, hashlib, base64, time, math, os, json
2018-10-27 03:29:25 +00:00
import core
2018-05-19 22:11:51 +00:00
from onionrblockapi import Block
import onionrutils, onionrexceptions, onionrcrypto, blockimporter, onionrevents as events, logger, config, onionr
2018-05-19 22:11:51 +00:00
2018-12-18 23:48:17 +00:00
def guessMime(path):
'''
2018-12-18 23:48:17 +00:00
Guesses the mime type from the input filename
'''
2018-12-18 23:48:17 +00:00
mimetypes = {
'html' : 'text/html',
'js' : 'application/javascript',
'css' : 'text/css',
'png' : 'image/png',
'jpg' : 'image/jpeg'
}
for mimetype in mimetypes:
if path.endswith('.%s' % mimetype):
return mimetypes[mimetype]
return 'text/plain'
def setBindIP(filePath):
'''Set a random localhost IP to a specified file (intended for private or public API localhost IPs)'''
hostOctets = [str(127), str(random.randint(0x02, 0xFF)), str(random.randint(0x02, 0xFF)), str(random.randint(0x02, 0xFF))]
data = '.'.join(hostOctets)
with open(filePath, 'w') as bindFile:
bindFile.write(data)
return data
class PublicAPI:
'''
The new client api server, isolated from the public api
'''
def __init__(self, clientAPI):
assert isinstance(clientAPI, API)
app = flask.Flask('PublicAPI')
self.i2pEnabled = config.get('i2p.host', False)
self.hideBlocks = [] # Blocks to be denied sharing
self.host = setBindIP(clientAPI._core.publicApiHostFile)
bindPort = config.get('client.public.port')
2018-07-30 00:37:12 +00:00
2018-12-18 23:48:17 +00:00
@app.route('/')
def banner():
#validateHost('public')
try:
with open('static-data/index.html', 'r') as html:
resp = Response(html.read(), mimetype='text/html')
except FileNotFoundError:
resp = Response("")
return resp
clientAPI.setPublicAPIInstance(self)
self.httpServer = WSGIServer((self.host, bindPort), app, log=None)
self.httpServer.serve_forever()
2018-08-04 02:52:45 +00:00
2018-12-18 23:48:17 +00:00
class API:
'''
Client HTTP api
'''
2018-08-04 02:52:45 +00:00
2018-12-18 23:48:17 +00:00
callbacks = {'public' : {}, 'private' : {}}
2018-08-04 02:52:45 +00:00
2018-10-27 03:29:25 +00:00
def __init__(self, debug, API_VERSION):
'''
Initialize the api server, preping variables for later use
This initilization defines all of the API entry points and handlers for the endpoints and errors
This also saves the used host (random localhost IP address) to the data folder in host.txt
'''
2018-02-23 01:58:36 +00:00
# configure logger and stuff
onionr.Onionr.setupConfig('data/', self = self)
2018-01-26 07:22:48 +00:00
2017-12-27 05:00:02 +00:00
self.debug = debug
self._privateDelayTime = 3
2018-10-27 03:29:25 +00:00
self._core = core.Core()
2018-02-07 09:04:58 +00:00
self._crypto = onionrcrypto.OnionrCrypto(self._core)
2018-01-26 06:28:11 +00:00
self._utils = onionrutils.OnionrUtils(self._core)
2017-12-27 05:00:02 +00:00
app = flask.Flask(__name__)
2018-12-18 23:48:17 +00:00
bindPort = int(config.get('client.client.port', 59496))
self.bindPort = bindPort
2018-12-18 23:48:17 +00:00
2018-12-09 17:29:39 +00:00
self.clientToken = config.get('client.webpassword')
self.timeBypassToken = base64.b16encode(os.urandom(32)).decode()
2018-12-18 23:48:17 +00:00
self.publicAPI = None # gets set when the thread calls our setter... bad hack but kinda necessary with flask
threading.Thread(target=PublicAPI, args=(self,)).start()
self.host = setBindIP(self._core.privateApiHostFile)
logger.info('Running api on %s:%s' % (self.host, self.bindPort))
self.httpServer = ''
2018-05-02 06:50:29 +00:00
2018-04-25 06:56:40 +00:00
@app.route('/')
2018-12-18 23:48:17 +00:00
def hello():
return Response("hello client")
@app.route('/shutdown')
def shutdown():
try:
2018-12-18 23:48:17 +00:00
self.publicAPI.httpServer.stop()
self.httpServer.stop()
except AttributeError:
pass
2018-12-18 23:48:17 +00:00
return Response("bye")
self.httpServer = WSGIServer((self.host, bindPort), app, log=None)
self.httpServer.serve_forever()
def setPublicAPIInstance(self, inst):
assert isinstance(inst, PublicAPI)
self.publicAPI = inst
2018-12-18 23:48:17 +00:00
def validateToken(self, token):
2018-12-09 17:29:39 +00:00
'''
2018-12-18 23:48:17 +00:00
Validate that the client token matches the given token
2018-12-09 17:29:39 +00:00
'''
2018-12-18 23:48:17 +00:00
if len(self.clientToken) == 0:
logger.error("client password needs to be set")
2018-07-30 00:37:12 +00:00
return False
2018-12-18 23:48:17 +00:00
try:
if not hmac.compare_digest(self.clientToken, token):
return False
else:
return True
except TypeError:
return False