1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
from __future__ import absolute_import
from __future__ import division
import glob
import platform
import sys
import time
import serial
from pwnlib.log import getLogger
from pwnlib.tubes import tube
log = getLogger(__name__)
class serialtube(tube.tube):
def __init__(
self, port = None, baudrate = 115200,
convert_newlines = True,
bytesize = 8, parity='N', stopbits=1, xonxoff = False,
rtscts = False, dsrdtr = False, *a, **kw):
super(serialtube, self).__init__(*a, **kw)
if port is None:
if platform.system() == 'Darwin':
port = glob.glob('/dev/tty.usbserial*')[0]
else:
port = '/dev/ttyUSB0'
self.convert_newlines = convert_newlines
# serial.Serial might throw an exception, which must be handled
# and propagated accordingly using self.exception
try:
self.conn = serial.Serial(
port = port,
baudrate = baudrate,
bytesize = bytesize,
parity = parity,
stopbits = stopbits,
timeout = 0,
xonxoff = xonxoff,
rtscts = rtscts,
writeTimeout = None,
dsrdtr = dsrdtr,
interCharTimeout = 0
)
except serial.SerialException:
# self.conn is set to None to avoid an AttributeError when
# initialization fails, but the program still tries closing
# the serial tube anyway
self.conn = None
self.exception("Could not open a serial tube on port %s", port)
# Implementation of the methods required for tube
def recv_raw(self, numb):
if not self.conn:
raise EOFError
with self.countdown():
while self.conn and self.countdown_active():
data = self.conn.read(numb)
if data:
return data
time.sleep(min(self.timeout, 0.1))
return None
def send_raw(self, data):
if not self.conn:
raise EOFError
if self.convert_newlines:
data = data.replace(b'\n', b'\r\n')
while data:
n = self.conn.write(data)
data = data[n:]
self.conn.flush()
def settimeout_raw(self, timeout):
pass
def can_recv_raw(self, timeout):
with self.countdown(timeout):
while self.conn and self.countdown_active():
if self.conn.inWaiting():
return True
time.sleep(min(self.timeout, 0.1))
return False
def connected_raw(self, direction):
return self.conn is not None
def close(self):
if self.conn:
self.conn.close()
self.conn = None
def fileno(self):
if not self.connected():
self.error("A closed serialtube does not have a file number")
return self.conn.fileno()
def shutdown_raw(self, direction):
self.close()
|