2016-05-20 13:27:20 -07:00
|
|
|
from __future__ import print_function
|
|
|
|
|
2014-07-26 07:27:28 -07:00
|
|
|
'''PipeTransport implements fake wire transport over local named pipe.
|
2013-09-12 20:32:27 -07:00
|
|
|
Use this transport for talking with trezor simulator.'''
|
|
|
|
|
|
|
|
import os
|
|
|
|
from select import select
|
2016-05-04 18:16:17 -07:00
|
|
|
from .transport import Transport
|
2013-09-12 20:32:27 -07:00
|
|
|
|
|
|
|
class PipeTransport(Transport):
|
|
|
|
def __init__(self, device, is_device, *args, **kwargs):
|
|
|
|
self.is_device = is_device # Set True if act as device
|
2016-02-10 07:46:58 -08:00
|
|
|
|
|
|
|
super(PipeTransport, self).__init__(device, *args, **kwargs)
|
|
|
|
|
2013-09-12 20:32:27 -07:00
|
|
|
def _open(self):
|
|
|
|
if self.is_device:
|
|
|
|
self.filename_read = self.device+'.to'
|
|
|
|
self.filename_write = self.device+'.from'
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2016-05-04 18:16:17 -07:00
|
|
|
os.mkfifo(self.filename_read, 0o600)
|
|
|
|
os.mkfifo(self.filename_write, 0o600)
|
2013-09-12 20:32:27 -07:00
|
|
|
else:
|
|
|
|
self.filename_read = self.device+'.from'
|
|
|
|
self.filename_write = self.device+'.to'
|
|
|
|
|
|
|
|
if not os.path.exists(self.filename_write):
|
|
|
|
raise Exception("Not connected")
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2013-09-12 20:32:27 -07:00
|
|
|
self.write_fd = os.open(self.filename_write, os.O_RDWR)#|os.O_NONBLOCK)
|
2016-05-04 19:57:14 -07:00
|
|
|
self.write_f = os.fdopen(self.write_fd, 'w+b', 0)
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2013-09-12 20:32:27 -07:00
|
|
|
self.read_fd = os.open(self.filename_read, os.O_RDWR)#|os.O_NONBLOCK)
|
2016-05-04 19:57:14 -07:00
|
|
|
self.read_f = os.fdopen(self.read_fd, 'rb', 0)
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2013-09-12 20:32:27 -07:00
|
|
|
def _close(self):
|
|
|
|
self.read_f.close()
|
|
|
|
self.write_f.close()
|
|
|
|
if self.is_device:
|
|
|
|
os.unlink(self.filename_read)
|
|
|
|
os.unlink(self.filename_write)
|
|
|
|
|
|
|
|
def ready_to_read(self):
|
|
|
|
rlist, _, _ = select([self.read_f], [], [], 0)
|
|
|
|
return len(rlist) > 0
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2014-07-26 07:27:28 -07:00
|
|
|
def _write(self, msg, protobuf_msg):
|
2013-09-12 20:32:27 -07:00
|
|
|
try:
|
|
|
|
self.write_f.write(msg)
|
|
|
|
self.write_f.flush()
|
|
|
|
except OSError:
|
2016-05-04 18:16:17 -07:00
|
|
|
print("Error while writing to socket")
|
2013-09-12 20:32:27 -07:00
|
|
|
raise
|
2016-02-10 07:46:58 -08:00
|
|
|
|
2013-09-12 20:32:27 -07:00
|
|
|
def _read(self):
|
|
|
|
try:
|
|
|
|
(msg_type, datalen) = self._read_headers(self.read_f)
|
|
|
|
return (msg_type, self.read_f.read(datalen))
|
|
|
|
except IOError:
|
2016-05-04 18:16:17 -07:00
|
|
|
print("Failed to read from device")
|
2013-09-12 20:32:27 -07:00
|
|
|
raise
|