Onionr/src/apiservers/private/__init__.py

119 lines
4.1 KiB
Python
Raw Normal View History

"""Onionr - Private P2P Communication.
This file handles all incoming http requests to the client, using Flask
"""
from typing import Dict
import hmac
import flask
from gevent.pywsgi import WSGIServer
from onionrutils import epoch
import httpapi
from filepaths import private_API_host_file
import logger
from etc import waitforsetvar
from . import register_private_blueprints
import config
2022-01-11 07:20:15 +00:00
"""
2022-01-11 07:20:15 +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/>.
"""
2019-07-12 07:07:30 +00:00
class PrivateAPI:
"""Client HTTP api for controlling onionr and using UI."""
callbacks: Dict[str, Dict] = {'public': {}, 'private': {}}
2018-12-09 17:29:39 +00:00
2019-08-02 23:00:04 +00:00
def __init__(self):
"""Initialize the api server, preping variables for later use.
This initialization 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
"""
2019-07-12 07:07:30 +00:00
self.config = config
self.startTime = epoch.get_epoch()
2019-01-08 05:51:39 +00:00
app = flask.Flask(__name__)
2022-01-11 07:20:15 +00:00
bind_port = int(config.get('client.client.port', 59496))
self.bindPort = bind_port
2019-01-08 05:51:39 +00:00
self.clientToken = config.get('client.webpassword')
if config.get('general.bind_address'):
with open(private_API_host_file, 'w') as bindFile:
bindFile.write(config.get('general.bind_address'))
self.host = config.get('general.bind_address')
else:
self.host = httpapi.apiutils.setbindip.set_bind_IP(
private_API_host_file)
2019-01-08 05:51:39 +00:00
logger.info('Running api on %s:%s' % (self.host, self.bindPort))
self.httpServer = ''
self.queueResponse = {}
2019-07-12 22:31:11 +00:00
self.get_block_data = httpapi.apiutils.GetBlockData(self)
register_private_blueprints.register_private_blueprints(self, app)
2019-07-12 22:31:11 +00:00
httpapi.load_plugin_blueprints(app)
2019-08-04 04:52:57 +00:00
self.app = app
2019-08-04 04:52:57 +00:00
def start(self):
"""Start client gevent API web server with flask client app."""
2019-08-04 04:52:57 +00:00
waitforsetvar.wait_for_set_var(self, "_too_many")
fd_handler = httpapi.fdsafehandler.FDSafeHandler
2022-01-11 07:20:15 +00:00
self.httpServer = WSGIServer((self.host, self.bindPort),
self.app, log=None,
handler_class=fd_handler)
2019-01-08 05:51:39 +00:00
self.httpServer.serve_forever()
2018-07-30 00:37:12 +00:00
2019-01-08 05:51:39 +00:00
def setPublicAPIInstance(self, inst):
"""Dynamically set public API instance."""
2019-01-08 05:51:39 +00:00
self.publicAPI = inst
2018-07-30 00:37:12 +00:00
2019-01-08 05:51:39 +00:00
def validateToken(self, token):
"""Validate that the client token matches the given token.
Used to prevent CSRF and other attacks.
"""
2019-08-07 22:46:57 +00:00
if not self.clientToken:
2019-01-08 05:51:39 +00:00
logger.error("client password needs to be set")
return False
try:
2019-11-27 04:11:08 +00:00
return hmac.compare_digest(self.clientToken, token)
2019-01-08 05:51:39 +00:00
except TypeError:
return False
def getUptime(self) -> int:
"""Safely wait for uptime to be set and return it."""
2019-01-28 22:49:04 +00:00
while True:
try:
return epoch.get_epoch() - self.startTime
except (AttributeError, NameError):
2019-01-28 22:49:04 +00:00
# Don't error on race condition with startup
pass
def getBlockData(self, bHash, decrypt=False, raw=False,
headerOnly=False) -> bytes:
"""Returns block data bytes."""
return self.get_block_data.get_block_data(bHash,
decrypt=decrypt,
raw=raw,
headerOnly=headerOnly)