summaryrefslogtreecommitdiff
path: root/InfraStack/OSAgnostic/WiMax/Agents/Supplicant/Source/SupplicantAgent.c
blob: 7cb519678d562f5d12d5cd43a1b3ab128aab79e5 (plain)
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
/**************************************************************************
 Copyright (c) 2007-2008, Intel Corporation. All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  3. Neither the name of the Intel Corporation nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.

***************************************************************************/

#include "SupplicantAgent.h"

#include "TraceModule.h" 
#include "Messenger.h"
#include "L4ConfigurationManager.h"
#include "IndicatorsSubscribers.h"
#include "wimax_osal_event_logger.h"
#include "wmxSDK_Apdo_Cmn.h"
#include "NDnSAgent_APDO.h"
#include "L5Dispatcher.h"
#include "Act.h"
#include "wimax_osal_services_cmn.h"
#include "wimax_osal_crypt_services.h"		
#include "wimax_osal_string.h"

#if defined(WPA_OPEN_SOURCE)
//open source supplicant include files
#include <eap_peer/util/common.h>
#include <eap_peer/eap.h>
#include <eap_peer/eap_config.h>
#include <eap_peer/util/wpabuf.h>
#include <eap_peer/eap_methods.h>

//////////////////////////////////////
// wpa_supplicant open source structures
struct eap_peer_ctx {
	Boolean eapSuccess;
	Boolean eapRestart;
	Boolean eapFail;
	Boolean eapResp;
	Boolean eapNoResp;
	Boolean eapReq;
	Boolean portEnabled;
	Boolean altAccept; /* for EAP */
	Boolean altReject; /* for EAP */

	struct wpabuf *eapReqData; /* for EAP */

	unsigned int idleWhile; /* for EAP state machine */

	struct eap_peer_config eap_config;
	struct eap_sm *eap;

	// msk key length and buffer size
	size_t	 MskKeyActualLen;
	UINT8    MskKey[MSK_SIZE];

	Boolean bInited; // for 
};

// open source peer structure instance
static struct eap_peer_ctx eap_ctx;
static struct eapol_callbacks eap_cb;
BOOL SupplicantLoaded = FALSE;
BOOL bMethodSet = FALSE;
 
//open source function defines
wmx_Status_t DelayLoadSupplicant();
void Opensource_SupAgent_SendEapResponse(const u8 *data, size_t data_len);

/************************************************************************
***********************	   Loading libeap.so wpa_supplicant	*********
*************************************************************************/
#else


/********************************************************************************
***********************											*****************
***********************	   Loading Device-Scape DLL				*****************
***********************											*****************
*********************************************************************************/

typedef swc_config_t*	(*EapCconfigAllocFuncPtr)( char*, int);
typedef int				(*EapCconfigResetFuncPtr)( swc_config_t*);
typedef int				(*EapCconfigFreeFuncPtr)( swc_config_t*);
typedef int				(*EapSetCtrlIfcCallbackFuncPtr)( swc_config_t*, void*, void*);
typedef int				(*EapSmInitFuncPtr)(swc_config_t*);
typedef int				(*EapSmSetEapMethodFuncPtr)(swc_config_t*, int);
typedef int				(*EapSetCallBacksFuncPtr)(swc_config_t*, void*, void*, void*, void*, void*, void*, void*);
typedef int				(*EapSmRunFuncPtr)(swc_config_t*);
typedef int				(*EapSmGetResponseFuncPtr)(swc_config_t*, u8*, size_t*);
typedef int				(*EapSetPasswordFuncPtr)(swc_config_t*, char*);
typedef int				(*EapSetIdentityFuncPtr)(swc_config_t*, char*);
typedef int				(*EapSmGetKeyFuncPtr)(swc_config_t*, u8*, size_t*);
typedef int				(*EapSetTlsPrivateKeyFuncPtr)(swc_config_t*, unsigned char*, int , int);
typedef int				(*EapSetTlsCaCertFuncPtr)(swc_config_t*, unsigned char*, int, int);
typedef int				(*EapSetTlsClientCertFuncPtr)(swc_config_t*, unsigned char*, int, int);
typedef int				(*SetTlsMaxSizeFuncPtr)(swc_config_t*, int);
typedef void			(*PrintFuncRegisterFuncPtr)(void (*printfunc)(const char *fmt, ...));
typedef int				(*EapSetPinFuncPtr)(swc_config_t*, char*);
typedef int				(*SetAkaMaxSizeFuncPtr)(swc_config_t*, int);
typedef int				(*SetLogLevelFuncPtr)(int);
typedef void			(*WpaHexdumpPtr)(int, const char *title, const UINT8 *buf, size_t len);
typedef int				(*EapSetTlsPrivateKeyPasswordFuncPtr)(swc_config_t *sc, char *passwd);
typedef int				(*EapSetTlsFunctionTable)(void *table, void *reserved);
typedef int				(*EapSmGetBEKFuncPtr)(swc_config_t*, u8*, size_t);
typedef void			(*WpaLogprocPtr)(int level, char *fmt, ...);

EapSmInitFuncPtr				swc_eap_sm_init_pt; //[findme][amirs] buffer for 64bit
EapSmInitFuncPtr				swc_eap_sm_init_ptr;
EapSmSetEapMethodFuncPtr		swc_set_eap_method_ptr;
EapSmSetEapMethodFuncPtr		swc_set_phase2_method_ptr;
EapSetCtrlIfcCallbackFuncPtr	swc_set_ctrl_iface_callback_ptr;
EapSetCallBacksFuncPtr			swc_eap_sm_set_callbacks_ptr;
EapCconfigAllocFuncPtr			swc_config_alloc_ptr;
EapCconfigResetFuncPtr			swc_config_reset_ptr;
EapSmGetResponseFuncPtr			swc_eap_sm_get_response_ptr;
EapSmRunFuncPtr					swc_eap_sm_run_ptr;
EapSetIdentityFuncPtr			swc_set_identity_ptr;
EapSetIdentityFuncPtr			swc_set_anonymous_identity_ptr;
EapSetPasswordFuncPtr			swc_set_password_ptr;
EapSmGetKeyFuncPtr				swc_eap_sm_get_key_ptr;
EapSetTlsPrivateKeyFuncPtr		swc_set_tls_private_key_ptr;
EapSetTlsPrivateKeyPasswordFuncPtr	swc_set_tls_private_key_passwd_ptr;
EapSetTlsCaCertFuncPtr			swc_set_tls_ca_cert_ptr;
EapSetTlsClientCertFuncPtr		swc_set_tls_client_cert_ptr;
EapSetTlsPrivateKeyFuncPtr		swc_set_tls_private_key2_ptr;
EapSetTlsCaCertFuncPtr			swc_set_tls_ca_cert2_ptr;
EapSetTlsClientCertFuncPtr		swc_set_tls_client_cert2_ptr;
SetTlsMaxSizeFuncPtr			swc_set_tls_max_size_ptr;
PrintFuncRegisterFuncPtr		swc_print_function_register_ptr;
EapSetPinFuncPtr				swc_set_pin_ptr;
SetAkaMaxSizeFuncPtr			swc_set_aka_max_size_ptr;
SetLogLevelFuncPtr				swc_set_log_level_ptr;
EapCconfigFreeFuncPtr			swc_config_free_ptr;
WpaHexdumpPtr					wpa_hexdump_ptr;
WpaLogprocPtr					wpa_logproc_ptr;
EapSetTlsFunctionTable			swc_set_tls_function_table_ptr;
EapSmGetBEKFuncPtr				swc_get_BEK_ptr;

/*************************
*	     Globals         *
**************************/

/*
 * Yes, this being static sinks ... anyway,should be inside
 * SupplicantConfig, but then we'd go into #include hell and thanks
 * but no, thanks.
 */

SupplicantData g_SuppData;
SupplicantData g_SuppData1; //[findme][amirs] buffer for 64bit

SupplicantConfig g_SuppConfig1; //[findme][amirs] buffer for 64bit
#endif
static struct eap_method_type eap_methods[3];
SupplicantConfig g_SuppConfig;

OSAL_dynlib_t	g_DSlib = NULL;
UINT8		   g_TargetBuf[L4_MSG_MAX_LENGTH]; // TODO: define the correct const
BOOL		   smRunRequired;
BOOL		   smInitRequired;
static List *indicatorSubscribersList = NULL;

#if !defined(WPA_OPEN_SOURCE)
EapSmInitFuncPtr				aaaamirswc_eap_sm_init_ptr; //[findme][amirs] buffer for 64bit
#endif
tUtilityFunctions *pUtils;
/*************************
*	     DEFINES         *
**************************/
#define TLS_MAX_SIZE 1300
#define INTERNAL_REQUEST_ID 0 // for posting a request to the messenger in the MessageHandler
#define MAX_SUP_STR_LEN 128


/*****************************************
*	     Internal Functions Declarations *
******************************************/
wmx_Status_t InitSupplicantLibrary(VOID);

#if !defined(WPA_OPEN_SOURCE)
Boolean EapGetBool(VOID *ctx, enum eap_bool_var var);
void EapSetBool(void *ctx, enum eap_bool_var  var, Boolean val);
int EapGetInt(VOID *ctx, enum eap_int_var  var);
void EapSetInt(VOID *ctx, enum eap_int_var var, UINT32 val);
UINT8* EapGetReqData(VOID *ctx, size_t * datalen);
int OSAL_Crypt_EapCreateDecryptPass(u8* passwordBuff, size_t * datalen);

VOID SuppCtrlIfcCb(VOID* pContext, UINT32 cb_type, UINT32 cb_subtype);
VOID InitMethodAndPassword();
wmx_Status_t LoadSupplicantLibrary();
void SupAgent_SendIndication( wmx_EventType_t eventType, wmx_CredID_t credID );
void SupAgent_CondEapSMRun();

eSuppRetStatus EapSMRun();
wmx_Status_t CondEapSMInit();

void Sup_PrintTrace(char *sourceStr, char *caption, char *prefix);
void wmxNds_SupOpCodeToStr(SUP_AGENT_CRED_OPCODE supOpCode, char *str, int strLength);
void DS_EapRestart(VOID);
#endif

void ResetSupplicantLibrary();
void Sup_PrintTrace(char *sourceStr, char *caption, char *prefix);
void wmxNds_SupOpCodeToStr(SUP_AGENT_CRED_OPCODE supOpCode, char *str, int strLength);
/////////////////////


//************************************************
// Connection Parameters to L5 Layer
//************************************************
static L5_CONNECTION supplicantConnection = NULL;
static tL5DispatcherFunctions *pFuncs;

// TODO: Check if can be removed
//typedef struct _L4_MESSAGE_STRUCT
//{
//	UINT32 messageOpcode;
//	UINT32 bufferLength;
//	UCHAR messageBuffer[0];//the start of the buffer
//} L4_MESSAGE_STRUCT;

/********************************************/

