basicswap_miserver/basicswap/http_server.py

619 lines
24 KiB
Python
Raw Normal View History

2019-07-17 15:12:06 +00:00
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2024 tecnovert
2019-07-17 15:12:06 +00:00
# Distributed under the MIT software license, see the accompanying
2020-10-30 08:55:45 +00:00
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
2019-07-17 15:12:06 +00:00
import os
2021-11-24 16:28:15 +00:00
import json
2023-02-16 21:44:07 +00:00
import shlex
2019-07-17 15:12:06 +00:00
import traceback
import threading
import http.client
from urllib import parse
2019-07-17 15:12:06 +00:00
from http.server import BaseHTTPRequestHandler, HTTPServer
2019-07-26 10:36:44 +00:00
from jinja2 import Environment, PackageLoader
2019-07-25 20:15:08 +00:00
from . import __version__
2019-07-17 15:12:06 +00:00
from .util import (
dumpj,
2023-02-16 21:44:07 +00:00
toBool,
LockedCoinError,
format_timestamp,
2019-07-17 15:12:06 +00:00
)
from .chainparams import (
Coins,
2022-01-23 12:00:28 +00:00
chainparams,
2019-07-17 15:12:06 +00:00
)
2021-10-18 18:48:48 +00:00
from .basicswap_util import (
2019-07-27 18:51:50 +00:00
strTxState,
2023-02-15 21:51:55 +00:00
strBidState,
2019-07-17 15:12:06 +00:00
)
2022-10-10 21:44:14 +00:00
2020-11-27 22:20:35 +00:00
from .js_server import (
js_error,
js_url_to_function,
2020-11-27 22:20:35 +00:00
)
2022-03-26 22:08:15 +00:00
from .ui.util import (
getCoinName,
2021-01-27 23:55:42 +00:00
get_data_entry,
2023-02-15 21:51:55 +00:00
get_data_entry_or,
listAvailableCoins,
2020-11-30 14:29:40 +00:00
)
2022-05-23 21:51:06 +00:00
from .ui.page_automation import (
page_automation_strategies,
page_automation_strategy,
page_automation_strategy_new,
2022-05-23 21:51:06 +00:00
)
2022-10-10 21:44:14 +00:00
2022-10-05 17:30:52 +00:00
from .ui.page_bids import page_bids, page_bid
from .ui.page_offers import page_offers, page_offer, page_newoffer
2022-10-08 12:37:22 +00:00
from .ui.page_tor import page_tor, get_tor_established_state
2022-10-05 17:30:52 +00:00
from .ui.page_wallet import page_wallets, page_wallet
2022-11-13 21:18:33 +00:00
from .ui.page_settings import page_settings
from .ui.page_encryption import page_changepassword, page_unlock, page_lock
from .ui.page_identity import page_identity
from .ui.page_smsgaddresses import page_smsgaddresses
from .ui.page_debug import page_debug
2019-07-26 10:36:44 +00:00
env = Environment(loader=PackageLoader('basicswap', 'templates'))
2019-07-26 16:07:32 +00:00
env.filters['formatts'] = format_timestamp
2019-07-25 20:15:08 +00:00
2019-07-17 15:12:06 +00:00
def extractDomain(url):
return url.split('://', 1)[1].split('/', 1)[0]
def listAvailableExplorers(swap_client):
explorers = []
for c in Coins:
2021-02-07 10:01:58 +00:00
if c not in chainparams:
continue
for i, e in enumerate(swap_client.coin_clients[c]['explorers']):
2022-10-24 18:49:36 +00:00
explorers.append(('{}_{}'.format(int(c), i), getCoinName(c) + ' - ' + extractDomain(e.base_url)))
return explorers
def listExplorerActions(swap_client):
actions = [('height', 'Chain Height'),
('block', 'Get Block'),
('tx', 'Get Transaction'),
('balance', 'Address Balance'),
('unspent', 'List Unspent')]
return actions
2022-10-11 05:55:35 +00:00
2023-02-16 21:44:07 +00:00
def parse_cmd(cmd: str, type_map: str):
params = shlex.split(cmd)
if len(params) < 1:
return '', []
method = params[0]
typed_params = []
params = params[1:]
for i, param in enumerate(params):
if i >= len(type_map):
type_ind = 's'
else:
type_ind = type_map[i]
if type_ind == 'i':
typed_params.append(int(param))
elif type_ind == 'f':
typed_params.append(float(param))
2023-02-16 21:44:07 +00:00
elif type_ind == 'b':
typed_params.append(toBool(param))
elif type_ind == 'j':
typed_params.append(json.loads(param))
else:
typed_params.append(param)
return method, typed_params
2019-07-17 15:12:06 +00:00
class HttpHandler(BaseHTTPRequestHandler):
2022-10-26 15:54:44 +00:00
def log_error(self, format, *args):
super().log_message(format, *args)
def log_message(self, format, *args):
# TODO: Add debug flag to re-enable.
pass
def generate_form_id(self):
return os.urandom(8).hex()
2019-07-29 10:14:46 +00:00
def checkForm(self, post_string, name, messages):
if post_string == '':
return None
form_data = parse.parse_qs(post_string)
2019-07-29 10:14:46 +00:00
form_id = form_data[b'formid'][0].decode('utf-8')
if self.server.last_form_id.get(name, None) == form_id:
messages.append('Prevented double submit for form {}.'.format(form_id))
return None
self.server.last_form_id[name] = form_id
2019-07-29 10:14:46 +00:00
return form_data
def render_template(self, template, args_dict, status_code=200, version=__version__):
2022-07-31 17:33:01 +00:00
swap_client = self.server.swap_client
if swap_client.ws_server:
args_dict['ws_url'] = swap_client.ws_server.url
if swap_client.debug:
args_dict['debug_mode'] = True
if swap_client.debug_ui:
args_dict['debug_ui_mode'] = True
2022-10-08 12:37:22 +00:00
if swap_client.use_tor_proxy:
args_dict['use_tor_proxy'] = True
# TODO: Cache value?
try:
args_dict['tor_established'] = True if get_tor_established_state(swap_client) == '1' else False
except Exception:
if swap_client.debug:
swap_client.log.error(traceback.format_exc())
2022-10-13 20:21:43 +00:00
if swap_client._show_notifications:
args_dict['notifications'] = swap_client.getNotifications()
2022-10-14 12:22:11 +00:00
if 'messages' in args_dict:
messages_with_ids = []
for msg in args_dict['messages']:
messages_with_ids.append((self.server.msg_id_counter, msg))
self.server.msg_id_counter += 1
args_dict['messages'] = messages_with_ids
2022-10-14 12:22:11 +00:00
if 'err_messages' in args_dict:
err_messages_with_ids = []
for msg in args_dict['err_messages']:
err_messages_with_ids.append((self.server.msg_id_counter, msg))
self.server.msg_id_counter += 1
args_dict['err_messages'] = err_messages_with_ids
2022-10-14 12:22:11 +00:00
2022-11-14 20:56:30 +00:00
shutdown_token = os.urandom(8).hex()
self.server.session_tokens['shutdown'] = shutdown_token
args_dict['shutdown_token'] = shutdown_token
2022-11-18 21:31:52 +00:00
encrypted, locked = swap_client.getLockedState()
args_dict['encrypted'] = encrypted
args_dict['locked'] = locked
2022-10-14 12:22:11 +00:00
if self.server.msg_id_counter >= 0x7FFFFFFF:
self.server.msg_id_counter = 0
args_dict['version'] = version
2022-10-24 18:49:36 +00:00
self.putHeaders(status_code, 'text/html')
2022-07-31 17:33:01 +00:00
return bytes(template.render(
title=self.server.title,
h2=self.server.title,
form_id=self.generate_form_id(),
2022-07-31 17:33:01 +00:00
**args_dict,
), 'UTF-8')
def render_simple_template(self, template, args_dict):
swap_client = self.server.swap_client
return bytes(template.render(
title=self.server.title,
**args_dict,
), 'UTF-8')
def page_info(self, info_str, post_string=None):
template = env.get_template('info.html')
2022-10-10 21:44:14 +00:00
swap_client = self.server.swap_client
summary = swap_client.getSummary()
return self.render_template(template, {
'title_str': 'BasicSwap Info',
'message_str': info_str,
2022-10-10 21:44:14 +00:00
'summary': summary,
})
def page_error(self, error_str, post_string=None):
template = env.get_template('error.html')
2022-10-10 21:44:14 +00:00
swap_client = self.server.swap_client
summary = swap_client.getSummary()
return self.render_template(template, {
'title_str': 'BasicSwap Error',
'message_str': error_str,
2022-10-10 21:44:14 +00:00
'summary': summary,
})
def page_explorers(self, url_split, post_string):
swap_client = self.server.swap_client
swap_client.checkSystemStatus()
2022-10-10 21:44:14 +00:00
summary = swap_client.getSummary()
result = None
explorer = -1
action = -1
messages = []
err_messages = []
form_data = self.checkForm(post_string, 'explorers', err_messages)
if form_data:
explorer = form_data[b'explorer'][0].decode('utf-8')
action = form_data[b'action'][0].decode('utf-8')
2019-08-05 22:04:40 +00:00
args = '' if b'args' not in form_data else form_data[b'args'][0].decode('utf-8')
try:
c, e = explorer.split('_')
exp = swap_client.coin_clients[Coins(int(c))]['explorers'][int(e)]
if action == 'height':
result = str(exp.getChainHeight())
elif action == 'block':
result = dumpj(exp.getBlock(args))
elif action == 'tx':
result = dumpj(exp.getTransaction(args))
elif action == 'balance':
result = dumpj(exp.getBalance(args))
elif action == 'unspent':
result = dumpj(exp.lookupUnspentByAddress(args))
else:
result = 'Unknown action'
except Exception as ex:
result = str(ex)
template = env.get_template('explorers.html')
2022-07-31 17:33:01 +00:00
return self.render_template(template, {
'messages': messages,
'err_messages': err_messages,
2022-07-31 17:33:01 +00:00
'explorers': listAvailableExplorers(swap_client),
'explorer': explorer,
'actions': listExplorerActions(swap_client),
'action': action,
2022-10-10 21:44:14 +00:00
'result': result,
'summary': summary,
2022-07-31 17:33:01 +00:00
})
2019-07-27 21:14:28 +00:00
def page_rpc(self, url_split, post_string):
swap_client = self.server.swap_client
swap_client.checkSystemStatus()
2022-10-10 21:44:14 +00:00
summary = swap_client.getSummary()
2019-07-27 21:14:28 +00:00
result = None
cmd = ''
coin_type = -1
2022-07-06 11:16:18 +00:00
coin_id = -1
2023-02-16 21:44:07 +00:00
call_type = 'cli'
type_map = ''
2019-07-27 21:14:28 +00:00
messages = []
err_messages = []
form_data = self.checkForm(post_string, 'rpc', err_messages)
2019-07-29 10:14:46 +00:00
if form_data:
try:
2023-02-16 21:44:07 +00:00
call_type = get_data_entry_or(form_data, 'call_type', 'cli')
type_map = get_data_entry_or(form_data, 'type_map', '')
try:
coin_id = int(get_data_entry(form_data, 'coin_type'))
if coin_id in (-2, -3, -4):
coin_type = Coins(Coins.XMR)
2023-12-29 13:36:00 +00:00
elif coin_id in (-5,):
coin_type = Coins(Coins.LTC)
elif coin_id in (-6,):
coin_type = Coins(Coins.DCR)
2023-02-16 21:44:07 +00:00
else:
coin_type = Coins(coin_id)
except Exception:
raise ValueError('Unknown Coin Type')
if coin_type in (Coins.DCR,):
call_type = 'http'
2023-02-16 21:44:07 +00:00
try:
cmd = get_data_entry(form_data, 'cmd')
except Exception:
raise ValueError('Invalid command')
2021-11-24 16:28:15 +00:00
if coin_type == Coins.XMR:
ci = swap_client.ci(coin_type)
arr = cmd.split(None, 1)
method = arr[0]
params = json.loads(arr[1]) if len(arr) > 1 else []
2022-07-06 11:16:18 +00:00
if coin_id == -4:
2023-12-29 13:36:00 +00:00
rv = ci.rpc_wallet(method, params)
2022-07-06 11:16:18 +00:00
elif coin_id == -3:
2023-12-29 13:36:00 +00:00
rv = ci.rpc(method, params)
2022-07-06 11:16:18 +00:00
elif coin_id == -2:
if params == []:
params = None
2023-12-29 13:36:00 +00:00
rv = ci.rpc2(method, params)
2022-07-06 11:16:18 +00:00
else:
raise ValueError('Unknown XMR RPC variant')
result = json.dumps(rv, indent=4)
2021-11-24 16:28:15 +00:00
else:
2023-02-16 21:44:07 +00:00
if call_type == 'http':
ci = swap_client.ci(coin_type)
2023-02-16 21:44:07 +00:00
method, params = parse_cmd(cmd, type_map)
if coin_id == -6:
rv = ci.rpc_wallet(method, params)
elif coin_id == -5:
rv = ci.rpc_wallet_mweb(method, params)
2023-12-29 13:36:00 +00:00
else:
if coin_type in (Coins.DCR, ):
rv = ci.rpc(method, params)
else:
rv = ci.rpc_wallet(method, params)
2023-08-11 22:01:04 +00:00
if not isinstance(rv, str):
rv = json.dumps(rv, indent=4)
result = cmd + '\n' + rv
2023-02-16 21:44:07 +00:00
else:
result = cmd + '\n' + swap_client.callcoincli(coin_type, cmd)
2019-07-29 10:14:46 +00:00
except Exception as ex:
result = cmd + '\n' + str(ex)
2022-07-06 11:16:18 +00:00
if self.server.swap_client.debug is True:
self.server.swap_client.log.error(traceback.format_exc())
2019-07-27 21:14:28 +00:00
template = env.get_template('rpc.html')
2022-07-06 11:16:18 +00:00
coins = listAvailableCoins(swap_client, with_variants=False)
with_xmr: bool = any(c[0] == Coins.XMR for c in coins)
2022-07-06 11:16:18 +00:00
coins = [c for c in coins if c[0] != Coins.XMR]
if any(c[0] == Coins.DCR for c in coins):
coins.append((-6, 'Decred Wallet'))
if any(c[0] == Coins.LTC for c in coins):
coins.append((-5, 'Litecoin MWEB Wallet'))
if with_xmr:
coins.append((-2, 'Monero'))
coins.append((-3, 'Monero JSON'))
coins.append((-4, 'Monero Wallet'))
2022-07-06 11:16:18 +00:00
2022-07-31 17:33:01 +00:00
return self.render_template(template, {
'messages': messages,
'err_messages': err_messages,
2022-07-31 17:33:01 +00:00
'coins': coins,
'coin_type': coin_id,
2023-02-16 21:44:07 +00:00
'call_type': call_type,
2022-07-31 17:33:01 +00:00
'result': result,
'messages': messages,
2022-10-10 21:44:14 +00:00
'summary': summary,
2022-07-31 17:33:01 +00:00
})
2019-07-17 15:12:06 +00:00
def page_active(self, url_split, post_string):
swap_client = self.server.swap_client
swap_client.checkSystemStatus()
2019-07-17 15:12:06 +00:00
active_swaps = swap_client.listSwapsInProgress()
2022-10-10 21:44:14 +00:00
summary = swap_client.getSummary()
2019-07-17 15:12:06 +00:00
2019-07-25 21:30:27 +00:00
template = env.get_template('active.html')
2022-07-31 17:33:01 +00:00
return self.render_template(template, {
'refresh': 30,
'active_swaps': [(s[0].hex(), s[1], strBidState(s[2]), strTxState(s[3]), strTxState(s[4])) for s in active_swaps],
2022-10-10 21:44:14 +00:00
'summary': summary,
2022-07-31 17:33:01 +00:00
})
2019-07-17 15:12:06 +00:00
def page_watched(self, url_split, post_string):
swap_client = self.server.swap_client
swap_client.checkSystemStatus()
2019-07-17 15:12:06 +00:00
watched_outputs, last_scanned = swap_client.listWatchedOutputs()
2022-10-10 21:44:14 +00:00
summary = swap_client.getSummary()
2019-07-25 21:30:27 +00:00
template = env.get_template('watched.html')
2022-07-31 17:33:01 +00:00
return self.render_template(template, {
'refresh': 30,
'last_scanned': [(getCoinName(ls[0]), ls[1]) for ls in last_scanned],
'watched_outputs': [(wo[1].hex(), getCoinName(wo[0]), wo[2], wo[3], int(wo[4])) for wo in watched_outputs],
2022-10-10 21:44:14 +00:00
'summary': summary,
2022-07-31 17:33:01 +00:00
})
2019-07-17 15:12:06 +00:00
def page_shutdown(self, url_split, post_string):
swap_client = self.server.swap_client
2021-11-22 20:24:48 +00:00
if len(url_split) > 2:
token = url_split[2]
expect_token = self.server.session_tokens.get('shutdown', None)
if token != expect_token:
return self.page_info('Unexpected token, still running.')
swap_client.stopRunning()
return self.page_info('Shutting down')
2019-07-17 15:12:06 +00:00
def page_index(self, url_split):
swap_client = self.server.swap_client
swap_client.checkSystemStatus()
2019-07-17 15:12:06 +00:00
summary = swap_client.getSummary()
2019-07-25 20:15:08 +00:00
template = env.get_template('index.html')
2022-07-31 17:33:01 +00:00
return self.render_template(template, {
'refresh': 30,
'summary': summary,
2022-11-14 20:56:30 +00:00
'use_tor_proxy': swap_client.use_tor_proxy
2022-07-31 17:33:01 +00:00
})
2019-07-17 15:12:06 +00:00
2021-01-02 16:16:44 +00:00
def page_404(self, url_split):
2022-10-11 09:38:20 +00:00
swap_client = self.server.swap_client
summary = swap_client.getSummary()
2021-01-02 16:16:44 +00:00
template = env.get_template('404.html')
2022-10-11 09:38:20 +00:00
return self.render_template(template, {
'summary': summary,
})
2021-01-02 16:16:44 +00:00
2019-07-17 15:12:06 +00:00
def putHeaders(self, status_code, content_type):
self.send_response(status_code)
if self.server.allow_cors:
self.send_header('Access-Control-Allow-Origin', '*')
2021-01-27 23:55:42 +00:00
self.send_header('Content-Type', content_type)
2019-07-17 15:12:06 +00:00
self.end_headers()
2021-01-27 23:55:42 +00:00
def handle_http(self, status_code, path, post_string='', is_json=False):
swap_client = self.server.swap_client
parsed = parse.urlparse(self.path)
url_split = parsed.path.split('/')
if post_string == '' and len(parsed.query) > 0:
post_string = parsed.query
2019-07-17 15:12:06 +00:00
if len(url_split) > 1 and url_split[1] == 'json':
try:
self.putHeaders(status_code, 'text/plain')
func = js_url_to_function(url_split)
2021-01-27 23:55:42 +00:00
return func(self, url_split, post_string, is_json)
2019-07-27 17:26:06 +00:00
except Exception as ex:
if swap_client.debug is True:
swap_client.log.error(traceback.format_exc())
2020-11-27 22:20:35 +00:00
return js_error(self, str(ex))
2021-01-02 16:16:44 +00:00
if len(url_split) > 1 and url_split[1] == 'static':
try:
static_path = os.path.join(os.path.dirname(__file__), 'static')
2022-07-30 17:00:53 +00:00
if len(url_split) > 3 and url_split[2] == 'sequence_diagrams':
with open(os.path.join(static_path, 'sequence_diagrams', url_split[3]), 'rb') as fp:
self.putHeaders(status_code, 'image/svg+xml')
2021-01-02 16:16:44 +00:00
return fp.read()
2022-07-30 17:00:53 +00:00
elif len(url_split) > 3 and url_split[2] == 'images':
filename = os.path.join(*url_split[3:])
_, extension = os.path.splitext(filename)
2022-07-31 17:33:01 +00:00
mime_type = {
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
2022-10-10 21:44:14 +00:00
'.gif': 'image/gif',
'.ico': 'image/x-icon',
2022-07-31 17:33:01 +00:00
}.get(extension, '')
2022-07-30 17:00:53 +00:00
if mime_type == '':
raise ValueError('Unknown file type ' + filename)
with open(os.path.join(static_path, 'images', filename), 'rb') as fp:
self.putHeaders(status_code, mime_type)
2021-01-02 16:16:44 +00:00
return fp.read()
2022-07-30 17:00:53 +00:00
elif len(url_split) > 3 and url_split[2] == 'css':
filename = os.path.join(*url_split[3:])
with open(os.path.join(static_path, 'css', filename), 'rb') as fp:
self.putHeaders(status_code, 'text/css; charset=utf-8')
2022-06-28 23:45:06 +00:00
return fp.read()
2022-07-31 21:40:58 +00:00
elif len(url_split) > 3 and url_split[2] == 'js':
filename = os.path.join(*url_split[3:])
with open(os.path.join(static_path, 'js', filename), 'rb') as fp:
self.putHeaders(status_code, 'application/javascript')
return fp.read()
2021-01-02 16:16:44 +00:00
else:
return self.page_404(url_split)
2022-07-30 17:00:53 +00:00
except FileNotFoundError:
return self.page_404(url_split)
except Exception as ex:
if swap_client.debug is True:
swap_client.log.error(traceback.format_exc())
2021-01-02 16:16:44 +00:00
return self.page_error(str(ex))
2019-07-17 15:12:06 +00:00
try:
if len(url_split) > 1:
2022-07-31 17:33:01 +00:00
page = url_split[1]
2022-07-31 17:33:01 +00:00
if page == 'active':
2019-07-17 15:12:06 +00:00
return self.page_active(url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'wallets':
return page_wallets(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'wallet':
return page_wallet(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'settings':
2022-11-13 21:18:33 +00:00
return page_settings(self, url_split, post_string)
2022-10-10 21:44:14 +00:00
if page == 'error':
return self.page_error(url_split, post_string)
if page == 'info':
return self.page_info(url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'rpc':
2019-07-27 21:14:28 +00:00
return self.page_rpc(url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'debug':
return page_debug(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'explorers':
return self.page_explorers(url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'offer':
return page_offer(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'offers':
return page_offers(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'newoffer':
return page_newoffer(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'sentoffers':
return page_offers(self, url_split, post_string, sent=True)
2022-07-31 17:33:01 +00:00
if page == 'bid':
2022-10-05 17:30:52 +00:00
return page_bid(self, url_split, post_string)
2022-10-10 21:44:14 +00:00
if page == 'receivedbids':
return page_bids(self, url_split, post_string, received=True)
2022-07-31 17:33:01 +00:00
if page == 'sentbids':
2022-10-05 17:30:52 +00:00
return page_bids(self, url_split, post_string, sent=True)
2022-07-31 17:33:01 +00:00
if page == 'availablebids':
2022-10-05 17:30:52 +00:00
return page_bids(self, url_split, post_string, available=True)
2022-07-31 17:33:01 +00:00
if page == 'watched':
2019-07-17 15:12:06 +00:00
return self.page_watched(url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'smsgaddresses':
return page_smsgaddresses(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'identity':
return page_identity(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'tor':
2022-03-26 22:08:15 +00:00
return page_tor(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'automation':
2022-05-23 21:51:06 +00:00
return page_automation_strategies(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'automationstrategy':
2022-05-23 21:51:06 +00:00
return page_automation_strategy(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'newautomationstrategy':
2022-05-23 21:51:06 +00:00
return page_automation_strategy_new(self, url_split, post_string)
2022-07-31 17:33:01 +00:00
if page == 'shutdown':
return self.page_shutdown(url_split, post_string)
if page == 'changepassword':
return page_changepassword(self, url_split, post_string)
if page == 'unlock':
return page_unlock(self, url_split, post_string)
if page == 'lock':
return page_lock(self, url_split, post_string)
if page != '':
return self.page_404(url_split)
2019-07-17 15:12:06 +00:00
return self.page_index(url_split)
except LockedCoinError:
return page_unlock(self, url_split, post_string)
2019-07-27 17:26:06 +00:00
except Exception as ex:
if swap_client.debug is True:
swap_client.log.error(traceback.format_exc())
2019-07-27 17:26:06 +00:00
return self.page_error(str(ex))
2019-07-17 15:12:06 +00:00
def do_GET(self):
response = self.handle_http(200, self.path)
self.wfile.write(response)
def do_POST(self):
2021-01-27 23:55:42 +00:00
post_string = self.rfile.read(int(self.headers.get('Content-Length')))
is_json = True if 'json' in self.headers.get('Content-Type', '') else False
response = self.handle_http(200, self.path, post_string, is_json)
2019-07-17 15:12:06 +00:00
self.wfile.write(response)
def do_HEAD(self):
self.putHeaders(200, 'text/html')
def do_OPTIONS(self):
self.send_response(200, 'ok')
if self.server.allow_cors:
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', '*')
self.end_headers()
class HttpThread(threading.Thread, HTTPServer):
def __init__(self, fp, host_name, port_no, allow_cors, swap_client):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
self.fp = fp
self.host_name = host_name
self.port_no = port_no
self.allow_cors = allow_cors
self.swap_client = swap_client
2022-10-10 21:44:14 +00:00
self.title = 'BasicSwap - ' + __version__
2019-07-17 15:12:06 +00:00
self.last_form_id = dict()
2021-11-22 20:24:48 +00:00
self.session_tokens = dict()
2022-03-26 22:08:15 +00:00
self.env = env
2022-10-14 12:22:11 +00:00
self.msg_id_counter = 0
2019-07-17 15:12:06 +00:00
self.timeout = 60
HTTPServer.__init__(self, (self.host_name, self.port_no), HttpHandler)
def stop(self):
self.stop_event.set()
# Send fake request
conn = http.client.HTTPConnection(self.host_name, self.port_no)
conn.connect()
conn.request('GET', '/none')
response = conn.getresponse()
data = response.read()
conn.close()
def serve_forever(self):
2023-02-14 21:34:01 +00:00
while not self.stop_event.is_set():
2019-07-17 15:12:06 +00:00
self.handle_request()
self.socket.close()
def run(self):
self.serve_forever()