1"""PCSC context singleton. 2 3__author__ = "http://www.gemalto.com" 4 5Copyright 2001-2012 gemalto 6Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com 7 8This file is part of pyscard. 9 10pyscard is free software; you can redistribute it and/or modify 11it under the terms of the GNU Lesser General Public License as published by 12the Free Software Foundation; either version 2.1 of the License, or 13(at your option) any later version. 14 15pyscard is distributed in the hope that it will be useful, 16but WITHOUT ANY WARRANTY; without even the implied warranty of 17MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18GNU Lesser General Public License for more details. 19 20You should have received a copy of the GNU Lesser General Public License 21along with pyscard; if not, write to the Free Software 22Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 23""" 24 25from threading import RLock 26 27from smartcard.scard import * 28from smartcard.pcsc.PCSCExceptions import EstablishContextException 29 30 31class PCSCContext(object): 32 """Manage a singleton pcsc context handle.""" 33 34 class __PCSCContextSingleton: 35 """The actual pcsc context class as a singleton.""" 36 37 def __init__(self): 38 hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER) 39 if hresult != 0: 40 raise EstablishContextException(hresult) 41 42 def getContext(self): 43 return self.hcontext 44 45 def releaseContext(self): 46 return SCardReleaseContext(self.hcontext) 47 48 # the singleton 49 mutex = RLock() 50 instance = None 51 52 def __init__(self): 53 PCSCContext.mutex.acquire() 54 try: 55 if not PCSCContext.instance: 56 self.renewContext() 57 finally: 58 PCSCContext.mutex.release() 59 60 def __getattr__(self, name): 61 if self.instance: 62 return getattr(self.instance, name) 63 64 def renewContext(): 65 PCSCContext.mutex.acquire() 66 try: 67 if PCSCContext.instance is not None: 68 PCSCContext.instance.releaseContext() 69 70 PCSCContext.instance = PCSCContext.__PCSCContextSingleton() 71 finally: 72 PCSCContext.mutex.release() 73 74 return PCSCContext.instance.getContext() 75 renewContext = staticmethod(renewContext) 76