/*static void custom_print_function(const char *fmt, ...)
{

	va_list ap;
	char buf[4096];

	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);

	printf("%s", buf);
}

// dbg
void PrintBuff(UINT8* buf, UINT32 len)
{
	int j, i=0;
	while(len>0)
	{
		if (len<16)
		{
			for (j=0; j<len; j++) printf("%02x ",buf[i++]);
			printf("\n"); break;
		}
		else  // print in lines of 16 values each
		{
			for (j=0; j<16; j++) printf("%02x ",buf[i++]); 	len-=16;
		}
 		printf("\n");
	}
}*/



/*
 * Methods configuration is set in  InitSupplicantLibrary()
 *
 * eap_ctx.eap_config.eap_methods = eap_methods
 */
static
void peer_set_method1(unsigned method)
{
	eap_methods[0].vendor = EAP_VENDOR_IETF;
	eap_methods[0].method = method;
}

static
void peer_set_method2(unsigned method)
{
	eap_methods[1].vendor = EAP_VENDOR_IETF;
	eap_methods[1].method = method;
}


#if defined(WPA_OPEN_SOURCE)
// eap_eample source code
static struct eap_peer_config * peer_get_config(void *ctx)
{
	struct eap_peer_ctx *peer = ctx;
	return &peer->eap_config;
}


static Boolean peer_get_bool(void *ctx, enum eapol_bool_var variable)
{
	struct eap_peer_ctx *peer = ctx;
	if (peer == NULL)
		return FALSE;
	switch (variable) {
	case EAPOL_eapSuccess:
		return peer->eapSuccess;
	case EAPOL_eapRestart:
		return peer->eapRestart;
	case EAPOL_eapFail:
		return peer->eapFail;
	case EAPOL_eapResp:
		return peer->eapResp;
	case EAPOL_eapNoResp:
		return peer->eapNoResp;
	case EAPOL_eapReq:
		return peer->eapReq;
	case EAPOL_portEnabled:
		return peer->portEnabled;
	case EAPOL_altAccept:
		return peer->altAccept;
	case EAPOL_altReject:
		return peer->altReject;
	}
	return FALSE;
}


static void peer_set_bool(void *ctx, enum eapol_bool_var variable,
			  Boolean value)
{
	struct eap_peer_ctx *peer = ctx;
	if (peer == NULL)
		return;
	switch (variable) {
	case EAPOL_eapSuccess:
		peer->eapSuccess = value;
		// send the eap success message to driver
		wmx_SetEapSuccess();
		break;
	case EAPOL_eapRestart:
		peer->eapRestart = value;
		break;
	case EAPOL_eapFail:
		peer->eapFail = value;
		wmx_SetEapFail(); // send EAP FAIL to the device
		break;
	case EAPOL_eapResp:
		peer->eapResp = value;
		break;
	case EAPOL_eapNoResp:
		peer->eapNoResp = value;
		break;
	case EAPOL_eapReq:
		peer->eapReq = value;
		break;
	case EAPOL_portEnabled:
		peer->portEnabled = value;
		break;
	case EAPOL_altAccept:
		peer->altAccept = value;
		break;
	case EAPOL_altReject:
		peer->altReject = value;
		break;
	}
}


static unsigned int peer_get_int(void *ctx, enum eapol_int_var variable)
{
	struct eap_peer_ctx *peer = ctx;
	if (peer == NULL)
		return 0;
	switch (variable) {
	case EAPOL_idleWhile:
		return peer->idleWhile;
	}
	return 0;
}


static void peer_set_int(void *ctx, enum eapol_int_var variable,
			 unsigned int value)
{
	struct eap_peer_ctx *peer = ctx;
	if (peer == NULL)
		return;
	switch (variable) {
	case EAPOL_idleWhile:
		peer->idleWhile = value;
		break;
	}
}


static struct wpabuf * peer_get_eapReqData(void *ctx)
{
	struct eap_peer_ctx *peer = ctx;
	if (peer == NULL || peer->eapReqData == NULL)
		return NULL;

	return peer->eapReqData;
}


static void peer_set_config_blob(void *ctx, struct wpa_config_blob *blob)
{
	printf("TODO: %s\n", __func__);
}


static const struct wpa_config_blob *
peer_get_config_blob(void *ctx, const char *name)
{
	printf("TODO: %s\n", __func__);
	return NULL;
}


static void peer_notify_pending(void *ctx)
{
	printf("TODO: %s\n", __func__);
}
#endif

void FinalizeSuppConfig()
{
	FreeIfAllocated(g_SuppConfig.identity);
	FreeIfAllocated(g_SuppConfig.anonidentity);
	FreeIfAllocated(g_SuppConfig.password);
	FreeIfAllocated(g_SuppConfig.cacert);
	FreeIfAllocated(g_SuppConfig.clientcert);
	FreeIfAllocated(g_SuppConfig.privatekey);
	FreeIfAllocated(g_SuppConfig.privatekeypasswd);
	FreeIfAllocated(g_SuppConfig.cacert2);
	FreeIfAllocated(g_SuppConfig.clientcert2);
	FreeIfAllocated(g_SuppConfig.privatekey2);
	FreeIfAllocated(g_SuppConfig.privatekeypasswd2);
	FreeIfAllocated(g_SuppConfig.simreader);
	FreeIfAllocated(g_SuppConfig.simpin);		
	FreeIfAllocated(g_SuppConfig.nai);
	if(g_DSlib != NULL)
	{
		ResetSupplicantLibrary();
	}

}

// Initialize the supplicant .dll by registering the callbacks
wmx_Status_t InitSupplicantLibrary(VOID)
{
#if ! defined(WPA_OPEN_SOURCE)
	int rc;	
	BOOL res;
	char answer[MAX_ANSWER_SIZE];
	void *ft;
#endif
	struct eap_config eap_config_null = {
		.opensc_engine_path = NULL,
		.pkcs11_engine_path = NULL,
		.pkcs11_module_path = NULL,
		.wps = NULL,
	};

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: InitSupplicantLibrary (IN)");
	// init DS status variable
	smRunRequired = FALSE;
	smInitRequired = TRUE;

#if defined(WPA_OPEN_SOURCE)
	memset(&eap_methods, 0, sizeof(eap_methods));
	eap_methods[2].vendor = EAP_VENDOR_IETF;
	eap_methods[2].method = EAP_TYPE_NONE;
	memset(&eap_ctx, 0, sizeof(eap_ctx));

	eap_ctx.eap_config.identity = (u8 *) os_strdup("user");
	eap_ctx.eap_config.identity_len = 4;
	eap_ctx.eap_config.password = (u8 *) os_strdup("password");
	eap_ctx.eap_config.password_len = 8;
	eap_ctx.eap_config.ca_cert = (u8 *) os_strdup("ca.pem");
	eap_ctx.eap_config.fragment_size = TLS_MAX_SIZE;
	eap_ctx.eap_config.eap_methods = eap_methods;

	memset(&eap_cb, 0, sizeof(eap_cb));
	eap_cb.get_config = peer_get_config;
	eap_cb.get_bool = peer_get_bool;
	eap_cb.set_bool = peer_set_bool;
	eap_cb.get_int = peer_get_int;
	eap_cb.set_int = peer_set_int;
	eap_cb.get_eapReqData = peer_get_eapReqData;
	eap_cb.set_config_blob = peer_set_config_blob;
	eap_cb.get_config_blob = peer_get_config_blob;
	eap_cb.notify_pending = peer_notify_pending;

	eap_peer_register_methods();
	eap_ctx.eap = eap_peer_sm_init(&eap_ctx, &eap_cb, &eap_ctx, &eap_config_null);
	if (eap_ctx.eap == NULL)
		return WMX_ST_FAIL;

	/* Enable "port" to allow authentication */
	eap_ctx.portEnabled = TRUE;
	eap_ctx.bInited = TRUE;
#else
	// init DS data and config holders
	memset(&g_SuppData, 0, sizeof(g_SuppData));
	//memset(&g_SuppConfig, 0, sizeof(g_SuppConfig));
	g_SuppData.sc= swc_config_alloc_ptr("Supplicant agent", SWC_INTERFACE_TYPE_WIMAX); // Supplicant agent is for informational purposes only.

	// DEBUG
	// Possible values: MSG_MSGDUMP, MSG_DEBUG, MSG_INFO, MSG_WARNING, MSG_ERROR
	swc_set_log_level_ptr(MSG_MSGDUMP);
	///////////////////////////////

	if (g_SuppData.sc != NULL)
	{
		// Register get and set callback functions
		rc = swc_eap_sm_set_callbacks_ptr(g_SuppData.sc,
											(void*)EapGetBool, 
											(void*)EapSetBool,
											(void*)EapGetInt, 
											(void*)EapSetInt,
											(void*)EapGetReqData,
											(void*)OSAL_Crypt_EapCreateDecryptPass,		
											&g_SuppData);		
		if (SWC_STATUS_SUCCESS != rc)
		{	
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_eap_sm_set_callbacks_ptr failed");
			return WMX_ST_FAIL;
		}

		// Register callback function for asynchronous supplicant events
		rc = swc_set_ctrl_iface_callback_ptr(g_SuppData.sc, (void*)SuppCtrlIfcCb, g_SuppData.sc);		
		if (SWC_STATUS_SUCCESS != rc)
		{	
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_set_ctrl_iface_callback_ptr failed");
			return WMX_ST_FAIL;
		}		

		// TODO: remove - only for testing
		//InitMethodAndPassword();

		//swc_print_function_register_ptr(custom_print_function);
		//swc_print_function_register_ptr(MSG_DEBUG);


		rc = swc_set_tls_max_size_ptr(g_SuppData.sc, TLS_MAX_SIZE);
		if (SWC_STATUS_SUCCESS != rc)
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_eap_sm_init_ptr failed");
			return WMX_ST_FAIL;
		}		
/******						//rc = swc_set_aka_max_size_ptr(g_SuppData.sc, MAX_PACKET_SIZE); ******/

		//added ability to set TLS function internally\externally
		ft = NULL;
		res = L4Configurations_getTLS_Source(answer);
		if ( (TRUE == res) && (0 == OSAL_stricmp("internal", answer)) )
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE, "Supplicant: TLS source - Internal");			
		}
		else
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE, "Supplicant: TLS source - External");			
			//ft = HardwareTlsImplementation;			
			ft = wmx_GetTlsFunctionTable(1);
		}
		
		if (swc_set_tls_function_table_ptr)
		{
			if (swc_set_tls_function_table_ptr(ft, NULL))
			{
				TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR, "Supplicant: Can not set TLS implementation");
			}
			else
			{
				if (ft)
				{
					TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Using external TLS implementation ");
				}
				else
				{
					TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Using internal TLS implementation ");
				}
			}
		}
		else
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: The SUPPLICANT does not support external TLS implementation");			
		}
		
		
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: InitSupplicantLibrary (OUT)");
	
		return WMX_ST_OK;
	}
	else 
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_config_alloc_ptr failed");
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: InitSupplicantLibrary (OUT)");
		return WMX_ST_FAIL;
	}

#endif //WPA_OPEN_SOURCE

	return WMX_ST_OK;
}

#if defined(WPA_OPEN_SOURCE)

