pcsc-mon 0.2.2

Monitor PC/SC smart card readers with hotplug and card event support
Documentation
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use anyhow::Error;
use once_cell::sync::Lazy;
use pcsc::{Card, Context, ReaderState, Scope, State};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Mutex;
use std::thread::JoinHandle;
use std::{
    ffi::CString,
    sync::{atomic::AtomicBool, Arc},
    time::Duration,
};

static PCSC_MONITOR: Lazy<Mutex<PcscMonitor>> = Lazy::new(|| Mutex::new(PcscMonitor::new()));

/// Represents a PC/SC monitor that tracks reader and card state changes.
///
/// `PcscMonitor` is a singleton interface for monitoring smart card readers
/// using PC/SC. It supports hotplug detection, card insertion/removal events,
/// and thread-safe callback registration.
///
/// The monitor runs in a background thread once started.
#[derive(Debug, thiserror::Error)]
pub enum ReaderError {
    #[error("PCSC error: {0}")]
    Pcsc(#[from] pcsc::Error),

    #[error("reader state mutex poisoned")]
    ReaderStatePoisoned,

    #[error("known readers mutex poisoned")]
    KnownReadersPoisoned,

    #[error("Handler Panic:{0}")]
    HandlerPanicked(#[from] Error),
}

fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}
pub struct PcscMonitor {
    on_reader_added: Option<Arc<dyn Fn(String) + Send + Sync>>,
    on_reader_removed: Option<Arc<dyn Fn(String) + Send + Sync>>,
    on_card_inserted: Option<Arc<dyn Fn(&Context, &Card) + Send + Sync>>,
    on_card_removed: Option<Arc<dyn Fn(String) + Send + Sync>>,
    on_error: Option<Arc<dyn Fn(ReaderError) + Send + Sync>>,
    known_readers: Arc<Mutex<Vec<String>>>,
    reader_states: Arc<Mutex<Vec<(String, State)>>>,
    started: AtomicBool,
}

impl PcscMonitor {
    /// Gets a global instance of the `PcscMonitor` to register callbacks.
    ///
    /// This method returns a locked [`MutexGuard`] to the global monitor instance.
    /// Use this to attach listeners and start monitoring.
    ///
    /// # Example
    /// ```rust
    /// let mut monitor = pcsc_mon::PcscMonitor::instance();
    /// monitor.on_reader_added(|reader| {
    ///     println!("Reader added: {}", reader);
    /// });
    /// monitor.start();
    /// ```
    pub fn instance() -> std::sync::MutexGuard<'static, PcscMonitor> {
        PCSC_MONITOR.lock().expect("PcscMonitor mutex poisoned")
    }
    fn new() -> Self {
        Self {
            // init other fields...
            started: AtomicBool::new(false),
            on_reader_added: None,
            on_reader_removed: None,
            on_card_inserted: None,
            on_card_removed: None,
            on_error: None,
            known_readers: Arc::new(Mutex::new(Vec::new())),
            reader_states: Arc::new(Mutex::new(Vec::new())),
        }
    }
    /// Registers a callback for reader addition events.
    ///
    /// The callback is called with the name of the reader when a new reader is connected.
    pub fn on_reader_added<F>(&mut self, f: F)
    where
        F: Fn(String) + Send + Sync + 'static,
    {
        self.on_reader_added = Some(Arc::new(f));
    }

    /// Registers a callback for reader removal events.
    ///
    /// The callback is called with the name of the reader when a reader is disconnected.
    ///
    /// **Note:** Internally sets the reader state to [`State::IGNORE`]. When the same
    /// reader is reconnected, a card must be inserted and removed again to re-trigger
    /// `on_card_inserted`.
    pub fn on_reader_removed<F>(&mut self, f: F)
    where
        F: Fn(String) + Send + Sync + 'static,
    {
        self.on_reader_removed = Some(Arc::new(f));
    }
    /// Registers a callback for card insertion events.
    ///
    /// The callback receives a reference to the [`Context`] and [`Card`] for direct interaction
    /// with the smart card.
    ///
    /// # Note
    /// The context and card are already connected when the callback runs.
    pub fn on_card_inserted<F>(&mut self, f: F)
    where
        F: Fn(&Context, &Card) + Send + Sync + 'static,
    {
        self.on_card_inserted = Some(Arc::new(f));
    }
    /// Registers a callback for card removal events.
    ///
    /// The callback is called with the name of the reader when the card is removed.
    pub fn on_card_removed<F>(&mut self, f: F)
    where
        F: Fn(String) + Send + Sync + 'static,
    {
        self.on_card_removed = Some(Arc::new(f));
    }

