startup: report PC/SC access denial instead of a silent serial fallback
When no reader was named and readers() failed (e.g. SCARD_E_NO_ACCESS - the user may not use pcscd), the auto-detect swallowed the error and pySim fell back to the Serial transport, failing on /dev/ttyUSB0 while the server still printed "listening". The startup now probes PC/SC, classifies the failure by hresult (access/service/reader), reports the cause with the pcscd group/polkit and pcsc_scan guidance and exits 2; the python -m guard uses sys.exit(main()). An explicit -d/--device keeps the serial path; a reader without a card stays a normal cardless start; a readerless start exits with its own message. start.sh runs the same access pre-flight before launching (readers() with a 3x retry for socket activation; -d is detected and skips it). READMEs, CHANGELOG (folded into the unreleased 3.38.1) and AGENTS updated. Tests: tests/test_pcsc_startup.py (16: the error classifier, the probe, the report guidance, the serial-arg detection and the source pins). 1083 Python + 1075 frontend.
This commit is contained in:
@@ -25,6 +25,19 @@ every change carries a descriptive commit message.
|
||||
- The startup TERMINAL PROFILE drain uses the chain's final SW, so an idle
|
||||
chain no longer costs one extra STATUS poll (~128 ms).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A PC/SC access denial is reported instead of a silent serial fallback.**
|
||||
When no reader was named and `readers()` failed (e.g. `SCARD_E_NO_ACCESS` —
|
||||
the user may not use `pcscd`), the error was swallowed and pySim fell back to
|
||||
the serial transport, failing on `/dev/ttyUSB0` while the server still printed
|
||||
"listening". The startup now probes PC/SC and reports **`PC/SC access
|
||||
denied`** (with the `pcscd` group/polkit guidance and the `pcsc_scan`
|
||||
cross-check), **`pcscd is not running`** or **`no PC/SC reader found`**, then
|
||||
exits 2; `start.sh` runs the same access pre-flight before launching. An
|
||||
explicit `-d <device>` keeps the serial path, and a reader present but no card
|
||||
is still a normal cardless start.
|
||||
|
||||
## [3.38.0] — 2026-10-24
|
||||
|
||||
### Added
|
||||
|
||||
@@ -759,7 +759,7 @@ The bundled Python server wraps [pySim](https://osmocom.org/projects/pysim/wiki)
|
||||
| `start.sh` / `start.bat` | Starts the server from the venv (serves the PWA + API on `:8080`). |
|
||||
| `update.sh` / `update.bat` | Updates a packaged install in place: fetches the latest release package, replaces the app files and re-installs the app into the existing `.venv` (pysim is kept). `--check`, `--version X.Y.Z`, `--zip FILE`, `--no-pip`, `--force`. |
|
||||
|
||||
`start.sh` asks for the first PC/SC reader when `pcscd` is running; otherwise the server still auto-detects a PC/SC reader itself, and with none present pysim falls back to its serial default `/dev/ttyUSB0` (pass `-d <device>` for a serial/FTDI reader). `start.bat` always passes `-p 0` (PC/SC is built into Windows). Extra arguments are passed through to the server, e.g. `./start.sh --gsmtap` or `start.bat --gsmtap 10.0.0.5:4729`. If no reader is found the server still starts ("Reader: none") — initialize the card later via the **Equip** button.
|
||||
`start.sh` checks PC/SC access before starting: if the user may not use `pcscd` (or the service is not running) it prints the cause with the group/polkit guidance and exits — the server **no longer falls back to a serial reader silently**. With access, the server auto-detects the first PC/SC reader; `start.bat` always passes `-p 0` (PC/SC is built into Windows). An explicit serial/FTDI reader is still possible with `-d <device>` (the pre-flight check is skipped). Extra arguments are passed through to the server, e.g. `./start.sh --gsmtap` or `start.bat --gsmtap 10.0.0.5:4729`. If no PC/SC reader is found the server reports it and exits — connect the reader and restart (a reader present but no card is still a normal cardless start).
|
||||
|
||||
### Manual installation (Linux/macOS)
|
||||
|
||||
@@ -799,8 +799,9 @@ its MSVC build chain) is not pulled in.
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
- **"Failed to establish context: Access denied"** — `pcscd` isn't running or the user lacks permission: `sudo systemctl enable --now pcscd && sudo usermod -a -G pcscd $USER`.
|
||||
- **"device file /dev/ttyUSB0 does not exist"** — no serial reader; connect a USB reader or pass `-d` explicitly. The server still starts without a reader.
|
||||
- **"Failed to establish context: Access denied"** — the user may not use `pcscd`: add the user to the `pcscd` group (`sudo usermod -a -G pcscd $USER`, then log out/in) or configure the polkit rule; start the service if needed (`sudo systemctl enable --now pcscd`). `start.sh` and the server report this and exit instead of falling back to a serial reader; `pcsc_scan` shows the same error.
|
||||
- **"device file /dev/ttyUSB0 does not exist"** — only with an explicit `-d <device>`: the device is not connected (or the path is wrong). Without `-d` the server no longer uses the serial transport.
|
||||
- **"no PC/SC reader found"** — connect a reader (`pcsc_scan` lists them) and restart; the server exits instead of starting without a reader.
|
||||
- **"Service not available" (0x8010001D) / reader gone after a `pcscd` restart** — the server recovers by itself: a watchdog revives pyscard's presence monitor and the next equip (automatic after re-insertion, or the **Equip** button) recreates the PC/SC transport (releasing the old link first). No server restart needed.
|
||||
- **"Card was removed" errors / auto-equip fails after a card swap** — a card insertion marks the PC/SC link for a rebuild (so the **first** attempt already uses a fresh link — on Windows the old one cannot connect after a swap), the auto-equip retries up to 3 times, and **every failed attempt rebuilds the transport** before the next one. A card removed while the server initializes at startup leaves it cardless with one line (no traceback), and the next insertion equips normally. The swallowed init error (with its traceback) is now printed as `AUTO-EQUIP: init output:`, and a card that is present but produced no card is a failure, not a silent "card gone". The watchdog re-arms with a doubling delay (5 s up to 60 s) while a card is present; a removed card clears the card state completely, so handlers answer "no card" instead of transmitting over the dead card.
|
||||
|
||||
|
||||
+4
-3
@@ -743,7 +743,7 @@ PWA проверяет версию сервера при подключении
|
||||
| `start.sh` / `start.bat` | Запускает сервер из venv (раздаёт PWA + API на `:8080`). |
|
||||
| `update.sh` / `update.bat` | Обновляет пакетную установку на месте: скачивает последний релизный пакет, заменяет файлы приложения и переустанавливает приложение в существующий `.venv` (pysim сохраняется). `--check`, `--version X.Y.Z`, `--zip FILE`, `--no-pip`, `--force`. |
|
||||
|
||||
`start.sh` при работающем `pcscd` запрашивает первый PC/SC-ридер; иначе сервер сам автоопределяет PC/SC-ридер, а если его нет — pysim откатывается на последовательное устройство по умолчанию `/dev/ttyUSB0` (для serial/FTDI-ридера укажите `-d <устройство>`). `start.bat` всегда передаёт `-p 0`. Дополнительные аргументы передаются серверу, например `./start.sh --gsmtap` или `start.bat --gsmtap 10.0.0.5:4729`. Без ридера сервер всё равно стартует («Reader: none») — карту можно инициализировать позже кнопкой **Equip**.
|
||||
`start.sh` перед запуском проверяет доступ к PC/SC: если пользователь не может использовать `pcscd` (или служба не запущена), он печатает причину и рекомендации (группа/polkit) и завершается — сервер **больше не откатывается на последовательный ридер молча**. При наличии доступа сервер сам находит первый PC/SC-ридер; `start.bat` всегда передаёт `-p 0` (в Windows PC/SC встроен). Явный serial/FTDI-ридер по-прежнему возможен через `-d <устройство>` (проверка пропускается). Дополнительные аргументы передаются серверу, например `./start.sh --gsmtap` или `start.bat --gsmtap 10.0.0.5:4729`. Если PC/SC-ридер не найден, сервер сообщает об этом и завершается — подключите ридер и перезапустите (ридер без карты — по-прежнему нормальный старт без карты).
|
||||
|
||||
### Ручная установка (Linux/macOS)
|
||||
|
||||
@@ -783,8 +783,9 @@ pysim-simple-server --http-port 8080
|
||||
|
||||
### Устранение неполадок
|
||||
|
||||
- **"Failed to establish context: Access denied"** — `pcscd` не запущен или нет прав: `sudo systemctl enable --now pcscd && sudo usermod -a -G pcscd $USER`.
|
||||
- **"device file /dev/ttyUSB0 does not exist"** — нет serial-ридера; подключите USB-ридер или укажите `-d`. Сервер всё равно стартует без ридера.
|
||||
- **"Failed to establish context: Access denied"** — у пользователя нет прав на `pcscd`: добавьте его в группу `pcscd` (`sudo usermod -a -G pcscd $USER`, затем выйдите и войдите) или настройте правило polkit; при необходимости запустите службу (`sudo systemctl enable --now pcscd`). `start.sh` и сервер сообщают об этом и завершаются вместо отката на serial-ридер; `pcsc_scan` показывает ту же ошибку.
|
||||
- **"device file /dev/ttyUSB0 does not exist"** — только при явном `-d <устройство>`: устройство не подключено (или путь неверен). Без `-d` сервер больше не использует последовательный транспорт.
|
||||
- **"no PC/SC reader found"** — подключите ридер (`pcsc_scan` покажет список) и перезапустите; сервер завершается, а не стартует без ридера.
|
||||
- **"Service not available" (0x8010001D) / ридер пропал после перезапуска `pcscd`** — сервер восстанавливается сам: сторож перезапускает монитор присутствия pyscard, а следующий equip (автоматически после повторной вставки карты или кнопкой **Equip**) пересоздаёт транспорт PC/SC (сначала освобождая старый линк). Перезапуск сервера не нужен.
|
||||
- **Ошибки "Card was removed" / equip не срабатывает после смены карты** — вставка карты помечает соединение PC/SC для пересоздания (поэтому **первая** попытка уже использует свежее соединение — в Windows старое после смены карты подключиться не может), авто-equip повторяется до 3 раз, и **каждая неудачная попытка пересоздаёт транспорт** перед следующей. Карта, снятая во время инициализации при старте сервера, оставляет его без карты с одной строкой (без трассировки), а следующая вставка инициализируется обычным образом. Проглоченная ошибка инициализации (с трассировкой) теперь печатается как `AUTO-EQUIP: init output:`, а «карта есть, но карта не создана» — это ошибка, а не тихое «карта пропала». Сторож повторяет с удвоением задержки (5 с … 60 с), пока карта в ридере; снятие карты полностью очищает состояние, поэтому обработчики отвечают «нет карты», а не шлют APDU мёртвой карте.
|
||||
|
||||
|
||||
+122
-17
@@ -7,7 +7,7 @@ import traceback
|
||||
from http.server import ThreadingHTTPServer
|
||||
from pySim.card_handler import CardHandler
|
||||
from pySim.commands import SimCardCommands
|
||||
from pySim.exceptions import NoCardError
|
||||
from pySim.exceptions import NoCardError, ReaderError
|
||||
from pySim.log import PySimLogger
|
||||
from pySim.cards import UiccCardBase
|
||||
|
||||
@@ -23,6 +23,107 @@ from .server import PysimHandler, StderrApduTracer, _LoggingApduTracer, VERSION,
|
||||
|
||||
_server_start = 0
|
||||
|
||||
# PC/SC hresults (pyscard's exceptions carry them; the messages are often
|
||||
# empty, so the hresult is the reliable signal).
|
||||
_PCSC_E_UNKNOWN_READER = 0x80100009
|
||||
_PCSC_E_NO_SERVICE = 0x8010001D
|
||||
_PCSC_E_SERVICE_STOPPED = 0x8010001E
|
||||
_PCSC_E_NO_ACCESS = 0x80100027
|
||||
_PCSC_E_NO_READERS_AVAILABLE = 0x8010002E
|
||||
|
||||
|
||||
class PcscUnavailable(RuntimeError):
|
||||
"""The PC/SC stack cannot be used (kind: access/service/reader)."""
|
||||
|
||||
def __init__(self, kind, cause=None):
|
||||
super().__init__(kind)
|
||||
self.kind = kind
|
||||
self.cause = cause
|
||||
|
||||
|
||||
def _pcsc_error_kind(exc):
|
||||
"""Classify a pyscard failure: 'access', 'service', 'reader' or None.
|
||||
|
||||
``SCARD_E_NO_ACCESS`` is the "Access denied" a user without permission to
|
||||
pcscd gets; the message is a fallback because some pyscard paths raise a
|
||||
CardConnectionException with an empty message and only the hresult."""
|
||||
hr = getattr(exc, 'hresult', None)
|
||||
msg = str(exc or '').lower()
|
||||
if hr == _PCSC_E_NO_ACCESS or 'access denied' in msg or 'access is denied' in msg:
|
||||
return 'access'
|
||||
if hr in (_PCSC_E_NO_SERVICE, _PCSC_E_SERVICE_STOPPED) or \
|
||||
'resource manager is not running' in msg or 'service not available' in msg:
|
||||
return 'service'
|
||||
if hr in (_PCSC_E_UNKNOWN_READER, _PCSC_E_NO_READERS_AVAILABLE) or \
|
||||
'no smart card readers' in msg:
|
||||
return 'reader'
|
||||
return None
|
||||
|
||||
|
||||
def _report_pcsc_unavailable(kind, exc=None):
|
||||
"""Print an actionable reason instead of starting a readerless server."""
|
||||
if kind == 'access':
|
||||
user = os.environ.get('USER') or os.environ.get('LOGNAME') or '$USER'
|
||||
sys.stderr.write('INIT: PC/SC access denied - the current user may not use pcscd.\n')
|
||||
sys.stderr.write(' Add the user to the pcscd group: sudo usermod -aG pcscd %s\n' % user)
|
||||
sys.stderr.write(' (then log out and back in), or configure the polkit rule that\n')
|
||||
sys.stderr.write(' allows the user to use pcscd. `pcsc_scan` shows the same\n')
|
||||
sys.stderr.write(' "SCardEstablishContext: Access denied" error.\n')
|
||||
elif kind == 'service':
|
||||
sys.stderr.write('INIT: pcscd is not running or not reachable.\n')
|
||||
sys.stderr.write(' Start it (sudo systemctl start pcscd) and restart the server.\n')
|
||||
else:
|
||||
sys.stderr.write('INIT: no PC/SC reader found.\n')
|
||||
sys.stderr.write(' Connect a reader (pcsc_scan lists them) and restart the server.\n')
|
||||
if exc is not None:
|
||||
hr = getattr(exc, 'hresult', None)
|
||||
detail = str(exc) or type(exc).__name__
|
||||
if hr not in (None, -1):
|
||||
detail += ' (hresult=0x%08X)' % hr
|
||||
sys.stderr.write(' (%s)\n' % detail)
|
||||
|
||||
|
||||
def _probe_pcsc_reader(retries=3, sleep_fn=time.sleep, readers_fn=None):
|
||||
"""Return the first PC/SC reader name or raise PcscUnavailable.
|
||||
|
||||
``SCARD_E_NO_ACCESS``/service failures are raised immediately (retrying
|
||||
cannot fix permissions or a stopped service); an empty list is retried
|
||||
(USB enumeration) and reported as 'reader' after the last attempt."""
|
||||
if readers_fn is None:
|
||||
from smartcard.System import readers as readers_fn
|
||||
last = None
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
found = readers_fn()
|
||||
except Exception as exc:
|
||||
last = exc
|
||||
kind = _pcsc_error_kind(exc)
|
||||
if kind in ('access', 'service'):
|
||||
raise PcscUnavailable(kind, exc) from exc
|
||||
else:
|
||||
if found:
|
||||
return str(found[0])
|
||||
last = None
|
||||
if attempt + 1 < retries:
|
||||
sys.stderr.write('INIT: no PC/SC reader yet, retrying in 2s...\n')
|
||||
sleep_fn(2)
|
||||
raise PcscUnavailable('reader', last)
|
||||
|
||||
|
||||
def _serial_arg_given(argv=None):
|
||||
"""True when the operator explicitly chose the serial reader (-d/--device).
|
||||
|
||||
The default (-d is /dev/ttyUSB0 in pySim's parser) must not masquerade as
|
||||
an explicit choice: only a flag on the command line counts."""
|
||||
argv = sys.argv[1:] if argv is None else argv
|
||||
for arg in argv:
|
||||
if arg in ('-d', '--device') or arg.startswith('--device='):
|
||||
return True
|
||||
if arg.startswith('-d') and not arg.startswith('--') and len(arg) > 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _log_stdout(msg):
|
||||
elapsed = time.time() - _server_start
|
||||
os.write(1, ('[%8.3f] %s\n' % (elapsed, msg)).encode())
|
||||
@@ -164,22 +265,18 @@ def main():
|
||||
rs = None
|
||||
sim_menu = None
|
||||
event_list = None
|
||||
# Auto-detect PC/SC reader if none was explicitly specified.
|
||||
# Handles late pcscd startup and USB enumeration delays.
|
||||
if opts.pcsc_dev is None and opts.pcsc_regex is None:
|
||||
# Auto-detect the PC/SC reader unless one was named explicitly or the
|
||||
# operator chose the serial transport (-d). A PC/SC access denial or a
|
||||
# missing service must be reported - silently falling back to the serial
|
||||
# reader left the server "listening" without a usable card link (v3.38.1).
|
||||
if opts.pcsc_dev is None and opts.pcsc_regex is None and not _serial_arg_given():
|
||||
try:
|
||||
from smartcard.System import readers
|
||||
for attempt in range(3):
|
||||
r = readers()
|
||||
if r:
|
||||
sys.stderr.write('INIT: PC/SC reader detected: %s\n' % r[0])
|
||||
reader = _probe_pcsc_reader()
|
||||
except PcscUnavailable as e:
|
||||
_report_pcsc_unavailable(e.kind, e.cause)
|
||||
return 2
|
||||
sys.stderr.write('INIT: PC/SC reader detected: %s\n' % reader)
|
||||
opts.pcsc_dev = 0
|
||||
break
|
||||
if attempt < 2:
|
||||
sys.stderr.write('INIT: no PC/SC readers found, retrying in 2s...\n')
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
pass # smartcard module not available or pcscd unreachable
|
||||
|
||||
try:
|
||||
kwargs = {}
|
||||
@@ -223,7 +320,15 @@ def main():
|
||||
# defaults, which made VERIFY go out with CLA A0 on a UICC).
|
||||
scc = card._scc
|
||||
scc.cat_cla = '80' if isinstance(card, UiccCardBase) else 'a0'
|
||||
except Exception:
|
||||
except ReaderError as e:
|
||||
sys.stderr.write('INIT: no PC/SC reader found: %s\n' % e)
|
||||
sys.stderr.write(' Connect the reader (pcsc_scan lists them) and restart the server.\n')
|
||||
return 2
|
||||
except Exception as e:
|
||||
kind = _pcsc_error_kind(e)
|
||||
if kind:
|
||||
_report_pcsc_unavailable(kind, e)
|
||||
return 2
|
||||
print("Warning: reader/card initialization failed:", file=sys.stderr)
|
||||
traceback.print_exc()
|
||||
ch = CardHandler(sl) if sl else None
|
||||
@@ -438,4 +543,4 @@ def main():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
sys.exit(main())
|
||||
@@ -16,14 +16,50 @@ LOG_FILE="$SCRIPT_DIR/simple_lastrun.log"
|
||||
exec > >(tee "$LOG_FILE") 2>&1
|
||||
export PYTHONUNBUFFERED=1 # keep the log live: a piped stdout is block-buffered
|
||||
|
||||
# Auto-detect reader
|
||||
# PC/SC pre-flight (v3.38.1): a user without access to pcscd must see the real
|
||||
# cause - the server no longer falls back to /dev/ttyUSB0 silently. An
|
||||
# explicit serial reader (-d/--device) keeps the serial path.
|
||||
SERIAL=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-d|--device|--device=*|-d*) SERIAL=1 ;;
|
||||
esac
|
||||
done
|
||||
READER_ARGS=""
|
||||
if command -v pcscd > /dev/null 2>&1; then
|
||||
# Give pcscd a moment if it's not running yet (USB enumeration delay)
|
||||
if ! pgrep -x pcscd > /dev/null 2>&1 && ! pgrep -x pcscd.bin > /dev/null 2>&1; then
|
||||
sleep 1
|
||||
fi
|
||||
if pgrep -x pcscd > /dev/null 2>&1 || pgrep -x pcscd.bin > /dev/null 2>&1; then
|
||||
if [ "$SERIAL" -eq 0 ]; then
|
||||
PYTHON_BIN="$VENV_DIR/bin/python"
|
||||
[ -x "$PYTHON_BIN" ] || PYTHON_BIN="$(command -v python3 || true)"
|
||||
if [ -n "$PYTHON_BIN" ]; then
|
||||
PCSC_ERR="$("$PYTHON_BIN" - <<'PY' 2>&1
|
||||
import time
|
||||
from smartcard.System import readers
|
||||
last = None
|
||||
for _ in range(3):
|
||||
try:
|
||||
readers()
|
||||
raise SystemExit(0)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as e:
|
||||
last = e
|
||||
hr = getattr(e, 'hresult', None)
|
||||
if hr == 0x80100027 or 'access denied' in str(e).lower():
|
||||
break # permissions do not fix themselves
|
||||
time.sleep(1) # pcscd may still be starting (socket activation)
|
||||
hr = getattr(last, 'hresult', -1)
|
||||
msg = str(last) or 'PC/SC error'
|
||||
print(msg + ((' (hresult=0x%08X)' % hr) if hr not in (None, -1) else ''))
|
||||
raise SystemExit(1)
|
||||
PY
|
||||
)" || {
|
||||
echo "Error: PC/SC is not accessible: ${PCSC_ERR:-unknown error}"
|
||||
echo " The server will not fall back to a serial reader silently."
|
||||
echo " - add the user to the pcscd group: sudo usermod -aG pcscd \"$USER\" (then log out/in),"
|
||||
echo " or configure the polkit rule that allows the user to use pcscd;"
|
||||
echo " - 'sudo systemctl start pcscd' if the service is not running;"
|
||||
echo " - 'pcsc_scan' shows the same 'Access denied' error when access is denied."
|
||||
exit 2
|
||||
}
|
||||
READER_ARGS="-p 0"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""PC/SC access-denied handling at startup (v3.38.1).
|
||||
|
||||
A user without permission to pcscd used to get a silent serial fallback that
|
||||
failed on /dev/ttyUSB0 while the server still printed "listening". The
|
||||
startup now classifies the pyscard failure, reports the cause with guidance
|
||||
and exits; ``start.sh`` runs the same access pre-flight.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import io
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from pysim_simple_server import __main__ as m
|
||||
|
||||
|
||||
class FakeExc(Exception):
|
||||
def __init__(self, hresult=None, message=''):
|
||||
super().__init__(message)
|
||||
self.hresult = hresult
|
||||
|
||||
|
||||
class ErrorKindTests(unittest.TestCase):
|
||||
def test_access_denied_by_hresult(self):
|
||||
# pyscard raises CardConnectionException(hresult=...) with an empty
|
||||
# message on the SCardEstablishContext failure
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(0x80100027)), 'access')
|
||||
|
||||
def test_access_denied_by_message(self):
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(None, 'Access denied.')),
|
||||
'access')
|
||||
|
||||
def test_service_errors(self):
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(0x8010001D)), 'service')
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(0x8010001E)), 'service')
|
||||
|
||||
def test_reader_errors(self):
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(0x8010002E)), 'reader')
|
||||
self.assertEqual(m._pcsc_error_kind(FakeExc(0x80100009)), 'reader')
|
||||
|
||||
def test_other_failures_are_not_classified(self):
|
||||
self.assertIsNone(m._pcsc_error_kind(FakeExc(0x8010000B))) # sharing
|
||||
self.assertIsNone(m._pcsc_error_kind(ValueError('boom')))
|
||||
|
||||
|
||||
class ProbeTests(unittest.TestCase):
|
||||
def test_the_first_reader_is_returned(self):
|
||||
self.assertEqual(
|
||||
m._probe_pcsc_reader(readers_fn=lambda: ['Reader X']), 'Reader X')
|
||||
|
||||
def test_access_denied_is_raised_immediately(self):
|
||||
calls = []
|
||||
|
||||
def denied():
|
||||
calls.append(1)
|
||||
raise FakeExc(0x80100027)
|
||||
|
||||
with self.assertRaises(m.PcscUnavailable) as cm:
|
||||
m._probe_pcsc_reader(retries=3, sleep_fn=lambda s: None,
|
||||
readers_fn=denied)
|
||||
self.assertEqual(cm.exception.kind, 'access')
|
||||
self.assertEqual(len(calls), 1) # permissions do not fix themselves
|
||||
|
||||
def test_an_empty_list_is_retried_then_reported(self):
|
||||
calls = []
|
||||
|
||||
def empty():
|
||||
calls.append(1)
|
||||
return []
|
||||
|
||||
with self.assertRaises(m.PcscUnavailable) as cm:
|
||||
m._probe_pcsc_reader(retries=2, sleep_fn=lambda s: None,
|
||||
readers_fn=empty)
|
||||
self.assertEqual(cm.exception.kind, 'reader')
|
||||
self.assertEqual(len(calls), 2)
|
||||
|
||||
def test_a_transient_failure_is_retried(self):
|
||||
calls = []
|
||||
|
||||
def flaky():
|
||||
calls.append(1)
|
||||
if len(calls) == 1:
|
||||
raise FakeExc(0x8010000B) # sharing violation
|
||||
return ['Reader Y']
|
||||
|
||||
self.assertEqual(
|
||||
m._probe_pcsc_reader(retries=2, sleep_fn=lambda s: None,
|
||||
readers_fn=flaky), 'Reader Y')
|
||||
self.assertEqual(len(calls), 2)
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
def _report(self, kind, exc=None):
|
||||
err = io.StringIO()
|
||||
with mock.patch('sys.stderr', err):
|
||||
m._report_pcsc_unavailable(kind, exc)
|
||||
return err.getvalue()
|
||||
|
||||
def test_access_guidance(self):
|
||||
text = self._report('access', FakeExc(0x80100027, 'Access denied.'))
|
||||
low = text.lower()
|
||||
self.assertIn('access denied', low)
|
||||
self.assertIn('pcscd', low)
|
||||
self.assertIn('usermod -aG pcscd'.lower(), low)
|
||||
self.assertIn('pcsc_scan', low)
|
||||
self.assertIn('0x80100027', text)
|
||||
|
||||
def test_service_guidance(self):
|
||||
text = self._report('service')
|
||||
self.assertIn('pcscd is not running', text)
|
||||
self.assertIn('systemctl start pcscd', text)
|
||||
|
||||
def test_reader_guidance(self):
|
||||
text = self._report('reader')
|
||||
self.assertIn('no PC/SC reader', text)
|
||||
self.assertIn('pcsc_scan', text)
|
||||
|
||||
|
||||
class SerialArgTests(unittest.TestCase):
|
||||
def test_explicit_serial_flags(self):
|
||||
for argv in (['-d', '/dev/ttyS0'], ['--device', 'x'],
|
||||
['--device=x'], ['-d/dev/ttyS0']):
|
||||
self.assertTrue(m._serial_arg_given(argv), argv)
|
||||
|
||||
def test_the_default_is_not_an_explicit_choice(self):
|
||||
for argv in ([], ['--http-port', '8080'], ['-p', '0']):
|
||||
self.assertFalse(m._serial_arg_given(argv), argv)
|
||||
|
||||
|
||||
class SourcePins(unittest.TestCase):
|
||||
def test_the_module_propagates_the_exit_code(self):
|
||||
src = Path(m.__file__).read_text()
|
||||
self.assertIn('sys.exit(main())', src)
|
||||
|
||||
def test_the_start_script_probes_access_and_guides(self):
|
||||
src = (Path(m.__file__).parent.parent / 'start.sh').read_text()
|
||||
self.assertIn('from smartcard.System import readers', src)
|
||||
self.assertIn('usermod -aG pcscd', src)
|
||||
self.assertIn('pcsc_scan', src)
|
||||
# the old "is pcscd running" heuristic is gone
|
||||
self.assertNotIn('pgrep -x pcscd', src)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user