int eap_sm_peer_step(void)
{
	int res;

	if ( bMethodSet == FALSE)
	{
		
		eap_peer_register_methods(); 	
		bMethodSet = TRUE;
	}

	res = eap_peer_sm_step(eap_ctx.eap);

	if (eap_ctx.eapResp) {
		struct wpabuf *resp;
		eap_ctx.eapResp = FALSE;
		resp = eap_get_eapRespData(eap_ctx.eap);
		if (resp) {
			Opensource_SupAgent_SendEapResponse(wpabuf_head(resp),
					      wpabuf_len(resp));
			wpabuf_free(resp);
		}
	}

	if (eap_ctx.eapSuccess) {
		res = 0;
		if (eap_key_available(eap_ctx.eap)) {
			const u8 *key;
			size_t key_len;
			key = eap_get_eapKeyData(eap_ctx.eap, &key_len);
			wpa_hexdump(MSG_DEBUG, "EAP keying material",
				    key, key_len);
			memcpy(eap_ctx.MskKey,key,key_len);
			eap_ctx.MskKeyActualLen = key_len;
		}
	}

	return res;
}

void eap_sm_peer_rx(const u8 *data, size_t data_len)
{
	/* Make received EAP message available to the EAP library */
	eap_ctx.eapReq = TRUE;
	wpabuf_free(eap_ctx.eapReqData);
	eap_ctx.eapReqData = wpabuf_alloc_copy(data, data_len);
}
#else
// for DEBUG
VOID InitMethodAndPassword()
{
	int rc;
	// For testing - replaces fetching the details from the ND&S agent	
	// Setting eap method, private key and certificate
	// make sure to put certificate files within the running directory
	rc = swc_set_eap_method_ptr(g_SuppData.sc, SWC_EAP_TYPE_TLS);
	rc = swc_set_tls_ca_cert_ptr(g_SuppData.sc,(unsigned char *)"cacert.pem", sizeof("cacerts.pem"), 0);
	rc = swc_set_tls_private_key_ptr(g_SuppData.sc,(unsigned char *)"supplicant_key.pem", sizeof("supplicant_key.pem"), 0);
	rc = swc_set_tls_client_cert_ptr(g_SuppData.sc,(unsigned char *)"supplicant_cert.pem", sizeof("supplicant_cert.pem"), 0);
	//rc = swc_set_tls_max_size_ptr(g_SuppData.sc, TLS_MAX_SIZE);
	rc = swc_set_identity_ptr(g_SuppData.sc, "oriti");
}

wmx_Status_t CondEapSMInit()
{
	int rc;
	if (smInitRequired == TRUE)
	{		
		// Init the state machine
		if(!swc_eap_sm_init_ptr)  //[findme][amirs] 64 bit hack
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_eap_sm_init_ptr is null putting old one");

			swc_eap_sm_init_ptr = aaaamirswc_eap_sm_init_ptr;
}

		if(!swc_eap_sm_init_ptr)
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_eap_sm_init_ptr is null return error");
			return WMX_ST_FAIL;
		}

		rc = swc_eap_sm_init_ptr(g_SuppData.sc);
		if (SWC_STATUS_SUCCESS != rc)
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: swc_eap_sm_init_ptr (CondEapSMInit) failed");
			return WMX_ST_FAIL;
		}
		smInitRequired = FALSE;
	}
	return WMX_ST_OK;
}
/*
* EapSMRun - 
* This function runs the SM and if the SM has generated a response, the function shall retrieve it 
* This function returns: e_SUPP_RESPONSE_AVAILABLE 
*						 e_SUPP_NO_RESPONSE
* Before calling the function set the global variables to the correct values
*/
eSuppRetStatus EapSMRun()
{
	size_t rc = e_SUPP_NO_RESPONSE;

	CondEapSMInit();

	smRunRequired = FALSE;

	// Run The State machine
	swc_eap_sm_run_ptr(g_SuppData.sc);

	// Check for response
	if (EapGetBool(&g_SuppData, EAP_eapResp) == TRUE) 
	{
		g_SuppData.RespBufferSize = RSP_MAX_SIZE;

		/* TODO: currently use static buffer to hold response information, check problems of multi threading */
		rc = swc_eap_sm_get_response_ptr(g_SuppData.sc, g_SuppData.RespBuffer, &g_SuppData.RespBufferSize);
		
		if (rc == SWC_STATUS_BUF_TOO_SMALL)
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Buffer For Response is Too Small");			
		}
		else if (rc != SWC_STATUS_SUCCESS) 
		{
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Failed to get response. Return status: %d",rc);
		}
		else // status is 'success', clear EAP_eapResp flag
		{
			// TODO: Check if it is necessary to clear the EAP_eapResp flag even in case of an error
			EapSetBool(&g_SuppData, EAP_eapResp, FALSE);
			return rc = e_SUPP_RESPONSE_AVAILABLE;
		}
	}

	return rc;
}


// Helper function to get the global variable values. The function is used by the agent and
// as a callback by the supplicant.dll
Boolean EapGetBool(VOID* pContext, enum eap_bool_var var)
{
	SupplicantData* pData  = pContext;
	EAP_SM_Variables* pEap_SMVars = &(pData->EapSmVars);

	switch (var) {
	case EAP_eapSuccess:
		return pEap_SMVars->eapSuccess;
	case EAP_eapRestart:
		return pEap_SMVars->eapRestart;
	case EAP_eapFail:
		return pEap_SMVars->eapFail;
	case EAP_eapResp:
		return pEap_SMVars->eapResp;
	case EAP_eapNoResp:
		return pEap_SMVars->eapNoResp;
	case EAP_eapReq:
		return pEap_SMVars->eapReq;
	case EAP_portEnabled:
		return pEap_SMVars->portEnabled;
	case EAP_altAccept:
		return pEap_SMVars->altAccept;
	case EAP_altReject:
		return pEap_SMVars->altReject;
	}

	return FALSE;
}

// Helper function to set value to the global variables. The function is used by the agent and
// as a callback by the supplicant.dll
void EapSetBool(VOID* pContext,  enum eap_bool_var var, Boolean val)
{
	SupplicantData* pData  = pContext;
	EAP_SM_Variables* pEap_SMVars = &(pData->EapSmVars);

	switch (var) 
	{
	case EAP_eapSuccess:
		pEap_SMVars->eapSuccess = val;
		break;
	case EAP_eapRestart:
		pEap_SMVars->eapRestart = val;
		break;
	case EAP_eapFail:
		pEap_SMVars->eapFail = val;
		break;
	case EAP_eapResp:
		pEap_SMVars->eapResp = val;
		break;
	case EAP_eapNoResp:
		pEap_SMVars->eapNoResp = val;
		break;
	case EAP_eapReq:
		pEap_SMVars->eapReq = val;
		break;
	case EAP_portEnabled:
		pEap_SMVars->portEnabled = val;
		break;
	case EAP_altAccept:
		pEap_SMVars->altAccept = val;
		break;
	case EAP_altReject:
		pEap_SMVars->altReject = val;
		break;
	}
}

// Helper function to get the global variable values. The function is used by the agent and
// as a callback by the supplicant.dll
int EapGetInt(VOID* pContext, enum eap_int_var var)
{
	SupplicantData* pData  = pContext;
	EAP_SM_Variables* pEap_SMVars = &(pData->EapSmVars);

	switch (var) 
	{
	case EAP_idleWhile:
		return pEap_SMVars->idleWhile;
	}

	return 0;
}

// Helper function to set value to the global variables. The function is used by the agent and
// as a callback by the supplicant.dll
void EapSetInt(VOID* pContext, enum eap_int_var var, UINT32 val)
{
	SupplicantData* pData  = pContext;
	EAP_SM_Variables* pEap_SMVars = &(pData->EapSmVars);

	switch (var) 
	{
	case EAP_idleWhile:
		pEap_SMVars->idleWhile = val;
		break;
	}
}

UINT8* EapGetReqData(VOID* pContext, size_t * datalen)
{
	SupplicantData* pData  = pContext;
	EAP_SM_Variables* pEap_SMVars = &(pData->EapSmVars);

	*datalen = pEap_SMVars->eapReqData_len;

	wpa_hexdump_ptr(MSG_DEBUG, "SupAgent: EapGetReqData payload", pEap_SMVars->eapReqData, pEap_SMVars->eapReqData_len);
	return pEap_SMVars->eapReqData;
}