    /// Registers a callback to handle Errors during the pcsc events
    ///
    /// The callback is called with the error thrown during reader or card state detection
    pub fn on_error<F>(&mut self, f: F)
    where
        F: Fn(ReaderError) + Send + Sync + 'static,
    {
        self.on_error = Some(Arc::new(f));
    }

    fn handle_callback<T: Fn() -> (), E: Fn(ReaderError) + Send + Sync>(f: T, error: E) {
        match catch_unwind(AssertUnwindSafe(|| f())) {
            Ok(_) => {}
            Err(panicms) => error(ReaderError::HandlerPanicked(Error::msg(panic_message(
                panicms,
            )))),
        };
    }

    fn spawn_reader_detector(&mut self) -> JoinHandle<()> {
        let on_reader_added = self.on_reader_added.clone();
        let on_reader_removed = self.on_reader_removed.clone();
        let on_error_read = self.on_error.clone();
        let known_readers_mutex = self.known_readers.clone();
        let reader_states_mutex = self.reader_states.clone();

        std::thread::spawn(move || loop {
            match Context::establish(Scope::User) {
                Ok(ctx) => {
                    loop {
                        let mut buf = [0u8; 2048];
                        let mut known_readers;
                        match known_readers_mutex.lock() {
                            Ok(readers) => {
                                known_readers = readers;
                            }
                            Err(e) => {
                                if let Some(ref cb) = on_error_read {
                                    Self::handle_callback(
                                        || cb(ReaderError::KnownReadersPoisoned),
                                        |msg| cb(msg),
                                    );
                                } else {
                                    eprintln!("Reader listing error: {:?}", e)
                                }
                                e.into_inner().clear();
                                known_readers_mutex.clear_poison();
                                std::thread::sleep(std::time::Duration::from_secs(1));
                                continue;
                            }
                        }
                        let mut reader_states;
                        match reader_states_mutex.lock() {
                            Ok(states) => {
                                reader_states = states;
                            }
                            Err(e) => {
                                if let Some(ref cb) = on_error_read {
                                    Self::handle_callback(
                                        || cb(ReaderError::ReaderStatePoisoned),
                                        |msg| cb(msg),
                                    );
                                } else {
                                    eprintln!("Reader listing error: {:?}", e)
                                }
                                e.into_inner().clear();
                                reader_states_mutex.clear_poison();
                                std::thread::sleep(std::time::Duration::from_secs(1));
                                continue;
                            }
                        }
                        match ctx.list_readers(&mut buf) {
                            Ok(readers_raw) => {
                                let readers = readers_raw
                                    .map(|r| r.to_string_lossy().into_owned())
                                    .collect::<Vec<_>>();

                                // Detect added readers
                                for r in readers.iter().filter(|r| !known_readers.contains(r)) {
                                    reader_states.push((r.clone(), State::UNAWARE));
                                    if let Some(ref cb) = on_reader_added {
                                        // match catch_unwind(AssertUnwindSafe(|| cb(r.clone()))) {
                                        //     Ok(_) => print!("Saul Goodman"),
                                        //     Err(panicms) => {
                                        //         if let Some(ref cb) = on_error_read {
                                        //             cb(ReaderError::HandlerPanicked(Error::msg(
                                        //                 panic_message(panicms),
                                        //             )));
                                        //         } else {
                                        //             eprintln!(
                                        //                 "failed to connect to card: {:?}",
                                        //                 panicms
                                        //             );
                                        //         }
                                        //     }
                                        // };
                                        Self::handle_callback(
                                            || cb(r.clone()),
                                            |msg| {
                                                if let Some(ref cb) = on_error_read {
                                                    cb(msg);
                                                } else {
                                                    eprintln!(
                                                        "failed to connect to card: {:?}",
                                                        msg
                                                    );
                                                }
                                            },
                                        );
                                    }
                                }

                                // Detect removed readers
                                for r in known_readers.iter().filter(|r| !readers.contains(r)) {
                                    if let Some(position) =
                                        reader_states.iter().position(|(name, _)| name == r)
                                    {
                                        reader_states.remove(position);
                                    }
                                    if let Some(ref cb) = on_reader_removed {
                                        // match catch_unwind(AssertUnwindSafe(|| cb(r.clone()))) {
                                        //     Ok(_) => print!("Saul Goodman"),
                                        //     Err(panicms) => {
                                        //         if let Some(ref cb) = on_error_read {
                                        //             cb(ReaderError::HandlerPanicked(Error::msg(
                                        //                 panic_message(panicms),
                                        //             )));
                                        //         } else {
                                        //             eprintln!(
                                        //                 "failed to connect to card: {:?}",
                                        //                 panicms
                                        //             );
                                        //         }
                                        //     }
                                        // };
                                        Self::handle_callback(
                                            || cb(r.clone()),
                                            |msg| {
                                                if let Some(ref cb) = on_error_read {
                                                    cb(msg);
                                                } else {
                                                    eprintln!(
                                                        "failed to connect to card: {:?}",
                                                        msg
                                                    );
                                                }
                                            },
                                        );
                                    }
                                }

                                *known_readers = readers;
                            }
                            Err(e) => {
                                if let Some(ref cb) = on_error_read {
                                    Self::handle_callback(
                                        || cb(ReaderError::Pcsc(e)),
                                        |msg| cb(msg),
                                    );
                                } else {
                                    eprintln!("Reader listing error: {:?}", e)
                                }
                                if e.eq(&pcsc::Error::ServiceStopped) {
                                    *known_readers = vec![];
                                    *reader_states = vec![];
                                    break;
                                }
                            }
                        }
                        std::thread::sleep(std::time::Duration::from_secs(1));
                    }
                }
                Err(e) => {
                    if let Some(ref cb) = on_error_read {
                        // match catch_unwind(AssertUnwindSafe(|| {
                        //     cb(ReaderError::Pcsc(e));
                        // })) {
                        //     Ok(_) => print!("Saul Goodman"),
                        //     Err(panicms) => {
                        //         if let Some(ref cb) = on_error_read {
                        //             cb(ReaderError::HandlerPanicked(Error::msg(panic_message(
                        //                 panicms,
                        //             ))));
                        //         } else {
                        //             eprintln!("failed to connect to card: {:?}", panicms);
                        //         }
                        //     }
                        // };
                        Self::handle_callback(|| cb(ReaderError::Pcsc(e)), |msg| cb(msg));
                    } else {
                        eprintln!("Reader listing error: {:?}", e)
                    }
                }
            }
            std::thread::sleep(std::time::Duration::from_secs(1));
        })
    }

