mirror of
https://github.com/trezor/trezor-firmware.git
synced 2024-11-27 01:48:17 +00:00
bridge: refactor after merging old changes
This commit is contained in:
parent
aac7726824
commit
daf97afb37
@ -14,7 +14,6 @@
|
|||||||
# You should have received a copy of the License along with this library.
|
# You should have received a copy of the License along with this library.
|
||||||
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
|
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
|
||||||
|
|
||||||
import binascii
|
|
||||||
import logging
|
import logging
|
||||||
import struct
|
import struct
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
@ -28,10 +27,21 @@ from .. import mapping, protobuf
|
|||||||
LOG = logging.getLogger(__name__)
|
LOG = logging.getLogger(__name__)
|
||||||
|
|
||||||
TREZORD_HOST = "http://127.0.0.1:21325"
|
TREZORD_HOST = "http://127.0.0.1:21325"
|
||||||
|
TREZORD_ORIGIN_HEADER = {"Origin": "https://python.trezor.io"}
|
||||||
|
|
||||||
|
CONNECTION = requests.Session()
|
||||||
|
CONNECTION.headers.update(TREZORD_ORIGIN_HEADER)
|
||||||
|
|
||||||
|
|
||||||
def get_error(resp: requests.Response) -> str:
|
def call_bridge(uri: str, data=None) -> requests.Response:
|
||||||
return " (error=%d str=%s)" % (resp.status_code, resp.json()["error"])
|
url = TREZORD_HOST + "/" + uri
|
||||||
|
r = CONNECTION.post(url, data=data)
|
||||||
|
if r.status_code != 200:
|
||||||
|
error_str = "trezord: {} failed with code {}: {}".format(
|
||||||
|
uri, r.status_code, r.json()["error"]
|
||||||
|
)
|
||||||
|
raise TransportException(error_str)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
class BridgeTransport(Transport):
|
class BridgeTransport(Transport):
|
||||||
@ -40,13 +50,12 @@ class BridgeTransport(Transport):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
PATH_PREFIX = "bridge"
|
PATH_PREFIX = "bridge"
|
||||||
HEADERS = {"Origin": "https://python.trezor.io"}
|
|
||||||
|
|
||||||
def __init__(self, device: Dict[str, Any]) -> None:
|
def __init__(self, device: Dict[str, Any]) -> None:
|
||||||
self.device = device
|
self.device = device
|
||||||
self.conn = requests.Session()
|
|
||||||
self.session = None # type: Optional[str]
|
self.session = None # type: Optional[str]
|
||||||
self.response = None # type: Optional[str]
|
self.request = None # type: Optional[str]
|
||||||
|
self.debug = False
|
||||||
|
|
||||||
def get_path(self) -> str:
|
def get_path(self) -> str:
|
||||||
return "%s:%s" % (self.PATH_PREFIX, self.device["path"])
|
return "%s:%s" % (self.PATH_PREFIX, self.device["path"])
|
||||||
@ -54,39 +63,32 @@ class BridgeTransport(Transport):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def enumerate(cls) -> Iterable["BridgeTransport"]:
|
def enumerate(cls) -> Iterable["BridgeTransport"]:
|
||||||
try:
|
try:
|
||||||
r = requests.post(TREZORD_HOST + "/enumerate", headers=cls.HEADERS)
|
return [BridgeTransport(dev) for dev in call_bridge("enumerate").json()]
|
||||||
if r.status_code != 200:
|
|
||||||
raise TransportException(
|
|
||||||
"trezord: Could not enumerate devices" + get_error(r)
|
|
||||||
)
|
|
||||||
return [BridgeTransport(dev) for dev in r.json()]
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
def _call(self, action: str, data: str = None) -> requests.Response:
|
||||||
|
session = self.session or "null"
|
||||||
|
uri = action + "/" + str(session)
|
||||||
|
return call_bridge(uri, data=data)
|
||||||
|
|
||||||
def begin_session(self) -> None:
|
def begin_session(self) -> None:
|
||||||
r = self.conn.post(
|
LOG.debug("acquiring session from {}".format(self.session))
|
||||||
TREZORD_HOST + "/acquire/%s/null" % self.device["path"],
|
data = self._call("acquire/" + self.device["path"])
|
||||||
headers=self.HEADERS,
|
self.session = data.json()["session"]
|
||||||
)
|
LOG.debug("acquired session {}".format(self.session))
|
||||||
if r.status_code != 200:
|
|
||||||
raise TransportException(
|
|
||||||
"trezord: Could not acquire session" + get_error(r)
|
|
||||||
)
|
|
||||||
self.session = r.json()["session"]
|
|
||||||
|
|
||||||
def end_session(self) -> None:
|
def end_session(self) -> None:
|
||||||
|
LOG.debug("releasing session {}".format(self.session))
|
||||||
if not self.session:
|
if not self.session:
|
||||||
return
|
return
|
||||||
r = self.conn.post(
|
self._call("release")
|
||||||
TREZORD_HOST + "/release/%s" % self.session, headers=self.HEADERS
|
|
||||||
)
|
|
||||||
if r.status_code != 200:
|
|
||||||
raise TransportException(
|
|
||||||
"trezord: Could not release session" + get_error(r)
|
|
||||||
)
|
|
||||||
self.session = None
|
self.session = None
|
||||||
|
|
||||||
def write(self, msg: protobuf.MessageType) -> None:
|
def write(self, msg: protobuf.MessageType) -> None:
|
||||||
|
if self.request is not None:
|
||||||
|
raise TransportException("Cannot enqueue two requests")
|
||||||
|
|
||||||
LOG.debug(
|
LOG.debug(
|
||||||
"sending message: {}".format(msg.__class__.__name__),
|
"sending message: {}".format(msg.__class__.__name__),
|
||||||
extra={"protobuf": msg},
|
extra={"protobuf": msg},
|
||||||
@ -95,28 +97,26 @@ class BridgeTransport(Transport):
|
|||||||
protobuf.dump_message(buffer, msg)
|
protobuf.dump_message(buffer, msg)
|
||||||
ser = buffer.getvalue()
|
ser = buffer.getvalue()
|
||||||
header = struct.pack(">HL", mapping.get_type(msg), len(ser))
|
header = struct.pack(">HL", mapping.get_type(msg), len(ser))
|
||||||
data = binascii.hexlify(header + ser).decode()
|
|
||||||
r = self.conn.post( # type: ignore # typeshed bug
|
self.request = (header + ser).hex()
|
||||||
TREZORD_HOST + "/call/%s" % self.session, data=data, headers=self.HEADERS
|
|
||||||
)
|
|
||||||
if r.status_code != 200:
|
|
||||||
raise TransportException("trezord: Could not write message" + get_error(r))
|
|
||||||
self.response = r.text
|
|
||||||
|
|
||||||
def read(self) -> protobuf.MessageType:
|
def read(self) -> protobuf.MessageType:
|
||||||
if self.response is None:
|
if self.request is None:
|
||||||
raise TransportException("No response stored")
|
raise TransportException("No request stored")
|
||||||
data = binascii.unhexlify(self.response)
|
|
||||||
headerlen = struct.calcsize(">HL")
|
try:
|
||||||
(msg_type, datalen) = struct.unpack(">HL", data[:headerlen])
|
data = bytes.fromhex(self._call("call", data=self.request).text)
|
||||||
buffer = BytesIO(data[headerlen : headerlen + datalen])
|
headerlen = struct.calcsize(">HL")
|
||||||
msg = protobuf.load_message(buffer, mapping.get_class(msg_type))
|
msg_type, datalen = struct.unpack(">HL", data[:headerlen])
|
||||||
LOG.debug(
|
buffer = BytesIO(data[headerlen : headerlen + datalen])
|
||||||
"received message: {}".format(msg.__class__.__name__),
|
msg = protobuf.load_message(buffer, mapping.get_class(msg_type))
|
||||||
extra={"protobuf": msg},
|
LOG.debug(
|
||||||
)
|
"received message: {}".format(msg.__class__.__name__),
|
||||||
self.response = None
|
extra={"protobuf": msg},
|
||||||
return msg
|
)
|
||||||
|
return msg
|
||||||
|
finally:
|
||||||
|
self.request = None
|
||||||
|
|
||||||
|
|
||||||
TRANSPORT = BridgeTransport
|
TRANSPORT = BridgeTransport
|
||||||
|
Loading…
Reference in New Issue
Block a user