/*
* SuppCtrlIfcCb - Control interface callback 
* @pContext: Pointer to callback context
* @cb_type: Type of callback
* @cb_subtype: Subtype of callback
*
* The function is responsible for receiving requests for credentials or
* events related to the authentication process. The function retrieves credentials and set them in the global variable.
*
*/
VOID SuppCtrlIfcCb(VOID* pContext, UINT32 cb_type, UINT32 cb_subtype)
{
	static char	*identity;
	static char	*password;
	static char	*pin;
	static int passwordLength;
	size_t rc;	

	UNREFERENCED_PARAMETER(pContext);

	if (cb_type == SWC_CALLBACK_TYPE_CREDENTIAL) 
	{		
		switch (cb_subtype) 
		{
		case SWC_CRED_IDENTITY: 				
			smRunRequired = TRUE;			
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_IDENTITY");		
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_IDENTITY);			
			break;
		case SWC_CRED_OTP: 
			//smRunRequired = TRUE;
			//SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_IDENTITY); // future feature
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_OTP");					
			break;
		case SWC_CRED_PASSWORD:
			smRunRequired = TRUE;
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_PASSWORD");
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_PASSWORD);
			break;
		case SWC_CRED_PIN:
			smRunRequired = TRUE;
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_PIN");
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_PIN);
			break;
		case SWC_CRED_NEW_PASSWORD:
			//smRunRequired = TRUE;
			//SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_NEW_PASSWORD); // future feature
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_NEW_PASSWORD");		
			break;
		case SWC_CRED_PASSPHRASE: 
			//smRunRequired = TRUE;
			//SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_PASSPHRASE); // future feature
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_PASSPHRASE");		
			break;			
		case SWC_CRED_PRIVATE_KEY: 
			smRunRequired = TRUE;
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_PRIVATE_KEY");
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_PRIVATE_KEY); // future feature
			break;
		case SWC_CRED_CA_CERTIFICATE:
			smRunRequired = TRUE;
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Credentials Request - SWC_CRED_CA_CERTIFICATE");
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_CREDENTIAL, SWC_CRED_CA_CERTIFICATE); // future feature
			break;
		
		default:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown credential request #%d",cb_subtype);					
			return;
		}
	} 
	else if (cb_type == SWC_CALLBACK_TYPE_EVENT) 
	{		
		switch (cb_subtype) {
		case SWC_EV_EAP_KEY_AVAILABLE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Event - Key available");
			g_SuppData.MskKeyActualLen = MSK_SIZE;
			// the g_SuppData.MskKeyActualLen contains the max allowed size on input and actual size on output
			rc = swc_eap_sm_get_key_ptr(g_SuppData.sc, g_SuppData.MskKey, &g_SuppData.MskKeyActualLen);
			if (rc != SWC_STATUS_SUCCESS) 
			{	
				TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Key was available though failed to retrieve it from supplicant");				
			}
			if (!swc_get_BEK_ptr)
			{
				TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Getting BEK key is not supported by supplicant!");				
			}
			else
			{
				unsigned char buf[16];
				if (swc_get_BEK_ptr(g_SuppData.sc, buf, 16) < 0)
				{
					TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Failed to get BEK key from supplicant!");				
				}
				else
				{
					TRACE(TR_MOD_NDNS_AGENT, TR_SEV_NOTICE,"Supplicant: BEK key - %X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X,%X", buf[0], buf[1], buf[2],
						buf[3], buf[4], buf[5],
						buf[6], buf[7], buf[8],
						buf[9], buf[10], buf[11],
						buf[12], buf[13], buf[14], buf[15]);
					
					SetBEK((wmx_pBEKBuffer_t)buf);
				}
			}
			break;
		case SWC_EV_EAP_SUCCESS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Event - Authentication Successful");
			g_SuppConfig.isValid = FALSE;			
			wmx_SetEapSuccess();
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_EVENT, SWC_EV_EAP_SUCCESS); // send EAP FAIL to the ND&S
			break;
		case SWC_EV_EAP_FAILURE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Event - Authentication failure");
			g_SuppConfig.isValid = FALSE;
			wmx_SetEapFail(); // send EAP FAIL to the device
			SupAgent_SendIndication(SWC_CALLBACK_TYPE_EVENT, SWC_EV_EAP_FAILURE); // send EAP FAIL to the ND&S
			break;
		case SWC_EV_REJECTED_CREDENTIAL:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Rejected Credential ");
			break;
		case SWC_EV_REJECTED_CHALLENGE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Rejected Challenge ");
			break;
		case SWC_EV_REJECTED_CERTIFICATE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Rejected Certificate ");
			break;
		case SWC_EV_REJECTED_IDENTITY:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Rejected Identity ");
			break;
		case SWC_EV_REJECTED_METHOD:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Rejected Method ");
			break;
		case SWC_EV_RESTRICTED_LOGON_HOURS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Restricted Logon Hours");
			break;
		case SWC_EV_ACCOUNT_DISABLED:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Account Disabled ");
			break;
		case SWC_EV_ACCOUNT_NO_DIAL_IN:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Account no dial-in ");
			break;
		case SWC_EV_TLV_INVALID:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: TLV Invalid ");
			break;
		case SWC_EV_TLV_UNKNOWN:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: TLV Unknown ");
			break;
		case SWC_EV_TLV_NAK:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: TLV NAK ");		
			break;
		case SWC_EV_FAST_CMAC_INVALID:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: FAST Compound MAC Invalid");
			break;
		case SWC_EV_FAST_PROVISION_SUCCESS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: FAST Provision Success");
			break;
		case SWC_EV_FAST_INVALID_PAC_KEY:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: FAST Invalid PAC Key");
			break;
		case SWC_EV_FAST_INVALID_PAC_OPAQUE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: FAST Invalid PAC Opaque");
			break;
		case SWC_EV_EAP_CLEAR_TEXT_SUCCESS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP Clear Text Success");
			break;
		case SWC_EV_EAP_CLEAR_TEXT_FAILURE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: EAP Clear Text Failure");
			break;
		case SWC_EV_EAP_INTERMEDIATE_SUCCESS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP Intermediate Success");
			break;
		case SWC_EV_EAP_INTERMEDIATE_FAILURE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: EAP Intermediate Failure");
			break;
		case SWC_EV_SIM_PIN_INCORRECT:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: SIM PIN Incorrect ");
			break;
		case SWC_EV_SIM_PIN_REQUIRED:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: SIM PIN Required");
			break;
		case SWC_EV_SIM_NO_READER:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: SIM No Reader");
			break;
		case SWC_EV_SIM_NO_CARD:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: SIM No Card");
			break;
		case SWC_EV_SIM_FAILURE:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: SIM Failure");
			break;
		///////////////////
		case SWC_EV_EAP_METHOD_TLS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting TLS method");
			break;
		case SWC_EV_EAP_METHOD_TTLS:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting TTLS method");
			break;
		case SWC_EV_EAP_METHOD_PEAP:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting PEAP method");
			break;
		case SWC_EV_EAP_METHOD_SIM:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting SIM method");
			break;
		case SWC_EV_EAP_METHOD_AKA:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting AKA method");
			break;
		case SWC_EV_EAP_METHOD_PSK:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting PSK method");
			break;
		case SWC_EV_EAP_METHOD_LEAP:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting LEAP method");
			break;
		case SWC_EV_EAP_METHOD_FAST:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: supporting FAST method");
			break;
		//////////////////
		default:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown event type %d", cb_subtype);			
			break;
		}
	} 
	else 
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown callback type %d", cb_type);
	}
}



void DS_EapRestart(VOID)
{
	memset(g_SuppData.MskKey,0,MSK_SIZE);

	g_SuppData.EapSmVars.eapRestart=TRUE;
	g_SuppData.EapSmVars.portEnabled = FALSE;
	EapSMRun();
	g_SuppData.EapSmVars.portEnabled = TRUE;

}
#endif

void ResetSupplicantLibrary()
{
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset library - start");
#if !defined(WPA_OPEN_SOURCE)
	if (g_SuppData.sc != NULL)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset library - erasing DS context");
		swc_config_reset_ptr(g_SuppData.sc);
		swc_config_free_ptr(g_SuppData.sc);
		g_SuppData.sc = NULL;
	}
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset library - erasing last eap request data");
	FreeIfAllocated(g_SuppData.EapSmVars.eapReqData);
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset library - end");
#else
	if( bMethodSet == TRUE ){	
		eap_peer_sm_deinit(eap_ctx.eap);
		eap_peer_unregister_methods();
		wpabuf_free(eap_ctx.eapReqData);
	
		FreeIfAllocated(eap_ctx.eap_config.identity);
		FreeIfAllocated(eap_ctx.eap_config.anonymous_identity);
		FreeIfAllocated(eap_ctx.eap_config.password);
		FreeIfAllocated(eap_ctx.eap_config.ca_cert);
		FreeIfAllocated(eap_ctx.eap_config.client_cert);
		FreeIfAllocated(eap_ctx.eap_config.private_key);
		FreeIfAllocated(eap_ctx.eap_config.private_key_passwd);
		bMethodSet = FALSE;
	}
#endif
}
/*******************************************/

void FinalizeSupplicantLibrary()
{	
	ResetSupplicantLibrary();
	if (g_DSlib != NULL)
	{
		OSAL_close_lib(g_DSlib);
		g_DSlib = NULL;
	}	
	FinalizeSuppConfig();
#if defined(WPA_OPEN_SOURCE)
		SupplicantLoaded = FALSE;
#endif //WPA_OPEN_SOURCE
}