    fn spawn_reader_state(&mut self) -> JoinHandle<()> {
        let on_card_inserted = self.on_card_inserted.clone();
        let on_card_removed = self.on_card_removed.clone();
        let on_error_card = self.on_error.clone();
        let reader_states_mutex = self.reader_states.clone();
        println!(
            "reader states mutex (reader state thread): {:?}",
            reader_states_mutex
        );
        std::thread::spawn(move || loop {
            match Context::establish(Scope::User) {
                Ok(ctx) => {
                    loop {
                        let mut reader_states;
                        match reader_states_mutex.lock() {
                            Ok(states) => {
                                reader_states = states;
                            }
                            Err(e) => {
                                if let Some(ref cb) = on_error_card {
                                    Self::handle_callback(
                                        || cb(ReaderError::ReaderStatePoisoned),
                                        |msg| cb(msg),
                                    );
                                } else {
                                    eprintln!("Reader listing error: {:?}", e)
                                }
                                e.into_inner().clear();
                                reader_states_mutex.clear_poison();
                                std::thread::sleep(Duration::from_millis(100));
                                continue;
                            }
                        }

                        let mut reader_states_structs: Vec<ReaderState> = reader_states
                            .iter()
                            .map(|(name, state)| {
                                ReaderState::new(
                                    CString::new(name.as_str()).expect("CString::new failed"),
                                    *state,
                                )
                            })
                            .collect();

                        match ctx.get_status_change(None, &mut reader_states_structs) {
                            Ok(_) => {
                                for (idx, state) in reader_states_structs.iter().enumerate() {
                                    let reader_name = &reader_states[idx].0;
                                    let event_state = state.event_state();
                                    let current_state = state.current_state();
                                    let changed = current_state == State::UNAWARE
                                        || !event_state.contains(current_state);

                                    // TODO: Check if event state update can be forced after reader is reattached. State goes to ignore until card is inserted and removed again

                                    if !changed {
                                        continue;
                                    }
                                    //println!("state changed to {:?}", event_state);
                                    if event_state.contains(State::PRESENT)
                                        && !event_state.contains(State::INUSE)
                                    {
                                        if let Some(ref cb) = on_card_inserted {
                                            match ctx.connect(
                                                state.name(),
                                                pcsc::ShareMode::Shared,
                                                pcsc::Protocols::ANY,
                                            ) {
                                                Ok(card) => {
                                                    Self::handle_callback(
                                                        || cb(&ctx, &card),
                                                        |msg| {
                                                            if let Some(ref cb) = on_error_card {
                                                                cb(msg);
                                                            } else {
                                                                eprintln!(
                                                                "failed to connect to card: {:?}",
                                                                msg
                                                            );
                                                            }
                                                        },
                                                    );
                                                }
                                                Err(e) => {
                                                    if let Some(ref cb) = on_error_card {
                                                        Self::handle_callback(
                                                            || cb(ReaderError::Pcsc(e)),
                                                            |msg| {
                                                                if let Some(ref cb) = on_error_card
                                                                {
                                                                    cb(msg);
                                                                } else {
                                                                    eprintln!(
                                                        "failed to connect to card: {:?}",
                                                        msg
                                                    );
                                                                }
                                                            },
                                                        );
                                                    } else {
                                                        eprintln!(
                                                            "failed to connect to card: {:?}",
                                                            e
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                    } else if event_state.contains(State::EMPTY) {
                                        if let Some(ref cb) = on_card_removed {
                                            Self::handle_callback(
                                                || cb(reader_name.clone()),
                                                |msg| {
                                                    if let Some(ref cb) = on_error_card {
                                                        cb(msg);
                                                    } else {
                                                        eprintln!(
                                                            "failed to connect to card: {:?}",
                                                            msg
                                                        );
                                                    }
                                                },
                                            );
                                        }
                                    }

                                    reader_states[idx].1 = event_state - State::CHANGED;
                                }
                            }
                            Err(e) => {
                                if let Some(ref cb) = on_error_card {
                                    Self::handle_callback(
                                        || cb(ReaderError::Pcsc(e)),
                                        |msg| cb(msg),
                                    );
                                } else {
                                    eprintln!("get_status_change error: {:?}", e)
                                }
                                if e.eq(&pcsc::Error::ServiceStopped) {
                                    *reader_states = vec![];
                                    break;
                                }
                            }
                        }

                        std::thread::sleep(Duration::from_millis(100));
                    }
                }
                Err(e) => {
                    if let Some(ref cb) = on_error_card {
                        Self::handle_callback(|| cb(ReaderError::Pcsc(e)), |msg| cb(msg));
                    } else {
                        eprintln!("get_status_change error: {:?}", e)
                    }
                }
            }
            std::thread::sleep(std::time::Duration::from_secs(1));
            // Track reader states
        })
    }

    /// Starts the monitoring thread.
    ///
    /// Begins polling for reader and card state changes. Should be called after all
    /// desired callbacks are registered.
    ///
    /// This is non-blocking: the monitoring thread runs in the background.

    pub fn start(&mut self) {
        if self.started.swap(true, std::sync::atomic::Ordering::SeqCst) {
            // Already started
            return;
        }
        // Establish PC/SC context

        // Clone callbacks for reader thread
        let _detector_handle = self.spawn_reader_detector();

        // Clone callbacks for card event thread
        let _state_handle = self.spawn_reader_state();

        // std::thread::spawn(move || loop {
        //     if detector_handle.is_finished() {
        //         match PCSC_MONITOR.try_lock(){
        //             Ok(mut monitor)=>{
        //                 detector_handle = monitor.spawn_reader_detector();
        //             },
        //             Err(e)=>println!("{:?}", e),

        //         }

        //     }
        //     if state_handle.is_finished() {
        //         match PCSC_MONITOR.try_lock(){
        //             Ok(mut monitor)=>{
        //                 state_handle = monitor.spawn_reader_state();
        //             },
        //             Err(e)=>println!("{:?}", e),

        //         }
        //     }
        //     std::thread::sleep(Duration::from_secs(10));
        // });
    }
}