blob: d384146a6c1d5d108f8a2894d3991a900a659acf [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4""" pySim: Transport Link for serial (RS232) based readers included with simcard
5"""
6
7#
8# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22#
23
24from __future__ import absolute_import
25
26import serial
27import time
28
29from pySim.exceptions import NoCardError, ProtocolError
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010030from pySim.transport import LinkBase
Sylvain Munaut76504e02010-12-07 00:24:32 +010031from pySim.utils import h2b, b2h
32
33
Sylvain Munaute7c15cd2010-12-07 10:01:55 +010034class SerialSimLink(LinkBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +010035
36 def __init__(self, device='/dev/ttyUSB0', baudrate=9600, rst='-rts', debug=False):
37 self._sl = serial.Serial(
38 port = device,
39 parity = serial.PARITY_EVEN,
40 bytesize = serial.EIGHTBITS,
41 stopbits = serial.STOPBITS_TWO,
42 timeout = 1,
43 xonxoff = 0,
44 rtscts = 0,
45 baudrate = baudrate,
46 )
47 self._rst_pin = rst
48 self._debug = debug
49
50 rv = self.reset_card()
51 if rv == 0:
52 raise NoCardError()
53 elif rv < 0:
54 raise ProtocolError()
55
56 def __del__(self):
57 self._sl.close()
58
59 def reset_card(self):
60 rst_meth_map = {
61 'rts': self._sl.setRTS,
62 'dtr': self._sl.setDTR,
63 }
64 rst_val_map = { '+':0, '-':1 }
65
66 try:
67 rst_meth = rst_meth_map[self._rst_pin[1:]]
68 rst_val = rst_val_map[self._rst_pin[0]]
69 except:
70 raise ValueError('Invalid reset pin %s' % self._rst_pin);
71
72 rst_meth(rst_val)
73 time.sleep(0.1) # 100 ms
74 self._sl.flushInput()
75 rst_meth(rst_val ^ 1)
76
77 b = self._rx_byte()
78 if not b:
79 return 0
80 if ord(b) != 0x3b:
81 return -1;
82 self._dbg_print("TS: 0x%x Direct convention" % ord(b))
83
84 while ord(b) == 0x3b:
85 b = self._rx_byte()
86
87 if not b:
88 return -1
89 t0 = ord(b)
90 self._dbg_print("T0: 0x%x" % t0)
91
92 for i in range(4):
93 if t0 & (0x10 << i):
94 self._dbg_print("T%si = %x" % (chr(ord('A')+i), ord(self._rx_byte())))
95
96 for i in range(0, t0 & 0xf):
97 self._dbg_print("Historical = %x" % ord(self._rx_byte()))
98
99 while True:
100 x = self._rx_byte()
101 if not x:
102 break
103 self._dbg_print("Extra: %x" % ord(x))
104
105 return 1
106
107 def _dbg_print(self, s):
108 if self._debug:
109 print s
110
111 def _tx_byte(self, b):
112 self._sl.write(b)
113 r = self._sl.read()
114 if r != b: # TX and RX are tied, so we must clear the echo
115 raise ProtocolError("Bad echo value. Expected %02x, got %s)" % (ord(b), '%02x'%ord(r) if r else '(nil)'))
116
117 def _tx_string(self, s):
118 """This is only safe if it's guaranteed the card won't send any data
119 during the time of tx of the string !!!"""
120 self._sl.write(s)
121 r = self._sl.read(len(s))
122 if r != s: # TX and RX are tied, so we must clear the echo
123 raise ProtocolError("Bad echo value (Expected: %s, got %s)" % (b2h(s), b2h(r)))
124
125 def _rx_byte(self):
126 return self._sl.read()
127
128 def send_apdu_raw(self, pdu):
Sylvain Munaute7c15cd2010-12-07 10:01:55 +0100129 """see LinkBase.send_apdu_raw"""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130
131 pdu = h2b(pdu)
132 data_len = ord(pdu[4]) # P3
133
134 # Send first CLASS,INS,P1,P2,P3
135 self._tx_string(pdu[0:5])
136
137 # Wait ack which can be
138 # - INS: Command acked -> go ahead
139 # - 0x60: NULL, just wait some more
140 # - SW1: The card can apparently proceed ...
141 while True:
142 b = self._rx_byte()
143 if b == pdu[1]:
144 break
145 elif b != '\x60':
146 # Ok, it 'could' be SW1
147 sw1 = b
148 sw2 = self._rx_byte()
149 nil = self._rx_byte()
150 if (sw2 and not nil):
151 return '', b2h(sw1+sw2)
152
153 raise ProtocolError()
154
155 # Send data (if any)
156 if len(pdu) > 5:
157 self._tx_string(pdu[5:])
158
159 # Receive data (including SW !)
160 # length = [P3 - tx_data (=len(pdu)-len(hdr)) + 2 (SW1/2) ]
161 to_recv = data_len - len(pdu) + 5 + 2
162
163 data = ''
164 while (len(data) < to_recv):
165 b = self._rx_byte()
166 if (to_recv == 2) and (b == '\x60'): # Ignore NIL if we have no RX data (hack ?)
167 continue
168 if not b:
169 break;
170 data += b
171
172 # Split datafield from SW
173 if len(data) < 2:
174 return None, None
175 sw = data[-2:]
176 data = data[0:-2]
177
178 # Return value
179 return b2h(data), b2h(sw)