wmx_Status_t LoadSupplicantLibrary()
{
	char str[MAX_PATH];
	UINT32 err;

	L4Configurations_getSupplicantLibName(str);
	
	// make sure to put supplicant.dll under the running dirctory
	g_DSlib = OSAL_load_lib(str);
	if( g_DSlib == NULL ) 
	{
		err = GetLastError();
		OSAL_sprintf_s(str, MAX_PATH,"Device-Scape library failed to be loaded (LastError=%d)", err);
		OSAL_EventLogger_Log(EVENTLOG_ERROR_TYPE, (char *)str);
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: %s", str);
		return WMX_ST_CONFIG_ERROR;
	}
#if !defined(WPA_OPEN_SOURCE)
	swc_eap_sm_init_ptr = (EapSmInitFuncPtr)OSAL_find_symbol(g_DSlib,"swc_eap_sm_init");
	swc_set_eap_method_ptr = (EapSmSetEapMethodFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_eap_method");
	swc_set_phase2_method_ptr = (EapSmSetEapMethodFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_phase2_method");
	swc_set_ctrl_iface_callback_ptr = (EapSetCtrlIfcCallbackFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_ctrl_iface_callback");
	swc_eap_sm_set_callbacks_ptr = (EapSetCallBacksFuncPtr)OSAL_find_symbol(g_DSlib,"swc_eap_sm_set_callbacks");
	swc_config_alloc_ptr = (EapCconfigAllocFuncPtr)OSAL_find_symbol(g_DSlib,"swc_config_alloc");
	swc_config_reset_ptr = (EapCconfigResetFuncPtr)OSAL_find_symbol(g_DSlib,"swc_config_reset");
	swc_config_free_ptr = (EapCconfigFreeFuncPtr)OSAL_find_symbol(g_DSlib,"swc_config_free");
	swc_eap_sm_get_response_ptr = (EapSmGetResponseFuncPtr)OSAL_find_symbol(g_DSlib,"swc_eap_sm_get_response");
	swc_eap_sm_run_ptr = (EapSmRunFuncPtr)OSAL_find_symbol(g_DSlib,"swc_eap_sm_run");
	swc_set_identity_ptr = (EapSetIdentityFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_identity");
	swc_set_anonymous_identity_ptr = (EapSetIdentityFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_anonymous_identity");
	swc_set_password_ptr = (EapSetPasswordFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_password");
	swc_eap_sm_get_key_ptr = (EapSmGetKeyFuncPtr)OSAL_find_symbol(g_DSlib,"swc_eap_sm_get_key");
	swc_set_tls_private_key_ptr = (EapSetTlsPrivateKeyFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_private_key");
	swc_set_tls_private_key_passwd_ptr = (EapSetTlsPrivateKeyPasswordFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_private_key_passwd");
	swc_set_tls_ca_cert_ptr = (EapSetTlsCaCertFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_ca_cert");
	swc_set_tls_client_cert_ptr = (EapSetTlsClientCertFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_client_cert");
	swc_set_tls_private_key2_ptr = (EapSetTlsPrivateKeyFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_private_key2");
	swc_set_tls_ca_cert2_ptr = (EapSetTlsCaCertFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_ca_cert2");
	swc_set_tls_client_cert2_ptr = (EapSetTlsClientCertFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_client_cert2");
	swc_set_tls_max_size_ptr = (SetTlsMaxSizeFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_tls_max_size");
	swc_print_function_register_ptr = (PrintFuncRegisterFuncPtr)OSAL_find_symbol(g_DSlib, "swc_print_function_register");
	swc_set_pin_ptr = (EapSetPinFuncPtr)OSAL_find_symbol(g_DSlib,"swc_set_sim_pin");
	swc_set_log_level_ptr = (SetLogLevelFuncPtr)OSAL_find_symbol(g_DSlib, "swc_set_log_level");
	wpa_hexdump_ptr = (WpaHexdumpPtr)OSAL_find_symbol(g_DSlib, "wpa_hexdump");
	wpa_logproc_ptr = (WpaLogprocPtr)OSAL_find_symbol(g_DSlib, "wpa_printf");
	//swc_set_aka_max_size_ptr = (SetAkaMaxSizeFuncPtr)OSAL_find_symbol(g_DSlib, "swc_set_aka_max_size");
	swc_set_tls_function_table_ptr = (EapSetTlsFunctionTable)OSAL_find_symbol(g_DSlib, "swc_config_use_external_tls");
swc_get_BEK_ptr = (EapSmGetBEKFuncPtr)OSAL_find_symbol(g_DSlib, "swc_eap_get_BEK_data");
aaaamirswc_eap_sm_init_ptr =swc_eap_sm_init_ptr;  //[findme][amirs] buffer for 64bit
#endif
	return WMX_ST_OK;
}

#if !defined(WPA_OPEN_SOURCE)
void SupAgent_SendEapResponse()
{
	UINT8 targetBuffer[L4_MSG_MAX_LENGTH];

	memcpy((void*)targetBuffer, (void*)g_SuppData.RespBuffer, g_SuppData.RespBufferSize);

	OSAL_MyPrintf("Sending EapResponse. Data size: %d\n", g_SuppData.RespBufferSize);
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP_RESP_DATA was sent to Driver. Buffer length: %d", g_SuppData.RespBufferSize);
	wmx_CmdSendEapResponse(g_SuppData.RespBufferSize, (wmx_pEapMessage_t)targetBuffer);
}
#endif 

void Opensource_SupAgent_SendEapResponse(const u8 *data, size_t data_len)
{
	OSAL_MyPrintf("Sending EapResponse. Data size: %d\n", data_len);
	wmx_CmdSendEapResponse(data_len, (wmx_pEapMessage_t) data);
}
//*******************************************
// Used to receive an EAP request, pass it
// to DS and send an EapResponse if required
//*******************************************
void WMX_EXT_CALL_CONV SupAgent_EapRequestAvailable( wmx_EapMsgLength_t	eapMsgLen, wmx_pEapMessage_t pEapMsg )
{	
	int rc;

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP request available (size: %d)", eapMsgLen);
#if !defined(WPA_OPEN_SOURCE)
	if (!g_SuppConfig.isEnabled)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_WARNING,"Supplicant: EAP request available, Supplicant disabled. Request discarded");
		return;
	}
	if((void*)pEapMsg == NULL)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: EAP request available, NULL buffer was received");	
		return;
	}		

	if (!g_SuppConfig.isValid)
	{
		// Reset Identity:			
		SupAgent_ResetSupplicant(); 		
	}

	OSAL_MyPrintf("EapRequest received. Data size: %d\n", eapMsgLen);
	rc = CondEapSMInit();

	if (rc != WMX_ST_OK) // sm init error
	{
		return;
	}

	FreeIfAllocated(g_SuppData.EapSmVars.eapReqData);
	g_SuppData.EapSmVars.eapReqData = (UINT8*)malloc(eapMsgLen);
	if (g_SuppData.EapSmVars.eapReqData == NULL)
	{
		TRACE(TR_MOD_NDNS_AGENT, TR_SEV_CRITICAL,"SupAgent_EapRequestAvailable: malloc failed");
		return;
	}

	memcpy((void*)g_SuppData.EapSmVars.eapReqData, (void*)pEapMsg, eapMsgLen);
	//g_SuppData.EapSmVars.eapReqData = (UINT8*)pEapMsg;
	g_SuppData.EapSmVars.eapReqData_len  = eapMsgLen;
	g_SuppData.EapSmVars.eapReq = TRUE;

	rc = EapSMRun();	

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP request available OUT (response: %s)", 
				(rc == e_SUPP_RESPONSE_AVAILABLE) ? "yes" : "no");

	// Check if a response from the supplicant.dll came
	if (rc == e_SUPP_RESPONSE_AVAILABLE)
	{
		SupAgent_SendEapResponse();
	}
#else
	if ( SupplicantLoaded == FALSE )
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_WARNING, ("Supplicant library is not loaded."));
		return;
	}
	eap_sm_peer_rx((const u8*)(pEapMsg) , eapMsgLen);
	rc=eap_sm_peer_step();

	if (rc == e_SUPP_RESPONSE_AVAILABLE)
	{
		//::todo
	}
	else
	{
		//::todo
	}
#endif
}

//*******************************************
// Used to receive an alternative EAP success
// and pass it to DS
//*******************************************
void WMX_EXT_CALL_CONV SupAgent_AlternativeEapSuccess()
{
#if !defined(WPA_OPEN_SOURCE)
	int rc;
	rc = CondEapSMInit();
	if (rc != WMX_ST_OK) // sm init error
	{
		return;
	}
	g_SuppData.EapSmVars.altAccept=TRUE;
	EapSMRun();
	
	g_SuppConfig.isValid = FALSE;
#else
	SupAgent_ResetSupplicant();
#endif
}

//*******************************************
// Used to receive an EAP key request
// (get key) and send the key to the driver
//*******************************************
void WMX_EXT_CALL_CONV SupAgent_EapKeyRequest()
{
	//TODO

#if !defined(WPA_OPEN_SOURCE)
	UINT8 targetBuffer[L4_MSG_MAX_LENGTH];

	memcpy((void*)targetBuffer, g_SuppData.MskKey, g_SuppData.MskKeyActualLen);
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: EAP_SET_KEY was sent to Driver. Buffer length: %d", g_SuppData.MskKeyActualLen);

	wmx_SetEapKey (g_SuppData.MskKeyActualLen, (wmx_pEapKey_t)targetBuffer);
#else
	wmx_SetEapKey(eap_ctx.MskKeyActualLen, (wmx_pEapKey_t) eap_ctx.MskKey);
#endif
}

//*******************************************//

wmx_Status_t SupAgent_RegisterCallbacksOnWrapper()
{
	wmx_Status_t status;
	status = wmx_RegisterEapRequestAvailableCB(&SupAgent_EapRequestAvailable);
	if ( WMX_ST_OK != status )
	{
		return status;
	}
	status = wmx_RegisterAlternativeEapSuccessCB(&SupAgent_AlternativeEapSuccess);
	if ( WMX_ST_OK != status )
	{
		return status;
	}
	status = wmx_RegisterEapKeyRequestCB(&SupAgent_EapKeyRequest);
	if ( WMX_ST_OK != status )
	{
		return status;
	}	

	status = wmx_RegisterEapRestartRequestCB(&SupAgent_ResetSupplicant);
	if ( WMX_ST_OK != status )
	{
		return status;
	}	
	return status;
}

wmx_Status_t SupAgent_UnRegisterCallbacksOnWrapper()
{
	wmx_Status_t status;
	status = wmx_UnregisterEapRequestAvailableCB();
	if ( WMX_ST_OK != status )
	{
		return status;
	}
	status = wmx_UnregisterAlternativeEapSuccessCB();
	if ( WMX_ST_OK != status )
	{
		return status;
	}
	status = wmx_UnregisterEapKeyRequestCB();
	if ( WMX_ST_OK != status )
	{
		return status;
	}	
	status = wmx_UnregisterEapRestartRequestCB();
	if ( WMX_ST_OK != status )
	{
		return status;
	}	
	return status;
}

//*******************************************
// Used to register a Target on Indication.
//*******************************************
wmx_Status_t SupAgent_RegisterIndicator(L5_TARGET_ID nOriginID, UINT32 status_indication_id)
{
	IndicatorSubscribers *indSubscribers = GetIndicatorSubscribers(indicatorSubscribersList, status_indication_id, TRUE);

	if(indSubscribers == NULL)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_CRITICAL,"INTERNAL_PROBLEM: Errot registering indicator;  indSubscribers == NULL");
		pFuncs->pfnSendErrorReport(L5_TARGET_SUPPLICANT, INTERNAL_PROBLEM, __FUNCTION__, __LINE__);
		return WMX_ST_FAIL;
	}

	Indications_AddSubscriber(indSubscribers, nOriginID);
	//Perform actions according to size of list and subscriber addition
	return WMX_ST_OK;
}

//*******************************************
// Used to unregister a Target from an Indication
//*******************************************
wmx_Status_t SupAgent_UnRegisterIndicator(L5_TARGET_ID nOriginID, UINT32 status_indication_id)
{
	IndicatorSubscribers *indSubscribers = GetIndicatorSubscribers(indicatorSubscribersList, status_indication_id, FALSE);

	if ((NULL == indSubscribers) || (!Indications_RemoveSubscriber(indSubscribers, nOriginID)))
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: UnRegisterIndicator Failed(TargetId=%d, indication_id=0x%x)", nOriginID, status_indication_id);
		//return WMX_ST_FAIL;
	}
	//Perform actions according to size of list and subscriber removal
	return WMX_ST_OK;	
}

//*******************************************
// Used to send a supplicant event indication
//*******************************************
void SupAgent_SendIndication( wmx_EventType_t eventType, wmx_CredID_t credId)
{
	wmx_SupEvent_t event;
	SendIndData *pSendIndData;
	pSUP_MESSAGE eventMessage;
	UINT32 bufferSize;
	UINT32 messageSize;
	UINT32 indDataSize;

	event.eventType = eventType;
	event.credId = credId;
	
	// allocate the indication data
	bufferSize = sizeof(wmx_SupEvent_t);
	messageSize = sizeof(SUP_MESSAGE_HEADER) + bufferSize;
	indDataSize = sizeof(SendIndData) + messageSize;
	pSendIndData = (SendIndData *)malloc(indDataSize);
	if (pSendIndData == NULL)
	{
		TRACE(TR_MOD_NDNS_AGENT, TR_SEV_CRITICAL,"SupAgent_SendIndication: malloc failed");
		return;
	}

	eventMessage = (pSUP_MESSAGE)pSendIndData->indication_buffer;

	// fill the indication data
	pSendIndData->pSenderFuncs = pFuncs;
	pSendIndData->senderL5Conn = supplicantConnection;
	pSendIndData->pSubscribersList = indicatorSubscribersList;
	pSendIndData->indication_id = SUP_OPCODE_IND_EVENT;
	eventMessage->header.opcode = SUP_OPCODE_IND_EVENT;
	eventMessage->header.bufferLength = bufferSize;
	*(wmx_pSupEvent_t)(eventMessage->buf) = event;

	// send the indication
	pUtils->tpfnPostRequest(
		MEDIUM, SUP_OPCODE_INDICATION_ARRIVED, pSendIndData, indDataSize, &SendIndicationToSubscribers);
	
	free(pSendIndData);
}

//************************************************
// Unregister L5 Target from indications lists.
//************************************************
void SupAgent_UnRegisterL5Target(L5_TARGET_ID targetID)
{
	// Iterate the status indication list, for each indicator - remove the target ID:
	IndicatorSubscribers *indSubscribers;
	ListItem* handle;

	handle = CreateIterator(indicatorSubscribersList);
	handle = Iterator_GetNext(indicatorSubscribersList, handle, &indSubscribers);
	while (handle)
	{
		Indications_RemoveSubscriber(indSubscribers, targetID);
		handle = Iterator_GetNext(indicatorSubscribersList, handle, &indSubscribers);
	}
	FreeIterator(indicatorSubscribersList);
}

//******************************************//
// helper functions
char *SupAgent_ExtractString(void *pvSentBuffer)
{
	pSUP_MESSAGE msg = (pSUP_MESSAGE)pvSentBuffer;
	char *str = (char*)msg->buf;	
	char *resultStr = (char*)malloc(OSAL_strnlen(str, MAX_STRING_VALIDATE) + 1);
	if (resultStr == NULL)
	{
		TRACE(TR_MOD_NDNS_AGENT, TR_SEV_CRITICAL,"malloc failed");
		return NULL;
	}

	OSAL_strcpy_s(resultStr, OSAL_strnlen(str, MAX_STRING_VALIDATE) + 1,str);

	return resultStr;
}




UINT32 SupAgent_ExtractUnsignedInt(void *pvSentBuffer)
{
	pSUP_MESSAGE msg = (pSUP_MESSAGE)pvSentBuffer;
	return *(UINT32*)msg->buf;
}

INT32 SupAgent_ExtractInt(void *pvSentBuffer)
{
	pSUP_MESSAGE msg = (pSUP_MESSAGE)pvSentBuffer;
	return *(INT32*)msg->buf;
}

#if !defined(WPA_OPEN_SOURCE)
// Conditional sm run order
void SupAgent_CondEapSMRun()
{
	int rc;

	if (smRunRequired == TRUE)
	{					
		rc = EapSMRun();
		// Check if a response from the supplicant.dll came
		if (rc == e_SUPP_RESPONSE_AVAILABLE)
		{
			SupAgent_SendEapResponse();
		}
	}
}
#endif


//*******************************************
// AppSrv Agent Interface - start
//*******************************************


// AppSrv Agent Interface - Initialize
void Supplicant_EventHandler( 
							 L5_CONNECTION Conn,
							 L5_EVENT eEvent,
							 void *pvEventData,
							 void *pvUserContext )
{
	UNREFERENCED_PARAMETER(Conn);
	UNREFERENCED_PARAMETER(pvEventData);
	UNREFERENCED_PARAMETER(pvUserContext);

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"%s L5 event received", L5_EVENT_STR(eEvent));

	// Unregister all indications that were registered on the agent
	if (L5_EVENT_DRIVER_DISCONNECTED == eEvent)
	{	
		// clean all indications' targets
		EmptyIndicatorsList(&indicatorSubscribersList);
	}	
}


void  Supplicant_InternalHandler( UINT32 internalRequestID, void *buffer, UINT32 bufferLength )
{
	pSUP_MESSAGE_HEADER msg = (pSUP_MESSAGE_HEADER)buffer;	
	char prefix[MAX_SUP_STR_LEN] ="Assign configuration";


	UNREFERENCED_PARAMETER(bufferLength);
	UNREFERENCED_PARAMETER(internalRequestID);
	
#if !defined(WPA_OPEN_SOURCE)
	BOOL isValid = g_SuppConfig.isValid;
	
	// by default - setting a value to the supplicant will cause a restart request.
	// the only case where a restart is not required is if this message was illegal (see "default" section below)
	g_SuppConfig.isValid = FALSE;

	switch (msg->opcode)
	{
		case SUP_OPCODE_SET_IDENTITY:
			FreeIfAllocated(g_SuppConfig.identity);
			g_SuppConfig.identity = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.identity,"Identity", prefix);
			swc_set_identity_ptr(g_SuppData.sc, g_SuppConfig.identity);
			SupAgent_CondEapSMRun();			
			break;
		case SUP_OPCODE_SET_ANONYMOUS_IDENTITY:
			FreeIfAllocated(g_SuppConfig.anonidentity);
			g_SuppConfig.anonidentity = SupAgent_ExtractString(buffer);	
			Sup_PrintTrace(g_SuppConfig.anonidentity,"OuterIdentity", prefix);
			swc_set_anonymous_identity_ptr(g_SuppData.sc, g_SuppConfig.anonidentity);
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_PASSWORD:
			FreeIfAllocated(g_SuppConfig.password);
			g_SuppConfig.password = SupAgent_ExtractString(buffer);	
			Sup_PrintTrace(g_SuppConfig.password,"Password", prefix);
			swc_set_password_ptr(g_SuppData.sc, g_SuppConfig.password);
			SupAgent_CondEapSMRun();
			break;
		//case SUP_OPCODE_SET_NEW_PASSWORD:
		//	break;
		case SUP_OPCODE_SET_EAP_METHOD:
			g_SuppConfig.eapmethod = SupAgent_ExtractUnsignedInt(buffer); 
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: %s - EapMethod = %d", prefix, g_SuppConfig.eapmethod);
			swc_set_eap_method_ptr(g_SuppData.sc, g_SuppConfig.eapmethod);
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_PHASE2_METHOD:
			g_SuppConfig.phase2 = SupAgent_ExtractUnsignedInt(buffer);
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: %s - Phase2 method = %d", prefix, g_SuppConfig.phase2);
			swc_set_phase2_method_ptr(g_SuppData.sc, g_SuppConfig.phase2);
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_CA_CERT:
			FreeIfAllocated(g_SuppConfig.cacert);
			g_SuppConfig.cacert = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.cacert,"CA cert", prefix);
			swc_set_tls_ca_cert_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.cacert, (int)OSAL_strnlen(g_SuppConfig.cacert, MAX_STRING_VALIDATE) + 1, 0);
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_CA_CERT2:
			FreeIfAllocated(g_SuppConfig.cacert2);
			g_SuppConfig.cacert2 = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.cacert2,"CA cert - phase2", prefix);
			swc_set_tls_ca_cert2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.cacert2, (int)OSAL_strnlen(g_SuppConfig.cacert2, MAX_STRING_VALIDATE) + 1, 0);			
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_CLIENT_CERT:
			FreeIfAllocated(g_SuppConfig.clientcert);
			g_SuppConfig.clientcert = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.clientcert,"Client cert", prefix);
			swc_set_tls_client_cert_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.clientcert, (int)OSAL_strnlen(g_SuppConfig.clientcert, MAX_STRING_VALIDATE) + 1, 0);			
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_CLIENT_CERT2:
			FreeIfAllocated(g_SuppConfig.clientcert2);
			g_SuppConfig.clientcert2 = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.clientcert2,"Client cert - phase2", prefix);
			swc_set_tls_client_cert2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.clientcert2, (int)OSAL_strnlen(g_SuppConfig.clientcert2, MAX_STRING_VALIDATE) + 1, 0);
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_PRIVATE_KEY:
			FreeIfAllocated(g_SuppConfig.privatekey);
			g_SuppConfig.privatekey = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.privatekey,"Private key", prefix);
			swc_set_tls_private_key_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.privatekey, (int)OSAL_strnlen(g_SuppConfig.privatekey, MAX_STRING_VALIDATE) + 1, 0);			
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD:
			FreeIfAllocated(g_SuppConfig.privatekeypasswd);
			g_SuppConfig.privatekeypasswd = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.privatekeypasswd,"Private key password", prefix);	
			swc_set_tls_private_key_passwd_ptr(g_SuppData.sc, (char *)g_SuppConfig.privatekeypasswd);			
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;

		case SUP_OPCODE_SET_TLS_PRIVATE_KEY2:
			FreeIfAllocated(g_SuppConfig.privatekey2);
			g_SuppConfig.privatekey2 = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.privatekey2,"Private key password - phase2", prefix);
			swc_set_tls_private_key2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.privatekey2, (int)OSAL_strnlen(g_SuppConfig.privatekey2, MAX_STRING_VALIDATE) + 1, 0);
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		//case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD:
		//	break;
		//case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD2:
		//	break;
		case SUP_OPCODE_SET_PIN:
			FreeIfAllocated(g_SuppConfig.simpin);
			g_SuppConfig.simpin = SupAgent_ExtractString(buffer);
			Sup_PrintTrace(g_SuppConfig.simpin,"PIN", prefix);
			swc_set_pin_ptr(g_SuppData.sc, g_SuppConfig.simpin);
			smInitRequired = TRUE; // TODO: check if it's needed
			SupAgent_CondEapSMRun();
			break;
		//case SUP_OPCODE_SET_PIN_MAX_SIZE:
		//  break;
		case SUP_OPCODE_SET_TLS_MAX_SIZE:
			swc_set_tls_max_size_ptr(g_SuppData.sc, SupAgent_ExtractInt(buffer));
			smInitRequired = TRUE;
			SupAgent_CondEapSMRun();
			break;
		default:
			g_SuppConfig.isValid = isValid; // return to previous value in case this was not a set command
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown SET message received");
			break;
	}	
