-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCardReaderCollection.cs
300 lines (255 loc) · 11.8 KB
/
CardReaderCollection.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using Xploit.Core.Rfid;
using Xploit.Core.Rfid.Enums;
using Xploit.Core.Rfid.Interfaces;
using Xploit.Core.Rfid.Mifare;
namespace XPloit.Core.Rfid
{
public class CardReaderCollection : IEnumerable<CardReader>, IDisposable
{
internal IntPtr _hContext = IntPtr.Zero;
BackgroundWorker _worker = null;
Dictionary<string, CardReader> _readers = new Dictionary<string, CardReader>();
public delegate void delOnCardAction(CardReader reader, HandledEventArgs e);
public delegate void delOnCardReaded(ICard card, HandledEventArgs e);
public event delOnCardAction OnCardInsert;
public event delOnCardAction OnCardRemove;
public event delOnCardReaded OnCardReaded;
/// <summary>
/// Devuelve el número de lectores existentes en la colección
/// </summary>
public int Count { get { return _readers.Values.Count; } }
/// <summary>
/// Constructor
/// </summary>
/// <param name="readers">Lectores</param>
public CardReaderCollection()
{
// Establish context
CardReader.API.SCardFunctionReturnCodes result = (CardReader.API.SCardFunctionReturnCodes)
CardReader.API.SCardEstablishContext(CardReader.API.SCARD_SCOPE_SYSTEM/*SCARD_SCOPE_USER*/, IntPtr.Zero, IntPtr.Zero, out _hContext);
long ret = 0;
IntPtr hContext;
UInt32 pcchReaders = 0;
ArrayList readersList = new ArrayList();
//establish context
ret = CardReader.API.SCardEstablishContext(CardReader.API.SCARD_SCOPE_USER, IntPtr.Zero, IntPtr.Zero, out hContext);
//get readers buffer len
ret = CardReader.API.SCardListReaders(hContext, IntPtr.Zero, null, ref pcchReaders);
byte[] mszReaders = new byte[pcchReaders];
// fill readers' buffer
ret = CardReader.API.SCardListReaders(hContext, IntPtr.Zero, mszReaders, ref pcchReaders);
ret = CardReader.API.SCardReleaseContext(hContext);
// Remember that readers is a multistring with a double trailing \0
// This is much easier and faster to do the allocation like this than the looping way
ASCIIEncoding ascii = new ASCIIEncoding();
string currbuff = ascii.GetString(mszReaders);
int len = (int)pcchReaders;
List<CardReader> r = new List<CardReader>();
foreach (string reader in MultiStringToArray(currbuff.ToCharArray()))
_readers.Add(reader, new CardReader(reader, _hContext));
}
static string[] MultiStringToArray(char[] multistring)
{
List<string> stringList = new List<string>();
int i = 0;
while (i < multistring.Length)
{
int j = i;
if (multistring[j++] == '\0') break;
while (j < multistring.Length)
{
if (multistring[j++] == '\0')
{
stringList.Add(new string(multistring, i, j - i - 1));
i = j;
break;
}
}
}
return stringList.ToArray();
}
/// <summary>
/// Obtiene el lector en base a su nombre
/// </summary>
/// <param name="name">Nombre del lector</param>
public CardReader this[string name]
{
get
{
CardReader r;
if (_readers.TryGetValue(name, out r))
return r;
return null;
}
}
public IEnumerator<CardReader> GetEnumerator() { return _readers.Values.GetEnumerator(); }
IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _readers.Values.GetEnumerator(); }
/// <summary>
/// Liberación de recursos
///
/// </summary>
public void Dispose()
{
if (_readers != null)
{
foreach (CardReader r in _readers.Values)
r.Dispose();
_readers.Clear();
}
if (_hContext != IntPtr.Zero)
{
int ret = CardReader.API.SCardReleaseContext(_hContext);
_hContext = IntPtr.Zero;
}
if (_worker != null)
{
_worker.CancelAsync();
_worker.Dispose();
_worker = null;
}
}
/// <summary>
/// Devuelve el primer lector o NULL
/// </summary>
public CardReader GetFirstOrNull()
{
foreach (CardReader r in _readers.Values)
return r;
return null;
}
void WaitChangeStatus(object sender, DoWorkEventArgs e)
{
CardReader.API.SCARD_READERSTATE[] states = new CardReader.API.SCARD_READERSTATE[Count];
CardReader[] readers = new CardReader[states.Length];
int x = 0;
foreach (CardReader r in this)
{
states[x].Reader = r.Name;
readers[x] = r;
x++;
}
while (!e.Cancel)
{
CardReader.API.SCardFunctionReturnCodes result;
// Obtain a lock when we use the context pointer,
// which may be modified in the Dispose() method.
lock (this)
{
if (_hContext == IntPtr.Zero) return;
//This thread will be executed every 1000ms.
//The thread also blocks for 1000ms, meaning
//that the application may keep on running for
//one extra second after the user has closed
//the Main Form.
result =
(CardReader.API.SCardFunctionReturnCodes)CardReader.API.GetStatusChange(this._hContext, 1000, states, states.Length);
}
if ((result == CardReader.API.SCardFunctionReturnCodes.SCARD_E_TIMEOUT))
{
// Time out has passed, but there is no new info. Just go on with the loop
continue;
}
else
{
for (int xx = 0, m = states.Length; xx < m; xx++)
{
CardReader.API.SCARD_READERSTATE st = states[xx];
CardReader r = readers[xx];
CardReader.API.CardState eventState = st.EventState;
bool isChanged = (eventState & CardReader.API.CardState.Changed) == CardReader.API.CardState.Changed;
if (isChanged)
{
bool isPresent = (eventState & CardReader.API.CardState.Present) == CardReader.API.CardState.Present;
bool isInUse = (eventState & CardReader.API.CardState.Empty) == CardReader.API.CardState.InUse;
bool isUnavailable = (eventState & CardReader.API.CardState.Empty) == CardReader.API.CardState.Unavailable;
if (isPresent && !isInUse && !isUnavailable)
{
// Hay tarjeta
if (!r._IsCardInserted)
{
r._IsCardInserted = true;
HandledEventArgs h = new HandledEventArgs(false);
if (OnCardInsert != null)
OnCardInsert(r, h);
// No se ha ejecutado una acción propia, la leemos nosotros
if (!h.Handled && OnCardReaded != null)
{
// Tarjeta leida
if (r.Connect() == EConnection.Ok)
{
ConfigMifareRead cfg = null;
//cfg = new ConfigMifareRead()
//{
// KeysOne = new byte[] { 0xB0 ,0xB1 ,0xB2 ,0xB3 ,0xB4 ,0xB5 },
// KeysZero = new byte[] { 0xB0 ,0xB1 ,0xB2 ,0xB3 ,0xB4 ,0xB5 },
//};
//for (byte xyx = 0; xyx < 16; xyx++)
//{
// cfg[xyx].ReadDataBlockStart = ConfigMifareReadSector.EBlockRange.DataBlock01;
// cfg[xyx].ReadDataBlockEnd = ConfigMifareReadSector.EBlockRange.DataBlock03;
// cfg[xyx].ReadTrailBlock = true;
// cfg[xyx].Login = new LoginMifareMethod()
// {
// KeyNum = ConfigMifareRead.EKeyNum.One,
// KeyType = ConfigMifareRead.EKeyType.A,
// };
//}
ICard card;
if (r.GetCard(out card, st.RGBAttribute(), cfg))
{
r.Disconnect();
OnCardReaded(card, h);
}
else
{
// Algún error ha ocurrido ... (en DniE tarda en reconocerlo)
r.Disconnect();
r._IsCardInserted = false;
}
}
}
}
}
else
{
bool isEmpty = (eventState & CardReader.API.CardState.Empty) == CardReader.API.CardState.Empty;
if (isEmpty)
{
// No hay tarjeta
if (r._IsCardInserted)
{
r._IsCardInserted = false;
if (OnCardRemove != null)
{
HandledEventArgs h = new HandledEventArgs(false);
OnCardRemove(r, h);
}
}
}
}
}
}
}
Thread.Sleep(1);
}
}
/// <summary>
/// Crea el hilo que espera a los eventos de escucha
/// </summary>
public void WaitChange()
{
if (Count <= 0) return;
if (_worker != null) return;
_worker = new BackgroundWorker();
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += WaitChangeStatus;
_worker.RunWorkerAsync();
}
}
}