forked from arnaudmorin/libgtop11dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application.cpp
652 lines (472 loc) · 15.6 KB
/
Application.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
* PKCS#11 library for .Net smart cards
* Copyright (C) 2007-2009 Gemalto <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef WIN32
#include <stdlib.h>
#endif
#include <memory>
#include <string>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include "Application.hpp"
#include "Configuration.hpp"
#include "PKCS11Exception.hpp"
#include "Log.hpp"
#ifdef WIN32
#include <shlobj.h> // For SHGetFolderPath
#else
#endif
// Determine Processor Endianess
#include <limits.h>
#if (UINT_MAX == 0xffffffffUL)
typedef unsigned int _u4;
#else
# if (ULONG_MAX == 0xffffffffUL)
typedef unsigned long _u4;
# else
# if (USHRT_MAX == 0xffffffffUL)
typedef unsigned short _u4;
# endif
# endif
#endif
_u4 endian = 1;
bool IS_LITTLE_ENDIAN = (*((unsigned char *)(&endian))) ? true : false;
bool IS_BIG_ENDIAN = (*((unsigned char *)(&endian))) ? false : true;
#ifdef MACOSX_LEOPARD
#define SCardIsValidContext(x) SCARD_S_SUCCESS
#endif
extern boost::condition_variable g_WaitForSlotEventCondition;
extern bool g_bDllUnloading;
/*
*/
Application::Application( ) {
Log::start( );
std::string stConfigurationDirectoryPath;
#ifdef WIN32
// For each user (roaming) data, use the CSIDL_APPDATA value.
// This defaults to the following path: "\Documents and Settings\All Users\Application Data"
TCHAR szPath[MAX_PATH];
SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, szPath );
stConfigurationDirectoryPath = std::string( szPath ) + std::string( "/Gemalto/DotNet PKCS11/" );
#else
char *home = getenv("HOME");
if (home)
stConfigurationDirectoryPath = std::string( home ) + std::string( "/.config/Gemalto/DotNet PKCS11/" );
else
stConfigurationDirectoryPath = std::string( "/tmp/Gemalto/DotNet PKCS11/" );
#endif
std::string stConfigurationFilePath = stConfigurationDirectoryPath + std::string( "Gemalto.NET.PKCS11.ini" );
Log::log( "Application::Application - stConfigurationFilePath <%s>", stConfigurationFilePath.c_str( ) );
boost::filesystem::path configurationDirectoryPath( stConfigurationFilePath );
if( ! boost::filesystem::exists( configurationDirectoryPath ) ) {
Log::s_bEnableLog = false;
Device::s_bEnableCache = true;
} else {
// Initialize the configuration
Configuration c;
try {
c.load( stConfigurationFilePath );
const std::string stCacheSectionName( "Cache" );
const std::string stCacheParameterEnable( "Enable" );
const std::string stLogSectionName( "Log" );
const std::string stLogParameterEnable( "Enable" );
const std::string stLogParameterPath( "Path" );
// Read the flag in the configuration to enable/disable the log
std::string stResult = "";
c.getValue( stLogSectionName, stLogParameterEnable, stResult );
if( 0 == stResult.compare( "1" ) ) {
Log::s_bEnableLog = true;
// Read the flag in the configuration for the log filepath
stResult = "";
c.getValue( stLogSectionName, stLogParameterPath, stResult );
if( stResult.size( ) > 0 ) {
Log::setLogPath( stResult );
} else {
#ifdef WIN32
Log::setLogPath( stConfigurationDirectoryPath );
#endif
}
}
// Read the flag in the configuration to enable/disable the cache on disk
stResult = "";
c.getValue( stCacheSectionName, stCacheParameterEnable, stResult );
if( 0 == stResult.compare( "1" ) ) {
Device::s_bEnableCache = true;
} else {
Device::s_bEnableCache = false;
}
} catch( ... ) {
// Unable to find the configuration file
// Use default settings instead
Log::error( "Application::Application", "No configuration file found. Use default settings" );
}
}
if( Log::s_bEnableLog ) {
Log::log( "" );
Log::log( "" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
#ifdef _WIN32
DWORD dwSessionID = -1;
DWORD dwProcessID = GetCurrentProcessId();
char szProcessPath[512] = {0};
char szDateTimeUTC[260];
SYSTEMTIME stNow;
GetModuleFileName(NULL, szProcessPath, sizeof(szProcessPath));
ProcessIdToSessionId(dwProcessID, &dwSessionID);
GetSystemTime(&stNow);
sprintf(szDateTimeUTC,"%04d-%02d-%02d %02d:%02d:%02d.%d(UTC)",
stNow.wYear,stNow.wMonth,stNow.wDay,stNow.wHour,stNow.wMinute,stNow.wSecond,stNow.wMilliseconds);
Log::log( " [%s]", szDateTimeUTC);
Log::log( " PKCS11 STARTS - Session ID = %d - Process ID = %d" , dwSessionID, dwProcessID);
Log::log( " LOADED BY \"%s\"", szProcessPath);
#else
Log::log( " PKCS11 STARTS" );
#endif
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "" );
}
DeviceMonitor::m_hContext = 0;
DeviceMonitor::m_bStopPolling = false;
DeviceMonitor::m_bAlive = false;
m_DeviceMonitor.reset( new DeviceMonitor( ) );
// Initialise the PCSC devices listener
m_DeviceMonitor->addListener( this );
Log::stop( "Application::Application" );
}
/*
*/
Application::~Application( ) {
if( Log::s_bEnableLog ) {
if (g_bDllUnloading)
{
Log::log( "========================" );
#ifdef _WIN32
char szDateTimeUTC[260];
SYSTEMTIME stNow;
GetSystemTime(&stNow);
sprintf(szDateTimeUTC,"%04d-%02d-%02d %02d:%02d:%02d.%d(UTC)",
stNow.wYear,stNow.wMonth,stNow.wDay,stNow.wHour,stNow.wMinute,stNow.wSecond,stNow.wMilliseconds);
Log::log( " [%s]", szDateTimeUTC);
#endif
Log::log( "PKCS11 Library Unloading" );
Log::log( "========================" );
Log::log( "" );
}
}
if( m_DeviceMonitor.get( ) ) {
// Remove the application from the PCSC devices listener list
m_DeviceMonitor->removeListener( this );
}
finalize( );
if( Log::s_bEnableLog ) {
Log::log( "" );
Log::log( "" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
#ifdef _WIN32
char szDateTimeUTC[260];
SYSTEMTIME stNow;
GetSystemTime(&stNow);
sprintf(szDateTimeUTC,"%04d-%02d-%02d %02d:%02d:%02d.%d(UTC)",
stNow.wYear,stNow.wMonth,stNow.wDay,stNow.wHour,stNow.wMinute,stNow.wSecond,stNow.wMilliseconds);
Log::log( " [%s]", szDateTimeUTC);
#endif
Log::log( " PKCS11 STOPS" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "###### ###### ###### ###### ###### ###### ###### ###### ######" );
Log::log( "" );
}
}
/*
*/
void Application::notifyReaderInserted( const std::string& a_stReaderName ) {
BOOST_FOREACH( boost::shared_ptr< Device >& d, m_DeviceMonitor->getDeviceList( ) ) {
// Search the device associated to this new reader
if( d.get( ) && ( 0 == d->getReaderName( ).compare( a_stReaderName ) ) ) {
// Create the PKCS11 slot associated to this new reader
addSlot( d );
return;
}
}
}
/*
*/
void Application::notifyReaderRemoved( const std::string& a_stReaderName ) {
unsigned char ucSlotId = 0;
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
// If the slot exists and the the names are the same
if( s.get( ) && !s->getReaderName( ).compare( a_stReaderName ) ) {
s->tokenDelete( );
s->setEvent( true, ucSlotId );
return;
}
++ucSlotId;
}
}
/*
*/
void Application::notifySmartCardRemoved( const std::string& a_stReaderName ) {
unsigned char ucSlotId = 0;
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
// If the slot exists and the the names are the same
if( s.get( ) && !s->getReaderName( ).compare( a_stReaderName ) ) {
s->tokenDelete( );
s->setEvent( true, ucSlotId );
return;
}
++ucSlotId;
}
}
/*
*/
void Application::notifySmartCardInserted( const std::string& a_stReaderName ) {
unsigned char ucSlotId = 0;
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
// If the slot exists and the names are the same
if( s.get( ) && !s->getReaderName( ).compare( a_stReaderName ) ) {
// LCA: Not create token on event but register insertion in slot
// s->tokenCreate( );
s->tokenInserted();
s->setEvent( true, ucSlotId );
return;
}
++ucSlotId;
}
}
/*
*/
void Application::notifySmartCardChanged( const std::string& a_stReaderName ) {
unsigned char ucSlotId = 0;
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
// If the slot exists and the the names are the same
if( s.get( ) && !s->getReaderName( ).compare( a_stReaderName ) ) {
s->tokenUpdate( );
s->setEvent( true, ucSlotId );
return;
}
++ucSlotId;
}
}
///*
//*/
//void Application::getSlotList( const CK_BBOOL& a_bTokenPresent, CK_SLOT_ID_PTR a_pSlotList, CK_ULONG_PTR a_pulCount ) {
//
// *a_pulCount = 1;
//
// if( a_pSlotList ) {
//
// a_pSlotList[ 0 ] = 1;
// }
//
///*
// CK_ULONG ulCountSlot = 0;
//
// CK_ULONG ulCountSlotWithToken = 0;
//
// CK_SLOT_ID iIndex = 0;
//
// CK_RV rv = CKR_OK;
//
// // Build the slot list
// size_t l = m_Slots.size( );
//
// for( size_t i = 0; i < l ; ++i ) {
//
// if( m_Slots[ i ].get( ) ) {
//
// if( !a_bTokenPresent ) {
//
// // Found a valid slot
// ++ulCountSlot;
//
// if( a_pSlotList ) {
//
// if ( ulCountSlot > *a_pulCount ) {
//
// rv = CKR_BUFFER_TOO_SMALL;
//
// } else {
//
// a_pSlotList[ iIndex ] = i;
//
// ++iIndex;
// }
// }
//
// } else if( m_Slots[ i ]->getToken( ).get( ) ) { //isCardPresent( ) ) {
//
// // Found a slot within a token
// ++ulCountSlotWithToken;
//
// if( a_pSlotList ) {
//
// if ( ulCountSlotWithToken > *a_pulCount ) {
//
// rv = CKR_BUFFER_TOO_SMALL;
// }
//
// a_pSlotList[ iIndex ] = i;
//
// ++iIndex;
// }
// }
// }
// }
//
// // Return the slot count
// if( a_bTokenPresent ) {
//
// *a_pulCount = ulCountSlotWithToken;
//
// } else {
//
// *a_pulCount = ulCountSlot;
// }
//
// if ( CKR_OK != rv ) {
//
// throw PKCS11Exception( CKR_BUFFER_TOO_SMALL );
// }
//*/
//}
/*
*/
void Application::getSlotList( const CK_BBOOL& a_bTokenPresent, CK_SLOT_ID_PTR a_pSlotList, CK_ULONG_PTR a_pulCount ) {
CK_ULONG ulCountSlot = 0;
CK_ULONG ulCountSlotWithToken = 0;
CK_SLOT_ID iIndex = 0;
CK_RV rv = CKR_OK;
// Build the slot list
size_t l = m_Slots.size( );
for( size_t i = 0; i < l ; ++i ) {
Slot* s = m_Slots[ i ].get( );
if( s ) {
if( !a_bTokenPresent ) {
// Found a valid slot
++ulCountSlot;
if( a_pSlotList ) {
if ( ulCountSlot > *a_pulCount ) {
rv = CKR_BUFFER_TOO_SMALL;
} else {
a_pSlotList[ iIndex ] = i;
++iIndex;
}
}
// } else if( m_Slots[ i ]->getToken( ).get( ) ) { //isCardPresent( ) ) {
} else if( /*s->isTokenInserted( ) ||*/ s->isCardPresent( ) ) {
// Found a slot within a token
++ulCountSlotWithToken;
if( a_pSlotList ) {
if ( ulCountSlotWithToken > *a_pulCount ) {
rv = CKR_BUFFER_TOO_SMALL;
}
a_pSlotList[ iIndex ] = i;
++iIndex;
}
}
}
}
// Return the slot count
if( a_bTokenPresent ) {
*a_pulCount = ulCountSlotWithToken;
} else {
*a_pulCount = ulCountSlot;
}
if ( CKR_OK != rv ) {
throw PKCS11Exception( CKR_BUFFER_TOO_SMALL );
}
}
/*
*/
const boost::shared_ptr< Slot >& Application::getSlot( const CK_SLOT_ID& a_slotId ) {
if( a_slotId >= m_Slots.size( ) ) {
throw PKCS11Exception( CKR_SLOT_ID_INVALID );
}
boost::shared_ptr< Slot >& s = m_Slots.at( a_slotId );
if( !s.get( ) ) {
throw PKCS11Exception( CKR_SLOT_ID_INVALID );
}
return s;
}
/* Initialize the slot list from the device list
*/
void Application::getDevices( void ) {
BOOST_FOREACH( boost::shared_ptr< Device >& d, m_DeviceMonitor->getDeviceList( ) ) {
if( d.get( ) ) {
unsigned char ucDeviceId = d->getDeviceID( );
m_Slots[ ucDeviceId ].reset( new Slot( d ) );
}
}
}
/*
*/
void Application::addSlot( const boost::shared_ptr< Device >& a_pDevice ) {
if( !a_pDevice ) {
return;
}
Log::begin( "Application::addSlot" );
unsigned char ucDeviceId = a_pDevice->getDeviceID( );
m_Slots[ ucDeviceId ].reset( new Slot( a_pDevice ) );
m_Slots[ ucDeviceId ]->setEvent( true, ucDeviceId );
Log::end( "Application::addSlot" );
}
/*
*/
const boost::shared_ptr< Slot >& Application::getSlotFromSession( const CK_SESSION_HANDLE& a_hSession ) {
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
if( s.get( ) && s->isSessionOwner( a_hSession ) ) {
return s;
}
}
throw PKCS11Exception( CKR_SESSION_HANDLE_INVALID );
}
/*
*/
void Application::initialize( ) {
// Start the PCSC devices listener
if( m_DeviceMonitor.get( ) ) {
m_DeviceMonitor->start( );
}
// Get the known PCSC devices
getDevices( );
}
//extern boost::mutex g_WaitForSlotEventMutex;
/*
*/
void Application::finalize( void ) {
g_WaitForSlotEventCondition.notify_all( );
bool bPcscValid = (DeviceMonitor::m_hContext && (SCARD_S_SUCCESS == SCardIsValidContext(DeviceMonitor::m_hContext)));
Log::log("Application::finalize : Stopping thread");
// Call the finalize method for all managed device
BOOST_FOREACH( boost::shared_ptr< Slot >& s, m_Slots ) {
if( s.get( ) ) {
s->finalize( bPcscValid );
}
}
// Stop the PCSC devices listenening thread
if( m_DeviceMonitor.get( ) ) {
//g_WaitForSlotEventMutex.unlock( );
//DeviceMonitor::m_bAlive = false;
m_DeviceMonitor->stop( );
if (DeviceMonitor::m_hContext && (SCARD_S_SUCCESS == SCardIsValidContext(DeviceMonitor::m_hContext)))
SCardReleaseContext( DeviceMonitor::m_hContext );
}
}