#else
	wmx_Status_t status 		= WMX_ST_OK;
	int eapmethod;

	if ( SupplicantLoaded == FALSE ) 
	{
		if ( (status=DelayLoadSupplicant()) != WMX_ST_OK)
			return;
		SupplicantLoaded = TRUE;
	}

	switch (msg->opcode)
	{
	case SUP_OPCODE_SET_IDENTITY:
		FreeIfAllocated(g_SuppConfig.identity);
		g_SuppConfig.identity = SupAgent_ExtractString(buffer);

		FreeIfAllocated(eap_ctx.eap_config.identity);
		eap_ctx.eap_config.identity = (u8*)SupAgent_ExtractString(buffer);
		eap_ctx.eap_config.identity_len = os_strlen((const char*)eap_ctx.eap_config.identity);
		Sup_PrintTrace((char *)eap_ctx.eap_config.identity, "Identity", prefix);
		break;
	case SUP_OPCODE_SET_ANONYMOUS_IDENTITY:
		FreeIfAllocated(g_SuppConfig.anonidentity);
		g_SuppConfig.anonidentity = SupAgent_ExtractString(buffer);	

		FreeIfAllocated(eap_ctx.eap_config.anonymous_identity);
		eap_ctx.eap_config.anonymous_identity = (u8*)SupAgent_ExtractString(buffer);
		eap_ctx.eap_config.anonymous_identity_len =
				os_strlen((const char*)eap_ctx.eap_config.anonymous_identity);
		Sup_PrintTrace((char *)eap_ctx.eap_config.anonymous_identity, "OuterIdentity", prefix);
		break;
	case SUP_OPCODE_SET_PASSWORD:
		FreeIfAllocated(g_SuppConfig.password);
		g_SuppConfig.password = SupAgent_ExtractString(buffer);	

		FreeIfAllocated(eap_ctx.eap_config.password);
		eap_ctx.eap_config.password 	= (u8*)SupAgent_ExtractString(buffer);
		eap_ctx.eap_config.password_len = os_strlen((const char*)eap_ctx.eap_config.password);
		Sup_PrintTrace((char*)eap_ctx.eap_config.password, "Password", prefix);
		break;
	case SUP_OPCODE_SET_EAP_METHOD:
		eapmethod = SupAgent_ExtractUnsignedInt(buffer);
		g_SuppConfig.eapmethod = eapmethod;
		peer_set_method1(eapmethod);
		bMethodSet = TRUE;
		break;
	case SUP_OPCODE_SET_PHASE2_METHOD:
		eapmethod = SupAgent_ExtractUnsignedInt(buffer);
		g_SuppConfig.phase2 = eapmethod;
		peer_set_method2(eapmethod);
		break;
	case SUP_OPCODE_SET_TLS_CA_CERT:
		FreeIfAllocated(g_SuppConfig.cacert);
		g_SuppConfig.cacert = SupAgent_ExtractString(buffer);

		FreeIfAllocated(eap_ctx.eap_config.ca_cert);
		eap_ctx.eap_config.ca_cert = (u8*)SupAgent_ExtractString(buffer);
		break;
	case SUP_OPCODE_SET_TLS_CA_CERT2:
		break;
	case SUP_OPCODE_SET_TLS_CLIENT_CERT:
		FreeIfAllocated(g_SuppConfig.clientcert);
		g_SuppConfig.clientcert = SupAgent_ExtractString(buffer);

		FreeIfAllocated(eap_ctx.eap_config.client_cert);
		eap_ctx.eap_config.client_cert = (u8*)SupAgent_ExtractString(buffer);
		Sup_PrintTrace((char*)eap_ctx.eap_config.client_cert, "Client cert", prefix);
		break;
	case SUP_OPCODE_SET_TLS_CLIENT_CERT2:
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY:
		FreeIfAllocated(g_SuppConfig.privatekey);
		g_SuppConfig.privatekey = SupAgent_ExtractString(buffer);

		FreeIfAllocated(eap_ctx.eap_config.private_key);
		eap_ctx.eap_config.private_key = (u8*)SupAgent_ExtractString(buffer);
		Sup_PrintTrace((char*)eap_ctx.eap_config.private_key, "Private key", prefix);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD:
		FreeIfAllocated(g_SuppConfig.privatekeypasswd);
		g_SuppConfig.privatekeypasswd = SupAgent_ExtractString(buffer);

		FreeIfAllocated(eap_ctx.eap_config.private_key_passwd);
		eap_ctx.eap_config.private_key_passwd = (u8*)SupAgent_ExtractString(buffer);
		Sup_PrintTrace((char*)eap_ctx.eap_config.private_key_passwd, "Private key password", prefix);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY2:
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD2:
		break;
	case SUP_OPCODE_SET_PIN:
		break;
	case SUP_OPCODE_SET_PIN_MAX_SIZE:
    	    break;
	case SUP_OPCODE_SET_TLS_MAX_SIZE:
		break;
	default:
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR, ("Unknown message of type SUP_OPCODE_SET arrived to MessageHandler"));
		break;
	}
