blob: a05d6c45b3387c0c34620a6dea6c322ef8f006d4 [file] [log] [blame]
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +07001# -*- coding: utf-8 -*-
2
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +07003# Copyright (C) 2020 Vadim Yanitskiy <axilirator@gmail.com>
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17#
18
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070019import logging as log
20import serial
21import time
22import re
Philipp Maier8c823782023-10-23 10:44:44 +020023import argparse
Harald Weltef9f8d7a2023-07-09 17:06:16 +020024from typing import Optional
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070025
Harald Weltef9f8d7a2023-07-09 17:06:16 +020026from pySim.utils import Hexstr, ResTuple
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070027from pySim.transport import LinkBase
28from pySim.exceptions import *
29
30# HACK: if somebody needs to debug this thing
31# log.root.setLevel(log.DEBUG)
32
Harald Weltec91085e2022-02-10 18:05:45 +010033
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070034class ModemATCommandLink(LinkBase):
Harald Weltec91085e2022-02-10 18:05:45 +010035 """Transport Link for 3GPP TS 27.007 compliant modems."""
Harald Weltebaec4e92023-11-03 11:49:54 +010036 name = "modem for Generic SIM Access (3GPP TS 27.007)"
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070037
Harald Welte0f177c12023-12-17 12:38:29 +010038 def __init__(self, opts: argparse.Namespace = argparse.Namespace(modem_dev='/dev/ttyUSB0',
39 modem_baud=115200), **kwargs):
40 device = opts.modem_dev
41 baudrate = opts.modem_baud
Harald Weltec91085e2022-02-10 18:05:45 +010042 super().__init__(**kwargs)
43 self._sl = serial.Serial(device, baudrate, timeout=5)
44 self._echo = False # this will be auto-detected by _check_echo()
45 self._device = device
46 self._atr = None
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020047
Harald Weltec91085e2022-02-10 18:05:45 +010048 # Check the AT interface
49 self._check_echo()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070050
Harald Weltec91085e2022-02-10 18:05:45 +010051 # Trigger initial reset
52 self.reset_card()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070053
Harald Weltec91085e2022-02-10 18:05:45 +010054 def __del__(self):
55 if hasattr(self, '_sl'):
56 self._sl.close()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070057
Harald Weltec91085e2022-02-10 18:05:45 +010058 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
59 # Convert from string to bytes, if needed
60 bcmd = cmd if type(cmd) is bytes else cmd.encode()
61 bcmd += b'\r'
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020062
Harald Weltec91085e2022-02-10 18:05:45 +010063 # Clean input buffer from previous/unexpected data
64 self._sl.reset_input_buffer()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070065
Harald Weltec91085e2022-02-10 18:05:45 +010066 # Send command to the modem
67 log.debug('Sending AT command: %s', cmd)
68 try:
69 wlen = self._sl.write(bcmd)
70 assert(wlen == len(bcmd))
71 except:
72 raise ReaderError('Failed to send AT command: %s' % cmd)
Robert Falkenbergdddcc602021-05-06 09:55:57 +020073
Harald Weltec91085e2022-02-10 18:05:45 +010074 rsp = b''
75 its = 1
76 t_start = time.time()
77 while True:
78 rsp = rsp + self._sl.read(self._sl.in_waiting)
79 lines = rsp.split(b'\r\n')
80 if len(lines) >= 2:
81 res = lines[-2]
82 if res == b'OK':
83 log.debug('Command finished with result: %s', res)
84 break
85 if res == b'ERROR' or res.startswith(b'+CME ERROR:'):
86 log.error('Command failed with result: %s', res)
87 break
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070088
Harald Weltec91085e2022-02-10 18:05:45 +010089 if time.time() - t_start >= timeout:
90 log.info('Command finished with timeout >= %ss', timeout)
91 break
92 time.sleep(patience)
93 its += 1
94 log.debug('Command took %0.6fs (%d cycles a %fs)',
95 time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070096
Harald Weltec91085e2022-02-10 18:05:45 +010097 if self._echo:
98 # Skip echo chars
99 rsp = rsp[wlen:]
100 rsp = rsp.strip()
101 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700102
Harald Weltec91085e2022-02-10 18:05:45 +0100103 log.debug('Got response from modem: %s', rsp)
104 return rsp
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700105
Harald Weltec91085e2022-02-10 18:05:45 +0100106 def _check_echo(self):
107 """Verify the correct response to 'AT' command
108 and detect if inputs are echoed by the device
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200109
Harald Weltec91085e2022-02-10 18:05:45 +0100110 Although echo of inputs can be enabled/disabled via
111 ATE1/ATE0, respectively, we rather detect the current
112 configuration of the modem without any change.
113 """
114 # Next command shall not strip the echo from the response
115 self._echo = False
116 result = self.send_at_cmd('AT')
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200117
Harald Weltec91085e2022-02-10 18:05:45 +0100118 # Verify the response
119 if len(result) > 0:
120 if result[-1] == b'OK':
121 self._echo = False
122 return
123 elif result[-1] == b'AT\r\r\nOK':
124 self._echo = True
125 return
126 raise ReaderError(
127 'Interface \'%s\' does not respond to \'AT\' command' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700128
Harald Weltec91085e2022-02-10 18:05:45 +0100129 def reset_card(self):
130 # Reset the modem, just to be sure
131 if self.send_at_cmd('ATZ') != [b'OK']:
132 raise ReaderError('Failed to reset the modem')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700133
Harald Weltec91085e2022-02-10 18:05:45 +0100134 # Make sure that generic SIM access is supported
135 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
136 raise ReaderError('The modem does not seem to support SIM access')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700137
Harald Weltec91085e2022-02-10 18:05:45 +0100138 log.info('Modem at \'%s\' is ready!' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700139
Harald Weltec91085e2022-02-10 18:05:45 +0100140 def connect(self):
141 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700142
Harald Weltec91085e2022-02-10 18:05:45 +0100143 def disconnect(self):
144 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700145
Harald Welteab6897c2023-07-09 16:21:23 +0200146 def wait_for_card(self, timeout: Optional[int] = None, newcardonly: bool = False):
Harald Weltec91085e2022-02-10 18:05:45 +0100147 pass # Nothing to do really ...
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200148
Harald Weltef9f8d7a2023-07-09 17:06:16 +0200149 def _send_apdu_raw(self, pdu: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100150 # Make sure pdu has upper case hex digits [A-F]
151 pdu = pdu.upper()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700152
Harald Weltec91085e2022-02-10 18:05:45 +0100153 # Prepare the command as described in 8.17
154 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
155 log.debug('Sending command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700156
Harald Weltec91085e2022-02-10 18:05:45 +0100157 # Send AT+CSIM command to the modem
Harald Weltec91085e2022-02-10 18:05:45 +0100158 rsp = self.send_at_cmd(cmd)
Tobias Engeld70ac222023-05-29 21:20:59 +0200159 if rsp[-1].startswith(b'+CME ERROR:'):
160 raise ProtocolError('AT+CSIM failed with: %s' % str(rsp))
Harald Weltec91085e2022-02-10 18:05:45 +0100161 if len(rsp) != 2 or rsp[-1] != b'OK':
162 raise ReaderError('APDU transfer failed: %s' % str(rsp))
163 rsp = rsp[0] # Get rid of b'OK'
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700164
Harald Weltec91085e2022-02-10 18:05:45 +0100165 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
166 try:
167 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
168 (rsp_pdu_len, rsp_pdu) = result.groups()
169 except:
170 raise ReaderError('Failed to parse response from modem: %s' % rsp)
171
172 # TODO: make sure we have at least SW
173 data = rsp_pdu[:-4].decode().lower()
174 sw = rsp_pdu[-4:].decode().lower()
175 log.debug('Command response: %s, %s', data, sw)
176 return data, sw
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200177
Philipp Maier58e89eb2023-10-10 11:59:03 +0200178 def __str__(self) -> str:
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200179 return "modem:%s" % self._device
Philipp Maier8c823782023-10-23 10:44:44 +0200180
181 @staticmethod
182 def argparse_add_reader_args(arg_parser: argparse.ArgumentParser):
Harald Welte0ecbf632023-11-03 12:38:42 +0100183 modem_group = arg_parser.add_argument_group('AT Command Modem Reader', """Talk to a SIM Card inside a
184mobile phone or cellular modem which is attached to this computer and offers an AT command interface including
185the AT+CSIM interface for Generic SIM access as specified in 3GPP TS 27.007.""")
Philipp Maier8c823782023-10-23 10:44:44 +0200186 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
187 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
188 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
189 help='Baud rate used for modem port')