id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
147,448
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardMonitor.py
testcase_CardMonitor.testthread
class testthread(threading.Thread): """thread""" def __init__(self, obsindex, testcase): threading.Thread.__init__(self) self.obsindex = obsindex self.testcase = testcase self.cardmonitor = CardMonitor() self.observer = None def run(self): # create and register observer self.observer = printobserver(self.obsindex, self.testcase) self.cardmonitor.addObserver(self.observer) time.sleep(1) self.cardmonitor.deleteObserver(self.observer)
class testthread(threading.Thread): '''thread''' def __init__(self, obsindex, testcase): pass def run(self): pass
3
1
6
0
6
1
1
0.17
1
2
2
0
2
4
2
27
16
2
12
7
9
2
12
7
9
1
1
0
2
147,449
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardMonitor.py
testcase_CardMonitor.testcase_cardmonitor
class testcase_cardmonitor(unittest.TestCase): """Test smartcard framework card monitoring classes""" def testcase_cardmonitorthread(self): """card monitor thread""" threads = [] for i in range(0, 4): t = testthread(i, self) threads.append(t) for t in threads: t.start() for t in threads: t.join()
class testcase_cardmonitor(unittest.TestCase): '''Test smartcard framework card monitoring classes''' def testcase_cardmonitorthread(self): '''card monitor thread''' pass
2
2
10
0
9
1
4
0.2
1
2
1
0
1
0
1
73
13
1
10
5
8
2
10
5
8
4
2
1
4
147,450
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardMonitor.py
testcase_CardMonitor.printobserver
class printobserver(CardObserver): """print observer""" def __init__(self, obsindex, testcase): self.obsindex = obsindex self.testcase = testcase def update(self, observable, handlers): (addedcards, removedcards) = handlers foundcards = {} self.testcase.assertEqual(removedcards, []) for card in addedcards: foundcards[toHexString(card.atr)] = 1 for atr in expectedATRs: if atr and foundcards: self.testcase.assertTrue(toHexString(atr) in foundcards)
class printobserver(CardObserver): '''print observer''' def __init__(self, obsindex, testcase): pass def update(self, observable, handlers): pass
3
1
6
0
6
0
3
0.08
1
0
0
0
2
2
2
5
16
2
13
9
10
1
13
9
10
4
2
2
5
147,451
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardConnection.py
testcase_CardConnection.testcase_CardConnection
class testcase_CardConnection(unittest.TestCase): """Test case for CardConnection.""" def testcase_CardConnection(self): """Test with default protocols the response to SELECT DF_TELECOM.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect() response, sw1, sw2 = cc.transmit(SELECT + DF_TELECOM) expectedSWs = {"9f 1a": 1, "6e 0": 2, "9f 20": 3, "9f 22": 4} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT0(self): """Test with T0 the response to SELECT DF_TELECOM.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol) response, sw1, sw2 = cc.transmit(SELECT + DF_TELECOM) expectedSWs = {"9f 1a": 1, "6e 0": 2, "9f 20": 3, "9f 22": 4} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT1inConnect(self): """Test that connecting with T1 on a T0 card fails.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: # should fail since the test card does not support T1 self.assertRaises( CardConnectionException, cc.connect, CardConnection.T1_protocol ) else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT1inTransmit(self): """Test that T1 in transmit for a T0 card fails.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect() self.assertRaises( CardConnectionException, cc.transmit, SELECT + DF_TELECOM, CardConnection.T1_protocol, ) else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT0T1(self): """Test test with T0 | T1 the response to SELECT DF_TELECOM.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol | CardConnection.T1_protocol) response, sw1, sw2 = cc.transmit(SELECT + DF_TELECOM) expectedSWs = {"9f 1a": 1, "6e 0": 2, "9f 20": 3, "9f 22": 4} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT0inTransmit(self): """Test with T0 in transmit the response to SELECT DF_TELECOM.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol) response, sw1, sw2 = cc.transmit( SELECT + DF_TELECOM, CardConnection.T0_protocol ) expectedSWs = {"9f 1a": 1, "6e 0": 2, "9f 20": 3, "9f 22": 4} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardConnectionT0T1inTransmitMustFail(self): """Test with bad parameter in transmit the response to SELECT DF_TELECOM.""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol | CardConnection.T1_protocol) self.assertRaises( CardConnectionException, cc.transmit, SELECT + DF_TELECOM, CardConnection.T0_protocol | CardConnection.T1_protocol, ) else: self.assertRaises(NoCardException, cc.connect) cc.disconnect() def testcase_CardReconnectProtocol(self): """Test .reconnect()""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol | CardConnection.T1_protocol) # reconnect in T=1 when a T=0 card (GPK 8K) shall fail self.assertRaises( CardConnectionException, cc.reconnect, protocol=CardConnection.T1_protocol, ) cc.disconnect() else: self.assertRaises(NoCardException, cc.connect) def testcase_CardReconnectMode(self): """Test .reconnect()""" for reader in readers(): cc = reader.createConnection() cc2 = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol | CardConnection.T1_protocol) # reconnect in exclusive mode should fail self.assertRaises( CardConnectionException, cc2.reconnect, mode=SCARD_SHARE_EXCLUSIVE ) cc.disconnect() else: self.assertRaises(NoCardException, cc.connect) def testcase_CardReconnectDisposition(self): """Test .reconnect()""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: cc.connect(CardConnection.T0_protocol | CardConnection.T1_protocol) cc.reconnect(disposition=SCARD_LEAVE_CARD) cc.reconnect(disposition=SCARD_RESET_CARD) cc.reconnect(disposition=SCARD_UNPOWER_CARD) cc.disconnect() else: self.assertRaises(NoCardException, cc.connect) def testcase_CardReconnectNoConnect(self): """Test .reconnect()""" for reader in readers(): cc = reader.createConnection() if expectedATRinReader[str(reader)]: # reconnect without connect first shall fail self.assertRaises(CardConnectionException, cc.reconnect) else: self.assertRaises(NoCardException, cc.connect)
class testcase_CardConnection(unittest.TestCase): '''Test case for CardConnection.''' def testcase_CardConnection(self): '''Test with default protocols the response to SELECT DF_TELECOM.''' pass def testcase_CardConnectionT0(self): '''Test with T0 the response to SELECT DF_TELECOM.''' pass def testcase_CardConnectionT1inConnect(self): '''Test that connecting with T1 on a T0 card fails.''' pass def testcase_CardConnectionT1inTransmit(self): '''Test that T1 in transmit for a T0 card fails.''' pass def testcase_CardConnectionT0T1(self): '''Test test with T0 | T1 the response to SELECT DF_TELECOM.''' pass def testcase_CardConnectionT0inTransmit(self): '''Test with T0 in transmit the response to SELECT DF_TELECOM.''' pass def testcase_CardConnectionT0T1inTransmitMustFail(self): '''Test with bad parameter in transmit the response to SELECT DF_TELECOM.''' pass def testcase_CardReconnectProtocol(self): '''Test .reconnect()''' pass def testcase_CardReconnectMode(self): '''Test .reconnect()''' pass def testcase_CardReconnectDisposition(self): '''Test .reconnect()''' pass def testcase_CardReconnectNoConnect(self): '''Test .reconnect()''' pass
12
12
14
1
12
1
3
0.13
1
4
3
0
11
0
11
83
168
19
132
43
120
17
101
43
89
3
2
2
33
147,452
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/ReaderToolbar.py
smartcard.wx.ReaderToolbar.ReaderToolbar
class ReaderToolbar(wx.ToolBar): """ReaderToolbar. Contains controls to select a reader from a listbox and connect to the cards.""" def __init__(self, parent): """Constructor, creating the reader toolbar.""" wx.ToolBar.__init__( self, parent, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.SIMPLE_BORDER | wx.TB_HORIZONTAL | wx.TB_FLAT | wx.TB_TEXT, name="Reader Toolbar", ) # create bitmaps for toolbar tsize = (16, 16) if None != ICO_READER: bmpReader = wx.Bitmap(ICO_READER, wx.BITMAP_TYPE_ICO) else: bmpReader = wx.ArtProvider_GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, tsize) if None != ICO_SMARTCARD: bmpCard = wx.Bitmap(ICO_SMARTCARD, wx.BITMAP_TYPE_ICO) else: bmpCard = wx.ArtProvider_GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, tsize) self.readercombobox = ReaderComboBox(self) # create and add controls self.AddSimpleTool( 10, bmpReader, "Select smart card reader", "Select smart card reader" ) self.AddControl(self.readercombobox) self.AddSeparator() self.AddSimpleTool(20, bmpCard, "Connect to smartcard", "Connect to smart card") self.AddSeparator() self.Realize()
class ReaderToolbar(wx.ToolBar): '''ReaderToolbar. Contains controls to select a reader from a listbox and connect to the cards.''' def __init__(self, parent): '''Constructor, creating the reader toolbar.''' pass
2
2
33
3
27
3
3
0.18
1
1
1
0
1
1
1
1
37
4
28
6
26
5
17
6
15
3
1
1
3
147,453
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/SimpleSCardApp.py
smartcard.wx.SimpleSCardApp.SimpleSCardApp
class SimpleSCardApp(wx.App): """The SimpleSCardApp class represents the smart card application. SimpleSCardApp is a subclass of wx.App. """ def __init__( self, appname="", apppanel=None, appstyle=TR_DEFAULT, appicon=None, pos=(-1, -1), size=(-1, -1), ): r"""Constructor for simple smart card application. @param appname: the application name @param apppanel: the application panel to display in the application frame @param appicon: the application icon file; the default is no icon @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - PANEL_APDUTRACER: display an APDU tracer panel - default is TR_DEFAULT = TR_SMARTCARD @param pos: the application position as a (x,y) tuple; default is (-1,-1) @param size: the application window size as a (x,y) tuple; default is (-1,-1) Example: C{app = SimpleSCardApp( appname = 'A simple smartcard application', apppanel = testpanel.MyPanel, appstyle = TR_READER | TR_SMARTCARD, appicon = 'resources\mysmartcard.ico')} """ self.appname = appname self.apppanel = apppanel self.appstyle = appstyle self.appicon = appicon self.pos = pos self.size = size wx.App.__init__(self, False) def OnInit(self): """Create and display application frame.""" self.frame = SimpleSCardAppFrame( self.appname, self.apppanel, self.appstyle, self.appicon, self.pos, self.size, ) self.frame.Show(True) self.SetTopWindow(self.frame) return True
class SimpleSCardApp(wx.App): '''The SimpleSCardApp class represents the smart card application. SimpleSCardApp is a subclass of wx.App. ''' def __init__( self, appname="", apppanel=None, appstyle=TR_DEFAULT, appicon=None, pos=(-1, -1), size=(-1, -1), ): '''Constructor for simple smart card application. @param appname: the application name @param apppanel: the application panel to display in the application frame @param appicon: the application icon file; the default is no icon @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - PANEL_APDUTRACER: display an APDU tracer panel - default is TR_DEFAULT = TR_SMARTCARD @param pos: the application position as a (x,y) tuple; default is (-1,-1) @param size: the application window size as a (x,y) tuple; default is (-1,-1) Example: C{app = SimpleSCardApp( appname = 'A simple smartcard application', apppanel = testpanel.MyPanel, appstyle = TR_READER | TR_SMARTCARD, appicon = 'resources\mysmartcard.ico')} ''' pass def OnInit(self): '''Create and display application frame.''' pass
3
3
26
1
14
11
1
0.83
1
1
1
0
2
7
2
2
57
4
29
18
18
24
14
10
11
1
1
0
2
147,454
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/SimpleSCardAppEventObserver.py
smartcard.wx.SimpleSCardAppEventObserver.SimpleSCardAppEventObserver
class SimpleSCardAppEventObserver: """This interface defines the event handlers called by the SimpleSCardApp.""" def __init__(self): self.selectedcard = None self.selectedreader = None # callbacks from SimpleCardAppFrame controls def OnActivateCard(self, card): """Called when a card is activated in the reader tree control or toolbar.""" self.selectedcard = card def OnActivateReader(self, reader): """Called when a reader is activated in the reader tree control or toolbar.""" self.selectedreader = reader def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" pass def OnDeselectCard(self, card): """Called when a card is selected in the reader tree control or toolbar.""" self.selectedcard = None def OnSelectCard(self, card): """Called when a card is selected in the reader tree control or toolbar.""" self.selectedcard = card def OnSelectReader(self, reader): """Called when a reader is selected in the reader tree control or toolbar.""" self.selectedreader = reader
class SimpleSCardAppEventObserver: '''This interface defines the event handlers called by the SimpleSCardApp.''' def __init__(self): pass def OnActivateCard(self, card): '''Called when a card is activated in the reader tree control or toolbar.''' pass def OnActivateReader(self, reader): '''Called when a reader is activated in the reader tree control or toolbar.''' pass def OnDeactivateCard(self, card): '''Called when a card is deactivated in the reader tree control or toolbar.''' pass def OnDeselectCard(self, card): '''Called when a card is selected in the reader tree control or toolbar.''' pass def OnSelectCard(self, card): '''Called when a card is selected in the reader tree control or toolbar.''' pass def OnSelectReader(self, reader): '''Called when a reader is selected in the reader tree control or toolbar.''' pass
8
7
4
0
2
2
1
0.94
0
0
0
3
7
2
7
7
38
7
16
10
8
15
16
10
8
1
0
0
7
147,455
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/SimpleSCardAppFrame.py
smartcard.wx.SimpleSCardAppFrame.BlankPanel
class BlankPanel(wx.Panel, SimpleSCardAppEventObserver): """A blank panel in case no panel is provided to SimpleSCardApp.""" def __init__(self, parent): wx.Panel.__init__(self, parent, -1) sizer = wx.GridSizer(1, 1, 0) self.SetSizer(sizer) self.SetAutoLayout(True)
class BlankPanel(wx.Panel, SimpleSCardAppEventObserver): '''A blank panel in case no panel is provided to SimpleSCardApp.''' def __init__(self, parent): pass
2
1
5
0
5
0
1
0.17
2
0
0
0
1
0
1
8
8
1
6
3
4
1
6
3
4
1
1
0
1
147,456
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/SimpleSCardAppFrame.py
smartcard.wx.SimpleSCardAppFrame.SimpleSCardAppFrame
class SimpleSCardAppFrame(wx.Frame): """The main frame of the simple smartcard application.""" def __init__( self, appname, apppanelclass, appstyle, appicon, pos=(-1, -1), size=(-1, -1), ): """ Constructor. Creates the frame with two panels: - the left-hand panel is holding the smartcard and/or reader tree - the right-hand panel is holding the application dialog @param appname: name of the application @param apppanelclass: the class of the panel to instantiate in the L{SimpleSCardAppFrame} @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - PANEL_APDUTRACER: display an APDU tracer panel - default is TR_DEFAULT = TR_SMARTCARD @param pos: the application position as a (x,y) tuple; default is (-1,-1) @param size: the application window size as a (x,y) tuple; default is (-1,-1) """ wx.Frame.__init__( self, None, wxID_SIMPLESCARDAPP_FRAME, appname, pos=pos, size=size, style=wx.DEFAULT_FRAME_STYLE, ) if appicon: _icon = wx.Icon(appicon, wx.BITMAP_TYPE_ICO) self.SetIcon(_icon) elif os.path.exists(smartcard.wx.ICO_SMARTCARD): _icon = wx.Icon(smartcard.wx.ICO_SMARTCARD, wx.BITMAP_TYPE_ICO) self.SetIcon(_icon) boxsizer = wx.BoxSizer(wx.VERTICAL) self.treeuserpanel = TreeAndUserPanelPanel(self, apppanelclass, appstyle) boxsizer.Add(self.treeuserpanel, 3, wx.EXPAND | wx.ALL) # create a toolbar if required if appstyle & smartcard.wx.SimpleSCardApp.TB_SMARTCARD: self.toolbar = ReaderToolbar.ReaderToolbar(self) self.SetToolBar(self.toolbar) else: self.toolbar = None # create an apdu tracer console if required if appstyle & smartcard.wx.SimpleSCardApp.PANEL_APDUTRACER: self.apdutracerpanel = APDUTracerPanel.APDUTracerPanel(self) boxsizer.Add(self.apdutracerpanel, 1, wx.EXPAND | wx.ALL) else: self.apdutracerpanel = None self.SetSizer(boxsizer) self.SetAutoLayout(True) self.Bind(wx.EVT_CLOSE, self.OnCloseFrame) if appstyle & smartcard.wx.SimpleSCardApp.TB_SMARTCARD: self.Bind( wx.EVT_COMBOBOX, self.OnReaderComboBox, self.toolbar.readercombobox ) def OnCloseFrame(self, evt): """Called when frame is closed, i.e. on wx.EVT_CLOSE""" evt.Skip() def OnExit(self, evt): """Called when frame application exits.""" self.Close(True) evt.Skip() def OnReaderComboBox(self, event): """Called when the user activates a reader in the toolbar combo box.""" cb = event.GetEventObject() reader = cb.GetClientData(cb.GetSelection()) if isinstance(reader, smartcard.reader.Reader.Reader): self.treeuserpanel.dialogpanel.OnActivateReader(reader)
class SimpleSCardAppFrame(wx.Frame): '''The main frame of the simple smartcard application.''' def __init__( self, appname, apppanelclass, appstyle, appicon, pos=(-1, -1), size=(-1, -1), ): ''' Constructor. Creates the frame with two panels: - the left-hand panel is holding the smartcard and/or reader tree - the right-hand panel is holding the application dialog @param appname: name of the application @param apppanelclass: the class of the panel to instantiate in the L{SimpleSCardAppFrame} @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - PANEL_APDUTRACER: display an APDU tracer panel - default is TR_DEFAULT = TR_SMARTCARD @param pos: the application position as a (x,y) tuple; default is (-1,-1) @param size: the application window size as a (x,y) tuple; default is (-1,-1) ''' pass def OnCloseFrame(self, evt): '''Called when frame is closed, i.e. on wx.EVT_CLOSE''' pass def OnExit(self, evt): '''Called when frame application exits.''' pass def OnReaderComboBox(self, event): '''Called when the user activates a reader in the toolbar combo box.''' pass
5
5
21
2
14
6
3
0.42
1
3
3
0
4
3
4
4
89
11
55
20
42
23
34
12
29
6
1
1
10
147,457
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_Card.py
testcase_Card.testcase_Card
class testcase_Card(unittest.TestCase): """Test case for smartcard.Card.""" def testcase_CardDictionary(self): """Create a dictionary with Card keys""" mydict = {} for reader in readers(): card = Card(reader, expectedATRinReader[reader.name]) mydict[card] = reader for card in list(mydict.keys()): self.assertTrue(str(card.reader) in expectedReaders) def testcase_Card_FromReaders(self): """Create a Card from Readers and test that the response to SELECT DF_TELECOM has two bytes.""" for reader in readers(): card = Card(reader, expectedATRinReader[reader.name]) cc = card.createConnection() if expectedATRinReader[str(reader)]: cc.connect() response, sw1, sw2 = cc.transmit(SELECT + DF_TELECOM) expectedSWs = {"9f 1a": 1, "9f 20": 2, "6e 0": 3} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) def testcase_Card_FromReaderStrings(self): """Create a Card from reader strings and test that the response to SELECT DF_TELECOM has two bytes.""" for reader in readers(): card = Card(str(reader), expectedATRinReader[reader.name]) cc = card.createConnection() if expectedATRinReader[str(reader)]: cc.connect() response, sw1, sw2 = cc.transmit(SELECT + DF_TELECOM) expectedSWs = {"9f 1a": 1, "9f 20": 2, "6e 0": 3} self.assertEqual([], response) self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}") else: self.assertRaises(NoCardException, cc.connect) def testcase_Card_Eq_NotEq(self): """Test == and != for Cards.""" for reader in readers(): card = Card(str(reader), expectedATRinReader[reader.name]) cardcopy = Card(str(reader), expectedATRinReader[str(reader)]) self.assertEqual(True, card == cardcopy) self.assertEqual(True, not card != cardcopy) for reader in readers(): card = Card(str(reader), expectedATRinReader[reader.name]) cardcopy = Card(str(reader), [0, 0]) self.assertEqual(True, card != cardcopy) self.assertEqual(True, not card == cardcopy)
class testcase_Card(unittest.TestCase): '''Test case for smartcard.Card.''' def testcase_CardDictionary(self): '''Create a dictionary with Card keys''' pass def testcase_Card_FromReaders(self): '''Create a Card from Readers and test that the response to SELECT DF_TELECOM has two bytes.''' pass def testcase_Card_FromReaderStrings(self): '''Create a Card from reader strings and test that the response to SELECT DF_TELECOM has two bytes.''' pass def testcase_Card_Eq_NotEq(self): '''Test == and != for Cards.''' pass
5
5
13
1
11
2
3
0.16
1
4
2
0
4
0
4
76
58
8
43
21
38
7
41
21
36
3
2
2
12
147,458
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/SimpleSCardAppFrame.py
smartcard.wx.SimpleSCardAppFrame.TreeAndUserPanelPanel
class TreeAndUserPanelPanel(wx.Panel): """The panel that contains the Card/Reader TreeCtrl and the user provided Panel.""" def __init__(self, parent, apppanelclass, appstyle): """ Constructor. Creates the panel with two panels: - the left-hand panel is holding the smartcard and/or reader tree - the right-hand panel is holding the application dialog @param apppanelclass: the class of the panel to instantiate in the L{SimpleSCardAppFrame} @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - default is TR_DEFAULT = TR_SMARTCARD """ wx.Panel.__init__(self, parent, -1) self.parent = parent self.selectedcard = None boxsizer = wx.BoxSizer(wx.HORIZONTAL) # create user dialog if None != apppanelclass: self.dialogpanel = apppanelclass(self) else: self.dialogpanel = BlankPanel(self) # create card/reader tree control if ( appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD or appstyle & smartcard.wx.SimpleSCardApp.TR_READER ): self.readertreepanel = CardAndReaderTreePanel.CardAndReaderTreePanel( self, appstyle, self.dialogpanel ) boxsizer.Add(self.readertreepanel, 1, wx.EXPAND | wx.ALL, 5) boxsizer.Add(self.dialogpanel, 2, wx.EXPAND | wx.ALL) if appstyle & smartcard.wx.SimpleSCardApp.TR_READER: self.Bind( wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateReader, self.readertreepanel.readertreectrl, ) self.Bind( wx.EVT_TREE_SEL_CHANGED, self.OnSelectReader, self.readertreepanel.readertreectrl, ) self.Bind( wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnReaderRightClick, self.readertreepanel.readertreectrl, ) self.Bind( wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.readertreepanel.readertreectrl, ) if appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD: self.Bind( wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateCard, self.readertreepanel.cardtreectrl, ) self.Bind( wx.EVT_TREE_SEL_CHANGED, self.OnSelectCard, self.readertreepanel.cardtreectrl, ) self.Bind( wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnCardRightClick, self.readertreepanel.cardtreectrl, ) self.SetSizer(boxsizer) self.SetAutoLayout(True) def ActivateCard(self, card): """Activate a card.""" if not hasattr(card, "connection"): card.connection = card.createConnection() if None != self.parent.apdutracerpanel: card.connection.addObserver(self.parent.apdutracerpanel) card.connection.connect() self.dialogpanel.OnActivateCard(card) def DeactivateCard(self, card): """Deactivate a card.""" if hasattr(card, "connection"): card.connection.disconnect() if None != self.parent.apdutracerpanel: card.connection.deleteObserver(self.parent.apdutracerpanel) delattr(card, "connection") self.dialogpanel.OnDeactivateCard(card) def OnActivateCard(self, event): """Called when the user activates a card in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.ActivateCard(itemdata) else: self.dialogpanel.OnDeselectCard(itemdata) def OnActivateReader(self, event): """Called when the user activates a reader in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.readertreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.ActivateCard(itemdata) elif isinstance(itemdata, smartcard.reader.Reader.Reader): self.dialogpanel.OnActivateReader(itemdata) event.Skip() def OnItemCollapsed(self, event): item = event.GetItem() self.readertreepanel.readertreectrl.Expand(item) def OnCardRightClick(self, event): """Called when user right-clicks a node in the card tree control.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"): self.connectID = wx.NewId() self.disconnectID = wx.NewId() self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID) self.Bind(wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID) menu = wx.Menu() if not hasattr(self.selectedcard, "connection"): menu.Append(self.connectID, "Connect") else: menu.Append(self.disconnectID, "Disconnect") self.PopupMenu(menu) menu.Destroy() def OnReaderRightClick(self, event): """Called when user right-clicks a node in the reader tree control.""" item = event.GetItem() if item: itemdata = self.readertreepanel.readertreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"): self.connectID = wx.NewId() self.disconnectID = wx.NewId() self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID) self.Bind(wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID) menu = wx.Menu() if not hasattr(self.selectedcard, "connection"): menu.Append(self.connectID, "Connect") else: menu.Append(self.disconnectID, "Disconnect") self.PopupMenu(menu) menu.Destroy() def OnConnect(self, event): if isinstance(self.selectedcard, smartcard.Card.Card): self.ActivateCard(self.selectedcard) def OnDisconnect(self, event): if isinstance(self.selectedcard, smartcard.Card.Card): self.DeactivateCard(self.selectedcard) def OnSelectCard(self, event): """Called when the user selects a card in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.dialogpanel.OnSelectCard(itemdata) else: self.dialogpanel.OnDeselectCard(itemdata) def OnSelectReader(self, event): """Called when the user selects a reader in the tree.""" item = event.GetItem() if item: itemdata = self.readertreepanel.readertreectrl.GetItemData(item) if isinstance(itemdata, smartcard.Card.Card): self.dialogpanel.OnSelectCard(itemdata) elif isinstance(itemdata, smartcard.reader.Reader.Reader): self.dialogpanel.OnSelectReader(itemdata) else: self.dialogpanel.OnDeselectCard(itemdata)
class TreeAndUserPanelPanel(wx.Panel): '''The panel that contains the Card/Reader TreeCtrl and the user provided Panel.''' def __init__(self, parent, apppanelclass, appstyle): ''' Constructor. Creates the panel with two panels: - the left-hand panel is holding the smartcard and/or reader tree - the right-hand panel is holding the application dialog @param apppanelclass: the class of the panel to instantiate in the L{SimpleSCardAppFrame} @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - TB_SMARTCARD: display a smartcard toolbar - TB_SMARTCARD: display a reader toolbar - default is TR_DEFAULT = TR_SMARTCARD ''' pass def ActivateCard(self, card): '''Activate a card.''' pass def DeactivateCard(self, card): '''Deactivate a card.''' pass def OnActivateCard(self, event): '''Called when the user activates a card in the tree.''' pass def OnActivateReader(self, event): '''Called when the user activates a reader in the tree.''' pass def OnItemCollapsed(self, event): pass def OnCardRightClick(self, event): '''Called when user right-clicks a node in the card tree control.''' pass def OnReaderRightClick(self, event): '''Called when user right-clicks a node in the reader tree control.''' pass def OnConnect(self, event): pass def OnDisconnect(self, event): pass def OnSelectCard(self, event): '''Called when the user selects a card in the tree.''' pass def OnSelectReader(self, event): '''Called when the user selects a reader in the tree.''' pass
13
10
16
1
13
2
3
0.16
1
2
2
0
12
6
12
12
202
25
152
35
139
25
111
35
98
5
1
3
40
147,459
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_getattrib.py
testcase_getattrib.testcase_getAttrib
class testcase_getAttrib(unittest.TestCase): """Test scard API for SCardGetAttrib""" def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) hresult, self.readers = SCardListReaders(self.hcontext, []) self.assertEqual(hresult, 0) def tearDown(self): hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) def _getAttrib(self, r): if r < len(expectedATRs) and [] != expectedATRs[r]: hresult, hcard, dwActiveProtocol = SCardConnect( self.hcontext, self.readers[r], SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, ) self.assertEqual(hresult, 0) try: hresult, reader, state, protocol, atr = SCardStatus(hcard) self.assertEqual(hresult, 0) self.assertEqual(reader, expectedReaders[r]) self.assertEqual(atr, expectedATRs[r]) if "SCARD_ATTR_ATR_STRING" in scard.__dict__: hresult, attrib = SCardGetAttrib(hcard, SCARD_ATTR_ATR_STRING) self.assertEqual(hresult, 0) self.assertEqual(expectedATRs[r], attrib) if "winscard" == resourceManager: hresult, attrib = SCardGetAttrib( hcard, SCARD_ATTR_DEVICE_SYSTEM_NAME_A ) self.assertEqual(hresult, 0) trimmedAttrib = attrib[:-1] self.assertEqual( expectedReaders[r], apply( struct.pack, ["<" + "B" * len(trimmedAttrib)] + trimmedAttrib, ), ) finally: hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD) self.assertEqual(hresult, 0) def test_getATR0(self): testcase_getAttrib._getAttrib(self, 0) def test_getATR1(self): testcase_getAttrib._getAttrib(self, 1) def test_getATR3(self): testcase_getAttrib._getAttrib(self, 2) def test_getATR4(self): testcase_getAttrib._getAttrib(self, 3)
class testcase_getAttrib(unittest.TestCase): '''Test scard API for SCardGetAttrib''' def setUp(self): pass def tearDown(self): pass def _getAttrib(self, r): pass def test_getATR0(self): pass def test_getATR1(self): pass def test_getATR3(self): pass def test_getATR4(self): pass
8
1
8
1
7
0
1
0.02
1
0
0
0
7
2
7
79
63
11
51
15
43
1
37
15
29
4
2
3
10
147,460
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ErrorChecker.py
smartcard.sw.ErrorChecker.ErrorChecker
class ErrorChecker: """Base class for status word error checking strategies. Error checking strategies are chained into an L{ErrorCheckingChain} to implement a Chain of Responsibility. Each strategy in the chain is called until an error is detected. The strategy raises a L{smartcard.sw.SWExceptions} exception when an error is detected. Implementation derived from Bruce Eckel, Thinking in Python. The L{ErrorCheckingChain} implements the Chain Of Responsibility design pattern. """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 """ pass
class ErrorChecker: '''Base class for status word error checking strategies. Error checking strategies are chained into an L{ErrorCheckingChain} to implement a Chain of Responsibility. Each strategy in the chain is called until an error is detected. The strategy raises a L{smartcard.sw.SWExceptions} exception when an error is detected. Implementation derived from Bruce Eckel, Thinking in Python. The L{ErrorCheckingChain} implements the Chain Of Responsibility design pattern. ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 ''' pass
2
2
10
2
2
6
1
5
0
0
0
7
1
0
1
1
23
5
3
2
1
15
3
2
1
1
0
0
1
147,461
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
smartcard.wx.CardAndReaderTreePanel.ReaderTreeCtrl
class ReaderTreeCtrl(BaseCardTreeCtrl): """The ReaderTreeCtrl monitors inserted cards and readers and notifies the application client dialog of any card activation.""" def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): """Constructor. Create a reader tree control.""" BaseCardTreeCtrl.__init__( self, parent, ID, pos, size, wx.TR_SINGLE | wx.TR_NO_BUTTONS, clientpanel ) self.mutex = RLock() self.root = self.AddRoot("Smartcard Readers") self.SetItemData(self.root, None) self.SetItemImage(self.root, self.fldrindex, wx.TreeItemIcon_Normal) self.SetItemImage(self.root, self.fldropenindex, wx.TreeItemIcon_Expanded) self.Expand(self.root) def AddATR(self, readernode, atr): """Add an ATR to a reader node.""" capchild = self.AppendItem(readernode, atr) self.SetItemData(capchild, None) self.SetItemImage(capchild, self.cardimageindex, wx.TreeItemIcon_Normal) self.SetItemImage(capchild, self.cardimageindex, wx.TreeItemIcon_Expanded) self.Expand(capchild) return capchild def GetATR(self, reader): """Return the ATR of the card inserted into the reader.""" atr = "no card inserted" try: if not type(reader) is str: connection = reader.createConnection() connection.connect() atr = toHexString(connection.getATR()) connection.disconnect() except NoCardException: pass except CardConnectionException: pass return atr def OnAddCards(self, addedcards): """Called when a card is inserted. Adds the smart card child to the reader node.""" self.mutex.acquire() try: parentnode = self.root for cardtoadd in addedcards: (childReader, cookie) = self.GetFirstChild(parentnode) found = False while childReader.IsOk() and not found: if self.GetItemText(childReader) == str(cardtoadd.reader): (childCard, cookie2) = self.GetFirstChild(childReader) self.SetItemText(childCard, toHexString(cardtoadd.atr)) self.SetItemData(childCard, cardtoadd) found = True else: (childReader, cookie) = self.GetNextChild(parentnode, cookie) # reader was not found, add reader node # this happens when card monitoring thread signals # added cards before reader monitoring thread signals # added readers if not found: childReader = self.AppendItem(parentnode, str(cardtoadd.reader)) self.SetItemData(childReader, cardtoadd.reader) self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Normal ) self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Expanded ) childCard = self.AddATR(childReader, toHexString(cardtoadd.atr)) self.SetItemData(childCard, cardtoadd) self.Expand(childReader) self.Expand(self.root) finally: self.mutex.release() self.EnsureVisible(self.root) self.Repaint() def OnAddReaders(self, addedreaders): """Called when a reader is inserted. Adds the smart card reader to the smartcard readers tree.""" self.mutex.acquire() try: parentnode = self.root for readertoadd in addedreaders: # is the reader already here? found = False (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk() and not found: if self.GetItemText(childReader) == str(readertoadd): found = True else: (childReader, cookie) = self.GetNextChild(parentnode, cookie) if not found: childReader = self.AppendItem(parentnode, str(readertoadd)) self.SetItemData(childReader, readertoadd) self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Normal ) self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Expanded ) self.AddATR(childReader, self.GetATR(readertoadd)) self.Expand(childReader) self.Expand(self.root) finally: self.mutex.release() self.EnsureVisible(self.root) self.Repaint() def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes the card from the tree.""" self.mutex.acquire() try: parentnode = self.root for cardtoremove in removedcards: (childReader, cookie) = self.GetFirstChild(parentnode) found = False while childReader.IsOk() and not found: if self.GetItemText(childReader) == str(cardtoremove.reader): (childCard, cookie2) = self.GetFirstChild(childReader) self.SetItemText(childCard, "no card inserted") found = True else: (childReader, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) finally: self.mutex.release() self.EnsureVisible(self.root) self.Repaint() def OnRemoveReaders(self, removedreaders): """Called when a reader is removed. Removes the reader from the smartcard readers tree.""" self.mutex.acquire() try: parentnode = self.root for readertoremove in removedreaders: (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk(): if self.GetItemText(childReader) == str(readertoremove): self.Delete(childReader) else: (childReader, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) finally: self.mutex.release() self.EnsureVisible(self.root) self.Repaint()
class ReaderTreeCtrl(BaseCardTreeCtrl): '''The ReaderTreeCtrl monitors inserted cards and readers and notifies the application client dialog of any card activation.''' def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): '''Constructor. Create a reader tree control.''' pass def AddATR(self, readernode, atr): '''Add an ATR to a reader node.''' pass def GetATR(self, reader): '''Return the ATR of the card inserted into the reader.''' pass def OnAddCards(self, addedcards): '''Called when a card is inserted. Adds the smart card child to the reader node.''' pass def OnAddReaders(self, addedreaders): '''Called when a reader is inserted. Adds the smart card reader to the smartcard readers tree.''' pass def OnRemoveCards(self, removedcards): '''Called when a card is removed. Removes the card from the tree.''' pass def OnRemoveReaders(self, removedreaders): '''Called when a reader is removed. Removes the reader from the smartcard readers tree.''' pass
8
8
22
1
19
2
3
0.13
1
4
2
0
7
2
7
9
165
13
134
38
118
18
108
30
100
5
2
4
24
147,462
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_locatecards.py
testcase_locatecards.testcase_locatecards
class testcase_locatecards(unittest.TestCase): """Test scard API for ATR retrieval with SCardLocateCards""" def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) def tearDown(self): hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) def test_locateCards(self): hresult, readers = SCardListReaders(self.hcontext, []) self.assertEqual(hresult, 0) foundReaders = {} for reader in readers: foundReaders[reader] = 1 for reader in expectedReaders: self.assertTrue(reader in foundReaders) if "winscard" == resourceManager: hresult, cards = SCardListCards(self.hcontext, [], []) self.assertEqual(hresult, 0) readerstates = [] for i in range(len(readers)): readerstates += [(readers[i], SCARD_STATE_UNAWARE)] hresult, newstates = SCardLocateCards(self.hcontext, cards, readerstates) self.assertEqual(hresult, 0) dictexpectedreaders = {} for reader in expectedReaders: dictexpectedreaders[reader] = 1 for reader, eventstate, atr in newstates: if reader in dictexpectedreaders and [] != expectedATRinReader[reader]: self.assertEqual(expectedATRinReader[reader], atr) self.assertTrue(eventstate & SCARD_STATE_PRESENT) self.assertTrue(eventstate & SCARD_STATE_CHANGED) # 10ms delay, so that time-out always occurs hresult, newstates = SCardGetStatusChange(self.hcontext, 10, newstates) self.assertEqual(hresult, SCARD_E_TIMEOUT) self.assertEqual( SCardGetErrorMessage(hresult), "The user-specified timeout value has expired. ", ) elif "pcsclite" == resourceManager: readerstates = [] for i in range(len(readers)): readerstates += [(readers[i], SCARD_STATE_UNAWARE)] hresult, newstates = SCardGetStatusChange(self.hcontext, 0, readerstates) self.assertEqual(hresult, 0) dictexpectedreaders = {} for reader in expectedReaders: dictexpectedreaders[reader] = 1 for reader, eventstate, atr in newstates: if reader in dictexpectedreaders and [] != expectedATRinReader[reader]: self.assertEqual(expectedATRinReader[reader], atr) self.assertTrue(eventstate & SCARD_STATE_PRESENT) self.assertTrue(eventstate & SCARD_STATE_CHANGED)
class testcase_locatecards(unittest.TestCase): '''Test scard API for ATR retrieval with SCardLocateCards''' def setUp(self): pass def tearDown(self): pass def test_locateCards(self): pass
4
1
20
3
17
0
5
0.04
1
1
0
0
3
1
3
75
65
12
51
15
47
2
47
15
43
13
2
3
15
147,463
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ISO7816_4ErrorChecker.py
smartcard.sw.ISO7816_4ErrorChecker.ISO7816_4ErrorChecker
class ISO7816_4ErrorChecker(ErrorChecker): """ISO7816-4 error checking strategy. This strategy raises the following exceptions: - sw1 sw2 - 62 00 81 82 83 84 FF WarningProcessingException - 63 00 81 C0->CF WarningProcessingException - 64 00 ExecutionErrorException - 67 00 CheckingErrorException - 68 81 82 CheckingErrorException - 69 81->88 99? c1? CheckingErrorException - 6a 80->88 CheckingErrorException - 6b 00 CheckingErrorException - 6d 00 CheckingErrorException - 6e 00 CheckingErrorException - 6f 00 CheckingErrorException This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 65 any - 66 any - 6c any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 80 85 - 6b any except 00 Use another checker in the error checking chain, e.g., the ISO7816_4SW1ErrorChecker, to raise exceptions on these undefined values. """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status words @param sw2: apdu data status words """ if sw1 in iso7816_4SW: exception, sw2dir = iso7816_4SW[sw1] if type(sw2dir) == type({}): try: message = sw2dir[sw2] raise exception(data, sw1, sw2, message) except KeyError: pass
class ISO7816_4ErrorChecker(ErrorChecker): '''ISO7816-4 error checking strategy. This strategy raises the following exceptions: - sw1 sw2 - 62 00 81 82 83 84 FF WarningProcessingException - 63 00 81 C0->CF WarningProcessingException - 64 00 ExecutionErrorException - 67 00 CheckingErrorException - 68 81 82 CheckingErrorException - 69 81->88 99? c1? CheckingErrorException - 6a 80->88 CheckingErrorException - 6b 00 CheckingErrorException - 6d 00 CheckingErrorException - 6e 00 CheckingErrorException - 6f 00 CheckingErrorException This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 65 any - 66 any - 6c any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 80 85 - 6b any except 00 Use another checker in the error checking chain, e.g., the ISO7816_4SW1ErrorChecker, to raise exceptions on these undefined values. ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status words @param sw2: apdu data status words ''' pass
2
2
17
2
9
6
4
3.3
1
2
0
0
1
0
1
2
51
8
10
4
8
33
10
4
8
4
1
3
4
147,464
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ISO7816_4_SW1ErrorChecker.py
smartcard.sw.ISO7816_4_SW1ErrorChecker.ISO7816_4_SW1ErrorChecker
class ISO7816_4_SW1ErrorChecker(ErrorChecker): """ISO7816-4 error checker based on status word sw1 only. This error checker raises the following exceptions: - sw1 sw2 - 62 any L{WarningProcessingException} - 63 any L{WarningProcessingException} - 64 any L{ExecutionErrorException} - 65 any L{ExecutionErrorException} - 66 any L{SecurityRelatedException} - 67 any L{CheckingErrorException} - 68 any L{CheckingErrorException} - 69 any L{CheckingErrorException} - 6a any L{CheckingErrorException} - 6b any L{CheckingErrorException} - 6c any L{CheckingErrorException} - 6d any L{CheckingErrorException} - 6e any L{CheckingErrorException} - 6f any L{CheckingErrorException} """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 """ if sw1 in iso7816_4SW1: exception = iso7816_4SW1[sw1] raise exception(data, sw1, sw2)
class ISO7816_4_SW1ErrorChecker(ErrorChecker): '''ISO7816-4 error checker based on status word sw1 only. This error checker raises the following exceptions: - sw1 sw2 - 62 any L{WarningProcessingException} - 63 any L{WarningProcessingException} - 64 any L{ExecutionErrorException} - 65 any L{ExecutionErrorException} - 66 any L{SecurityRelatedException} - 67 any L{CheckingErrorException} - 68 any L{CheckingErrorException} - 69 any L{CheckingErrorException} - 6a any L{CheckingErrorException} - 6b any L{CheckingErrorException} - 6c any L{CheckingErrorException} - 6d any L{CheckingErrorException} - 6e any L{CheckingErrorException} - 6f any L{CheckingErrorException} ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 ''' pass
2
2
10
1
4
5
2
4.6
1
0
0
0
1
0
1
2
31
3
5
3
3
23
5
3
3
2
1
1
2
147,465
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ISO7816_8ErrorChecker.py
smartcard.sw.ISO7816_8ErrorChecker.ISO7816_8ErrorChecker
class ISO7816_8ErrorChecker(ErrorChecker): """ISO7816-8 error checker. This error checker raises the following exceptions: - sw1 sw2 - 63 00,c0-cf L{WarningProcessingException} - 65 81 L{ExecutionErrorException} - 66 00,87,88 L{SecurityRelatedException} - 67 00 L{CheckingErrorException} - 68 82,84 L{CheckingErrorException} - 69 82,83,84,85 L{CheckingErrorException} - 6A 81,82,86,88 L{CheckingErrorException} This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 62 any - 6f any and on undefined sw2 values, e.g.: - sw1 sw2 - 66 81 82 - 67 any except 00 Use another checker in the error checking chain, e.g., the L{ISO7816_4_SW1ErrorChecker} or L{ISO7816_4ErrorChecker}, to raise exceptions on these undefined values. """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 """ if sw1 in iso7816_8SW: exception, sw2dir = iso7816_8SW[sw1] if type(sw2dir) == type({}): try: message = sw2dir[sw2] raise exception(data, sw1, sw2, message) except KeyError: pass
class ISO7816_8ErrorChecker(ErrorChecker): '''ISO7816-8 error checker. This error checker raises the following exceptions: - sw1 sw2 - 63 00,c0-cf L{WarningProcessingException} - 65 81 L{ExecutionErrorException} - 66 00,87,88 L{SecurityRelatedException} - 67 00 L{CheckingErrorException} - 68 82,84 L{CheckingErrorException} - 69 82,83,84,85 L{CheckingErrorException} - 6A 81,82,86,88 L{CheckingErrorException} This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 62 any - 6f any and on undefined sw2 values, e.g.: - sw1 sw2 - 66 81 82 - 67 any except 00 Use another checker in the error checking chain, e.g., the L{ISO7816_4_SW1ErrorChecker} or L{ISO7816_4ErrorChecker}, to raise exceptions on these undefined values. ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 ''' pass
2
2
17
2
9
6
4
2.8
1
2
0
0
1
0
1
2
46
8
10
4
8
28
10
4
8
4
1
3
4
147,466
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ISO7816_9ErrorChecker.py
smartcard.sw.ISO7816_9ErrorChecker.ISO7816_9ErrorChecker
class ISO7816_9ErrorChecker(ErrorChecker): """ISO7816-8 error checker. This error checker raises the following exceptions: - sw1 sw2 - 62 82 WarningProcessingException - 64 00 ExecutionErrorException - 69 82 CheckingErrorException - 6A 80,84,89,8A CheckingErrorException This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 63 any - 6F any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 81 83 - 64 any except 00 Use another checker in the error checking chain, e.g., the L{ISO7816_4_SW1ErrorChecker} or L{ISO7816_4ErrorChecker}, to raise exceptions on these undefined values. """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 """ if sw1 in iso7816_9SW: exception, sw2dir = iso7816_9SW[sw1] if type(sw2dir) == type({}): try: message = sw2dir[sw2] raise exception(data, sw1, sw2, message) except KeyError: pass
class ISO7816_9ErrorChecker(ErrorChecker): '''ISO7816-8 error checker. This error checker raises the following exceptions: - sw1 sw2 - 62 82 WarningProcessingException - 64 00 ExecutionErrorException - 69 82 CheckingErrorException - 6A 80,84,89,8A CheckingErrorException This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 63 any - 6F any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 81 83 - 64 any except 00 Use another checker in the error checking chain, e.g., the L{ISO7816_4_SW1ErrorChecker} or L{ISO7816_4ErrorChecker}, to raise exceptions on these undefined values. ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 ''' pass
2
2
17
2
9
6
4
2.5
1
2
0
0
1
0
1
2
43
8
10
4
8
25
10
4
8
4
1
3
4
147,467
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/SWExceptions.py
smartcard.sw.SWExceptions.CheckingErrorException
class CheckingErrorException(SWException): """Raised when a checking error is detected from sw1, sw2. Examples of checking error: sw1=67 to 6F (ISO781604).""" def __init__(self, data, sw1, sw2, message=""): SWException.__init__(self, data, sw1, sw2, "checking error - " + message)
class CheckingErrorException(SWException): '''Raised when a checking error is detected from sw1, sw2. Examples of checking error: sw1=67 to 6F (ISO781604).''' def __init__(self, data, sw1, sw2, message=""): pass
2
1
2
0
2
0
1
0.67
1
0
0
0
1
0
1
13
6
1
3
2
1
2
3
2
1
1
4
0
1
147,468
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/SWExceptions.py
smartcard.sw.SWExceptions.ExecutionErrorException
class ExecutionErrorException(SWException): """Raised when an execution error is detected from sw1, sw2. Examples of execution error: sw1=64 or sw=65 (ISO7816-4).""" def __init__(self, data, sw1, sw2, message=""): SWException.__init__(self, data, sw1, sw2, "execution error - " + message)
class ExecutionErrorException(SWException): '''Raised when an execution error is detected from sw1, sw2. Examples of execution error: sw1=64 or sw=65 (ISO7816-4).''' def __init__(self, data, sw1, sw2, message=""): pass
2
1
2
0
2
0
1
0.67
1
0
0
0
1
0
1
13
6
1
3
2
1
2
3
2
1
1
4
0
1
147,469
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/SWExceptions.py
smartcard.sw.SWExceptions.SWException
class SWException(Exception): """Base class for status word exceptions. Status word exceptions are generated when errors and warnings are detected in the sw1 and sw2 bytes of the response apdu. """ def __init__(self, data, sw1, sw2, message=""): self.message = message """response apdu data""" self.data = data """response apdu sw1""" self.sw1 = sw1 """response apdu sw2""" self.sw2 = sw2 def __str__(self): return repr("Status word exception: " + self.message + "!")
class SWException(Exception): '''Base class for status word exceptions. Status word exceptions are generated when errors and warnings are detected in the sw1 and sw2 bytes of the response apdu. ''' def __init__(self, data, sw1, sw2, message=""): pass def __str__(self): pass
3
1
5
0
4
2
1
0.88
1
0
0
5
2
4
2
12
19
4
8
7
5
7
8
7
5
1
3
0
2
147,470
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitor.py
testcase_readermonitor.testthread
class testthread(threading.Thread): """thread""" def __init__(self, obsindex, testcase): threading.Thread.__init__(self) self.obsindex = obsindex self.testcase = testcase self.readermonitor = ReaderMonitor() self.observer = None def run(self): # create and register observer self.observer = printobserver(self.obsindex, self.testcase) self.readermonitor.addObserver(self.observer) time.sleep(1) self.readermonitor.deleteObserver(self.observer)
class testthread(threading.Thread): '''thread''' def __init__(self, obsindex, testcase): pass def run(self): pass
3
1
6
0
6
1
1
0.17
1
2
2
0
2
4
2
27
16
2
12
7
9
2
12
7
9
1
1
0
2
147,471
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/SWExceptions.py
smartcard.sw.SWExceptions.SecurityRelatedException
class SecurityRelatedException(SWException): """Raised when a security issue is detected from sw1, sw2. Examples of security issue: sw1=66 (ISO7816-4).""" def __init__(self, data, sw1, sw2, message=""): SWException.__init__(self, data, sw1, sw2, "security issue - " + message)
class SecurityRelatedException(SWException): '''Raised when a security issue is detected from sw1, sw2. Examples of security issue: sw1=66 (ISO7816-4).''' def __init__(self, data, sw1, sw2, message=""): pass
2
1
2
0
2
0
1
0.67
1
0
0
0
1
0
1
13
6
1
3
2
1
2
3
2
1
1
4
0
1
147,472
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/SWExceptions.py
smartcard.sw.SWExceptions.WarningProcessingException
class WarningProcessingException(SWException): """Raised when a warning processing is detected from sw1, sw2. Examples of warning processing exception: sw1=62 or sw=63 (ISO7816-4).""" def __init__(self, data, sw1, sw2, message=""): SWException.__init__(self, data, sw1, sw2, "warning processing - " + message)
class WarningProcessingException(SWException): '''Raised when a warning processing is detected from sw1, sw2. Examples of warning processing exception: sw1=62 or sw=63 (ISO7816-4).''' def __init__(self, data, sw1, sw2, message=""): pass
2
1
2
0
2
0
1
0.67
1
0
0
0
1
0
1
13
6
1
3
2
1
2
3
2
1
1
4
0
1
147,473
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/op21_ErrorChecker.py
smartcard.sw.op21_ErrorChecker.op21_ErrorChecker
class op21_ErrorChecker(ErrorChecker): """Open platform 2.1 error checker. This error checker raises the following exceptions: - sw1 sw2 - 62 83 L{WarningProcessingException} - 63 00 L{WarningProcessingException} - 64 00 L{ExecutionErrorException} - 65 81 L{ExecutionErrorException} - 67 00 L{CheckingErrorException} - 69 82 85 L{CheckingErrorException} - 6A 80 81 82 84 86 88 L{CheckingErrorException} - 6D 00 L{CheckingErrorException} - 6E 00 L{CheckingErrorException} - 94 84 85 L{CheckingErrorException} This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 63 any - 6F any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 81 83 - 64 any except 00 Use another checker in the error checking chain to raise exceptions on these undefined values. """ def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 """ if sw1 in op21_SW: exception, sw2dir = op21_SW[sw1] if type(sw2dir) == type({}): try: message = sw2dir[sw2] raise exception(data, sw1, sw2, message) except KeyError: pass
class op21_ErrorChecker(ErrorChecker): '''Open platform 2.1 error checker. This error checker raises the following exceptions: - sw1 sw2 - 62 83 L{WarningProcessingException} - 63 00 L{WarningProcessingException} - 64 00 L{ExecutionErrorException} - 65 81 L{ExecutionErrorException} - 67 00 L{CheckingErrorException} - 69 82 85 L{CheckingErrorException} - 6A 80 81 82 84 86 88 L{CheckingErrorException} - 6D 00 L{CheckingErrorException} - 6E 00 L{CheckingErrorException} - 94 84 85 L{CheckingErrorException} This checker does not raise exceptions on undefined sw1 values, e.g.: - sw1 sw2 - 63 any - 6F any and on undefined sw2 values, e.g.: - sw1 sw2 - 62 81 83 - 64 any except 00 Use another checker in the error checking chain to raise exceptions on these undefined values. ''' def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error. Derived classes must raise a L{smartcard.sw.SWExceptions} upon error. @param data: apdu response data @param sw1: apdu data status word 1 @param sw2: apdu data status word 2 ''' pass
2
2
17
2
9
6
4
3
1
2
0
0
1
0
1
2
48
8
10
4
8
30
10
4
8
4
1
3
4
147,474
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/ulist.py
smartcard.ulist.ulist
class ulist(list): """ulist ensures that all items are unique and provides an __onadditem__ hook to perform custom action in subclasses.""" # # override list methods # def __init__(self, initlist=None): if initlist is not None and initlist != []: list.__init__(self, [initlist[0]]) for item in initlist[1:]: if not list.__contains__(self, item): list.append(self, item) else: list.__init__(self, initlist) def __add__(self, other): newother = self.__remove_duplicates(other) self.__appendother__(newother) return self.__class__(list(self) + list(newother)) def __iadd__(self, other): newother = self.__remove_duplicates(other) self.__appendother__(newother) list.__iadd__(self, newother) return self def __radd__(self, other): newother = self.__remove_duplicates(other) return list.__add__(self, newother) def append(self, item): if not list.__contains__(self, item): list.append(self, item) self.__onadditem__(item) def insert(self, i, item): if not list.__contains__(self, item): list.insert(self, i, item) self.__onadditem__(item) def pop(self, i=-1): item = list.pop(self, i) self.__onremoveitem__(item) return item def remove(self, item): list.remove(self, item) self.__onremoveitem__(item) # # non list methods # def __remove_duplicates(self, _other): """Remove from other items already in list.""" if ( not isinstance(_other, type(self)) and not isinstance(_other, type(list)) and not isinstance(_other, list) ): other = [_other] else: other = list(_other) # remove items already in self newother = [] for i in range(0, len(other)): item = other.pop(0) if not list.__contains__(self, item): newother.append(item) # remove duplicate items in other other = [] if newother != []: other.append(newother[0]) for i in range(1, len(newother)): item = newother.pop() if not other.__contains__(item): other.append(item) return other def __appendother__(self, other): """Append other to object.""" for item in other: self.__onadditem__(item) def __onadditem__(self, item): """Called for each item added. Override in subclasses for adding custom action.""" pass def __onremoveitem__(self, item): """Called for each item removed. Override in subclasses for adding custom action.""" pass
class ulist(list): '''ulist ensures that all items are unique and provides an __onadditem__ hook to perform custom action in subclasses.''' def __init__(self, initlist=None): pass def __add__(self, other): pass def __iadd__(self, other): pass def __radd__(self, other): pass def append(self, item): pass def insert(self, i, item): pass def pop(self, i=-1): pass def remove(self, item): pass def __remove_duplicates(self, _other): '''Remove from other items already in list.''' pass def __appendother__(self, other): '''Append other to object.''' pass def __onadditem__(self, item): '''Called for each item added. Override in subclasses for adding custom action.''' pass def __onremoveitem__(self, item): '''Called for each item removed. Override in subclasses for adding custom action.''' pass
13
5
6
0
5
1
2
0.25
1
2
0
2
12
0
12
45
97
16
65
23
52
16
59
23
46
7
2
3
24
147,475
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitor.py
testcase_readermonitor.testcase_readermonitor
class testcase_readermonitor(unittest.TestCase): """Test smartcard framework reader monitoring methods""" def testcase_readermonitorthread(self): """readermonitor thread""" threads = [] for i in range(0, 4): t = testthread(i, self) threads.append(t) for t in threads: t.start() for t in threads: t.join()
class testcase_readermonitor(unittest.TestCase): '''Test smartcard framework reader monitoring methods''' def testcase_readermonitorthread(self): '''readermonitor thread''' pass
2
2
10
0
9
1
4
0.2
1
2
1
0
1
0
1
73
13
1
10
5
8
2
10
5
8
4
2
1
4
147,476
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/APDUHexValidator.py
smartcard.wx.APDUHexValidator.APDUHexValidator
class APDUHexValidator(wx.PyValidator): """A wxValidator that matches APDU in hexadecimal such as: A4 A0 00 00 02 A4A0000002""" def __init__(self): wx.Validator.__init__(self) self.Bind(wx.EVT_CHAR, self.OnChar) def Clone(self): return APDUHexValidator() def Validate(self, win): tc = self.GetWindow() value = tc.GetValue() if not apduregexp.match(value): return False return True def OnChar(self, event): key = event.GetKeyCode() if wx.WXK_SPACE == key or chr(key) in string.hexdigits: value = event.GetEventObject().GetValue() + chr(key) if apduregexp.match(value): event.Skip() return if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip() return if not wx.Validator.IsSilent(): wx.Bell() return
class APDUHexValidator(wx.PyValidator): '''A wxValidator that matches APDU in hexadecimal such as: A4 A0 00 00 02 A4A0000002''' def __init__(self): pass def Clone(self): pass def Validate(self, win): pass def OnChar(self, event): pass
5
1
8
2
6
0
2
0.12
1
0
0
0
4
0
4
4
38
10
25
9
20
3
25
9
20
5
1
2
9
147,477
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/APDUTracerPanel.py
smartcard.wx.APDUTracerPanel.APDUTracerPanel
class APDUTracerPanel(wx.Panel, CardConnectionObserver): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) boxsizer = wx.BoxSizer(wx.HORIZONTAL) self.apdutextctrl = wx.TextCtrl( self, wxID_APDUTEXTCTRL, "", pos=wx.DefaultPosition, style=wx.TE_MULTILINE | wx.TE_READONLY, ) boxsizer.Add(self.apdutextctrl, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(boxsizer) self.SetAutoLayout(True) self.Bind(wx.EVT_TEXT_MAXLEN, self.OnMaxLength, self.apdutextctrl) def OnMaxLength(self, evt): """Reset text buffer when max length is reached.""" self.apdutextctrl.SetValue("") evt.Skip() def update(self, cardconnection, ccevent): """CardConnectionObserver callback.""" apduline = "" if "connect" == ccevent.type: apduline += "connecting to " + cardconnection.getReader() elif "disconnect" == ccevent.type: apduline += "disconnecting from " + cardconnection.getReader() elif "command" == ccevent.type: apduline += "> " + toHexString(ccevent.args[0]) elif "response" == ccevent.type: if [] == ccevent.args[0]: apduline += "< %-2X %-2X" % tuple(ccevent.args[-2:]) else: apduline += ( "< " + toHexString(ccevent.args[0]) + "%-2X %-2X" % tuple(ccevent.args[-2:]) ) self.apdutextctrl.AppendText(apduline + "\n")
class APDUTracerPanel(wx.Panel, CardConnectionObserver): def __init__(self, parent): pass def OnMaxLength(self, evt): '''Reset text buffer when max length is reached.''' pass def update(self, cardconnection, ccevent): '''CardConnectionObserver callback.''' pass
4
2
15
2
12
1
3
0.06
2
1
0
0
3
1
3
5
48
10
36
7
32
2
22
7
18
6
2
2
8
147,478
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
smartcard.wx.CardAndReaderTreePanel.BaseCardTreeCtrl
class BaseCardTreeCtrl(wx.TreeCtrl): """Base class for the smart card and reader tree controls.""" def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): """Constructor. Initializes a smartcard or reader tree control.""" wx.TreeCtrl.__init__( self, parent, ID, pos, size, wx.TR_SINGLE | wx.TR_NO_BUTTONS ) self.clientpanel = clientpanel self.parent = parent isz = (16, 16) il = wx.ImageList(isz[0], isz[1]) self.capindex = il.Add( wx.ArtProvider.GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, isz) ) self.fldrindex = il.Add( wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, isz) ) self.fldropenindex = il.Add( wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, isz) ) if None != ICO_SMARTCARD: self.cardimageindex = il.Add(wx.Bitmap(ICO_SMARTCARD, wx.BITMAP_TYPE_ICO)) if None != ICO_READER: self.readerimageindex = il.Add(wx.Bitmap(ICO_READER, wx.BITMAP_TYPE_ICO)) self.il = il self.SetImageList(self.il) def Repaint(self): self.Refresh()
class BaseCardTreeCtrl(wx.TreeCtrl): '''Base class for the smart card and reader tree controls.''' def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): '''Constructor. Initializes a smartcard or reader tree control.''' pass def Repaint(self): pass
3
2
18
1
17
1
2
0.06
1
0
0
2
2
8
2
2
40
4
34
21
23
2
18
13
15
3
1
1
4
147,479
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
smartcard.wx.CardAndReaderTreePanel.CardAndReaderTreePanel
class CardAndReaderTreePanel(wx.Panel): """Panel containing the smart card and reader tree controls.""" class _CardObserver(CardObserver): """Inner CardObserver. Gets notified of card insertion removal by the CardMonitor.""" def __init__(self, cardtreectrl): self.cardtreectrl = cardtreectrl def update(self, observable, handlers): """CardObserver callback that is notified when cards are added or removed.""" addedcards, removedcards = handlers self.cardtreectrl.OnRemoveCards(removedcards) self.cardtreectrl.OnAddCards(addedcards) class _ReaderObserver(ReaderObserver): """Inner ReaderObserver. Gets notified of reader insertion/removal by the ReaderMonitor.""" def __init__(self, readertreectrl): self.readertreectrl = readertreectrl def update(self, observable, handlers): """ReaderObserver callback that is notified when readers are added or removed.""" addedreaders, removedreaders = handlers self.readertreectrl.OnRemoveReaders(removedreaders) self.readertreectrl.OnAddReaders(addedreaders) def __init__(self, parent, appstyle, clientpanel): """Constructor. Create a smartcard and reader tree control on the left-hand side of the application main frame. @param parent: the tree panel parent @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - default is TR_DEFAULT = TR_SMARTCARD @param clientpanel: the client panel to notify of smartcard and reader events """ wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS) sizer = wx.BoxSizer(wx.VERTICAL) # create the smartcard tree if appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD: self.cardtreectrl = CardTreeCtrl(self, clientpanel=clientpanel) # create the smartcard insertion observer self.cardtreecardobserver = self._CardObserver(self.cardtreectrl) # register as a CardObserver; we will ge # notified of added/removed cards self.cardmonitor = CardMonitor() self.cardmonitor.addObserver(self.cardtreecardobserver) sizer.Add(self.cardtreectrl, flag=wx.EXPAND | wx.ALL, proportion=1) # create the reader tree if appstyle & smartcard.wx.SimpleSCardApp.TR_READER: self.readertreectrl = ReaderTreeCtrl(self, clientpanel=clientpanel) # create the reader insertion observer self.readertreereaderobserver = self._ReaderObserver(self.readertreectrl) # register as a ReaderObserver; we will ge # notified of added/removed readers self.readermonitor = ReaderMonitor() self.readermonitor.addObserver(self.readertreereaderobserver) # create the smartcard insertion observer self.readertreecardobserver = self._CardObserver(self.readertreectrl) # register as a CardObserver; we will get # notified of added/removed cards self.cardmonitor = CardMonitor() self.cardmonitor.addObserver(self.readertreecardobserver) sizer.Add(self.readertreectrl, flag=wx.EXPAND | wx.ALL, proportion=1) self.SetSizer(sizer) self.SetAutoLayout(True) def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers if hasattr(self, "cardmonitor"): self.cardmonitor.deleteObserver(self.cardtreecardobserver) if hasattr(self, "readermonitor"): self.readermonitor.deleteObserver(self.readertreereaderobserver) self.cardmonitor.deleteObserver(self.readertreecardobserver) event.Skip()
class CardAndReaderTreePanel(wx.Panel): '''Panel containing the smart card and reader tree controls.''' class _CardObserver(CardObserver): '''Inner CardObserver. Gets notified of card insertion removal by the CardMonitor.''' def __init__(self, cardtreectrl): pass def update(self, observable, handlers): '''CardObserver callback that is notified when cards are added or removed.''' pass class _ReaderObserver(ReaderObserver): '''Inner ReaderObserver. Gets notified of reader insertion/removal by the ReaderMonitor.''' def __init__(self, cardtreectrl): pass def update(self, observable, handlers): '''ReaderObserver callback that is notified when readers are added or removed.''' pass def __init__(self, cardtreectrl): '''Constructor. Create a smartcard and reader tree control on the left-hand side of the application main frame. @param parent: the tree panel parent @param appstyle: a combination of the following styles (bitwise or |) - TR_SMARTCARD: display a smartcard tree panel - TR_READER: display a reader tree panel - default is TR_DEFAULT = TR_SMARTCARD @param clientpanel: the client panel to notify of smartcard and reader events ''' pass def OnDestroy(self, event): '''Called on panel destruction.''' pass
9
7
13
2
7
4
2
0.74
1
6
6
0
2
7
2
2
93
20
42
21
33
31
42
21
33
3
1
1
10
147,480
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
smartcard.wx.CardAndReaderTreePanel.CardTreeCtrl
class CardTreeCtrl(BaseCardTreeCtrl): """The CardTreeCtrl monitors inserted cards and notifies the application client dialog of any card activation.""" def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): """Constructor. Create a smartcard tree control.""" BaseCardTreeCtrl.__init__( self, parent, ID, pos, size, wx.TR_SINGLE | wx.TR_NO_BUTTONS, clientpanel ) self.root = self.AddRoot("Smartcards") self.SetItemData(self.root, None) self.SetItemImage(self.root, self.fldrindex, wx.TreeItemIcon_Normal) self.SetItemImage(self.root, self.fldropenindex, wx.TreeItemIcon_Expanded) self.Expand(self.root) def OnAddCards(self, addedcards): """Called when a card is inserted. Adds a smart card to the smartcards tree.""" parentnode = self.root for cardtoadd in addedcards: childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr)) self.SetItemText(childCard, toHexString(cardtoadd.atr)) self.SetItemData(childCard, cardtoadd) self.SetItemImage(childCard, self.cardimageindex, wx.TreeItemIcon_Normal) self.SetItemImage(childCard, self.cardimageindex, wx.TreeItemIcon_Expanded) self.Expand(childCard) self.Expand(self.root) self.EnsureVisible(self.root) self.Repaint() def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes a card from the tree.""" parentnode = self.root for cardtoremove in removedcards: (childCard, cookie) = self.GetFirstChild(parentnode) while childCard.IsOk(): if self.GetItemText(childCard) == toHexString(cardtoremove.atr): self.Delete(childCard) (childCard, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) self.EnsureVisible(self.root) self.Repaint()
class CardTreeCtrl(BaseCardTreeCtrl): '''The CardTreeCtrl monitors inserted cards and notifies the application client dialog of any card activation.''' def __init__( self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, clientpanel=None, ): '''Constructor. Create a smartcard tree control.''' pass def OnAddCards(self, addedcards): '''Called when a card is inserted. Adds a smart card to the smartcards tree.''' pass def OnRemoveCards(self, removedcards): '''Called when a card is removed. Removes a card from the tree.''' pass
4
4
15
0
13
2
2
0.17
1
0
0
0
3
1
3
5
52
4
41
19
29
7
31
11
27
4
2
3
7
147,481
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitor.py
testcase_readermonitor.printobserver
class printobserver(ReaderObserver): """observer""" def __init__(self, obsindex, testcase): self.obsindex = obsindex self.testcase = testcase def update(self, observable, handlers): (addedreaders, removedreaders) = handlers foundreaders = {} self.testcase.assertEqual(removedreaders, []) for reader in addedreaders: foundreaders[str(reader)] = 1 if foundreaders: for reader in expectedReaders: self.testcase.assertTrue(reader in foundreaders)
class printobserver(ReaderObserver): '''observer''' def __init__(self, obsindex, testcase): pass def update(self, observable, handlers): pass
3
1
6
0
6
0
3
0.08
1
1
0
0
2
2
2
5
16
2
13
8
10
1
13
8
10
4
2
2
5
147,482
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_readergroups.py
testcase_readergroups.testcase_readergroups
class testcase_readergroups(unittest.TestCase): """Test scard reader groups API""" def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) def tearDown(self): hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) def test_listReaders(self): # list current readers and compare with expected list hresult, readers = SCardListReaders(self.hcontext, []) self.assertEqual(hresult, 0) for i in range(len(expectedReaders)): self.assertEqual(readers[i], expectedReaders[i]) # list current reader groups and compare with expected list hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) if "winscard" == resourceManager: # add a new group newgroup = "SCard$MyOwnGroup" expectedGroups.append(newgroup) hresult = SCardIntroduceReaderGroup(self.hcontext, newgroup) self.assertEqual(hresult, 0) dummyreader = readers[0] + " alias" hresult = SCardIntroduceReader(self.hcontext, dummyreader, readers[0]) self.assertEqual(hresult, 0) hresult = SCardAddReaderToGroup(self.hcontext, dummyreader, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) # list readers in new group hresult, newreaders = SCardListReaders(self.hcontext, [newgroup]) self.assertEqual(hresult, 0) self.assertEqual(newreaders[0], dummyreader) # remove reader from new group hresult = SCardRemoveReaderFromGroup(self.hcontext, dummyreader, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) expectedGroups.remove(newgroup) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) hresult = SCardForgetReaderGroup(self.hcontext, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) hresult = SCardForgetReader(self.hcontext, dummyreader) self.assertEqual(hresult, 0)
class testcase_readergroups(unittest.TestCase): '''Test scard reader groups API''' def setUp(self): pass def tearDown(self): pass def test_listReaders(self): pass
4
1
22
5
16
2
3
0.13
1
1
0
0
3
1
3
75
71
17
48
12
44
6
48
12
44
7
2
2
9
147,483
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/manual/testcase_manualCardRequest.py
testcase_manualCardRequest.testcase_manualCardRequest
class testcase_manualCardRequest(unittest.TestCase, CardObserver): """Test case for CardRequest.""" def removeAllCards(self): """Wait for no card present""" print("please remove all inserted smart cards") cardz = get_cards(readerz) cardrequest = CardRequest(timeout=None) while len(cardz) > 0: cardz = cardrequest.waitforcardevent() print("ok") def testcase_CardRequestNewCardAnyCardTypeInfiniteTimeOut(self): """Test smartcard.CardRequest for any new card without time-out.""" self.removeAllCards() cardtype = AnyCardType() cardrequest = CardRequest(timeout=None, cardType=cardtype, newcardonly=True) print("re-insert any combination of cards six time") count = 0 for _ in range(0, 6): cardservice = cardrequest.waitforcard() try: cardservice.connection.connect() print( toHexString(cardservice.connection.getATR()), "in", cardservice.connection.getReader(), ) except CardConnectionException: # card was removed too fast pass cardservice.connection.disconnect() count += 1 self.assertEqual(6, count) def testcase_CardRequestNewCardATRCardTypeInfiniteTimeOut(self): """Test smartcard.CardRequest for new card with given ATR without time-out.""" self.removeAllCards() count = 0 for _ in range(0, 6): card = random.choice(cardz) cardtype = ATRCardType(card.atr) cardrequest = CardRequest(timeout=None, cardType=cardtype, newcardonly=True) print("re-insert card", toHexString(card.atr), "into", card.reader) cardservice = cardrequest.waitforcard() print("ok") try: cardservice.connection.connect() self.assertEqual(cardservice.connection.getATR(), card.atr) except CardConnectionException: # card was removed too fast pass cardservice.connection.disconnect() count += 1 self.assertEqual(6, count) def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutNoInsertion(self): """Test smartcard.CardRequest for new card with time-out and no insertion before time-out.""" self.removeAllCards() # make sure we have 6 time-outs cardtype = AnyCardType() cardrequest = CardRequest(timeout=1, cardType=cardtype, newcardonly=True) count = 0 for _ in range(0, 6): before = time.time() try: cardrequest.waitforcard() except CardRequestTimeoutException: elapsed = int(10 * (time.time() - before)) print(".", end=" ") self.assertTrue(elapsed >= 10 and elapsed <= 11.0) count += 1 print("\n") self.assertEqual(6, count) def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutInsertion(self): """Test smartcard.CardRequest for new card with time-out and insertion before time-out.""" self.removeAllCards() # make sure insertion is within 5s cardtype = AnyCardType() cardrequest = CardRequest(timeout=5, cardType=cardtype, newcardonly=True) count = 0 for _ in range(0, 6): try: print("re-insert any card within the next 5 seconds") before = time.time() cardrequest.waitforcard() count += 1 elapsed = int(10 * (time.time() - before)) self.assertTrue(elapsed <= 55.0) except CardRequestTimeoutException: print("too slow... Test will show a failure") print("\n") self.assertEqual(6, count) def testcase_CardRequestNewCardInReaderNotPresentInfiniteTimeOut(self): """Test smartcard.CardRequest for any new card in a specific reader not present without time-out.""" print("please remove a smart card reader") _readerz = readers() while True: readerz = readers() if len(_readerz) > len(readerz): break time.sleep(0.1) for reader in readerz: _readerz.remove(reader) cardtype = AnyCardType() cardrequest = CardRequest( timeout=None, readers=[_readerz[0]], cardType=cardtype, newcardonly=True ) print("Re-insert reader", _readerz[0], "with a card inside") cardservice = cardrequest.waitforcard() cardservice.connection.connect() print( toHexString(cardservice.connection.getATR()), "in", cardservice.connection.getReader(), ) cardservice.connection.disconnect()
class testcase_manualCardRequest(unittest.TestCase, CardObserver): '''Test case for CardRequest.''' def removeAllCards(self): '''Wait for no card present''' pass def testcase_CardRequestNewCardAnyCardTypeInfiniteTimeOut(self): '''Test smartcard.CardRequest for any new card without time-out.''' pass def testcase_CardRequestNewCardATRCardTypeInfiniteTimeOut(self): '''Test smartcard.CardRequest for new card with given ATR without time-out.''' pass def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutNoInsertion(self): '''Test smartcard.CardRequest for new card with time-out and no insertion before time-out.''' pass def testcase_CardRequestNewCardAnyCardTypeFiniteTimeOutInsertion(self): '''Test smartcard.CardRequest for new card with time-out and insertion before time-out.''' pass def testcase_CardRequestNewCardInReaderNotPresentInfiniteTimeOut(self): '''Test smartcard.CardRequest for any new card in a specific reader not present without time-out.''' pass
7
7
21
2
17
2
3
0.15
2
7
5
0
6
0
6
81
132
15
102
38
95
15
92
38
85
4
2
2
18
147,484
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_geterrormessage.py
testcase_geterrormessage.testcase_geterrormessage
class testcase_geterrormessage(unittest.TestCase): """Test scard API for ATR retrieval with SCardLocateCards""" def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) def tearDown(self): hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) def test_getErrorMessage(self): hresult, readers = SCardListReaders(self.hcontext, []) self.assertEqual(hresult, 0) hresult = SCardReleaseContext(pow(2, 63) >> 60) if "win32" == sys.platform: self.assertEqual( (SCARD_E_INVALID_HANDLE == hresult or ERROR_INVALID_HANDLE == hresult), True, ) else: self.assertEqual((SCARD_E_INVALID_HANDLE == hresult), True) self.assertEqual( ( SCardGetErrorMessage(hresult).rstrip() == "Invalid handle.".rstrip() or SCardGetErrorMessage(hresult).rstrip() == "The handle is invalid.".rstrip() ), True, )
class testcase_geterrormessage(unittest.TestCase): '''Test scard API for ATR retrieval with SCardLocateCards''' def setUp(self): pass def tearDown(self): pass def test_getErrorMessage(self): pass
4
1
9
0
8
0
1
0.04
1
0
0
0
3
1
3
75
31
4
26
7
22
1
15
7
11
2
2
1
4
147,485
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/sw/ErrorCheckingChain.py
smartcard.sw.ErrorCheckingChain.ErrorCheckingChain
class ErrorCheckingChain: """The error checking chain is a list of response apdu status word (sw1, sw2) error check strategies. Each strategy in the chain is called until an error is detected. A L{smartcard.sw.SWExceptions} exception is raised when an error is detected. No exception is raised if no error is detected. Implementation derived from Bruce Eckel, Thinking in Python. The L{ErrorCheckingChain} implements the Chain Of Responsibility design pattern. """ def __init__(self, chain, strategy): """constructor. Appends a strategy to the L{ErrorCheckingChain} chain.""" self.strategy = strategy self.chain = chain self.chain.append(self) self.excludes = [] def next(self): """Returns next error checking strategy.""" # Where this link is in the chain: location = self.chain.index(self) if not self.end(): return self.chain[location + 1] def addFilterException(self, exClass): """Add an exception filter to the error checking chain. @param exClass: the exception to exclude, e.g. L{smartcard.sw.SWExceptions.WarningProcessingException} A filtered exception will not be raised when the sw1,sw2 conditions that would raise the exception are met. """ self.excludes.append(exClass) if self.end(): return self.next().addFilterException(exClass) def end(self): """Returns True if this is the end of the error checking strategy chain.""" return self.chain.index(self) + 1 >= len(self.chain) def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error on the chain.""" try: self.strategy(data, sw1, sw2) except tuple(self.excludes) as exc: # The following additional filter may look redundant, it isn't. # It checks that type(exc) is *equal* to any of self.excludes, # rather than equal-or-subclass to any of self.excludes. # This maintains backward compatibility with the behaviour of # pyscard <= 1.6.16. # if exception is filtered, return for exception in self.excludes: if exception == exc_info()[0]: return # otherwise reraise exception raise # if not done, call next strategy if self.end(): return return self.next()(data, sw1, sw2)
class ErrorCheckingChain: '''The error checking chain is a list of response apdu status word (sw1, sw2) error check strategies. Each strategy in the chain is called until an error is detected. A L{smartcard.sw.SWExceptions} exception is raised when an error is detected. No exception is raised if no error is detected. Implementation derived from Bruce Eckel, Thinking in Python. The L{ErrorCheckingChain} implements the Chain Of Responsibility design pattern. ''' def __init__(self, chain, strategy): '''constructor. Appends a strategy to the L{ErrorCheckingChain} chain.''' pass def next(self): '''Returns next error checking strategy.''' pass def addFilterException(self, exClass): '''Add an exception filter to the error checking chain. @param exClass: the exception to exclude, e.g. L{smartcard.sw.SWExceptions.WarningProcessingException} A filtered exception will not be raised when the sw1,sw2 conditions that would raise the exception are met. ''' pass def end(self): '''Returns True if this is the end of the error checking strategy chain.''' pass def __call__(self, data, sw1, sw2): '''Called to test data, sw1 and sw2 for error on the chain.''' pass
6
6
10
1
5
4
2
1.07
0
1
0
0
5
3
5
5
67
9
28
12
22
30
28
11
22
5
0
3
11
147,486
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.SmartcardException
class SmartcardException(Exception): """Base class for smartcard exceptions. smartcard exceptions are generated by the smartcard module and shield scard (i.e. PCSC) exceptions raised by the scard module. """ def __init__(self, message="", hresult=-1, *args): super().__init__(message, *args) self.hresult = int(hresult) def __str__(self): text = super().__str__() if self.hresult != -1: hresult = self.hresult if hresult < 0: # convert 0x-7FEFFFE3 into 0x8010001D hresult += 0x100000000 text += f": {SCardGetErrorMessage(self.hresult)} (0x{hresult:08X})" return text
class SmartcardException(Exception): '''Base class for smartcard exceptions. smartcard exceptions are generated by the smartcard module and shield scard (i.e. PCSC) exceptions raised by the scard module. ''' def __init__(self, message="", hresult=-1, *args): pass def __str__(self): pass
3
1
7
1
6
1
2
0.42
1
2
0
12
2
1
2
12
22
5
12
6
9
5
12
6
9
3
3
2
4
147,487
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardConnectionEvent.py
smartcard.CardConnectionEvent.CardConnectionEvent
class CardConnectionEvent: """Base class for card connection events. This event is notified by CardConnection objects.""" def __init__(self, type, args=None): """ @param type: 'connect', 'reconnect', 'disconnect', 'command', 'response' @param args: None for 'connect', 'reconnect' or 'disconnect' command APDU byte list for 'command' [response data, sw1, sw2] for 'response' """ self.type = type self.args = args
class CardConnectionEvent: '''Base class for card connection events. This event is notified by CardConnection objects.''' def __init__(self, type, args=None): ''' @param type: 'connect', 'reconnect', 'disconnect', 'command', 'response' @param args: None for 'connect', 'reconnect' or 'disconnect' command APDU byte list for 'command' [response data, sw1, sw2] for 'response' ''' pass
2
2
9
0
3
6
1
2
0
0
0
0
1
2
1
1
14
2
4
4
2
8
4
4
2
1
0
0
1
147,488
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardRequest.py
smartcard.CardRequest.CardRequest
class CardRequest: """A CardRequest is used for waitForCard() invocations and specifies what kind of smart card an application is waited for. """ def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): """Construct new CardRequest. @param newcardonly: if True, request a new card default is False, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card default is to consider all readers @param cardType: the L{smartcard.CardType.CardType} to wait for; default is L{smartcard.CardType.AnyCardType}, i.e. the request will succeed with any card @param cardServiceClass: the specific card service class to create and bind to the card default is to create and bind a L{smartcard.PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second to wait forever, set timeout to None """ self.pcsccardrequest = PCSCCardRequest( newcardonly, readers, cardType, cardServiceClass, timeout ) def getReaders(self): """Returns the list or readers on which to wait for cards.""" return self.pcsccardrequest.getReaders() def waitforcard(self): """Wait for card insertion and returns a card service.""" return self.pcsccardrequest.waitforcard() def waitforcardevent(self): """Wait for card insertion or removal.""" return self.pcsccardrequest.waitforcardevent()
class CardRequest: '''A CardRequest is used for waitForCard() invocations and specifies what kind of smart card an application is waited for. ''' def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): '''Construct new CardRequest. @param newcardonly: if True, request a new card default is False, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card default is to consider all readers @param cardType: the L{smartcard.CardType.CardType} to wait for; default is L{smartcard.CardType.AnyCardType}, i.e. the request will succeed with any card @param cardServiceClass: the specific card service class to create and bind to the card default is to create and bind a L{smartcard.PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second to wait forever, set timeout to None ''' pass def getReaders(self): '''Returns the list or readers on which to wait for cards.''' pass def waitforcard(self): '''Wait for card insertion and returns a card service.''' pass def waitforcardevent(self): '''Wait for card insertion or removal.''' pass
5
5
11
1
4
5
1
1.33
0
1
1
0
4
1
4
4
51
9
18
13
6
24
9
6
4
1
0
0
4
147,489
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardService.py
smartcard.CardService.CardService
class CardService: """Card service abstract class.""" def __init__(self, connection, cardname=None): """Construct a new card service and bind to a smart card in a reader. @param connection: the CardConnection used to access the smart card """ self.connection = connection self.cardname = cardname def __del__(self): """Destructor. Disconnect card and destroy card service resources.""" self.connection.disconnect() @staticmethod def supports(cardname): pass
class CardService: '''Card service abstract class.''' def __init__(self, connection, cardname=None): '''Construct a new card service and bind to a smart card in a reader. @param connection: the CardConnection used to access the smart card ''' pass def __del__(self): '''Destructor. Disconnect card and destroy card service resources.''' pass @staticmethod def supports(cardname): pass
5
3
4
0
2
1
1
0.56
0
0
0
1
2
2
3
3
18
4
9
7
4
5
8
6
4
1
0
0
3
147,490
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardType.py
smartcard.CardType.ATRCardType
class ATRCardType(CardType): """The ATRCardType defines a card from an ATR and a mask.""" def __init__(self, atr, mask=None): """ATRCardType constructor. @param atr: the ATR of the CardType @param mask: an optional mask to be applied to the ATR for L{CardType} matching default is None """ super().__init__() self.atr = list(atr) self.mask = mask if mask is None: self.maskedatr = self.atr else: if len(self.atr) != len(self.mask): raise InvalidATRMaskLengthException(toHexString(mask)) self.maskedatr = list(map(lambda x, y: x & y, self.atr, self.mask)) def matches(self, atr, reader=None): """Returns true if the atr matches the masked CardType atr. @param atr: the atr to check for matching @param reader: the reader (optional); default is None When atr is compared to the CardType ATR, matches returns true if and only if CardType.atr & CardType.mask = atr & CardType.mask, where & is the bitwise logical AND.""" if len(atr) != len(self.atr): return not True if self.mask is not None: maskedatr = list(map(lambda x, y: x & y, list(atr), self.mask)) else: maskedatr = atr return self.maskedatr == maskedatr
class ATRCardType(CardType): '''The ATRCardType defines a card from an ATR and a mask.''' def __init__(self, atr, mask=None): '''ATRCardType constructor. @param atr: the ATR of the CardType @param mask: an optional mask to be applied to the ATR for L{CardType} matching default is None ''' pass def matches(self, atr, reader=None): '''Returns true if the atr matches the masked CardType atr. @param atr: the atr to check for matching @param reader: the reader (optional); default is None When atr is compared to the CardType ATR, matches returns true if and only if CardType.atr & CardType.mask = atr & CardType.mask, where & is the bitwise logical AND.''' pass
3
3
17
2
9
6
3
0.63
1
4
1
0
2
3
2
4
37
6
19
7
16
12
17
7
14
3
1
2
6
147,491
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardType.py
smartcard.CardType.AnyCardType
class AnyCardType(CardType): """The AnyCardType matches any card.""" def __init__(self): super().__init__() def matches(self, atr, reader=None): """Always returns true, i.e. AnyCardType matches any card. @param atr: the atr to check for matching @param reader: the reader (optional); default is None""" return True
class AnyCardType(CardType): '''The AnyCardType matches any card.''' def __init__(self): pass def matches(self, atr, reader=None): '''Always returns true, i.e. AnyCardType matches any card. @param atr: the atr to check for matching @param reader: the reader (optional); default is None''' pass
3
2
4
1
2
2
1
0.8
1
1
0
0
2
0
2
4
12
3
5
3
2
4
5
3
2
1
1
0
2
147,492
LudovicRousseau/pyscard
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_listcards.py
testcase_listcards.testcase_listcards
class testcase_listcards(unittest.TestCase): """Test scard API for ATR retrieval""" # setup for all unit tests: establish context and introduce # a dummy card interface def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) self.dummycardname = "dummycard" self.dummycardATR = [ 0x3B, 0x75, 0x94, 0x00, 0x00, 0x62, 0x02, 0x02, 0x01, 0x01, ] self.dummycardMask = [ 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, ] self.dummycardguid1 = smartcard.guid.strToGUID( "{AD4F1667-EA75-4124-84D4-641B3B197C65}" ) self.dummycardguid2 = smartcard.guid.strToGUID( "{382AE95A-7C2C-449c-A179-56C6DE6FF3BC}" ) testcase_listcards.__introduceinterface(self) # teardown for all unit tests: release context and forget # dummy card interface def tearDown(self): testcase_listcards.__forgetinterface(self) hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) # introduce a dummy card interface # card ATR same as e-gate def __introduceinterface(self): hresult = SCardForgetCardType(self.hcontext, self.dummycardname) dummycardPrimaryGUID = self.dummycardguid1 dummycardGUIDS = self.dummycardguid1 + self.dummycardguid2 hresult = SCardIntroduceCardType( self.hcontext, self.dummycardname, dummycardPrimaryGUID, dummycardGUIDS, self.dummycardATR, self.dummycardMask, ) self.assertEqual(hresult, 0) # forget dummy card interface def __forgetinterface(self): hresult = SCardForgetCardType(self.hcontext, self.dummycardname) self.assertEqual(hresult, 0) # locate a known card # Cryptoflex 8k v2 is present in standard Windows 2000 def test_listcryptoflexbyatr(self): slbCryptoFlex8kv2ATR = [ 0x3B, 0x95, 0x15, 0x40, 0x00, 0x68, 0x01, 0x02, 0x00, 0x00, ] slbCryptoFlex8kv2Name = ["Schlumberger Cryptoflex 8K v2"] hresult, card = SCardListCards( self.hcontext, slbCryptoFlex8kv2ATR, []) self.assertEqual(hresult, 0) self.assertEqual(card, slbCryptoFlex8kv2Name) # locate dummy card by interface def test_listdummycardbyguid(self): guidstolocate = self.dummycardguid2 + self.dummycardguid1 locatedcardnames = [self.dummycardname] hresult, card = SCardListCards(self.hcontext, [], guidstolocate) self.assertEqual(hresult, 0) self.assertEqual(card, locatedcardnames) # list our dummy card interfaces and check # that they match the introduced interfaces def test_listdummycardinterfaces(self): hresult, interfaces = SCardListInterfaces( self.hcontext, self.dummycardname) self.assertEqual(hresult, 0) self.assertEqual(2, len(interfaces)) self.assertEqual(self.dummycardguid1, interfaces[0]) self.assertEqual(self.dummycardguid2, interfaces[1]) # locate all cards and interfaces in the system def test_listallcards(self): # dummycard has been introduced in the test setup and # will be removed in the test teardown. Other cards are # the cards present by default on Windows 2000 expectedCards = [ "dummycard", "GemSAFE Smart Card (8K)", "Schlumberger Cryptoflex 4K", "Schlumberger Cryptoflex 8K", "Schlumberger Cryptoflex 8K v2", ] hresult, cards = SCardListCards(self.hcontext, [], []) self.assertEqual(hresult, 0) foundCards = {} for i in range(len(cards)): foundCards[cards[i]] = 1 for i in expectedCards: self.assertTrue(i in foundCards) # dummycard has a primary provider, # other cards have no primary provider expectedPrimaryProviderResult = { "dummycard": [0, self.dummycardguid1], "GemSAFE": [2, None], "Schlumberger Cryptoflex 4k": [2, None], "Schlumberger Cryptoflex 8k": [2, None], "Schlumberger Cryptoflex 8k v2": [2, None], } for i in range(len(cards)): hresult, providername = SCardGetCardTypeProviderName( self.hcontext, cards[i], SCARD_PROVIDER_PRIMARY ) if cards[i] in expectedPrimaryProviderResult: self.assertEqual( hresult, expectedPrimaryProviderResult[cards[i]][0] ) if hresult == SCARD_S_SUCCESS: self.assertEqual( providername, smartcard.guid.GUIDToStr( expectedPrimaryProviderResult[cards[i]][1] ), ) # dummycard has no CSP, other cards have a CSP expectedProviderCSPResult = { "dummycard": [2, None], "GemSAFE": [0, "Gemplus GemSAFE Card CSP v1.0"], "Schlumberger Cryptoflex 4k": [ 0, "Schlumberger Cryptographic Service Provider", ], "Schlumberger Cryptoflex 8k": [ 0, "Schlumberger Cryptographic Service Provider", ], "Schlumberger Cryptoflex 8k v2": [ 0, "Schlumberger Cryptographic Service Provider", ], } for i in range(len(cards)): hresult, providername = SCardGetCardTypeProviderName( self.hcontext, cards[i], SCARD_PROVIDER_CSP ) if cards[i] in expectedProviderCSPResult: self.assertEqual( hresult, expectedProviderCSPResult[cards[i]][0]) self.assertEqual( providername, expectedProviderCSPResult[cards[i]][1] )
class testcase_listcards(unittest.TestCase): '''Test scard API for ATR retrieval''' def setUp(self): pass def tearDown(self): pass def __introduceinterface(self): pass def __forgetinterface(self): pass def test_listcryptoflexbyatr(self): pass def test_listdummycardbyguid(self): pass def test_listdummycardinterfaces(self): pass def test_listallcards(self): pass
9
1
19
0
18
1
2
0.14
1
1
0
0
8
6
8
80
178
11
147
34
138
20
63
34
54
8
2
3
15
147,493
LudovicRousseau/pyscard
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/test/frameworkpcsc/testcase_pcscreadergroups.py
testcase_pcscreadergroups.testcase_readergroups
class testcase_readergroups(unittest.TestCase): """Test smartcard framework readers factory methods""" def setUp(self): groups = PCSCReaderGroups().instance groups.remove("Pinpad$Readers") groups.remove("Biometric$Readers") def testcase_add(self): """Test for groups=groups+newgroups""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups = groups + newgroup self.assertEqual(groups, groupssnapshot + [newgroup]) groups.remove(newgroup) def testcase_addlist(self): """Test for groups=groups+[newgroups]""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroups = ["Pinpad$Readers", "Biometric$Readers"] groups = groups + newgroups self.assertEqual(groups, groupssnapshot + newgroups) for group in newgroups: groups.remove(group) def testcase_iadd(self): """Test for groups+=newgroup""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups += newgroup self.assertEqual(groups, groupssnapshot + [newgroup]) groups.remove(newgroup) def testcase_iaddlist(self): """Test for groups+=[newgroups]""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroups = ["Pinpad$Readers", "Biometric$Readers"] groups += newgroups self.assertEqual(groups, groupssnapshot + newgroups) for group in newgroups: groups.remove(group) def testcase_append(self): """Test for groups.append(newgroup)""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups.append(newgroup) self.assertEqual(groups, groupssnapshot + [newgroup]) groups.remove(newgroup) def testcase_insert(self): """Test for groups.insert(newgroup)""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups.insert(0, newgroup) self.assertEqual(groups, [newgroup] + groupssnapshot) groups.remove(newgroup) def testcase_removereadergroup_pop(self): """Test for groups.pop()""" groupssnapshot = list(PCSCReaderGroups().instance) groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups.insert(0, newgroup) self.assertEqual(groups, [newgroup] + groupssnapshot) groups.pop(0) self.assertEqual(groups, groupssnapshot) def testcase_addreadertogroup(self): """Test for adding readers to group""" groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups.insert(0, newgroup) for r in PCSCReader.readers("SCard$DefaultReaders"): r.addtoreadergroup(newgroup) self.assertEqual( PCSCReader.readers( "SCard$DefaultReaders"), PCSCReader.readers(newgroup) ) groups.pop(0) self.assertEqual([], PCSCReader.readers(newgroup)) def testcase_removereaderfromgroup(self): """Test for removing readers from group""" groups = PCSCReaderGroups().instance newgroup = "Pinpad$Readers" groups.insert(0, newgroup) for r in PCSCReader.readers("SCard$DefaultReaders"): r.addtoreadergroup(newgroup) self.assertEqual( PCSCReader.readers( "SCard$DefaultReaders"), PCSCReader.readers(newgroup) ) for r in PCSCReader.readers("SCard$DefaultReaders"): r.removefromreadergroup(newgroup) self.assertEqual([], PCSCReader.readers(newgroup)) groups.pop(0) self.assertEqual([], PCSCReader.readers(newgroup))
class testcase_readergroups(unittest.TestCase): '''Test smartcard framework readers factory methods''' def setUp(self): pass def testcase_add(self): '''Test for groups=groups+newgroups''' pass def testcase_addlist(self): '''Test for groups=groups+[newgroups]''' pass def testcase_iadd(self): '''Test for groups+=newgroup''' pass def testcase_iaddlist(self): '''Test for groups+=[newgroups]''' pass def testcase_append(self): '''Test for groups.append(newgroup)''' pass def testcase_insert(self): '''Test for groups.insert(newgroup)''' pass def testcase_removereadergroup_pop(self): '''Test for groups.pop()''' pass def testcase_addreadertogroup(self): '''Test for adding readers to group''' pass def testcase_removereaderfromgroup(self): '''Test for removing readers from group''' pass
11
10
9
0
8
1
2
0.12
1
3
2
0
10
0
10
82
102
10
82
41
71
10
78
41
67
3
2
1
15
147,494
LudovicRousseau/pyscard
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readergroups.py
testcase_readergroups.testcase_readergroups
class testcase_readergroups(unittest.TestCase): """Test smartcard framework readersgroups.""" pinpadgroup = "Pinpad$Readers" biogroup = "Biometric$Readers" def testcase_readergroup_add(self): """tests groups=groups+[newgroups]""" # take a snapshot of current groups groupssnapshot = list(readergroups()) groups = readergroups() # add pinpad group groups = groups + [self.pinpadgroup] self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add pinpad a second time and biometric once groups = groups + [self.biogroup, self.pinpadgroup] self.assertEqual(groups, groupssnapshot + [self.pinpadgroup, self.biogroup]) # clean-up groups.remove(self.biogroup) groups.remove(self.pinpadgroup) def testcase_readergroup_iadd(self): """test groups+=[newgroups]""" # take a snapshot of current groups groupssnapshot = list(readergroups()) groups = readergroups() # add pinpad group groups += [self.pinpadgroup] self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add pinpad a second time and biometric once groups += [self.biogroup, self.pinpadgroup] self.assertEqual(groups, groupssnapshot + [self.pinpadgroup, self.biogroup]) # clean-up groups.remove(self.biogroup) groups.remove(self.pinpadgroup) def testcase_readergroup_radd(self): """test groups=[newgroups]+groups""" # take a snapshot of current groups groupssnapshot = list(readergroups()) groups = readergroups() # add pinpad group zgroups = [self.pinpadgroup] + groups self.assertEqual(groups, groupssnapshot) self.assertEqual(zgroups, groupssnapshot + [self.pinpadgroup]) self.assertTrue(isinstance(zgroups, list)) self.assertTrue(isinstance(groups, type(readergroups()))) # add pinpad a tiwce and biometric once zgroups = [self.pinpadgroup, self.biogroup, self.pinpadgroup] + groups self.assertEqual(groups, groupssnapshot) self.assertEqual( zgroups, groupssnapshot + [self.pinpadgroup, self.biogroup] ) self.assertTrue(isinstance(zgroups, list)) self.assertTrue(isinstance(groups, type(readergroups()))) def testcase_readergroup_append(self): """test groups.append(newgroups)""" # take a snapshot of current groups groupssnapshot = list(readergroups()) groups = readergroups() # add pinpad group groups.append(self.pinpadgroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add pinpad a second time groups.append(self.pinpadgroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add biometric once groups.append(self.biogroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup, self.biogroup]) # clean-up groups.remove(self.biogroup) groups.remove(self.pinpadgroup) def testcase_readergroup_insert(self): """test groups.insert(i,newgroups)""" # take a snapshot of current groups groupssnapshot = list(readergroups()) groups = readergroups() # add pinpad group groups.insert(0, self.pinpadgroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add pinpad a second time groups.insert(1, self.pinpadgroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup]) # add biometric once groups.insert(1, self.biogroup) self.assertEqual(groups, groupssnapshot + [self.pinpadgroup, self.biogroup]) # clean-up groups.remove(self.biogroup) groups.remove(self.pinpadgroup)
class testcase_readergroups(unittest.TestCase): '''Test smartcard framework readersgroups.''' def testcase_readergroup_add(self): '''tests groups=groups+[newgroups]''' pass def testcase_readergroup_iadd(self): '''test groups+=[newgroups]''' pass def testcase_readergroup_radd(self): '''test groups=[newgroups]+groups''' pass def testcase_readergroup_append(self): '''test groups.append(newgroups)''' pass def testcase_readergroup_insert(self): '''test groups.insert(i,newgroups)''' pass
6
6
20
4
11
5
1
0.47
1
2
0
0
5
0
5
77
112
27
58
19
52
27
56
19
50
1
2
0
5
147,495
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
smartcard.CardMonitoring.CardObserver
class CardObserver(Observer): """ CardObserver is a base abstract class for objects that are to be notified upon smart card insertion / removal. """ def __init__(self): pass def update(self, observable, handlers): """Called upon smart card insertion / removal. @param observable: @param handlers: - addedcards: list of inserted smart cards causing notification - removedcards: list of removed smart cards causing notification """ pass
class CardObserver(Observer): ''' CardObserver is a base abstract class for objects that are to be notified upon smart card insertion / removal. ''' def __init__(self): pass def update(self, observable, handlers): '''Called upon smart card insertion / removal. @param observable: @param handlers: - addedcards: list of inserted smart cards causing notification - removedcards: list of removed smart cards causing notification ''' pass
3
2
6
1
2
3
1
2
1
0
0
7
2
0
2
3
18
3
5
3
2
10
5
3
2
1
1
0
2
147,496
LudovicRousseau/pyscard
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_readergroups.py
testcase_readergroups.testcase_readergroups
class testcase_readergroups(unittest.TestCase): """Test scard reader groups API""" def setUp(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) self.assertEqual(hresult, 0) def tearDown(self): hresult = SCardReleaseContext(self.hcontext) self.assertEqual(hresult, 0) def test_listReaders(self): # list current readers and compare with expected list hresult, readers = SCardListReaders(self.hcontext, []) self.assertEqual(hresult, 0) for i in range(len(expectedReaders)): self.assertEqual(readers[i], expectedReaders[i]) # list current reader groups and compare with expected list hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) if "winscard" == resourceManager: # add a new group newgroup = "SCard$MyOwnGroup" expectedGroups.append(newgroup) hresult = SCardIntroduceReaderGroup(self.hcontext, newgroup) self.assertEqual(hresult, 0) dummyreader = readers[0] + " alias" hresult = SCardIntroduceReader( self.hcontext, dummyreader, readers[0]) self.assertEqual(hresult, 0) hresult = SCardAddReaderToGroup( self.hcontext, dummyreader, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) # list readers in new group hresult, newreaders = SCardListReaders(self.hcontext, [newgroup]) self.assertEqual(hresult, 0) self.assertEqual(newreaders[0], dummyreader) # remove reader from new group hresult = SCardRemoveReaderFromGroup( self.hcontext, dummyreader, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) expectedGroups.remove(newgroup) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) hresult = SCardForgetReaderGroup(self.hcontext, newgroup) self.assertEqual(hresult, 0) hresult, readerGroups = SCardListReaderGroups(self.hcontext) self.assertEqual(hresult, 0) for i in range(len(expectedGroups)): self.assertEqual(readerGroups[i], expectedGroups[i]) hresult = SCardForgetReader(self.hcontext, dummyreader) self.assertEqual(hresult, 0)
class testcase_readergroups(unittest.TestCase): '''Test scard reader groups API''' def setUp(self): pass def tearDown(self): pass def test_listReaders(self): pass
4
1
22
5
16
2
3
0.13
1
1
0
0
3
1
3
75
71
17
48
12
44
6
48
12
44
7
2
2
9
147,497
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.CardRequestException
class CardRequestException(SmartcardException): """Raised when a CardRequest wait fails.""" pass
class CardRequestException(SmartcardException): '''Raised when a CardRequest wait fails.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
12
4
1
2
1
1
1
2
1
1
0
4
0
0
147,498
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.CardRequestTimeoutException
class CardRequestTimeoutException(SmartcardException): """Raised when a CardRequest times out.""" def __init__(self, hresult=-1, *args): SmartcardException.__init__( self, "Time-out during card request", hresult=hresult, *args )
class CardRequestTimeoutException(SmartcardException): '''Raised when a CardRequest times out.''' def __init__(self, hresult=-1, *args): pass
2
1
4
0
4
0
1
0.2
1
0
0
0
1
0
1
13
7
1
5
2
3
1
3
2
1
1
4
0
1
147,499
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.CardServiceNotFoundException
class CardServiceNotFoundException(SmartcardException): """Raised when the CardService is not found""" pass
class CardServiceNotFoundException(SmartcardException): '''Raised when the CardService is not found''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
12
4
1
2
1
1
1
2
1
1
0
4
0
0
147,500
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.CardServiceStoppedException
class CardServiceStoppedException(SmartcardException): """Raised when the CardService was stopped""" pass
class CardServiceStoppedException(SmartcardException): '''Raised when the CardService was stopped''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
12
4
1
2
1
1
1
2
1
1
0
4
0
0
147,501
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.InvalidATRMaskLengthException
class InvalidATRMaskLengthException(SmartcardException): """Raised when an ATR mask does not match an ATR length.""" def __init__(self, mask): SmartcardException.__init__(self, "Invalid ATR mask length: %s" % mask)
class InvalidATRMaskLengthException(SmartcardException): '''Raised when an ATR mask does not match an ATR length.''' def __init__(self, mask): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,502
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.InvalidReaderException
class InvalidReaderException(SmartcardException): """Raised when trying to access an invalid smartcard reader.""" def __init__(self, readername): SmartcardException.__init__(self, "Invalid reader: %s" % readername)
class InvalidReaderException(SmartcardException): '''Raised when trying to access an invalid smartcard reader.''' def __init__(self, readername): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,503
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.ListReadersException
class ListReadersException(SmartcardException): """Raised when smartcard readers cannot be listed.""" def __init__(self, hresult): SmartcardException.__init__(self, "Failed to list readers", hresult=hresult)
class ListReadersException(SmartcardException): '''Raised when smartcard readers cannot be listed.''' def __init__(self, hresult): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,504
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py
sample_CardConnectionDecorator.SecureChannelConnection
class SecureChannelConnection(CardConnectionDecorator): """This decorator is a mockup of secure channel connection. It merely pretends to cypher/uncypher upon apdu transmission.""" def __init__(self, cardconnection): CardConnectionDecorator.__init__(self, cardconnection) def cypher(self, data): """Cypher mock-up; you would include the secure channel logics here.""" print("cyphering", toHexString(data)) return data def uncypher(self, data): """Uncypher mock-up; you would include the secure channel logics here.""" print("uncyphering", toHexString(data)) return data def transmit(self, command, protocol=None): """Cypher/uncypher APDUs before transmission""" cypheredbytes = self.cypher(command) data, sw1, sw2 = CardConnectionDecorator.transmit(self, cypheredbytes, protocol) if [] != data: data = self.uncypher(data) return data, sw1, sw2
class SecureChannelConnection(CardConnectionDecorator): '''This decorator is a mockup of secure channel connection. It merely pretends to cypher/uncypher upon apdu transmission.''' def __init__(self, cardconnection): pass def cypher(self, data): '''Cypher mock-up; you would include the secure channel logics here.''' pass def uncypher(self, data): '''Uncypher mock-up; you would include the secure channel logics here.''' pass def transmit(self, command, protocol=None): '''Cypher/uncypher APDUs before transmission''' pass
5
4
5
0
4
1
1
0.4
1
0
0
0
4
0
4
74
25
4
15
7
10
6
15
7
10
2
10
1
5
147,505
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
smartcard.CardMonitoring.CardMonitoringThread
class CardMonitoringThread: """Card insertion thread. This thread waits for card insertion. """ class __CardMonitoringThreadSingleton(Thread): """The real card monitoring thread class. A single instance of this class is created by the public L{CardMonitoringThread} class. """ def __init__(self, observable): Thread.__init__(self) self.observable = observable self.stopEvent = Event() self.stopEvent.clear() self.cards = [] self.daemon = True # the actual monitoring thread def run(self): """Runs until stopEvent is notified, and notify observers of all card insertion/removal. """ self.cardrequest = CardRequest(timeout=60) while self.stopEvent.is_set() != 1: try: currentcards = self.cardrequest.waitforcardevent() addedcards = [] for card in currentcards: if not self.cards.__contains__(card): addedcards.append(card) removedcards = [] for card in self.cards: if not currentcards.__contains__(card): removedcards.append(card) if addedcards != [] or removedcards != []: self.cards = currentcards self.observable.setChanged() self.observable.notifyObservers((addedcards, removedcards)) except CardRequestTimeoutException: pass except SmartcardException as exc: # FIXME Tighten the exceptions caught by this block traceback.print_exc() # Most likely raised during interpreter shutdown due # to unclean exit which failed to remove all observers. # To solve this, we set the stop event and pass the # exception to let the thread finish gracefully. if exc.hresult == SCARD_E_NO_SERVICE: self.stopEvent.set() # stop the thread by signaling stopEvent def stop(self): self.stopEvent.set() # the singleton instance = None def __init__(self, observable): if not CardMonitoringThread.instance: CardMonitoringThread.instance = ( CardMonitoringThread.__CardMonitoringThreadSingleton(observable) ) CardMonitoringThread.instance.start() def join(self, *args, **kwargs): if self.instance: self.instance.join(*args, **kwargs) CardMonitoringThread.instance = None def __getattr__(self, name): if self.instance: return getattr(self.instance, name)
class CardMonitoringThread: '''Card insertion thread. This thread waits for card insertion. ''' class __CardMonitoringThreadSingleton(Thread): '''The real card monitoring thread class. A single instance of this class is created by the public L{CardMonitoringThread} class. ''' def __init__(self, observable): pass def run(self): '''Runs until stopEvent is notified, and notify observers of all card insertion/removal. ''' pass def stop(self): pass def __init__(self, observable): pass def join(self, *args, **kwargs): pass def __getattr__(self, name): pass
8
3
10
1
8
1
3
0.38
0
1
1
0
3
0
3
3
80
14
48
19
40
18
46
18
38
10
0
4
18
147,506
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
smartcard.CardMonitoring.CardMonitor
class CardMonitor: """Class that monitors smart card insertion / removals. and notify observers note: a card monitoring thread will be running as long as the card monitor has observers, or CardMonitor.stop() is called. Do not forget to delete all your observers by calling L{deleteObserver}, or your program will run forever... Uses the singleton pattern from Thinking in Python Bruce Eckel, http://mindview.net/Books/TIPython to make sure there is only one L{CardMonitor}. """ class __CardMonitorSingleton(Observable): """The real smart card monitor class. A single instance of this class is created by the public CardMonitor class. """ def __init__(self): Observable.__init__(self) if _START_ON_DEMAND_: self.rmthread = None else: self.rmthread = CardMonitoringThread(self) def addObserver(self, observer): """Add an observer. We only start the card monitoring thread when there are observers. """ Observable.addObserver(self, observer) if _START_ON_DEMAND_: if self.countObservers() > 0 and self.rmthread is None: self.rmthread = CardMonitoringThread(self) else: observer.update(self, (self.rmthread.cards, [])) def deleteObserver(self, observer): """Remove an observer. We delete the L{CardMonitoringThread} reference when there are no more observers. """ Observable.deleteObserver(self, observer) if _START_ON_DEMAND_: if self.countObservers() == 0: if self.rmthread is not None: self.rmthread.stop() self.rmthread.join() self.rmthread = None def __str__(self): return "CardMonitor" # the singleton instance = None lock = Lock() def __init__(self): with CardMonitor.lock: if not CardMonitor.instance: CardMonitor.instance = CardMonitor.__CardMonitorSingleton() def __getattr__(self, name): return getattr(self.instance, name)
class CardMonitor: '''Class that monitors smart card insertion / removals. and notify observers note: a card monitoring thread will be running as long as the card monitor has observers, or CardMonitor.stop() is called. Do not forget to delete all your observers by calling L{deleteObserver}, or your program will run forever... Uses the singleton pattern from Thinking in Python Bruce Eckel, http://mindview.net/Books/TIPython to make sure there is only one L{CardMonitor}. ''' class __CardMonitorSingleton(Observable): '''The real smart card monitor class. A single instance of this class is created by the public CardMonitor class. ''' def __init__(self): pass def addObserver(self, observer): '''Add an observer. We only start the card monitoring thread when there are observers. ''' pass def deleteObserver(self, observer): '''Remove an observer. We delete the L{CardMonitoringThread} reference when there are no more observers. ''' pass def __str__(self): pass def __init__(self): pass def __getattr__(self, name): pass
8
4
7
0
5
1
2
0.7
0
1
1
0
2
0
2
2
69
13
33
11
25
23
31
11
23
4
0
3
13
147,507
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardConnectionObserver.py
smartcard.CardConnectionObserver.ConsoleCardConnectionObserver
class ConsoleCardConnectionObserver(CardConnectionObserver): def update(self, cardconnection, ccevent): if "connect" == ccevent.type: print("connecting to " + cardconnection.getReader()) elif "reconnect" == ccevent.type: print("reconnecting to " + cardconnection.getReader()) elif "disconnect" == ccevent.type: print("disconnecting from " + cardconnection.getReader()) elif "command" == ccevent.type: print("> " + toHexString(ccevent.args[0])) elif "response" == ccevent.type: if [] == ccevent.args[0]: print("< [] %02X %02X" % tuple(ccevent.args[-2:])) else: print( "< " + toHexString(ccevent.args[0]) + " " + "%02X %02X" % tuple(ccevent.args[-2:]) )
class ConsoleCardConnectionObserver(CardConnectionObserver): def update(self, cardconnection, ccevent): pass
2
0
24
5
19
0
7
0
1
1
0
0
1
0
1
3
26
6
20
2
18
0
10
2
8
7
2
2
7
147,508
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_CustomCardType.py
sample_CustomCardType.DCCardType
class DCCardType(CardType): # define our custom CardType # this card type defines direct convention card # (first atr byte equal to 0x3b) def matches(self, atr, reader=None): return atr[0] == 0x3B
class DCCardType(CardType): def matches(self, atr, reader=None): pass
2
0
2
0
2
0
1
1
1
0
0
0
1
0
1
3
7
1
3
2
1
3
3
2
1
1
1
0
1
147,509
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_CustomErrorChecker.py
sample_CustomErrorChecker.MyErrorChecker
class MyErrorChecker(ErrorChecker): """Our custom error checker that will except if 0x61<sw1<0x70.""" def __call__(self, data, sw1, sw2): print(sw1, sw2) if 0x61 < sw1 and 0x70 > sw1: raise SWException(data, sw1, sw2)
class MyErrorChecker(ErrorChecker): '''Our custom error checker that will except if 0x61<sw1<0x70.''' def __call__(self, data, sw1, sw2): pass
2
1
4
0
4
0
2
0.2
1
1
1
0
1
0
1
2
7
1
5
2
3
1
5
2
3
2
1
1
2
147,510
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_MonitorCards.py
sample_MonitorCards.PrintObserver
class PrintObserver(CardObserver): """A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards """ def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: print("+Inserted: ", toHexString(card.atr)) for card in removedcards: print("-Removed: ", toHexString(card.atr))
class PrintObserver(CardObserver): '''A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards ''' def update(self, observable, actions): pass
2
1
6
0
6
0
3
0.57
1
0
0
0
1
0
1
4
12
1
7
4
5
4
7
4
5
3
2
1
3
147,511
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_MonitorCardsAndTransmit.py
sample_MonitorCardsAndTransmit.selectDFTELECOMObserver
class selectDFTELECOMObserver(CardObserver): """A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards """ def __init__(self): self.observer = ConsoleCardConnectionObserver() def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: print("+Inserted: ", toHexString(card.atr)) card.connection = card.createConnection() card.connection.connect() card.connection.addObserver(self.observer) apdu = SELECT + DF_TELECOM response, sw1, sw2 = card.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] response, sw1, sw2 = card.connection.transmit(apdu) for card in removedcards: print("-Removed: ", toHexString(card.atr))
class selectDFTELECOMObserver(CardObserver): '''A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards ''' def __init__(self): pass def update(self, observable, actions): pass
3
1
9
1
8
0
3
0.24
1
1
1
0
2
1
2
5
24
3
17
8
14
4
17
8
14
4
2
2
5
147,512
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_MonitorReaders.py
sample_MonitorReaders.printobserver
class printobserver(ReaderObserver): """A simple reader observer that is notified when readers are added/removed from the system and prints the list of readers """ def update(self, observable, actions): (addedreaders, removedreaders) = actions print("Added readers", addedreaders) print("Removed readers", removedreaders)
class printobserver(ReaderObserver): '''A simple reader observer that is notified when readers are added/removed from the system and prints the list of readers ''' def update(self, observable, actions): pass
2
1
4
0
4
0
1
0.8
1
0
0
0
1
0
1
4
10
1
5
3
3
4
5
3
3
1
2
0
1
147,513
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_TransmitCardObserver.py
sample_TransmitCardObserver.transmitobserver
class transmitobserver(CardObserver): """A card observer that is notified when cards are inserted/removed from the system, connects to cards and SELECT DF_TELECOM""" def __init__(self): self.cards = [] def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: if card not in self.cards: self.cards += [card] print("+Inserted: ", toHexString(card.atr)) card.connection = card.createConnection() card.connection.connect() response, sw1, sw2 = card.connection.transmit(SELECT_DF_TELECOM) print(f"{sw1:.2x} {sw2:.2x}") for card in removedcards: print("-Removed: ", toHexString(card.atr)) if card in self.cards: self.cards.remove(card)
class transmitobserver(CardObserver): '''A card observer that is notified when cards are inserted/removed from the system, connects to cards and SELECT DF_TELECOM''' def __init__(self): pass def update(self, observable, actions): pass
3
1
9
1
8
0
3
0.12
1
0
0
0
2
1
2
5
22
3
17
7
14
2
17
7
14
5
2
2
6
147,514
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_apduTracerInterpreter.py
sample_apduTracerInterpreter.TracerAndSELECTInterpreter
class TracerAndSELECTInterpreter(CardConnectionObserver): """This observer will interprer SELECT and GET RESPONSE bytes and replace them with a human readable string.""" def update(self, cardconnection, ccevent): if "connect" == ccevent.type: print("connecting to " + cardconnection.getReader()) elif "disconnect" == ccevent.type: print("disconnecting from " + cardconnection.getReader()) elif "command" == ccevent.type: str = toHexString(ccevent.args[0]) str = str.replace("A0 A4 00 00 02", "SELECT") str = str.replace("A0 C0 00 00", "GET RESPONSE") print(">", str) elif "response" == ccevent.type: if [] == ccevent.args[0]: print("< []", "%-2X %-2X" % tuple(ccevent.args[-2:])) else: print( "<", toHexString(ccevent.args[0]), "%-2X %-2X" % tuple(ccevent.args[-2:]), )
class TracerAndSELECTInterpreter(CardConnectionObserver): '''This observer will interprer SELECT and GET RESPONSE bytes and replace them with a human readable string.''' def update(self, cardconnection, ccevent): pass
2
1
23
4
19
0
6
0.1
1
1
0
0
1
0
1
3
27
5
20
3
18
2
12
3
10
6
2
2
6
147,515
LudovicRousseau/pyscard
LudovicRousseau_pyscard/setup.py
setup.BuildPyBuildExtFirst
class BuildPyBuildExtFirst(build_py): """Workaround substitute `build_py` command for SWIG""" def run(self): if which("swig") is None: print("Install swig and try again") print("") exit(1) # Run build_ext first so that SWIG generated files are included self.run_command("build_ext") return build_py.run(self)
class BuildPyBuildExtFirst(build_py): '''Workaround substitute `build_py` command for SWIG''' def run(self): pass
2
1
8
0
7
1
2
0.25
1
0
0
0
1
0
1
71
11
1
8
2
6
2
8
2
6
2
3
1
2
147,516
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/ATR.py
smartcard.ATR.ATR
class ATR: """Parse and represent Answer to Reset sequences. Answer to Reset sequences are defined in ISO 7816-3, section 8. """ clockrateconversion: list[int | str] = [ 372, 372, 558, 744, 1116, 1488, 1860, "RFU", "RFU", 512, 768, 1024, 1536, 2048, "RFU", "RFU", ] bitratefactor: list[int | str] = [ "RFU", 1, 2, 4, 8, 16, 32, 64, 12, 20, "RFU", "RFU", "RFU", "RFU", "RFU", "RFU", ] currenttable: list[int | str] = [25, 50, 100, "RFU"] def __init__(self, atr: list[int]) -> None: """Parse ATR and initialize members: - TS: initial character - T0: format character - TA[n], TB[n], TC[n], TD[n], for n=0,1,...: protocol parameters @note: protocol parameters indices start at 0, e.g. TA[0], TA[1] correspond to the ISO standard TA1, TA2 parameters - historicalBytes: the ATR T1, T2, ..., TK historical bytes - TCK: checksum byte (only for protocols different from T=0) - FI: clock rate conversion factor - DI: voltage adjustment factor - PI1: programming voltage factor - II: maximum programming current factor - N: extra guard time """ if len(atr) < 2: raise SmartcardException(f"ATR sequences must be at least 2 bytes long") if atr[0] not in {0x3B, 0x3F}: raise SmartcardException(f"invalid TS 0x{atr[0]:02x}") self.atr = atr # initial character self.TS = self.atr[0] # format character self.T0 = self.atr[1] # count of historical bytes self.K = self.T0 & 0x0F # initialize optional characters lists self.TA: list[None | int] = [] self.TB: list[None | int] = [] self.TC: list[None | int] = [] self.TD: list[None | int] = [] self.Y: list[int] = [] td: None | int = self.T0 offset = 1 while td is not None: self.Y.append(td >> 4 & 0x0F) self.TA += [None] self.TB += [None] self.TC += [None] self.TD += [None] if self.Y[-1] & 0x01: # TA offset += 1 self.TA[-1] = self.atr[offset] if self.Y[-1] & 0x02: # TB offset += 1 self.TB[-1] = self.atr[offset] if self.Y[-1] & 0x04: # TC offset += 1 self.TC[-1] = self.atr[offset] if self.Y[-1] & 0x08: # TD offset += 1 self.TD[-1] = self.atr[offset] td = self.TD[-1] self.interfaceBytesCount = offset - 1 # historical bytes self.historicalBytes = self.atr[offset + 1 : offset + 1 + self.K] # checksum self.TCK: int | None = None self.checksumOK: bool | None = None self.hasChecksum = len(self.atr) == offset + 1 + self.K + 1 if self.hasChecksum: self.TCK = self.atr[-1] self.checksumOK = functools.reduce(operator.xor, self.atr[1:]) == 0 # clock-rate conversion factor self.FI: int | None = None if self.TA[0] is not None: self.FI = self.TA[0] >> 4 & 0x0F # bit-rate adjustment factor self.DI: int | None = None if self.TA[0] is not None: self.DI = self.TA[0] & 0x0F # maximum programming current factor self.II: int | None = None if self.TB[0] is not None: self.II = self.TB[0] >> 5 & 0x03 # programming voltage factor self.PI1: int | None = None if self.TB[0] is not None: self.PI1 = self.TB[0] & 0x1F # extra guard time self.N = self.TC[0] @property def hasTA(self) -> list[bool]: """Deprecated. Replace usage with `ATR.TA[i] is not None`.""" warnings.warn("Replace usage with `ATR.TA[i] is not None`", DeprecationWarning) return [ta is not None for ta in self.TA] @property def hasTB(self) -> list[bool]: """Deprecated. Replace usage with `ATR.TB[i] is not None`.""" warnings.warn("Replace usage with `ATR.TB[i] is not None`", DeprecationWarning) return [tb is not None for tb in self.TB] @property def hasTC(self) -> list[bool]: """Deprecated. Replace usage with `ATR.TC[i] is not None`.""" warnings.warn("Replace usage with `ATR.TC[i] is not None`", DeprecationWarning) return [tc is not None for tc in self.TC] @property def hasTD(self) -> list[bool]: """Deprecated. Replace usage with `ATR.TD[i] is not None`.""" warnings.warn("Replace usage with `ATR.TD[i] is not None`", DeprecationWarning) return [td is not None for td in self.TD] def getChecksum(self) -> int | None: """Return the checksum of the ATR. Checksum is mandatory only for T=1.""" return self.TCK def getHistoricalBytes(self) -> list[int]: """Return historical bytes.""" return self.historicalBytes def getHistoricalBytesCount(self) -> int: """Return count of historical bytes.""" return len(self.historicalBytes) def getInterfaceBytesCount(self) -> int: """Return count of interface bytes.""" return self.interfaceBytesCount def getTA1(self) -> int | None: """Return TA1 byte.""" return self.TA[0] def getTB1(self) -> int | None: """Return TB1 byte.""" return self.TB[0] def getTC1(self) -> int | None: """Return TC1 byte.""" return self.TC[0] def getTD1(self) -> int | None: """Return TD1 byte.""" return self.TD[0] def getBitRateFactor(self) -> int | str: """Return bit rate factor.""" if self.DI is not None: return ATR.bitratefactor[self.DI] return 1 def getClockRateConversion(self) -> int | str: """Return clock rate conversion.""" if self.FI is not None: return ATR.clockrateconversion[self.FI] return 372 def getProgrammingCurrent(self) -> int | str: """Return maximum programming current.""" if self.II is not None: return ATR.currenttable[self.II] return 50 def getProgrammingVoltage(self) -> int: """Return programming voltage.""" if self.PI1 is not None: return 5 * (1 + self.PI1) return 5 def getGuardTime(self) -> int | None: """Return extra guard time.""" return self.N def getSupportedProtocols(self) -> dict[str, bool]: """Returns a dictionary of supported protocols.""" protocols: dict[str, bool] = {} for td in self.TD: if td is not None: protocols[f"T={td & 0x0F}"] = True if self.TD[0] is None: protocols["T=0"] = True return protocols def isT0Supported(self) -> bool: """Return True if T=0 is supported.""" return "T=0" in self.getSupportedProtocols() def isT1Supported(self) -> bool: """Return True if T=1 is supported.""" return "T=1" in self.getSupportedProtocols() def isT15Supported(self) -> bool: """Return True if T=15 is supported.""" return "T=15" in self.getSupportedProtocols() def render(self) -> str: """Render the ATR to a readable format.""" lines: list[str] = [] enumerated_tx_values = enumerate(zip(self.TA, self.TB, self.TC, self.TD), 1) for i, (ta, tb, tc, td) in enumerated_tx_values: if ta is not None: lines.append(f"TA{i}: {ta:x}") if tb is not None: lines.append(f"TB{i}: {tb:x}") if tc is not None: lines.append(f"TC{i}: {tc:x}") if td is not None: lines.append(f"TD{i}: {td:x}") lines.append(f"supported protocols {','.join(self.getSupportedProtocols())}") lines.append(f"T=0 supported: {self.isT0Supported()}") lines.append(f"T=1 supported: {self.isT1Supported()}") if self.getChecksum() is not None: lines.append(f"checksum: {self.getChecksum()}") lines.append(f"\tclock rate conversion factor: {self.getClockRateConversion()}") lines.append(f"\tbit rate adjustment factor: {self.getBitRateFactor()}") lines.append(f"\tmaximum programming current: {self.getProgrammingCurrent()}") lines.append(f"\tprogramming voltage: {self.getProgrammingVoltage()}") lines.append(f"\tguard time: {self.getGuardTime()}") lines.append(f"nb of interface bytes: {self.getInterfaceBytesCount()}") lines.append(f"nb of historical bytes: {self.getHistoricalBytesCount()}") return "\n".join(lines) def dump(self) -> None: """Deprecated. Replace usage with `print(ATR.render())`""" warnings.warn("Replace usage with `print(ATR.render())`", DeprecationWarning) print(self.render()) def __str__(self) -> str: """Render the ATR as a space-separated string of uppercase hexadecimal pairs.""" return bytes(self.atr).hex(" ").upper()
class ATR: '''Parse and represent Answer to Reset sequences. Answer to Reset sequences are defined in ISO 7816-3, section 8. ''' def __init__(self, atr: list[int]) -> None: '''Parse ATR and initialize members: - TS: initial character - T0: format character - TA[n], TB[n], TC[n], TD[n], for n=0,1,...: protocol parameters @note: protocol parameters indices start at 0, e.g. TA[0], TA[1] correspond to the ISO standard TA1, TA2 parameters - historicalBytes: the ATR T1, T2, ..., TK historical bytes - TCK: checksum byte (only for protocols different from T=0) - FI: clock rate conversion factor - DI: voltage adjustment factor - PI1: programming voltage factor - II: maximum programming current factor - N: extra guard time ''' pass @property def hasTA(self) -> list[bool]: '''Deprecated. Replace usage with `ATR.TA[i] is not None`.''' pass @property def hasTB(self) -> list[bool]: '''Deprecated. Replace usage with `ATR.TB[i] is not None`.''' pass @property def hasTC(self) -> list[bool]: '''Deprecated. Replace usage with `ATR.TC[i] is not None`.''' pass @property def hasTD(self) -> list[bool]: '''Deprecated. Replace usage with `ATR.TD[i] is not None`.''' pass def getChecksum(self) -> int | None: '''Return the checksum of the ATR. Checksum is mandatory only for T=1.''' pass def getHistoricalBytes(self) -> list[int]: '''Return historical bytes.''' pass def getHistoricalBytesCount(self) -> int: '''Return count of historical bytes.''' pass def getInterfaceBytesCount(self) -> int: '''Return count of interface bytes.''' pass def getTA1(self) -> int | None: '''Return TA1 byte.''' pass def getTB1(self) -> int | None: '''Return TB1 byte.''' pass def getTC1(self) -> int | None: '''Return TC1 byte.''' pass def getTD1(self) -> int | None: '''Return TD1 byte.''' pass def getBitRateFactor(self) -> int | str: '''Return bit rate factor.''' pass def getClockRateConversion(self) -> int | str: '''Return clock rate conversion.''' pass def getProgrammingCurrent(self) -> int | str: '''Return maximum programming current.''' pass def getProgrammingVoltage(self) -> int: '''Return programming voltage.''' pass def getGuardTime(self) -> int | None: '''Return extra guard time.''' pass def getSupportedProtocols(self) -> dict[str, bool]: '''Returns a dictionary of supported protocols.''' pass def isT0Supported(self) -> bool: '''Return True if T=0 is supported.''' pass def isT1Supported(self) -> bool: '''Return True if T=1 is supported.''' pass def isT15Supported(self) -> bool: '''Return True if T=15 is supported.''' pass def render(self) -> str: '''Render the ATR to a readable format.''' pass def dump(self) -> None: '''Deprecated. Replace usage with `print(ATR.render())`''' pass def __str__(self) -> str: '''Render the ATR as a space-separated string of uppercase hexadecimal pairs.''' pass
30
26
9
1
6
2
2
0.31
0
10
1
0
25
19
25
25
301
59
188
59
158
58
150
55
124
13
0
2
50
147,517
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/AbstractCardRequest.py
smartcard.AbstractCardRequest.AbstractCardRequest
class AbstractCardRequest: """The base class for xxxCardRequest classes. A CardRequest is used for waitForCard() invocations and specifies what kind of smart card an application is waited for.""" def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): """Construct new CardRequest. @param newcardonly: if True, request a new card; default is False, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card; default is to consider all readers @param cardType: the L{smartcard.CardType.CardType} to wait for; default is L{smartcard.CardType.AnyCardType}, i.e. the request will succeed with any card @param cardServiceClass: the specific card service class to create and bind to the card;default is to create and bind a L{smartcard.PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second; to wait forever, set timeout to None """ self.newcardonly = newcardonly self.readersAsked = readers self.cardType = cardType self.cardServiceClass = cardServiceClass self.timeout = timeout # if no CardType requested, use AnyCardType if self.cardType is None: self.cardType = AnyCardType() # if no card service requested, use pass-thru card service if self.cardServiceClass is None: self.cardServiceClass = PassThruCardService def getReaders(self): """Returns the list or readers on which to wait for cards.""" # if readers not given, use all readers if self.readersAsked is None: return smartcard.System.readers() else: return self.readersAsked def waitforcard(self): """Wait for card insertion and returns a card service.""" pass def waitforcardevent(self): """Wait for card insertion or removal.""" pass
class AbstractCardRequest: '''The base class for xxxCardRequest classes. A CardRequest is used for waitForCard() invocations and specifies what kind of smart card an application is waited for.''' def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): '''Construct new CardRequest. @param newcardonly: if True, request a new card; default is False, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card; default is to consider all readers @param cardType: the L{smartcard.CardType.CardType} to wait for; default is L{smartcard.CardType.AnyCardType}, i.e. the request will succeed with any card @param cardServiceClass: the specific card service class to create and bind to the card;default is to create and bind a L{smartcard.PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second; to wait forever, set timeout to None ''' pass def getReaders(self): '''Returns the list or readers on which to wait for cards.''' pass def waitforcard(self): '''Wait for card insertion and returns a card service.''' pass def waitforcardevent(self): '''Wait for card insertion or removal.''' pass
5
5
14
2
7
6
2
0.96
0
2
2
1
4
5
4
4
65
12
27
17
15
26
19
10
14
3
0
1
7
147,518
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Card.py
smartcard.Card.Card
class Card: """Card class.""" def __init__(self, reader, atr): """Card constructor. @param reader: reader in which the card is inserted @param atr: ATR of the card""" self.reader = reader self.atr = atr def __repr__(self): """Return a string representing the Card (atr and reader concatenation).""" return toHexString(self.atr) + " / " + str(self.reader) def __eq__(self, other): """Return True if self==other (same reader and same atr). Return False otherwise.""" if isinstance(other, Card): return self.atr == other.atr and repr(self.reader) == repr(other.reader) else: return False def __ne__(self, other): """Return True if self!=other (same reader and same atr).Returns False otherwise.""" return not self.__eq__(other) def __hash__(self): """Returns a hash value for this object (str(self) is unique).""" return hash(str(self)) def createConnection(self): """Return a CardConnection to the Card object.""" readerobj = None if isinstance(self.reader, Reader): readerobj = self.reader elif type(self.reader) == str: for reader in readers(): if self.reader == str(reader): readerobj = reader if readerobj: return readerobj.createConnection() else: # raise CardConnectionException( # 'not a valid reader: ' + str(self.reader)) return None
class Card: '''Card class.''' def __init__(self, reader, atr): '''Card constructor. @param reader: reader in which the card is inserted @param atr: ATR of the card''' pass def __repr__(self): '''Return a string representing the Card (atr and reader concatenation).''' pass def __eq__(self, other): '''Return True if self==other (same reader and same atr). Return False otherwise.''' pass def __ne__(self, other): '''Return True if self!=other (same reader and same atr).Returns False otherwise.''' pass def __hash__(self): '''Returns a hash value for this object (str(self) is unique).''' pass def createConnection(self): '''Return a CardConnection to the Card object.''' pass
7
7
7
0
4
2
2
0.52
0
3
1
0
6
2
6
6
48
7
27
11
20
14
24
11
17
6
0
3
12
147,519
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardConnection.py
smartcard.CardConnection.CardConnection
class CardConnection(Observable): """Card connection abstract class.""" T0_protocol = 0x00000001 """ protocol T=0 """ T1_protocol = 0x00000002 """ protocol T=1 """ RAW_protocol = 0x00010000 """ protocol RAW (direct access to the reader) """ T15_protocol = 0x00000008 """ protocol T=15 """ def __init__(self, reader): """Construct a new card connection. @param reader: name of the reader in which the smartcard to connect to is located. """ Observable.__init__(self) self.reader = reader """ reader name """ self.errorcheckingchain = None """ see L{setErrorCheckingChain} """ self.defaultprotocol = CardConnection.T0_protocol | CardConnection.T1_protocol """ see L{setProtocol} and L{getProtocol} """ def __del__(self): """Connect to card.""" pass def addSWExceptionToFilter(self, exClass): """Add a status word exception class to be filtered. @param exClass: the class to filter, e.g. L{smartcard.sw.SWExceptions.WarningProcessingException} Filtered exceptions will not be raised when encountered in the error checking chain.""" if self.errorcheckingchain is not None: self.errorcheckingchain[0].addFilterException(exClass) def addObserver(self, observer): """Add a L{CardConnection} observer.""" Observable.addObserver(self, observer) def deleteObserver(self, observer): """Remove a L{CardConnection} observer.""" Observable.deleteObserver(self, observer) def connect(self, protocol=None, mode=None, disposition=None): """Connect to card. @param protocol: a bit mask of the protocols to use, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} @param mode: C{smartcard.scard.SCARD_SHARE_SHARED} (default), C{smartcard.scard.SCARD_SHARE_EXCLUSIVE} or C{smartcard.scard.SCARD_SHARE_DIRECT} @param disposition: C{smartcard.scard.SCARD_LEAVE_CARD} (default), C{smartcard.scard.SCARD_RESET_CARD}, C{smartcard.scard.SCARD_UNPOWER_CARD} or C{smartcard.scard.SCARD_EJECT_CARD} """ Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent("connect")) def reconnect(self, protocol=None, mode=None, disposition=None): """Reconnect to card. @param protocol: a bit mask of the protocols to use, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} @param mode: C{smartcard.scard.SCARD_SHARE_SHARED} (default), C{smartcard.scard.SCARD_SHARE_EXCLUSIVE} or C{smartcard.scard.SCARD_SHARE_DIRECT} @param disposition: C{smartcard.scard.SCARD_LEAVE_CARD}, C{smartcard.scard.SCARD_RESET_CARD} (default), C{smartcard.scard.SCARD_UNPOWER_CARD} or C{smartcard.scard.SCARD_EJECT_CARD} """ Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent("reconnect")) def disconnect(self): """Disconnect from card.""" Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent("disconnect")) def getATR(self): """Return card ATR""" pass def getProtocol(self): """Return bit mask for the protocol of connection, or None if no protocol set. The return value is a bit mask of L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} """ return self.defaultprotocol def getReader(self): """Return card connection reader""" return self.reader def setErrorCheckingChain(self, errorcheckingchain): """Add an error checking chain. @param errorcheckingchain: a L{smartcard.sw.ErrorCheckingChain} object The error checking strategies in errorchecking chain will be tested with each received response APDU, and a L{smartcard.sw.SWExceptions.SWException} will be raised upon error.""" self.errorcheckingchain = errorcheckingchain def setProtocol(self, protocol): """Set protocol for card connection. @param protocol: a bit mask of L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} >>> setProtocol(CardConnection.T1_protocol | CardConnection.T0_protocol) """ self.defaultprotocol = protocol def transmit(self, command, protocol=None): """Transmit an apdu. Internally calls L{doTransmit()} class method and notify observers upon command/response APDU events. Subclasses must override the L{doTransmit()} class method. @param command: list of bytes to transmit @param protocol: the transmission protocol, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, or L{CardConnection.RAW_protocol} """ Observable.setChanged(self) Observable.notifyObservers( self, CardConnectionEvent("command", [command, protocol]) ) data, sw1, sw2 = self.doTransmit(command, protocol) Observable.setChanged(self) Observable.notifyObservers( self, CardConnectionEvent("response", [data, sw1, sw2]) ) if self.errorcheckingchain is not None: self.errorcheckingchain[0](data, sw1, sw2) return data, sw1, sw2 def doTransmit(self, command, protocol): """Performs the command APDU transmission. Subclasses must override this method for implementing apdu transmission.""" return [], 0, 0 def control(self, controlCode, command=None): """Send a control command and buffer. Internally calls L{doControl()} class method and notify observers upon command/response events. Subclasses must override the L{doControl()} class method. @param controlCode: command code @param command: list of bytes to transmit """ if command is None: command = [] Observable.setChanged(self) Observable.notifyObservers( self, CardConnectionEvent("command", [controlCode, command]) ) data = self.doControl(controlCode, command) Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent("response", data)) if self.errorcheckingchain is not None: self.errorcheckingchain[0](data) return data def doControl(self, controlCode, command): """Performs the command control. Subclasses must override this method for implementing control.""" return [] def getAttrib(self, attribId): """return the requested attribute @param attribId: attribute id like C{smartcard.scard.SCARD_ATTR_VENDOR_NAME} """ Observable.setChanged(self) Observable.notifyObservers(self, CardConnectionEvent("attrib", [attribId])) data = self.doGetAttrib(attribId) if self.errorcheckingchain is not None: self.errorcheckingchain[0](data) return data def doGetAttrib(self, attribId): """Performs the command get attrib. Subclasses must override this method for implementing get attrib.""" return [] def __enter__(self): """Enter the runtime context.""" return self def __exit__(self, type, value, traceback): """Exit the runtime context trying to disconnect.""" self.disconnect()
class CardConnection(Observable): '''Card connection abstract class.''' def __init__(self, reader): '''Construct a new card connection. @param reader: name of the reader in which the smartcard to connect to is located. ''' pass def __del__(self): '''Connect to card.''' pass def addSWExceptionToFilter(self, exClass): '''Add a status word exception class to be filtered. @param exClass: the class to filter, e.g. L{smartcard.sw.SWExceptions.WarningProcessingException} Filtered exceptions will not be raised when encountered in the error checking chain.''' pass def addObserver(self, observer): '''Add a L{CardConnection} observer.''' pass def deleteObserver(self, observer): '''Remove a L{CardConnection} observer.''' pass def connect(self, protocol=None, mode=None, disposition=None): '''Connect to card. @param protocol: a bit mask of the protocols to use, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} @param mode: C{smartcard.scard.SCARD_SHARE_SHARED} (default), C{smartcard.scard.SCARD_SHARE_EXCLUSIVE} or C{smartcard.scard.SCARD_SHARE_DIRECT} @param disposition: C{smartcard.scard.SCARD_LEAVE_CARD} (default), C{smartcard.scard.SCARD_RESET_CARD}, C{smartcard.scard.SCARD_UNPOWER_CARD} or C{smartcard.scard.SCARD_EJECT_CARD} ''' pass def reconnect(self, protocol=None, mode=None, disposition=None): '''Reconnect to card. @param protocol: a bit mask of the protocols to use, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} @param mode: C{smartcard.scard.SCARD_SHARE_SHARED} (default), C{smartcard.scard.SCARD_SHARE_EXCLUSIVE} or C{smartcard.scard.SCARD_SHARE_DIRECT} @param disposition: C{smartcard.scard.SCARD_LEAVE_CARD}, C{smartcard.scard.SCARD_RESET_CARD} (default), C{smartcard.scard.SCARD_UNPOWER_CARD} or C{smartcard.scard.SCARD_EJECT_CARD} ''' pass def disconnect(self): '''Disconnect from card.''' pass def getATR(self): '''Return card ATR''' pass def getProtocol(self): '''Return bit mask for the protocol of connection, or None if no protocol set. The return value is a bit mask of L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} ''' pass def getReader(self): '''Return card connection reader''' pass def setErrorCheckingChain(self, errorcheckingchain): '''Add an error checking chain. @param errorcheckingchain: a L{smartcard.sw.ErrorCheckingChain} object The error checking strategies in errorchecking chain will be tested with each received response APDU, and a L{smartcard.sw.SWExceptions.SWException} will be raised upon error.''' pass def setProtocol(self, protocol): '''Set protocol for card connection. @param protocol: a bit mask of L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, L{CardConnection.RAW_protocol}, L{CardConnection.T15_protocol} >>> setProtocol(CardConnection.T1_protocol | CardConnection.T0_protocol) ''' pass def transmit(self, command, protocol=None): '''Transmit an apdu. Internally calls L{doTransmit()} class method and notify observers upon command/response APDU events. Subclasses must override the L{doTransmit()} class method. @param command: list of bytes to transmit @param protocol: the transmission protocol, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, or L{CardConnection.RAW_protocol} ''' pass def doTransmit(self, command, protocol): '''Performs the command APDU transmission. Subclasses must override this method for implementing apdu transmission.''' pass def control(self, controlCode, command=None): '''Send a control command and buffer. Internally calls L{doControl()} class method and notify observers upon command/response events. Subclasses must override the L{doControl()} class method. @param controlCode: command code @param command: list of bytes to transmit ''' pass def doControl(self, controlCode, command): '''Performs the command control. Subclasses must override this method for implementing control.''' pass def getAttrib(self, attribId): '''return the requested attribute @param attribId: attribute id like C{smartcard.scard.SCARD_ATTR_VENDOR_NAME} ''' pass def doGetAttrib(self, attribId): '''Performs the command get attrib. Subclasses must override this method for implementing get attrib.''' pass def __enter__(self): '''Enter the runtime context.''' pass def __exit__(self, type, value, traceback): '''Exit the runtime context trying to disconnect.''' pass
22
22
9
1
4
4
1
1.15
1
1
1
2
21
3
21
55
215
41
81
32
59
93
75
32
53
3
8
1
26
147,520
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardConnectionDecorator.py
smartcard.CardConnectionDecorator.CardConnectionDecorator
class CardConnectionDecorator(CardConnection): """Card connection decorator class.""" def __init__(self, cardConnectionComponent): """Construct a new card connection decorator. CardConnectionComponent: CardConnection component to decorate """ self.component = cardConnectionComponent def addSWExceptionToFilter(self, exClass): """call inner component addSWExceptionToFilter""" self.component.addSWExceptionToFilter(exClass) def addObserver(self, observer): """call inner component addObserver""" self.component.addObserver(observer) def deleteObserver(self, observer): """call inner component deleteObserver""" self.component.deleteObserver(observer) def connect(self, protocol=None, mode=None, disposition=None): """call inner component connect""" self.component.connect(protocol, mode, disposition) def reconnect(self, protocol=None, mode=None, disposition=None): """call inner component reconnect""" self.component.reconnect(protocol, mode, disposition) def disconnect(self): """call inner component disconnect""" self.component.disconnect() def getATR(self): """call inner component getATR""" return self.component.getATR() def getProtocol(self): """call inner component getProtocol""" return self.component.getProtocol() def getReader(self): """call inner component getReader""" return self.component.getReader() def setErrorCheckingChain(self, errorcheckingchain): """call inner component setErrorCheckingChain""" self.component.setErrorCheckingChain(errorcheckingchain) def setProtocol(self, protocol): """call inner component setProtocol""" return self.component.setProtocol(protocol) def transmit(self, command, protocol=None): """call inner component transmit""" return self.component.transmit(command, protocol) def control(self, controlCode, command=None): """call inner component control""" if command is None: command = [] return self.component.control(controlCode, command) def getAttrib(self, attribId): """call inner component getAttrib""" return self.component.getAttrib(attribId)
class CardConnectionDecorator(CardConnection): '''Card connection decorator class.''' def __init__(self, cardConnectionComponent): '''Construct a new card connection decorator. CardConnectionComponent: CardConnection component to decorate ''' pass def addSWExceptionToFilter(self, exClass): '''call inner component addSWExceptionToFilter''' pass def addObserver(self, observer): '''call inner component addObserver''' pass def deleteObserver(self, observer): '''call inner component deleteObserver''' pass def connect(self, protocol=None, mode=None, disposition=None): '''call inner component connect''' pass def reconnect(self, protocol=None, mode=None, disposition=None): '''call inner component reconnect''' pass def disconnect(self): '''call inner component disconnect''' pass def getATR(self): '''call inner component getATR''' pass def getProtocol(self): '''call inner component getProtocol''' pass def getReader(self): '''call inner component getReader''' pass def setErrorCheckingChain(self, errorcheckingchain): '''call inner component setErrorCheckingChain''' pass def setProtocol(self, protocol): '''call inner component setProtocol''' pass def transmit(self, command, protocol=None): '''call inner component transmit''' pass def control(self, controlCode, command=None): '''call inner component control''' pass def getAttrib(self, attribId): '''call inner component getAttrib''' pass
16
16
3
0
2
1
1
0.55
1
0
0
4
15
1
15
70
67
16
33
17
17
18
33
17
17
2
9
1
16
147,521
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/wx/pcscdiag/pcscdiag.py
pcscdiag.pcscdiag
class pcscdiag(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(600, 400)) w, h = self.GetClientSize() self.tree = wx.TreeCtrl( self, wx.NewIdRef(), wx.DefaultPosition, (w, h), wx.TR_HAS_BUTTONS | wx.TR_EDIT_LABELS, ) self.InitTree() self.OnExpandAll() def InitTree(self): self.tree.AddRoot("Readers and ReaderGroups") readerNode = self.tree.AppendItem(self.tree.GetRootItem(), "Readers") for reader in smartcard.System.readers(): childReader = self.tree.AppendItem(readerNode, repr(reader)) childCard = self.tree.AppendItem(childReader, getATR(reader)) readerGroupNode = self.tree.AppendItem( self.tree.GetRootItem(), "Readers Groups" ) for readergroup in smartcard.System.readergroups(): childReaderGroup = self.tree.AppendItem(readerGroupNode, readergroup) readers = smartcard.System.readers(readergroup) for reader in readers: child = self.tree.AppendItem(childReaderGroup, repr(reader)) def OnExpandAll(self): """expand all nodes""" root = self.tree.GetRootItem() fn = self.tree.Expand self.traverse(root, fn) self.tree.Expand(root) def traverse(self, traverseroot, function, cookie=0): """recursively walk tree control""" if self.tree.ItemHasChildren(traverseroot): firstchild, cookie = self.tree.GetFirstChild(traverseroot) function(firstchild) self.traverse(firstchild, function, cookie) child = self.tree.GetNextSibling(traverseroot) if child: function(child) self.traverse(child, function, cookie)
class pcscdiag(wx.Frame): def __init__(self, parent, title): pass def InitTree(self): pass def OnExpandAll(self): '''expand all nodes''' pass def traverse(self, traverseroot, function, cookie=0): '''recursively walk tree control''' pass
5
2
11
1
10
1
2
0.05
1
0
0
0
4
1
4
4
50
7
41
20
36
2
33
20
28
4
1
2
9
147,522
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardConnectionObserver.py
smartcard.CardConnectionObserver.CardConnectionObserver
class CardConnectionObserver(Observer): """ CardConnectionObserver is a base class for objects that are to be notified upon L{CardConnection} events. """ def update(self, cardconnection, cardconnectionevent): """Called upon CardConnection event. @param cardconnection: the observed card connection object @param cardconnectionevent: the CardConnectionEvent sent by the connection """ pass
class CardConnectionObserver(Observer): ''' CardConnectionObserver is a base class for objects that are to be notified upon L{CardConnection} events. ''' def update(self, cardconnection, cardconnectionevent): '''Called upon CardConnection event. @param cardconnection: the observed card connection object @param cardconnectionevent: the CardConnectionEvent sent by the connection ''' pass
2
2
7
1
2
4
1
2.67
1
0
0
3
1
0
1
2
13
2
3
2
1
8
3
2
1
1
1
0
1
147,523
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/wx/cardmonitor/cardmonitor.py
cardmonitor.SamplePanel
class SamplePanel(wx.Panel, SimpleSCardAppEventObserver): """A simple panel that displays activated cards and readers. The panel implements the SimpleSCardAppEventObserver, and has a chance to react on reader and card activation/deactivation.""" def __init__(self, parent): wx.Panel.__init__(self, parent, -1) sizer = wx.FlexGridSizer(0, 3, 0, 0) sizer.AddGrowableCol(1) sizer.AddGrowableRow(1) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) self.feedbacktext = wx.StaticText( self, ID_TEXT, "", wx.DefaultPosition, wx.DefaultSize, 0 ) sizer.Add(self.feedbacktext, 0, wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) self.SetSizer(sizer) self.SetAutoLayout(True) # callbacks from SimpleSCardAppEventObserver interface def OnActivateCard(self, card): """Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.""" SimpleSCardAppEventObserver.OnActivateCard(self, card) self.feedbacktext.SetLabel("Activated card: " + repr(card)) def OnActivateReader(self, reader): """Called when a reader is activated by double-clicking on the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnActivateReader(self, reader) self.feedbacktext.SetLabel("Activated reader: " + repr(reader)) def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnActivateCard(self, card) self.feedbacktext.SetLabel("Deactivated card: " + repr(card)) def OnSelectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectCard(self, card) self.feedbacktext.SetLabel("Selected card: " + repr(card)) def OnSelectReader(self, reader): """Called when a reader is selected by clicking on the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectReader(self, reader) self.feedbacktext.SetLabel("Selected reader: " + repr(reader))
class SamplePanel(wx.Panel, SimpleSCardAppEventObserver): '''A simple panel that displays activated cards and readers. The panel implements the SimpleSCardAppEventObserver, and has a chance to react on reader and card activation/deactivation.''' def __init__(self, parent): pass def OnActivateCard(self, card): '''Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.''' pass def OnActivateReader(self, reader): '''Called when a reader is activated by double-clicking on the reader tree control or toolbar.''' pass def OnDeactivateCard(self, card): '''Called when a card is deactivated in the reader tree control or toolbar.''' pass def OnSelectCard(self, card): '''Called when a card is selected by clicking on the card or reader tree control or toolbar.''' pass def OnSelectReader(self, reader): '''Called when a reader is selected by clicking on the reader tree control or toolbar.''' pass
7
6
8
1
6
2
1
0.43
2
0
0
0
6
1
6
13
61
11
35
9
28
15
33
9
26
1
1
0
6
147,524
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py
SampleAPDUManagerPanel.SampleAPDUManagerPanel
class SampleAPDUManagerPanel(wx.Panel, SimpleSCardAppEventObserver): """A simple panel that displays activated cards and readers and can send APDU to a connected card.""" def __init__(self, parent): wx.Panel.__init__(self, parent, -1) SimpleSCardAppEventObserver.__init__(self) self.layoutControls() self.Bind(wx.EVT_BUTTON, self.OnTransmit, self.transmitbutton) # callbacks from SimpleSCardAppEventObserver interface def OnActivateCard(self, card): """Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.""" SimpleSCardAppEventObserver.OnActivateCard(self, card) self.feedbacktext.SetLabel("Activated card: " + repr(card)) self.transmitbutton.Enable() def OnActivateReader(self, reader): """Called when a reader is activated by double-clicking on the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnActivateReader(self, reader) self.feedbacktext.SetLabel("Activated reader: " + repr(reader)) self.transmitbutton.Disable() def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnActivateCard(self, card) self.feedbacktext.SetLabel("Deactivated card: " + repr(card)) self.transmitbutton.Disable() def OnDeselectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectCard(self, card) self.feedbacktext.SetLabel("Deselected card: " + repr(card)) self.transmitbutton.Disable() def OnSelectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectCard(self, card) self.feedbacktext.SetLabel("Selected card: " + repr(card)) if hasattr(self.selectedcard, "connection"): self.transmitbutton.Enable() def OnSelectReader(self, reader): """Called when a reader is selected by clicking on the reader tree control or toolbar.""" SimpleSCardAppEventObserver.OnSelectReader(self, reader) self.feedbacktext.SetLabel("Selected reader: " + repr(reader)) self.transmitbutton.Disable() # callbacks def OnTransmit(self, event): if hasattr(self.selectedcard, "connection"): apdu = self.commandtextctrl.GetValue() data, sw1, sw2 = self.selectedcard.connection.transmit(toBytes(apdu)) self.SW1textctrl.SetValue("%x" % sw1) self.SW2textctrl.SetValue("%x" % sw2) self.responsetextctrl.SetValue(toHexString(data + [sw1, sw2])) event.Skip() def layoutControls(self): # create controls statictextCommand = wx.StaticText( self, ID_TEXT_COMMAND, "Command", wx.DefaultPosition, wx.DefaultSize, 0 ) self.commandtextctrl = wx.TextCtrl( self, ID_TEXTCTRL_COMMAND, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE, validator=APDUHexValidator(), ) statictextResponse = wx.StaticText( self, ID_TEXT_RESPONSE, "Response", wx.DefaultPosition, wx.DefaultSize, 0 ) self.responsetextctrl = wx.TextCtrl( self, ID_TEXTCTRL_RESPONSE, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY, ) statictextStatusWords = wx.StaticText( self, ID_TEXT_SW, "Status Words", wx.DefaultPosition, wx.DefaultSize, 0 ) statictextSW1 = wx.StaticText( self, ID_TEXT_SW1, "SW1", wx.DefaultPosition, wx.DefaultSize, 0 ) self.SW1textctrl = wx.TextCtrl( self, ID_TEXTCTRL_SW1, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY, ) statictextSW2 = wx.StaticText( self, ID_TEXT_SW2, "SW2", wx.DefaultPosition, wx.DefaultSize, 0 ) self.SW2textctrl = wx.TextCtrl( self, ID_TEXTCTRL_SW2, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY, ) self.feedbacktext = wx.StaticText( self, ID_CARDSTATE, "", wx.DefaultPosition, wx.DefaultSize, 0 ) # layout controls boxsizerCommand = wx.BoxSizer(wx.HORIZONTAL) boxsizerCommand.Add(statictextCommand, 1, wx.ALIGN_CENTER | wx.ALL, 5) boxsizerCommand.Add(self.commandtextctrl, 5, wx.EXPAND | wx.ALL, 5) boxsizerResponse = wx.BoxSizer(wx.HORIZONTAL) boxsizerResponse.Add(statictextResponse, 1, wx.ALIGN_CENTER | wx.ALL, 5) boxsizerResponse.Add(self.responsetextctrl, 5, wx.EXPAND | wx.ALL, 5) boxsizerSW = wx.BoxSizer(wx.HORIZONTAL) boxsizerSW.Add(statictextSW1, 0, wx.ALIGN_CENTER | wx.ALL, 5) boxsizerSW.Add(self.SW1textctrl, 0, wx.EXPAND | wx.ALL, 5) boxsizerSW.Add(statictextSW2, 0, wx.ALIGN_CENTER | wx.ALL, 5) boxsizerSW.Add(self.SW2textctrl, 0, wx.EXPAND | wx.ALL, 5) item11 = wx.BoxSizer(wx.HORIZONTAL) item11.Add(statictextStatusWords, 0, wx.ALIGN_CENTER | wx.ALL, 5) item11.Add(boxsizerSW, 0, wx.EXPAND | wx.ALL, 5) boxsizerResponseAndSW = wx.BoxSizer(wx.VERTICAL) boxsizerResponseAndSW.Add(boxsizerResponse, 0, wx.EXPAND | wx.ALL, 5) boxsizerResponseAndSW.Add(item11, 0, wx.EXPAND | wx.ALL, 5) staticboxAPDU = wx.StaticBox(self, -1, "APDU") boxsizerAPDU = wx.StaticBoxSizer(staticboxAPDU, wx.VERTICAL) boxsizerAPDU.Add(boxsizerCommand, 1, wx.EXPAND | wx.ALL, 5) boxsizerAPDU.Add(boxsizerResponseAndSW, 4, wx.EXPAND | wx.ALL, 5) staticboxEvents = wx.StaticBox(self, -1, "Card/Reader Events") boxsizerEvents = wx.StaticBoxSizer(staticboxEvents, wx.HORIZONTAL) boxsizerEvents.Add(self.feedbacktext, 0, wx.ALIGN_CENTER | wx.ALL, 5) sizerboxTransmitButton = wx.BoxSizer(wx.HORIZONTAL) sizerboxTransmitButton.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) self.transmitbutton = wx.Button( self, ID_TRANSMIT, "Transmit", wx.DefaultPosition, wx.DefaultSize, 0 ) self.transmitbutton.Disable() sizerboxTransmitButton.Add(self.transmitbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5) sizerboxTransmitButton.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) sizerPanel = wx.BoxSizer(wx.VERTICAL) sizerPanel.Add(boxsizerAPDU, 3, wx.EXPAND | wx.ALL, 5) sizerPanel.Add(boxsizerEvents, 1, wx.EXPAND | wx.ALL, 5) sizerPanel.Add(sizerboxTransmitButton, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(sizerPanel) self.SetAutoLayout(True) sizerPanel.Fit(self)
class SampleAPDUManagerPanel(wx.Panel, SimpleSCardAppEventObserver): '''A simple panel that displays activated cards and readers and can send APDU to a connected card.''' def __init__(self, parent): pass def OnActivateCard(self, card): '''Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.''' pass def OnActivateReader(self, reader): '''Called when a reader is activated by double-clicking on the reader tree control or toolbar.''' pass def OnDeactivateCard(self, card): '''Called when a card is deactivated in the reader tree control or toolbar.''' pass def OnDeselectCard(self, card): '''Called when a card is selected by clicking on the card or reader tree control or toolbar.''' pass def OnSelectCard(self, card): '''Called when a card is selected by clicking on the card or reader tree control or toolbar.''' pass def OnSelectReader(self, reader): '''Called when a reader is selected by clicking on the reader tree control or toolbar.''' pass def OnTransmit(self, event): pass def layoutControls(self): pass
10
7
17
1
14
2
1
0.15
2
1
1
0
9
6
9
16
170
21
130
34
120
19
87
34
77
2
1
1
11
147,525
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.NoCardException
class NoCardException(SmartcardException): """Raised when no card in is present in reader.""" def __init__(self, message, hresult): SmartcardException.__init__(self, message, hresult=hresult)
class NoCardException(SmartcardException): '''Raised when no card in is present in reader.''' def __init__(self, message, hresult): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,526
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Exceptions.py
smartcard.Exceptions.NoReadersException
class NoReadersException(SmartcardException): """Raised when the system has no smartcard reader.""" def __init__(self, *args): SmartcardException.__init__(self, "No reader found", *args)
class NoReadersException(SmartcardException): '''Raised when the system has no smartcard reader.''' def __init__(self, *args): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,527
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/CardType.py
smartcard.CardType.CardType
class CardType: """Abstract base class for CardTypes. Known subclasses: L{smartcard.CardType.AnyCardType} L{smartcard.CardType.ATRCardType}.""" def __init__(self): """CardType constructor.""" pass def matches(self, atr, reader=None): """Returns true if atr and card connected match the L{CardType}. @param atr: the atr to check for matching @param reader: the reader (optional); default is None The reader can be used in some subclasses to do advanced matching that require connecting to the card.""" pass
class CardType: '''Abstract base class for CardTypes. Known subclasses: L{smartcard.CardType.AnyCardType} L{smartcard.CardType.ATRCardType}.''' def __init__(self): '''CardType constructor.''' pass def matches(self, atr, reader=None): '''Returns true if atr and card connected match the L{CardType}. @param atr: the atr to check for matching @param reader: the reader (optional); default is None The reader can be used in some subclasses to do advanced matching that require connecting to the card.''' pass
3
3
6
1
2
3
1
1.8
0
0
0
3
2
0
2
2
19
5
5
3
2
9
5
3
2
1
0
0
2
147,528
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/ExclusiveConnectCardConnection.py
smartcard.ExclusiveConnectCardConnection.ExclusiveConnectCardConnection
class ExclusiveConnectCardConnection(CardConnectionDecorator): """This decorator uses exclusive access to the card during connection to prevent other processes to connect to this card.""" def __init__(self, cardconnection): CardConnectionDecorator.__init__(self, cardconnection) def connect(self, protocol=None, mode=None, disposition=None): """Disconnect and reconnect in exclusive mode PCSCCardconnections.""" CardConnectionDecorator.connect(self, protocol, mode, disposition) component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection ): pcscprotocol = PCSCCardConnection.translateprotocolmask(protocol) if 0 == pcscprotocol: pcscprotocol = component.getProtocol() if component.hcard is not None: hresult = SCardDisconnect(component.hcard, SCARD_LEAVE_CARD) if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to disconnect: " + SCardGetErrorMessage(hresult) ) hresult, component.hcard, dwActiveProtocol = SCardConnect( component.hcontext, str(component.reader), SCARD_SHARE_EXCLUSIVE, pcscprotocol, ) if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to connect with SCARD_SHARE_EXCLUSIVE" + SCardGetErrorMessage(hresult) ) # print('reconnected exclusive') break if hasattr(component, "component"): component = component.component else: break
class ExclusiveConnectCardConnection(CardConnectionDecorator): '''This decorator uses exclusive access to the card during connection to prevent other processes to connect to this card.''' def __init__(self, cardconnection): pass def connect(self, protocol=None, mode=None, disposition=None): '''Disconnect and reconnect in exclusive mode PCSCCardconnections.''' pass
3
2
19
1
17
1
5
0.11
1
2
1
0
2
0
2
72
42
3
35
7
32
4
22
7
19
8
10
4
9
147,529
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCCardConnection.py
smartcard.pcsc.PCSCCardConnection.PCSCCardConnection
class PCSCCardConnection(CardConnection): """PCSCCard connection class. Handles connection with a card thru a PCSC reader.""" def __init__(self, reader): """Construct a new PCSC card connection. @param reader: the reader in which the smartcard to connect to is located. """ CardConnection.__init__(self, reader) self.hcard = None hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to establish context : " + SCardGetErrorMessage(hresult), hresult=hresult, ) def __del__(self): """Destructor. Clean PCSC connection resources.""" # race condition: module CardConnection # can disappear before __del__ is called self.disconnect() hresult = SCardReleaseContext(self.hcontext) if hresult != SCARD_S_SUCCESS and hresult != SCARD_E_INVALID_VALUE: raise CardConnectionException( "Failed to release context: " + SCardGetErrorMessage(hresult), hresult=hresult, ) CardConnection.__del__(self) def connect(self, protocol=None, mode=None, disposition=None): """Connect to the card. If protocol is not specified, connect with the default connection protocol. If mode is not specified, connect with C{smartcard.scard.SCARD_SHARE_SHARED}.""" CardConnection.connect(self, protocol) pcscprotocol = translateprotocolmask(protocol) if 0 == pcscprotocol: pcscprotocol = self.getProtocol() if mode is None: mode = SCARD_SHARE_SHARED # store the way to dispose the card if disposition is None: disposition = SCARD_UNPOWER_CARD self.disposition = disposition hresult, self.hcard, dwActiveProtocol = SCardConnect( self.hcontext, str(self.reader), mode, pcscprotocol ) if hresult != SCARD_S_SUCCESS: self.hcard = None if hresult in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD): raise NoCardException("Unable to connect", hresult=hresult) else: raise CardConnectionException( "Unable to connect with protocol: " + dictProtocol[pcscprotocol] + ". " + SCardGetErrorMessage(hresult), hresult=hresult, ) protocol = 0 if dwActiveProtocol == SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1: # special case for T0 | T1 # this happens when mode=SCARD_SHARE_DIRECT and no protocol is # then negotiated with the card protocol = CardConnection.T0_protocol | CardConnection.T1_protocol else: for p in dictProtocol: if p == dwActiveProtocol: protocol = eval("CardConnection.%s_protocol" % dictProtocol[p]) PCSCCardConnection.setProtocol(self, protocol) def reconnect(self, protocol=None, mode=None, disposition=None): """Reconnect to the card. If protocol is not specified, connect with the default connection protocol. If mode is not specified, connect with C{smartcard.scard.SCARD_SHARE_SHARED}. If disposition is not specified, do a warm reset (C{smartcard.scard.SCARD_RESET_CARD})""" CardConnection.reconnect(self, protocol) if self.hcard is None: raise CardConnectionException("Card not connected") pcscprotocol = translateprotocolmask(protocol) if 0 == pcscprotocol: pcscprotocol = self.getProtocol() if mode is None: mode = SCARD_SHARE_SHARED # store the way to dispose the card if disposition is None: disposition = SCARD_RESET_CARD self.disposition = disposition hresult, dwActiveProtocol = SCardReconnect( self.hcard, mode, pcscprotocol, self.disposition ) if hresult != SCARD_S_SUCCESS: self.hcard = None if hresult in (SCARD_W_REMOVED_CARD, SCARD_E_NO_SMARTCARD): raise NoCardException("Unable to reconnect", hresult=hresult) else: raise CardConnectionException( "Unable to reconnect with protocol: " + dictProtocol[pcscprotocol] + ". " + SCardGetErrorMessage(hresult), hresult=hresult, ) protocol = 0 if dwActiveProtocol == SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1: # special case for T0 | T1 # this happens when mode=SCARD_SHARE_DIRECT and no protocol is # then negotiated with the card protocol = CardConnection.T0_protocol | CardConnection.T1_protocol else: for p in dictProtocol: if p == dwActiveProtocol: protocol = eval("CardConnection.%s_protocol" % dictProtocol[p]) PCSCCardConnection.setProtocol(self, protocol) def disconnect(self): """Disconnect from the card.""" # when __del__() is invoked in response to a module being deleted, # e.g., when execution of the program is done, other globals referenced # by the __del__() method may already have been deleted. # this causes CardConnection.disconnect to except with a TypeError try: CardConnection.disconnect(self) except TypeError: pass if self.hcard is not None: hresult = SCardDisconnect(self.hcard, self.disposition) self.hcard = None if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to disconnect: " + SCardGetErrorMessage(hresult), hresult=hresult, ) def getATR(self): """Return card ATR""" CardConnection.getATR(self) if self.hcard is None: raise CardConnectionException("Card not connected") hresult, reader, state, protocol, atr = SCardStatus(self.hcard) if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to get status: " + SCardGetErrorMessage(hresult), hresult=hresult, ) return atr def doTransmit(self, command, protocol=None): """Transmit an apdu to the card and return response apdu. @param command: command apdu to transmit (list of bytes) @param protocol: the transmission protocol, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, or L{CardConnection.RAW_protocol} @return: a tuple (response, sw1, sw2) where - response are the response bytes excluding status words - sw1 is status word 1, e.g. 0x90 - sw2 is status word 2, e.g. 0x1A """ if protocol is None: protocol = self.getProtocol() CardConnection.doTransmit(self, command, protocol) pcscprotocolheader = translateprotocolheader(protocol) if 0 == pcscprotocolheader: raise CardConnectionException( "Invalid protocol in transmit: must be " + "CardConnection.T0_protocol, " + "CardConnection.T1_protocol, or " + "CardConnection.RAW_protocol" ) if self.hcard is None: raise CardConnectionException("Card not connected") hresult, response = SCardTransmit(self.hcard, pcscprotocolheader, command) if hresult != SCARD_S_SUCCESS: raise CardConnectionException( "Failed to transmit with protocol " + dictProtocolHeader[pcscprotocolheader] + ". " + SCardGetErrorMessage(hresult), hresult=hresult, ) if len(response) < 2: raise CardConnectionException( "Card returned no valid response", hresult=hresult ) sw1 = (response[-2] + 256) % 256 sw2 = (response[-1] + 256) % 256 data = [(x + 256) % 256 for x in response[:-2]] return list(data), sw1, sw2 def doControl(self, controlCode, command=None): """Transmit a control command to the reader and return response. @param controlCode: control command @param command: command data to transmit (list of bytes) @return: response are the response bytes (if any) """ if command is None: command = [] CardConnection.doControl(self, controlCode, command) hresult, response = SCardControl(self.hcard, controlCode, command) if hresult != SCARD_S_SUCCESS: raise SmartcardException( "Failed to control " + SCardGetErrorMessage(hresult), hresult=hresult ) data = [(x + 256) % 256 for x in response] return list(data) def doGetAttrib(self, attribId): """get an attribute @param attribId: Identifier for the attribute to get @return: response are the attribute byte array """ CardConnection.doGetAttrib(self, attribId) hresult, response = SCardGetAttrib(self.hcard, attribId) if hresult != SCARD_S_SUCCESS: raise SmartcardException( "Failed to getAttrib " + SCardGetErrorMessage(hresult), hresult=hresult ) return response
class PCSCCardConnection(CardConnection): '''PCSCCard connection class. Handles connection with a card thru a PCSC reader.''' def __init__(self, reader): '''Construct a new PCSC card connection. @param reader: the reader in which the smartcard to connect to is located. ''' pass def __del__(self): '''Destructor. Clean PCSC connection resources.''' pass def connect(self, protocol=None, mode=None, disposition=None): '''Connect to the card. If protocol is not specified, connect with the default connection protocol. If mode is not specified, connect with C{smartcard.scard.SCARD_SHARE_SHARED}.''' pass def reconnect(self, protocol=None, mode=None, disposition=None): '''Reconnect to the card. If protocol is not specified, connect with the default connection protocol. If mode is not specified, connect with C{smartcard.scard.SCARD_SHARE_SHARED}. If disposition is not specified, do a warm reset (C{smartcard.scard.SCARD_RESET_CARD})''' pass def disconnect(self): '''Disconnect from the card.''' pass def getATR(self): '''Return card ATR''' pass def doTransmit(self, command, protocol=None): '''Transmit an apdu to the card and return response apdu. @param command: command apdu to transmit (list of bytes) @param protocol: the transmission protocol, from L{CardConnection.T0_protocol}, L{CardConnection.T1_protocol}, or L{CardConnection.RAW_protocol} @return: a tuple (response, sw1, sw2) where - response are the response bytes excluding status words - sw1 is status word 1, e.g. 0x90 - sw2 is status word 2, e.g. 0x1A ''' pass def doControl(self, controlCode, command=None): '''Transmit a control command to the reader and return response. @param controlCode: control command @param command: command data to transmit (list of bytes) @return: response are the response bytes (if any) ''' pass def doGetAttrib(self, attribId): '''get an attribute @param attribId: Identifier for the attribute to get @return: response are the attribute byte array ''' pass
10
10
27
3
18
6
5
0.33
1
6
3
0
9
3
9
64
251
37
161
30
151
53
112
30
102
10
9
3
41
147,530
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCCardRequest.py
smartcard.pcsc.PCSCCardRequest.PCSCCardRequest
class PCSCCardRequest(AbstractCardRequest): """PCSC CardRequest class.""" def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): """Construct new PCSCCardRequest. @param newcardonly: if C{True}, request a new card. default is C{False}, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card default is to consider all readers @param cardType: the L{CardType} class to wait for; default is L{AnyCardType}, i.e. the request will returns with new or already inserted cards @param cardServiceClass: the specific card service class to create and bind to the card default is to create and bind a L{PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second to wait forever, set timeout to C{None} """ AbstractCardRequest.__init__( self, newcardonly, readers, cardType, cardServiceClass, timeout ) # if timeout is None, translate to scard.INFINITE if self.timeout is None: self.timeout = INFINITE # otherwise, from seconds to milliseconds else: self.timeout = int(self.timeout * 1000) hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) self.evt = threading.Event() self.hresult = SCARD_S_SUCCESS self.readerstates = {} self.newstates = [] self.timeout_init = self.timeout def __del__(self): hresult = SCardReleaseContext(self.hcontext) if hresult != SCARD_S_SUCCESS: raise ReleaseContextException(hresult) self.hcontext = -1 def getReaderNames(self): """Returns the list of PCSC readers on which to wait for cards.""" # get inserted readers hresult, pcscreaders = SCardListReaders(self.hcontext, []) # renew the context in case PC/SC was stopped # this happens on Windows when the last reader is disconnected if hresult in (SCARD_E_SERVICE_STOPPED, SCARD_E_NO_SERVICE): hresult = SCardReleaseContext(self.hcontext) if hresult != SCARD_S_SUCCESS: raise ReleaseContextException(hresult) hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) hresult, pcscreaders = SCardListReaders(self.hcontext, []) if SCARD_E_NO_READERS_AVAILABLE == hresult: return [] if SCARD_S_SUCCESS != hresult: raise ListReadersException(hresult) readers = [] # if no readers asked, use all inserted readers if self.readersAsked is None: readers = pcscreaders # otherwise use only the asked readers that are inserted else: for reader in self.readersAsked: if not isinstance(reader, str): reader = str(reader) if reader in pcscreaders: readers = readers + [reader] return readers # thread waiting for a change # the main thread will handle a possible KeyboardInterrupt def getStatusChange(self): self.hresult, self.newstates = SCardGetStatusChange( self.hcontext, self.timeout, list(self.readerstates.values()) ) self.evt.set() def waitforcard(self): """Wait for card insertion and returns a card service.""" AbstractCardRequest.waitforcard(self) cardfound = False # create a dictionary entry for new readers readerstates = {} readernames = self.getReaderNames() # add PnP special reader readernames.append("\\\\?PnP?\\Notification") for reader in readernames: if reader not in readerstates: readerstates[reader] = (reader, SCARD_STATE_UNAWARE) # call SCardGetStatusChange only if we have some readers if {} != readerstates: hresult, newstates = SCardGetStatusChange( self.hcontext, 0, list(readerstates.values()) ) else: hresult = SCARD_S_SUCCESS newstates = [] # we can expect normally time-outs or reader # disappearing just before the call # otherwise, raise exception on error if ( SCARD_S_SUCCESS != hresult and SCARD_E_TIMEOUT != hresult and SCARD_E_UNKNOWN_READER != hresult ): raise CardRequestException( "Failed to SCardGetStatusChange " + SCardGetErrorMessage(hresult), hresult=hresult, ) # update readerstate for state in newstates: readername, eventstate, atr = state readerstates[readername] = (readername, eventstate) # if a new card is not requested, just return the first available if not self.newcardonly: for state in newstates: readername, eventstate, atr = state if eventstate & SCARD_STATE_PRESENT: reader = PCSCReader(readername) if self.cardType.matches(atr, reader): if self.cardServiceClass.supports("dummy"): cardfound = True return self.cardServiceClass(reader.createConnection()) startDate = datetime.now() self.timeout = self.timeout_init while not cardfound: # create a dictionary entry for new readers readernames = self.getReaderNames() if self.readersAsked is None: # add PnP special reader readernames.append("\\\\?PnP?\\Notification") for reader in readernames: if reader not in readerstates: readerstates[reader] = (reader, SCARD_STATE_UNAWARE) # remove dictionary entry for readers that disappeared for oldreader in list(readerstates.keys()): if oldreader not in readernames: del readerstates[oldreader] # wait for card insertion self.readerstates = readerstates waitThread = threading.Thread(target=self.getStatusChange) waitThread.start() # the main thread handles a possible KeyboardInterrupt try: waitThread.join() except KeyboardInterrupt: hresult = SCardCancel(self.hcontext) if hresult != SCARD_S_SUCCESS: raise CardRequestException( "Failed to SCardCancel " + SCardGetErrorMessage(hresult), hresult=hresult, ) # wait for the thread to finish in case of KeyboardInterrupt self.evt.wait(timeout=None) # get values set in the getStatusChange thread hresult = self.hresult newstates = self.newstates # compute remaining timeout if self.timeout != INFINITE: delta = datetime.now() - startDate self.timeout -= int(delta.total_seconds() * 1000) if self.timeout < 0: self.timeout = 0 # time-out if hresult in (SCARD_E_TIMEOUT, SCARD_E_CANCELLED): raise CardRequestTimeoutException(hresult=hresult) # reader vanished before or during the call elif SCARD_E_UNKNOWN_READER == hresult: pass # this happens on Windows when the last reader is disconnected elif hresult in (SCARD_E_SYSTEM_CANCELLED, SCARD_E_NO_SERVICE): pass # some error happened elif SCARD_S_SUCCESS != hresult: raise CardRequestException( "Failed to get status change " + SCardGetErrorMessage(hresult), hresult=hresult, ) # something changed! else: # check if we have to return a match, i.e. # if no new card in inserted and there is a card found # or if a new card is requested, and there is a change+present for state in newstates: readername, eventstate, atr = state r, oldstate = readerstates[readername] # the status can change on a card already inserted, e.g. # unpowered, in use, ... # if a new card is requested, clear the state changed bit # if the card was already inserted and is still inserted if self.newcardonly: if oldstate & SCARD_STATE_PRESENT and eventstate & ( SCARD_STATE_CHANGED | SCARD_STATE_PRESENT ): eventstate = eventstate & (0xFFFFFFFF ^ SCARD_STATE_CHANGED) if ( self.newcardonly and eventstate & SCARD_STATE_PRESENT and eventstate & SCARD_STATE_CHANGED ) or (not self.newcardonly and eventstate & SCARD_STATE_PRESENT): reader = PCSCReader(readername) if self.cardType.matches(atr, reader): if self.cardServiceClass.supports("dummy"): cardfound = True return self.cardServiceClass(reader.createConnection()) # update state dictionary readerstates[readername] = (readername, eventstate) def waitforcardevent(self): """Wait for card insertion or removal.""" AbstractCardRequest.waitforcardevent(self) presentcards = [] startDate = datetime.now() eventfound = False self.timeout = self.timeout_init previous_readernames = self.getReaderNames() while not eventfound: # get states from previous run readerstates = self.readerstates # reinitialize at each iteration just in case a new reader appeared _readernames = self.getReaderNames() readernames = _readernames if self.readersAsked is None: # add PnP special reader readernames.append("\\\\?PnP?\\Notification") # first call? if len(readerstates) == 0: # init for reader in readernames: # create a dictionary entry for new readers readerstates[reader] = (reader, SCARD_STATE_UNAWARE) hresult, newstates = SCardGetStatusChange( self.hcontext, 0, list(readerstates.values()) ) # check if a new reader with a card has just been connected for reader in _readernames: # is the reader a new one? if reader not in readerstates: # create a dictionary entry for new reader readerstates[reader] = (reader, SCARD_STATE_UNAWARE) hresult, newstates = SCardGetStatusChange( self.hcontext, 0, list(readerstates.values()) ) # added reader is the last one (index is -1) _, state, _ = newstates[-1] if state & SCARD_STATE_PRESENT: eventfound = True # check if a reader has been removed to_remove = [] for reader in readerstates: if reader not in readernames: _, state = readerstates[reader] # was the card present? if state & SCARD_STATE_PRESENT: eventfound = True to_remove.append(reader) if to_remove: for reader in to_remove: # remove reader del readerstates[reader] # get newstates with new reader list hresult, newstates = SCardGetStatusChange( self.hcontext, 0, list(readerstates.values()) ) if eventfound: break # update previous readers list (without PnP special reader) previous_readernames = _readernames # wait for card insertion self.readerstates = readerstates waitThread = threading.Thread(target=self.getStatusChange) waitThread.start() # the main thread handles a possible KeyboardInterrupt try: waitThread.join() except KeyboardInterrupt: hresult = SCardCancel(self.hcontext) if hresult != SCARD_S_SUCCESS: raise CardRequestException( "Failed to SCardCancel " + SCardGetErrorMessage(hresult), hresult=hresult, ) # wait for the thread to finish in case of KeyboardInterrupt self.evt.wait(timeout=None) # get values set in the getStatusChange thread hresult = self.hresult newstates = self.newstates # compute remaining timeout if self.timeout != INFINITE: delta = datetime.now() - startDate self.timeout -= int(delta.total_seconds() * 1000) if self.timeout < 0: self.timeout = 0 # time-out if hresult in (SCARD_E_TIMEOUT, SCARD_E_CANCELLED): raise CardRequestTimeoutException(hresult=hresult) # the reader was unplugged during the loop elif SCARD_E_UNKNOWN_READER == hresult: pass # this happens on Windows when the last reader is disconnected elif hresult in (SCARD_E_SYSTEM_CANCELLED, SCARD_E_NO_SERVICE): pass # some error happened elif SCARD_S_SUCCESS != hresult: raise CardRequestException( "Failed to get status change " + SCardGetErrorMessage(hresult), hresult=hresult, ) # something changed! else: for state in newstates: readername, eventstate, atr = state # ignore PnP reader if readername == "\\\\?PnP?\\Notification": continue if eventstate & SCARD_STATE_CHANGED: eventfound = True # update readerstates for next SCardGetStatusChange() call self.readerstates = {} for reader, state, atr in newstates: self.readerstates[reader] = (reader, state) # return all the cards present for state in newstates: readername, eventstate, atr = state if readername == "\\\\?PnP?\\Notification": continue if eventstate & SCARD_STATE_PRESENT: presentcards.append(Card.Card(readername, atr)) return presentcards
class PCSCCardRequest(AbstractCardRequest): '''PCSC CardRequest class.''' def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1, ): '''Construct new PCSCCardRequest. @param newcardonly: if C{True}, request a new card. default is C{False}, i.e. accepts cards already inserted @param readers: the list of readers to consider for requesting a card default is to consider all readers @param cardType: the L{CardType} class to wait for; default is L{AnyCardType}, i.e. the request will returns with new or already inserted cards @param cardServiceClass: the specific card service class to create and bind to the card default is to create and bind a L{PassThruCardService} @param timeout: the time in seconds we are ready to wait for connecting to the requested card. default is to wait one second to wait forever, set timeout to C{None} ''' pass def __del__(self): pass def getReaderNames(self): '''Returns the list of PCSC readers on which to wait for cards.''' pass def getStatusChange(self): pass def waitforcard(self): '''Wait for card insertion and returns a card service.''' pass def waitforcardevent(self): '''Wait for card insertion or removal.''' pass
7
5
67
11
42
14
13
0.34
1
14
7
0
6
7
6
10
409
74
250
51
236
85
195
44
188
31
1
6
76
147,531
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCContext.py
smartcard.pcsc.PCSCContext.PCSCContext
class PCSCContext: """Manage a singleton pcsc context handle.""" class __PCSCContextSingleton: """The actual pcsc context class as a singleton.""" def __init__(self): hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) def getContext(self): return self.hcontext def releaseContext(self): return SCardReleaseContext(self.hcontext) # the singleton mutex = RLock() instance = None def __init__(self): with PCSCContext.mutex: if not PCSCContext.instance: self.renewContext() def __getattr__(self, name): if self.instance: return getattr(self.instance, name) @staticmethod def renewContext(): with PCSCContext.mutex: if PCSCContext.instance is not None: PCSCContext.instance.releaseContext() PCSCContext.instance = PCSCContext.__PCSCContextSingleton() return PCSCContext.instance.getContext()
class PCSCContext: '''Manage a singleton pcsc context handle.''' class __PCSCContextSingleton: '''The actual pcsc context class as a singleton.''' def __init__(self): pass def getContext(self): pass def releaseContext(self): pass def __init__(self): pass def __getattr__(self, name): pass @staticmethod def renewContext(): pass
9
2
4
0
4
0
2
0.12
0
1
1
0
2
0
3
3
39
10
26
12
17
3
25
11
17
2
0
2
10
147,532
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.AddReaderToGroupException
class AddReaderToGroupException(BaseSCardException): """Raised when scard fails to add a new reader to a PCSC reader group.""" def __init__(self, hresult, readername="", groupname=""): super().__init__( message="Failed to add reader: " + readername + " to group: " + groupname, hresult=hresult, ) self.readername = readername self.groupname = groupname
class AddReaderToGroupException(BaseSCardException): '''Raised when scard fails to add a new reader to a PCSC reader group.''' def __init__(self, hresult, readername="", groupname=""): pass
2
1
7
0
7
0
1
0.13
1
1
0
0
1
2
1
13
10
1
8
4
6
1
5
4
3
1
4
0
1
147,533
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.BaseSCardException
class BaseSCardException(Exception): """Base class for scard (aka PCSC) exceptions. scard exceptions are raised by the scard module, i.e. low-level PCSC access to readers and cards. """ def __init__(self, hresult=-1, message="", *args): """Constructor that stores the pcsc error status.""" if not message: message = "scard exception" super().__init__(message, *args) self.message = message self.hresult = hresult def __str__(self): """Returns a string representation of the exception.""" text = super().__str__() if self.hresult != -1: hresult = self.hresult if hresult < 0: # convert 0x-7FEFFFE3 into 0x8010001D hresult += 0x100000000 text += f": {smartcard.scard.SCardGetErrorMessage(self.hresult)} (0x{hresult:08X})" return text
class BaseSCardException(Exception): '''Base class for scard (aka PCSC) exceptions. scard exceptions are raised by the scard module, i.e. low-level PCSC access to readers and cards. ''' def __init__(self, hresult=-1, message="", *args): '''Constructor that stores the pcsc error status.''' pass def __str__(self): '''Returns a string representation of the exception.''' pass
3
3
9
0
7
2
3
0.47
1
1
0
6
2
2
2
12
26
4
15
7
12
7
15
7
12
3
3
2
5
147,534
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.EstablishContextException
class EstablishContextException(BaseSCardException): """Raised when scard failed to establish context with PCSC.""" def __init__(self, hresult): super().__init__(message="Failed to establish context", hresult=hresult)
class EstablishContextException(BaseSCardException): '''Raised when scard failed to establish context with PCSC.''' def __init__(self, hresult): pass
2
1
2
0
2
0
1
0.33
1
1
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,535
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Synchronization.py
smartcard.Synchronization._SynchronizationProtocol
class _SynchronizationProtocol(Protocol): mutex: threading.Lock | threading.RLock
class _SynchronizationProtocol(Protocol): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
24
2
0
2
1
1
0
2
1
1
0
5
0
0
147,536
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.IntroduceReaderException
class IntroduceReaderException(BaseSCardException): """Raised when scard fails to introduce a new reader to PCSC.""" def __init__(self, hresult, readername=""): super().__init__( message="Failed to introduce a new reader: " + readername, hresult=hresult ) self.readername = readername
class IntroduceReaderException(BaseSCardException): '''Raised when scard fails to introduce a new reader to PCSC.''' def __init__(self, hresult, readername=""): pass
2
1
5
0
5
0
1
0.17
1
1
0
0
1
1
1
13
8
1
6
3
4
1
4
3
2
1
4
0
1
147,537
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.ReleaseContextException
class ReleaseContextException(BaseSCardException): """Raised when scard failed to release PCSC context.""" def __init__(self, hresult): super().__init__(message="Failed to release context", hresult=hresult)
class ReleaseContextException(BaseSCardException): '''Raised when scard failed to release PCSC context.''' def __init__(self, hresult): pass
2
1
2
0
2
0
1
0.33
1
1
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,538
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.RemoveReaderFromGroupException
class RemoveReaderFromGroupException(BaseSCardException): """Raised when scard fails to remove a reader from a PCSC reader group.""" def __init__(self, hresult, readername="", groupname=""): BaseSCardException.__init__(self, hresult) self.readername = readername self.groupname = groupname super().__init__( message="Failed to remove reader: " + readername + " from group: " + groupname, hresult=hresult, )
class RemoveReaderFromGroupException(BaseSCardException): '''Raised when scard fails to remove a reader from a PCSC reader group.''' def __init__(self, hresult, readername="", groupname=""): pass
2
1
11
0
11
0
1
0.08
1
1
0
0
1
2
1
13
14
1
12
4
10
1
6
4
4
1
4
0
1
147,539
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCReader.py
smartcard.pcsc.PCSCReader.PCSCReader
class PCSCReader(Reader): """PCSC reader class.""" def __init__(self, readername): """Constructs a new PCSC reader.""" Reader.__init__(self, readername) def addtoreadergroup(self, groupname): """Add reader to a reader group.""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if SCARD_S_SUCCESS != hresult: raise EstablishContextException(hresult) try: hresult = SCardIntroduceReader(hcontext, self.name, self.name) if SCARD_S_SUCCESS != hresult and SCARD_E_DUPLICATE_READER != hresult: raise IntroduceReaderException(hresult, self.name) hresult = SCardAddReaderToGroup(hcontext, self.name, groupname) if SCARD_S_SUCCESS != hresult: raise AddReaderToGroupException(hresult, self.name, groupname) finally: hresult = SCardReleaseContext(hcontext) if SCARD_S_SUCCESS != hresult: raise ReleaseContextException(hresult) def removefromreadergroup(self, groupname): """Remove a reader from a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if SCARD_S_SUCCESS != hresult: raise EstablishContextException(hresult) try: hresult = SCardRemoveReaderFromGroup(hcontext, self.name, groupname) if SCARD_S_SUCCESS != hresult: raise RemoveReaderFromGroupException(hresult, self.name, groupname) finally: hresult = SCardReleaseContext(hcontext) if SCARD_S_SUCCESS != hresult: raise ReleaseContextException(hresult) def createConnection(self): """Return a card connection thru PCSC reader.""" return CardConnectionDecorator(PCSCCardConnection(self.name)) class Factory: @staticmethod def create(readername): return PCSCReader(readername) @staticmethod def readers(groups=None): if groups is None: groups = [] creaders = [] hcontext = PCSCContext().getContext() try: pcsc_readers = __PCSCreaders__(hcontext, groups) except (CardServiceStoppedException, CardServiceNotFoundException): hcontext = PCSCContext.renewContext() pcsc_readers = __PCSCreaders__(hcontext, groups) for reader in pcsc_readers: creaders.append(PCSCReader.Factory.create(reader)) return creaders
class PCSCReader(Reader): '''PCSC reader class.''' def __init__(self, readername): '''Constructs a new PCSC reader.''' pass def addtoreadergroup(self, groupname): '''Add reader to a reader group.''' pass def removefromreadergroup(self, groupname): '''Remove a reader from a reader group''' pass def createConnection(self): '''Return a card connection thru PCSC reader.''' pass class Factory: @staticmethod def createConnection(self): pass @staticmethod def readers(groups=None): pass
10
5
9
1
8
1
3
0.1
1
11
11
0
4
0
5
13
65
10
50
16
40
5
46
14
38
5
1
2
16
147,540
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCReaderGroups.py
smartcard.pcsc.PCSCReaderGroups.PCSCReaderGroups
class PCSCReaderGroups(readergroups): """PCSC readers groups.""" def __init__(self, initlist=None): """Create a single instance of pcscinnerreadergroups on first call""" self.innerclazz = pcscinnerreadergroups readergroups.__init__(self, initlist)
class PCSCReaderGroups(readergroups): '''PCSC readers groups.''' def __init__(self, initlist=None): '''Create a single instance of pcscinnerreadergroups on first call''' pass
2
2
4
0
3
1
1
0.5
1
1
1
0
1
1
1
3
7
1
4
3
2
2
4
3
2
1
1
0
1
147,541
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCReaderGroups.py
smartcard.pcsc.PCSCReaderGroups.pcscinnerreadergroups
class pcscinnerreadergroups(innerreadergroups): """Smartcard PCSC readers groups inner class. The PCSCReaderGroups singleton manages the creation of the unique instance of this class. """ def __init__(self, initlist=None): """Constructor.""" innerreadergroups.__init__(self, initlist) self.unremovablegroups = ["SCard$DefaultReaders"] def getreadergroups(self): """Returns the list of smartcard reader groups.""" innerreadergroups.getreadergroups(self) hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) hresult, readers = SCardListReaderGroups(hcontext) if hresult != SCARD_S_SUCCESS: raise ListReadersException(hresult) hresult = SCardReleaseContext(hcontext) if hresult != SCARD_S_SUCCESS: raise ReleaseContextException(hresult) return readers def addreadergroup(self, newgroup): """Add a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if SCARD_S_SUCCESS != hresult: raise error("Failed to establish context: " + SCardGetErrorMessage(hresult)) try: hresult = SCardIntroduceReaderGroup(hcontext, newgroup) if SCARD_S_SUCCESS != hresult: raise error( "Unable to introduce reader group: " + SCardGetErrorMessage(hresult) ) else: innerreadergroups.addreadergroup(self, newgroup) finally: hresult = SCardReleaseContext(hcontext) if SCARD_S_SUCCESS != hresult: raise error( "Failed to release context: " + SCardGetErrorMessage(hresult) ) def removereadergroup(self, group): """Remove a reader group""" hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if SCARD_S_SUCCESS != hresult: raise error("Failed to establish context: " + SCardGetErrorMessage(hresult)) try: hresult = SCardForgetReaderGroup(hcontext, group) if hresult != SCARD_S_SUCCESS: raise error( "Unable to forget reader group: " + SCardGetErrorMessage(hresult) ) else: innerreadergroups.removereadergroup(self, group) finally: hresult = SCardReleaseContext(hcontext) if SCARD_S_SUCCESS != hresult: raise error( "Failed to release context: " + SCardGetErrorMessage(hresult) )
class pcscinnerreadergroups(innerreadergroups): '''Smartcard PCSC readers groups inner class. The PCSCReaderGroups singleton manages the creation of the unique instance of this class. ''' def __init__(self, initlist=None): '''Constructor.''' pass def getreadergroups(self): '''Returns the list of smartcard reader groups.''' pass def addreadergroup(self, newgroup): '''Add a reader group''' pass def removereadergroup(self, group): '''Remove a reader group''' pass
5
5
15
1
13
1
3
0.15
1
3
3
0
4
1
4
58
70
10
52
10
47
8
40
10
35
4
4
2
13
147,542
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/reader/Reader.py
smartcard.reader.Reader.Reader
class Reader: """Reader abstract class. The reader class is responsible for creating connections with a card. """ def __init__(self, readername): """Constructs a new reader and store readername.""" self.name = readername def addtoreadergroup(self, groupname): """Add reader to a reader group.""" pass def removefromreadergroup(self, groupname): """Remove reader from a reader group.""" pass def createConnection(self): """Returns a card connection thru reader.""" pass def __eq__(self, other): """Returns True if self==other (same name).""" if type(other) == type(self): return self.name == other.name else: return False def __hash__(self): """Returns a hash value for this object (self.name is unique).""" return hash(self.name) def __repr__(self): """Returns card reader name string for `object` calls.""" return "'%s'" % self.name def __str__(self): """Returns card reader name string for str(object) calls.""" return self.name
class Reader: '''Reader abstract class. The reader class is responsible for creating connections with a card. ''' def __init__(self, readername): '''Constructs a new reader and store readername.''' pass def addtoreadergroup(self, groupname): '''Add reader to a reader group.''' pass def removefromreadergroup(self, groupname): '''Remove reader from a reader group.''' pass def createConnection(self): '''Returns a card connection thru reader.''' pass def __eq__(self, other): '''Returns True if self==other (same name).''' pass def __hash__(self): '''Returns a hash value for this object (self.name is unique).''' pass def __repr__(self): '''Returns card reader name string for `object` calls.''' pass def __str__(self): '''Returns card reader name string for str(object) calls.''' pass
9
9
3
0
2
1
1
0.6
0
1
0
1
8
1
8
8
41
9
20
10
11
12
19
10
10
2
0
1
9
147,543
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCExceptions.py
smartcard.pcsc.PCSCExceptions.ListReadersException
class ListReadersException(BaseSCardException): """Raised when scard failed to list readers.""" def __init__(self, hresult): super().__init__(message="Failed to list readers", hresult=hresult)
class ListReadersException(BaseSCardException): '''Raised when scard failed to list readers.''' def __init__(self, hresult): pass
2
1
2
0
2
0
1
0.33
1
1
0
0
1
0
1
13
5
1
3
2
1
1
3
2
1
1
4
0
1
147,544
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Synchronization.py
smartcard.Synchronization.Synchronization
class Synchronization(_SynchronizationProtocol): # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = threading.RLock()
class Synchronization(_SynchronizationProtocol): def __init__(self): pass
2
0
2
0
2
0
1
0.33
1
0
0
4
1
1
1
25
5
1
3
3
1
1
3
3
1
1
6
0
1
147,545
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py
sample_CardConnectionDecorator.FakeATRConnection
class FakeATRConnection(CardConnectionDecorator): """This decorator changes the fist byte of the ATR. This is just an example to show that decorators can be nested.""" def __init__(self, cardconnection): CardConnectionDecorator.__init__(self, cardconnection) def getATR(self): """Replace first BYTE of ATR by 3F""" atr = CardConnectionDecorator.getATR(self) return [0x3F] + atr[1:]
class FakeATRConnection(CardConnectionDecorator): '''This decorator changes the fist byte of the ATR. This is just an example to show that decorators can be nested.''' def __init__(self, cardconnection): pass def getATR(self): '''Replace first BYTE of ATR by 3F''' pass
3
2
3
0
3
1
1
0.5
1
0
0
0
2
0
2
72
11
2
6
4
3
3
6
4
3
1
10
0
2
147,546
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/ReaderMonitoring.py
smartcard.ReaderMonitoring.ReaderMonitor
class ReaderMonitor(Observable): """Class that monitors reader insertion/removal. and notify observers note: a reader monitoring thread will be running as long as the reader monitor has observers, or ReaderMonitor.stop() is called. It implements the shared state design pattern, where objects of the same type all share the same state, in our case essentially the ReaderMonitoring Thread. Thanks to Frank Aune for implementing the shared state pattern logics. """ __shared_state = {} def __init__( self, startOnDemand=True, readerProc=smartcard.System.readers, period=1 ): self.__dict__ = self.__shared_state Observable.__init__(self) self.startOnDemand = startOnDemand self.readerProc = readerProc self.period = period if self.startOnDemand: self.rmthread = None else: self.rmthread = ReaderMonitoringThread(self, self.readerProc, self.period) self.rmthread.start() def addObserver(self, observer): """Add an observer.""" Observable.addObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread only runs when there are observers. if self.startOnDemand: if 0 < self.countObservers(): if not self.rmthread: self.rmthread = ReaderMonitoringThread( self, self.readerProc, self.period ) # start reader monitoring thread in another thread to # avoid a deadlock; addObserver and notifyObservers called # in the ReaderMonitoringThread run() method are # synchronized import _thread _thread.start_new_thread(self.rmthread.start, ()) else: observer.update(self, (self.rmthread.readers, [])) def deleteObserver(self, observer): """Remove an observer.""" Observable.deleteObserver(self, observer) # If self.startOnDemand is True, the reader monitoring # thread is stopped when there are no more observers. if self.startOnDemand: if 0 == self.countObservers(): self.rmthread.stop() del self.rmthread self.rmthread = None def __str__(self): return self.__class__.__name__
class ReaderMonitor(Observable): '''Class that monitors reader insertion/removal. and notify observers note: a reader monitoring thread will be running as long as the reader monitor has observers, or ReaderMonitor.stop() is called. It implements the shared state design pattern, where objects of the same type all share the same state, in our case essentially the ReaderMonitoring Thread. Thanks to Frank Aune for implementing the shared state pattern logics. ''' def __init__( self, startOnDemand=True, readerProc=smartcard.System.readers, period=1 ): pass def addObserver(self, observer): '''Add an observer.''' pass def deleteObserver(self, observer): '''Remove an observer.''' pass def __str__(self): pass
5
3
12
1
9
3
3
0.56
1
1
1
0
4
5
4
38
66
10
36
14
28
20
30
12
24
4
8
3
10
147,547
LudovicRousseau/pyscard
LudovicRousseau_pyscard/src/smartcard/ExclusiveTransmitCardConnection.py
smartcard.ExclusiveTransmitCardConnection.ExclusiveTransmitCardConnection
class ExclusiveTransmitCardConnection(CardConnectionDecorator): """This decorator uses L{SCardBeginTransaction}/L{SCardEndTransaction} to preserve other processes of threads to access the card during transmit().""" def __init__(self, cardconnection): CardConnectionDecorator.__init__(self, cardconnection) def lock(self): """Lock card with L{SCardBeginTransaction}.""" component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection ): hresult = SCardBeginTransaction(component.hcard) if SCARD_S_SUCCESS != hresult: raise CardConnectionException( "Failed to lock with SCardBeginTransaction: " + SCardGetErrorMessage(hresult) ) else: # print('locked') pass break if hasattr(component, "component"): component = component.component else: break def unlock(self): """Unlock card with L{SCardEndTransaction}.""" component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection ): hresult = SCardEndTransaction(component.hcard, SCARD_LEAVE_CARD) if SCARD_S_SUCCESS != hresult: raise CardConnectionException( "Failed to unlock with SCardEndTransaction: " + SCardGetErrorMessage(hresult) ) else: # print('unlocked') pass break if hasattr(component, "component"): component = component.component else: break def transmit(self, command, protocol=None): """Gain exclusive access to card during APDU transmission for if this decorator decorates a PCSCCardConnection.""" data, sw1, sw2 = CardConnectionDecorator.transmit(self, command, protocol) return data, sw1, sw2
class ExclusiveTransmitCardConnection(CardConnectionDecorator): '''This decorator uses L{SCardBeginTransaction}/L{SCardEndTransaction} to preserve other processes of threads to access the card during transmit().''' def __init__(self, cardconnection): pass def lock(self): '''Lock card with L{SCardBeginTransaction}.''' pass def unlock(self): '''Unlock card with L{SCardEndTransaction}.''' pass def transmit(self, command, protocol=None): '''Gain exclusive access to card during APDU transmission for if this decorator decorates a PCSCCardConnection.''' pass
5
4
13
0
11
2
3
0.2
1
1
1
0
4
0
4
74
58
5
44
10
39
9
30
10
25
5
10
3
12