#endif

}

// AppSrv Agent Interface - MessagesHandler
void Supplicant_MessagesHandler(L5_CONNECTION Conn,
								L5_TARGET_ID nOriginID,

								UINT32 dwSentMessageID,
								void  *pvSentBuffer,
								UINT32 cbSentBufferSize,

								UINT32 *pdwResponseMessageID,
								void  *pvResponseBuffer,
								UINT32 *cbResponseBufferSize,

								void *pvUserContext,
								void *pvReserved )
{
	wmx_Status_t status;
	pSUP_MESSAGE_HEADER msg;
	char opCodeStr[MAX_SUP_STR_LEN] ="";
	
	UNREFERENCED_PARAMETER(pvReserved);
	UNREFERENCED_PARAMETER(pvUserContext);
	UNREFERENCED_PARAMETER(cbResponseBufferSize);
	UNREFERENCED_PARAMETER(pvResponseBuffer);
	UNREFERENCED_PARAMETER(Conn);

	msg = (pSUP_MESSAGE_HEADER)pvSentBuffer;
	switch (dwSentMessageID)
	{
		case SUP_OPCODE_REGISTER_INDICATION:
			status = SupAgent_RegisterIndicator(nOriginID, *(UINT32*)pvSentBuffer);
			if (NULL != pdwResponseMessageID)
			{
				*pdwResponseMessageID = status;
			}
			break;
		case SUP_OPCODE_UNREGISTER_INDICATION:
			status = SupAgent_UnRegisterIndicator(nOriginID, *(UINT32*)pvSentBuffer);
			if (NULL != pdwResponseMessageID)
			{
				*pdwResponseMessageID = status;
			}
			break;
		case SUP_OPCODE_ENABLE:
#if !defined(WPA_OPEN_SOURCE)
			g_SuppConfig.isEnabled = TRUE;
#endif
			*pdwResponseMessageID = WMX_ST_OK;
			break;
		case SUP_OPCODE_DISABLE:
#if !defined(WPA_OPEN_SOURCE)
			g_SuppConfig.isEnabled = FALSE;
#endif
			*pdwResponseMessageID = WMX_ST_OK;
			break;		
		case SUP_OPCODE_SET:
			wmxNds_SupOpCodeToStr(msg->opcode, opCodeStr, MAX_SUP_STR_LEN - 1);
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: SET request received - %s", opCodeStr);
			switch (msg->opcode)
			{
				case SUP_OPCODE_SET_IDENTITY:
				case SUP_OPCODE_SET_ANONYMOUS_IDENTITY:
				case SUP_OPCODE_SET_PASSWORD:
				//case SUP_OPCODE_SET_NEW_PASSWORD:
				case SUP_OPCODE_SET_EAP_METHOD:
				case SUP_OPCODE_SET_PHASE2_METHOD:
				case SUP_OPCODE_SET_TLS_CA_CERT:					
				case SUP_OPCODE_SET_TLS_CA_CERT2:					
				case SUP_OPCODE_SET_TLS_CLIENT_CERT:					
				case SUP_OPCODE_SET_TLS_CLIENT_CERT2:					
				case SUP_OPCODE_SET_TLS_PRIVATE_KEY:					
				case SUP_OPCODE_SET_TLS_PRIVATE_KEY2:					
				case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD:					
				//case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD2:
				case SUP_OPCODE_SET_PIN:
				//case SUP_OPCODE_SET_PIN_MAX_SIZE:
				case SUP_OPCODE_SET_TLS_MAX_SIZE:
				{				
					pUtils->tpfnPostRequest(	
						MEDIUM, msg->opcode, pvSentBuffer, cbSentBufferSize, &Supplicant_InternalHandler );
					if (NULL != pdwResponseMessageID)
					{
						*pdwResponseMessageID = WMX_ST_OK;
					}
					break;
				}
				default:
					TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown SET message received");
					if (NULL != pdwResponseMessageID)
					{
					*pdwResponseMessageID = WMX_ST_FAIL;
					}
					break;
				}
				break;
		case SUP_OPCODE_RESET:
			// Perform the following actions:
			// Erase/Free previous credentials that might have been set in the config context before.
			// Restart the supplicant with empty context to be assigned later on. (Will erase the supplicant context itself)
			{
				TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO, "Supplicant: SUP_OPCODE_RESET received");
#if !defined(WPA_OPEN_SOURCE)
				FinalizeSuppConfig();
				SupAgent_ResetSupplicant();
#endif
				*pdwResponseMessageID = WMX_ST_OK;
				break;
			}
		default:
			TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Unknown message received");
			if (NULL != pdwResponseMessageID)
			{
				*pdwResponseMessageID = WMX_ST_FAIL;
			}
			break;
	}
}

void Sup_PrintTrace(char *sourceStr, char *caption, char *prefix)
{
	#define MAX_TEMP_STR_LEN 1024

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: %s - %s = %s", prefix, caption, sourceStr);
}

void ReassignSupConfig()
{
#if !defined(WPA_OPEN_SOURCE)
	char prefix[MAX_SUP_STR_LEN] ="Reassign configuration";

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: Reassign configuration - start");
	if (g_SuppConfig.identity)
	{
		Sup_PrintTrace(g_SuppConfig.identity,"Identity", prefix);
		swc_set_identity_ptr(g_SuppData.sc, g_SuppConfig.identity);
	}
	if (g_SuppConfig.anonidentity)
	{
		Sup_PrintTrace(g_SuppConfig.anonidentity,"OuterIdentity", prefix);		
		swc_set_anonymous_identity_ptr(g_SuppData.sc, g_SuppConfig.anonidentity);
	}
	if (g_SuppConfig.password)
	{
		Sup_PrintTrace(g_SuppConfig.password,"Password", prefix);		
		swc_set_password_ptr(g_SuppData.sc, g_SuppConfig.password);
	}
	if (g_SuppConfig.eapmethod)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: %s - EapMethod = %d", prefix, g_SuppConfig.eapmethod);
		swc_set_eap_method_ptr(g_SuppData.sc, g_SuppConfig.eapmethod);
	}
	if (g_SuppConfig.phase2)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: %s - Phase2 method = %d", prefix, g_SuppConfig.phase2);
		swc_set_phase2_method_ptr(g_SuppData.sc, g_SuppConfig.phase2);
	}
	if (g_SuppConfig.cacert)
	{
		Sup_PrintTrace(g_SuppConfig.cacert,"CA cert", prefix);
		swc_set_tls_ca_cert_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.cacert, (int)OSAL_strnlen(g_SuppConfig.cacert, MAX_STRING_VALIDATE) + 1, 0);			
	}
	if (g_SuppConfig.cacert2)
	{
		Sup_PrintTrace(g_SuppConfig.cacert2,"CA cert - phase2", prefix);		
		swc_set_tls_ca_cert2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.cacert2, (int)OSAL_strnlen(g_SuppConfig.cacert2, MAX_STRING_VALIDATE) + 1, 0);			
	}
	if (g_SuppConfig.clientcert)
	{
		Sup_PrintTrace(g_SuppConfig.clientcert,"Client cert", prefix);		
		swc_set_tls_client_cert_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.clientcert, (int)OSAL_strnlen(g_SuppConfig.clientcert, MAX_STRING_VALIDATE) + 1, 0);
	}
	if (g_SuppConfig.clientcert2)
	{
		Sup_PrintTrace(g_SuppConfig.clientcert2,"Client cert - phase2", prefix);
		swc_set_tls_client_cert2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.clientcert2, (int)OSAL_strnlen(g_SuppConfig.clientcert2, MAX_STRING_VALIDATE) + 1, 0);
	}
	if (g_SuppConfig.privatekey)
	{
		Sup_PrintTrace(g_SuppConfig.privatekey,"Private key", prefix);		
		swc_set_tls_private_key_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.privatekey, (int)OSAL_strnlen(g_SuppConfig.privatekey, MAX_STRING_VALIDATE) + 1, 0);
	}
	if (g_SuppConfig.privatekeypasswd)
	{
		Sup_PrintTrace(g_SuppConfig.privatekeypasswd,"Private key password", prefix);		
		swc_set_tls_private_key_passwd_ptr(g_SuppData.sc, (char *)g_SuppConfig.privatekeypasswd);
	}
	if (g_SuppConfig.privatekey2)
	{
		Sup_PrintTrace(g_SuppConfig.privatekey2,"Private key password - phase2", prefix);		
		swc_set_tls_private_key2_ptr(g_SuppData.sc, (unsigned char *)g_SuppConfig.privatekey2, (int)OSAL_strnlen(g_SuppConfig.privatekey2, MAX_STRING_VALIDATE) + 1, 0);
	}
	if (g_SuppConfig.simpin)
	{
		Sup_PrintTrace(g_SuppConfig.simpin,"PIN", prefix);		
		swc_set_pin_ptr(g_SuppData.sc, g_SuppConfig.simpin);
	}
#else

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: Reassign configuration - start");
	if (g_SuppConfig.identity)
	{
		FreeIfAllocated(eap_ctx.eap_config.identity);
		eap_ctx.eap_config.identity = (u8*)SupAgent_ExtractString(g_SuppConfig.identity);
		eap_ctx.eap_config.identity_len = os_strlen((const char*)eap_ctx.eap_config.identity);
	}
	if (g_SuppConfig.anonidentity)
	{
	
		FreeIfAllocated(eap_ctx.eap_config.anonymous_identity);
		eap_ctx.eap_config.anonymous_identity = (u8*)SupAgent_ExtractString(g_SuppConfig.anonidentity);
		eap_ctx.eap_config.anonymous_identity_len =
				os_strlen((const char*)eap_ctx.eap_config.anonymous_identity);
	}
	if (g_SuppConfig.password)
	{

		FreeIfAllocated(eap_ctx.eap_config.password);
		eap_ctx.eap_config.password 	= (u8*)SupAgent_ExtractString(g_SuppConfig.password);
		eap_ctx.eap_config.password_len = os_strlen((const char*)eap_ctx.eap_config.password);
	}
	if (g_SuppConfig.eapmethod)
	{
		peer_set_method1(g_SuppConfig.eapmethod);
	}
	if (g_SuppConfig.cacert)
	{

		FreeIfAllocated(eap_ctx.eap_config.ca_cert);
		eap_ctx.eap_config.ca_cert = (u8*)SupAgent_ExtractString(g_SuppConfig.cacert);
	
	}
	if (g_SuppConfig.clientcert)
	{
		FreeIfAllocated(eap_ctx.eap_config.client_cert);
		eap_ctx.eap_config.client_cert = (u8*)SupAgent_ExtractString(g_SuppConfig.clientcert);
	}
	if (g_SuppConfig.privatekey)
	{
		FreeIfAllocated(eap_ctx.eap_config.private_key);
		eap_ctx.eap_config.private_key = (u8*)SupAgent_ExtractString(g_SuppConfig.privatekey);
	}
	if (g_SuppConfig.privatekeypasswd)
	{
		FreeIfAllocated(eap_ctx.eap_config.private_key_passwd);
		eap_ctx.eap_config.private_key_passwd = (u8*)SupAgent_ExtractString(g_SuppConfig.privatekeypasswd);
	}

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE,"Supplicant: Reassign configuration - end");
#endif
}

void SupAgent_ResetSupplicant()
{
#if !defined(WPA_OPEN_SOURCE)
	if (!g_SuppConfig.isEnabled)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_WARNING,"Supplicant: Reset - Supplicant disabled. Request discarded");
		return;
	}
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset - start");
	ResetSupplicantLibrary();	
	InitSupplicantLibrary();
	ReassignSupConfig();
	g_SuppConfig.isValid = TRUE;

	// Reassigning new TTLS Identity in TTLS case. Otherwise - Original TLS Identity will be assigned
	//SupAgent_RefreshIdentity();
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Reset - end");
#else
	if (SupplicantLoaded == TRUE ){
	ResetSupplicantLibrary();
	InitSupplicantLibrary();
	ReassignSupConfig();
	}
#endif
}

void wmxNds_SupOpCodeToStr(SUP_AGENT_CRED_OPCODE supOpCode, char *str, int strLength)
{
	switch (supOpCode)
	{
	case SUP_OPCODE_SET_IDENTITY:
		OSAL_strncpy_s(str, strLength,"Set identity", strLength);
		break;
	case SUP_OPCODE_SET_ANONYMOUS_IDENTITY:
		OSAL_strncpy_s(str, strLength,"Set outer identity", strLength);
		break;
	case SUP_OPCODE_SET_PASSWORD:
		OSAL_strncpy_s(str, strLength,"Set password", strLength);
		break;
	case SUP_OPCODE_SET_NEW_PASSWORD:
		OSAL_strncpy_s(str, strLength,"set new password", strLength);
		break;
	case SUP_OPCODE_SET_EAP_METHOD:
		OSAL_strncpy_s(str, strLength,"Set EAP method", strLength);
		break;
	case SUP_OPCODE_SET_PHASE2_METHOD:
		OSAL_strncpy_s(str, strLength,"Set EAP method - phase 2", strLength);
		break;
	case SUP_OPCODE_SET_TLS_CA_CERT:
		OSAL_strncpy_s(str, strLength,"Set CA cert", strLength);
		break;
	case SUP_OPCODE_SET_TLS_CA_CERT2:
		OSAL_strncpy_s(str, strLength,"Set CA cert - phase 2", strLength);
		break;
	case SUP_OPCODE_SET_TLS_CLIENT_CERT:
		OSAL_strncpy_s(str, strLength,"Set client cert", strLength);
		break;
	case SUP_OPCODE_SET_TLS_CLIENT_CERT2:
		OSAL_strncpy_s(str, strLength,"Set client cert - phase 2", strLength);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY:
		OSAL_strncpy_s(str, strLength,"Set private key", strLength);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY2:
		OSAL_strncpy_s(str, strLength,"Set private key - phase 2", strLength);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD:
		OSAL_strncpy_s(str, strLength,"Set private key password", strLength);
		break;
	case SUP_OPCODE_SET_TLS_PRIVATE_KEY_PASSWD2:
		OSAL_strncpy_s(str, strLength,"Set private key password - phase 2", strLength);
		break;
	case SUP_OPCODE_SET_PIN:
		OSAL_strncpy_s(str, strLength,"Set PIN", strLength);
		break;
	case SUP_OPCODE_SET_PIN_MAX_SIZE:
		OSAL_strncpy_s(str, strLength,"Set PIN max size", strLength);
		break;
	case SUP_OPCODE_SET_TLS_MAX_SIZE:
		OSAL_strncpy_s(str, strLength,"Set TLS max size", strLength);
		break;
	case SUP_OPCODE_IND_EVENT:
	case SUP_OPCODE_ERROR:
	default:
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,
		      "Unhandled supplicant opcode %d\n", supOpCode);
	}
}


EXTERN_C EXPORT void SupplicantAgent_Finalize()
{	
	wmxSup_FinalizeAgent();
	if(pFuncs != NULL)
	{
		pFuncs->pfnDisconnect( supplicantConnection );
		pFuncs = NULL;
	}
	FinalizeSupplicantLibrary();
	CleanIndicatorsList(&indicatorSubscribersList);

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Agent shutdown Succeeded");
}

EXTERN_C EXPORT BOOL SupplicantAgent_Stop()
{
	SupAgent_UnRegisterCallbacksOnWrapper();
	EmptyIndicatorsList(&indicatorSubscribersList);
	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Agent stopped");
	
	return TRUE;
}

EXTERN_C EXPORT BOOL SupplicantAgent_Start()
{
	BOOL initSt = TRUE;
	wmx_Status_t status;
	
	// Register Callbacks
	status = SupAgent_RegisterCallbacksOnWrapper();
	if ( status != WMX_ST_OK )
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Can't register callbacks");		
		initSt = FALSE;
	}
	else
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Agent started. Target ID=%d", L5_TARGET_SUPPLICANT);
	}

	return initSt;
}

EXTERN_C EXPORT APPSRV_INIT_ST SupplicantAgent_Initialize(tL5DispatcherFunctions *L5disp, tUtilityFunctions *UtilFn)
{	
	L5_RESULT l5Result;
	wmx_Status_t status;

	APPSRV_INIT_ST initSt = INIT_SUCCESS;
	pFuncs = L5disp;
	pUtils = UtilFn;
	

// to finding out the libeap.so or ds supplicant
	char str[MAX_PATH];
	L4Configurations_getSupplicantLibName(str);
#if !defined(WPA_OPEN_SOURCE)
	status = LoadSupplicantLibrary(); // Load DS Supplicant.dll
	if (status != WMX_ST_OK)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Can't load Supplicant library");
		if( WMX_ST_CONFIG_ERROR == status )
		{
			initSt = INIT_CONFIG_FAIL;			
		}
		else
		{		
			initSt = INIT_FAIL;
		}
		goto Finalize;
	}
#endif
	OSAL_strcpy_s((char*)g_TargetBuf, L4_MSG_MAX_LENGTH, "This is sup test\n");

	AllocIndicatorsList(&indicatorSubscribersList);
#if !defined(WPA_OPEN_SOURCE)
	memset(&g_SuppConfig, 0, sizeof(g_SuppConfig));
	status = InitSupplicantLibrary(); // Init DS Supplicant.dll
	if (status != WMX_ST_OK)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Can't init Supplicant library");
		FinalizeSupplicantLibrary();
		CleanIndicatorsList(&indicatorSubscribersList);
		initSt = INIT_FAIL;
		goto Finalize;
	}	
#endif
	// Init L5 connection and methods
	/*
	pFuncs = L5_DISPATCHER_GetServiceDispatcherFunctions();
	if (NULL == pFuncs)
	{
	FinalizeSupplicantLibrary();
	CleanIndicatorsList(&indicatorSubscribersList);
	return INIT_FAIL;
	}*/

	l5Result = pFuncs->pfnConnectEx(/*	NULL, 
									0, */
									L5_TARGET_SUPPLICANT, 
									&Supplicant_MessagesHandler, 
									&Supplicant_EventHandler,  
									NULL, 
									THREAD_ID_DEFAULT,
									&supplicantConnection );

	if ((L5_RESULT_OK != l5Result) || (NULL == supplicantConnection))
	{
		FinalizeSupplicantLibrary();
		CleanIndicatorsList(&indicatorSubscribersList);
		initSt = INIT_FAIL;
		goto Finalize;
	}

	// Init Wrapper
	status = wmxSup_InitAgent();
	if ( status != WMX_ST_OK )
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Can't init wrappers");
		initSt = INIT_FAIL;
	}

Finalize:
	if (initSt == INIT_SUCCESS)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_INFO,"Supplicant: Agent initialization succeeded. Target ID=%d", L5_TARGET_SUPPLICANT);
	}
	else
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR,"Supplicant: Agent initialization failed");
	}
	return initSt;
}
//*******************************************
// AppSrv Agent Interface - end
//*******************************************
#if defined(WPA_OPEN_SOURCE)

wmx_Status_t DelayLoadSupplicant()
{
	wmx_Status_t status = WMX_ST_OK;
	status = InitSupplicantLibrary(); // Init the open source supplicant
	if (status != WMX_ST_OK)
	{
		TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_ERR, ("Can't init Supplicant library"));
		FinalizeSupplicantLibrary();
		return status;
	}
	

	TRACE(TR_MOD_SUPPLICANT_AGENT, TR_SEV_NOTICE, "SupplicantAgent_Initialize Succeeded. Target ID=%d", L5_TARGET_SUPPLICANT);

	return status;

}
#endif