summaryrefslogtreecommitdiffstats
path: root/src/eap_peer/eap_proxy_qmi.c
blob: e828129ff47d0b0119e5a83757f1fe5d94c19a02 (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
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
/*--------------------------------------------------------------------------
Copyright (c) 2013-2017, The Linux Foundation. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
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 "includes.h"
#include "common.h"

#ifdef CONFIG_EAP_PROXY
#include "qmi_client.h"
#include "eap_proxy.h"
#include "eap_proxy_qmi.h"
#include "qmi_client.h"
#include "qmi_idl_lib.h"
#include "authentication_service_v01.h"
#include "user_identity_module_v01.h"
#include "eap_config.h"
#include "common/wpa_ctrl.h"
#if defined(ANDROID)
#include <cutils/properties.h>
#ifdef CONFIG_EAP_PROXY_MDM_DETECT
#include "mdm_detect.h"
#endif /* CONFIG_EAP_PROXY_MDM_DETECT */
#if defined(__BIONIC_FORTIFY)
#include <sys/system_properties.h>
#endif
#endif
#include <pthread.h>
#include <sys/syscall.h>
#include <sys/types.h>

#define IMSI_LENGTH 15
#define WPA_UIM_QMI_EVENT_MASK_CARD_STATUS        \
                                        (1 << QMI_UIM_EVENT_CARD_STATUS_BIT_V01)
#define WPA_UIM_QMI_EVENT_READ_TRANSPARENT_REQ    \
                                        (1 << QMI_UIM_READ_TRANSPARENT_REQ_V01)

/* Default timeout (in milli-seconds) for synchronous QMI message */
#define WPA_UIM_QMI_DEFAULT_TIMEOUT               5000

#define EAP_PROXY_PROPERTY_BASEBAND     "ro.baseband"
#ifdef CONFIG_EAP_PROXY_MSM8994_TARGET
#define EAP_PROXY_TARGET_PLATFORM       "ro.board.platform"
#endif /* CONFIG_EAP_PROXY_MSM8994_TARGET */
#if defined(__BIONIC_FORTIFY)
#define EAP_PROXY_PROPERTY_BASEBAND_SIZE   PROP_VALUE_MAX
#else
#define EAP_PROXY_PROPERTY_BASEBAND_SIZE   10
#endif
#define EAP_PROXY_BASEBAND_VALUE_MSM       "msm"
#define EAP_PROXY_BASEBAND_VALUE_APQ       "apq"
#define EAP_PROXY_BASEBAND_VALUE_SVLTE1    "svlte1"
#define EAP_PROXY_BASEBAND_VALUE_SVLTE2A   "svlte2a"
#define EAP_PROXY_BASEBAND_VALUE_SGLTE     "sglte"
#define EAP_PROXY_BASEBAND_VALUE_CSFB      "csfb"
#define EAP_PROXY_BASEBAND_VALUE_MDMUSB    "mdm"
#ifdef CONFIG_EAP_PROXY_MSM8994_TARGET
#define EAP_PROXY_TARGET_PLATFORM_MSM8994  "msm8994"
#endif /* CONFIG_EAP_PROXY_MSM8994_TARGET */
#define EAP_PROXY_TARGET_FUSION4_5_PCIE    "fusion4_5_pcie"
#define EAP_PROXY_BASEBAND_VALUE_UNDEFINED "undefined"

#ifndef ANDROID
#ifdef SYS_gettid
static inline pid_t gettid(void)
{
        return syscall(SYS_gettid);
}
#else
static inline pid_t gettid(void)
{
        return -1;
}
#endif
#endif

// Lock to serialize concurrent calls to eloop_register_timeout.
static pthread_mutex_t eloop_lock = PTHREAD_MUTEX_INITIALIZER;

static void eap_proxy_qmi_deinit(struct eap_proxy_sm *eap_proxy);
static void eap_proxy_eapol_sm_set_bool(struct eap_proxy_sm *sm,
                         enum eapol_bool_var var, Boolean value);
static Boolean eap_proxy_eapol_sm_get_bool(struct eap_proxy_sm *sm,
                                        enum eapol_bool_var var);
static void eap_proxy_post_init(struct eap_proxy_sm *eap_proxy);

/* Call-back function to process an authenticationr result indication from
 * QMI EAP service */
static void handle_qmi_eap_ind(qmi_client_type user_handle,
                unsigned int msg_id,
                void* ind_buf,
                unsigned int ind_buf_len,
                void* ind_cb_data);

static u8 *eap_proxy_getKey(struct eap_proxy_sm *eap_proxy);
static u8 * eap_proxy_get_keys(struct eap_proxy_sm *sm);
static enum eap_proxy_status eap_proxy_qmi_response_wait(struct eap_proxy_sm *eap_proxy);
static int eap_proxy_is_state_changed(struct eap_proxy_sm *sm);
static enum eap_proxy_status eap_proxy_process(struct eap_proxy_sm  *eap_proxy,
                                        u8 *eapReqData, int eapReqDataLen, struct eap_sm *eap_sm);
static char bin_to_hexchar(u8 ch);

static void wpa_qmi_client_indication_cb
(
        qmi_client_type                user_handle,
        unsigned int                   msg_id,
        void                          *ind_buf_ptr,
        unsigned int                   ind_buf_len,
        void                          *ind_cb_data
);
static void dump_buff(u8 *buff, int len);
#ifdef CONFIG_CTRL_IFACE
static const char *eap_proxy_sm_state_txt(int state);
#endif /* CONFIG_CTRL_IFACE */
static Boolean eap_proxy_build_identity(struct eap_proxy_sm *eap_proxy, u8 id,
                                                 struct eap_sm *eap_sm);

#ifdef SIM_AKA_IDENTITY_IMSI
static char *imsi;
static int imsi_len_g = 0;
static int card_mnc_len = -1;
#ifdef CONFIG_EAP_PROXY_DUAL_SIM
static unsigned int slot = 0;
static unsigned int session_type;
#endif /* CONFIG_EAP_PROXY_DUAL_SIM */

static Boolean wpa_qmi_register_events(int sim_num, wpa_uim_struct_type *wpa_uim);
static Boolean wpa_qmi_read_card_imsi(int sim_num, wpa_uim_struct_type *wpa_uim);
static Boolean wpa_qmi_read_card_status(int sim_num, wpa_uim_struct_type *wpa_uim);
static Boolean wpa_qmi_register_auth_inds(int sim_num, struct eap_proxy_sm *eap_proxy);

#endif
#define EAP_SUB_TYPE_SIM_START     0x0a
#define EAP_SUB_TYPE_AKA_IDENTITY  0x05
#define EAP_RESP_TYPE_NAK             3

// Define static global eap_proxy
#define MAX_EAP_PROXY_INTERFACE 4
static struct eap_proxy_sm eap_proxy_gb[MAX_EAP_PROXY_INTERFACE];

static struct eap_proxy_sm * get_next_eap_proxy()
{
	for (int i = 0; i < MAX_EAP_PROXY_INTERFACE; i++) {
		if (eap_proxy_gb[i].initialized)
			continue;
		return &eap_proxy_gb[i];
	}
	wpa_printf(MSG_ERROR, "eap_proxy: All interfaces are in use. max=%d", MAX_EAP_PROXY_INTERFACE);
	return NULL;
}

static void eap_proxy_clear_qmi_cb_data(struct qmi_cb_data *data) {
    if (data == NULL)
        return;

    if (data->buflen > 0)
        os_free(data->buf);

    dl_list_del(&data->list);
    os_free(data);
}

static struct qmi_cb_data* eap_proxy_prepare_qmi_cb_data(
                 qmi_client_type user_handle, unsigned int msg_id,
                 void *ind_buf_ptr, unsigned int ind_buf_len,
                 void *ind_cb_data) {

        struct qmi_cb_data *cb_data;

        cb_data = os_zalloc(sizeof(*cb_data));
        if (cb_data == NULL) {
                wpa_printf(MSG_ERROR, "eap_proxy: failed to allocate memory");
                return NULL;
        }

        if (ind_buf_len > 0) {
            cb_data->buf = os_zalloc(ind_buf_len);
            if (cb_data->buf == NULL) {
                wpa_printf(MSG_ERROR, "eap_proxy: failed to allocate memory");
                os_free(cb_data);
                return NULL;
            }
            os_memcpy(cb_data->buf, ind_buf_ptr, ind_buf_len);
        }

        cb_data->userHandle = user_handle;
        cb_data->msg_id = msg_id;
        cb_data->buflen = ind_buf_len;
        cb_data->userdata = ind_cb_data;

        return cb_data;
}

#ifdef SIM_AKA_IDENTITY_IMSI
static void __wpa_qmi_client_indication_cb(void *eloop_ctx, void *timeout_ctx)
{
	u32 decoded_payload_len = 0;
	qmi_client_error_type qmi_err = QMI_NO_ERR;
	void * decoded_payload = NULL;
	uim_status_change_ind_msg_v01* status_change_ind_ptr = NULL;
	u32 i, card_info_len = 0;

	struct qmi_cb_data *cb_data = (struct qmi_cb_data *)eloop_ctx;
	struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)cb_data->userdata;

	wpa_printf(MSG_ERROR, "eap_proxy: %s: msg_id=0x%08x", __func__, cb_data->msg_id);

	if (cb_data->userHandle == NULL) {
		wpa_printf(MSG_ERROR, "eap_proxy: qmi_client_type missing in callback");
		goto fail;
	}

	if (eap_proxy == NULL || !eap_proxy->initialized) {
		wpa_printf(MSG_ERROR, "eap_proxy: not initialized, discard client indiataion");
		goto fail;
	}

	if (cb_data->buf == NULL) {
		wpa_printf(MSG_ERROR, "eap_proxy: indication buffer NULL, discard client indiataion");
		goto fail;
	}

	qmi_idl_get_message_c_struct_len(uim_get_service_object_v01(),
					 QMI_IDL_INDICATION, cb_data->msg_id,
					 &decoded_payload_len);

	if(!decoded_payload_len) {
		wpa_printf(MSG_ERROR, "eap_proxy: cann't decode payload, discard client indiataion");
		goto fail;
	}

	decoded_payload = os_zalloc(decoded_payload_len);
	if (decoded_payload == NULL) {
		wpa_printf(MSG_ERROR, "eap_proxy: failed to allocate memory");
		goto fail;
	}

	qmi_err = qmi_client_message_decode(cb_data->userHandle,
					    QMI_IDL_INDICATION, cb_data->msg_id,
					    cb_data->buf, cb_data->buflen,
					    decoded_payload, decoded_payload_len);

	if (qmi_err == QMI_NO_ERR) {
		switch (cb_data->msg_id) {
		case QMI_UIM_STATUS_CHANGE_IND_V01:
			status_change_ind_ptr = (uim_status_change_ind_msg_v01*)decoded_payload;
			if (!status_change_ind_ptr->card_status_valid)
				goto fail;

			card_info_len = status_change_ind_ptr->card_status.card_info_len;
			for (i = 0; i < card_info_len; i++) {
				wpa_printf(MSG_ERROR, "eap_proxy: card_state=%u error_code=%u",
					   status_change_ind_ptr->card_status.card_info[i].card_state,
					   status_change_ind_ptr->card_status.card_info[i].error_code);
				if (UIM_CARD_STATE_ABSENT_V01 == status_change_ind_ptr->card_status.card_info[i].card_state ||
				    (UIM_CARD_STATE_ERROR_V01 == status_change_ind_ptr->card_status.card_info[i].card_state &&
				     UIM_CARD_ERROR_CODE_POSSIBLY_REMOVED_V01 == status_change_ind_ptr->card_status.card_info[i].error_code)) {
					wpa_printf(MSG_ERROR, "eap_proxy: %s SIM card removed. flush pmksa entries.", __func__);
					eap_proxy->eapol_cb->eap_proxy_notify_sim_status(eap_proxy->ctx, SIM_STATE_ERROR);
					break; /* only one flush will do */
				}
			}
			break;
		default:
			wpa_printf(MSG_ERROR, "eap_proxy: Unknown QMI Indicaiton %u", cb_data->msg_id);
			break;
		}
	}
fail:
	if (decoded_payload != NULL)
		os_free(decoded_payload);

	eap_proxy_clear_qmi_cb_data(cb_data);
	return;
}

static void wpa_qmi_client_indication_cb
(
        qmi_client_type                user_handle,
        unsigned int                   msg_id,
        void                          *ind_buf_ptr,
        unsigned int                   ind_buf_len,
        void                          *ind_cb_data
)
{
        struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)ind_cb_data;
        struct qmi_cb_data *cb_data = NULL;

        if (eap_proxy == NULL)
                return;

        pthread_mutex_lock(&eloop_lock);       // Lock
        wpa_printf(MSG_ERROR, "eap_proxy: %s eap_proxy=%p", __func__, eap_proxy);
        cb_data = eap_proxy_prepare_qmi_cb_data(user_handle, msg_id, ind_buf_ptr,
                                                ind_buf_len, ind_cb_data);
        if (cb_data == NULL) {
                pthread_mutex_unlock(&eloop_lock);      // Unlock
                return;
        }

        dl_list_add(&eap_proxy->callback, &cb_data->list);
        eloop_register_timeout(0, 0, __wpa_qmi_client_indication_cb, cb_data, NULL);
        pthread_mutex_unlock(&eloop_lock);      // Unlock

}

static Boolean wpa_qmi_register_auth_inds(int sim_num, struct eap_proxy_sm *eap_proxy)
{
        qmi_client_error_type qmi_err_code = QMI_NO_ERR;
        auth_indication_register_resp_msg_v01  event_resp_msg;
        auth_indication_register_req_msg_v01 event_reg_params;

        /* Register for events first */
        os_memset(&event_reg_params, 0, sizeof(auth_indication_register_req_msg_v01));
        os_memset(&event_resp_msg, 0, sizeof(auth_indication_register_resp_msg_v01));

        event_reg_params.report_eap_notification_code_valid = TRUE;
        event_reg_params.report_eap_notification_code = 1;

        wpa_printf(MSG_ERROR, "registering for notification codes\n");
        qmi_err_code = qmi_client_send_msg_sync(
                        eap_proxy->qmi_auth_svc_client_ptr[sim_num],
                        QMI_AUTH_INDICATION_REGISTER_REQ_V01,
                        (void *) &event_reg_params,
                        sizeof(auth_indication_register_req_msg_v01),
                        (void*) &event_resp_msg,
                        sizeof(auth_indication_register_resp_msg_v01),
                        WPA_UIM_QMI_DEFAULT_TIMEOUT);

        if (qmi_err_code != QMI_NO_ERR ||
            (event_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01 &&
             event_resp_msg.resp.error != QMI_ERR_NO_EFFECT_V01)) {
                wpa_printf(MSG_ERROR,"QMI-ERROR Error for "
                           "QMI_AUTH_INDICATION_REGISTER_REQ_V01, qmi_err_code=%d"
                           "Error=%d\n", qmi_err_code,
                            event_resp_msg.resp.error);
                return FALSE;
        }

        return TRUE;

}

static Boolean wpa_qmi_register_events(int sim_num, wpa_uim_struct_type *wpa_uim)
{
        qmi_client_error_type               qmi_err_code      = 0;
        uim_event_reg_resp_msg_v01          event_resp_msg;
        uim_event_reg_req_msg_v01           event_reg_params;

        /* Register for events first */
        os_memset(&event_reg_params, 0, sizeof(uim_event_reg_req_msg_v01));
        os_memset(&event_resp_msg, 0, sizeof(uim_event_reg_resp_msg_v01));

        event_reg_params.event_mask |= (WPA_UIM_QMI_EVENT_MASK_CARD_STATUS);
        qmi_err_code = qmi_client_send_msg_sync(wpa_uim[sim_num].qmi_uim_svc_client_ptr,
                                                QMI_UIM_EVENT_REG_REQ_V01,
                                                (void *) &event_reg_params,
                                                sizeof(uim_event_reg_req_msg_v01),
                                                (void *) &event_resp_msg,
                                                sizeof(uim_event_reg_resp_msg_v01),
                                                WPA_UIM_QMI_DEFAULT_TIMEOUT);

        wpa_printf(MSG_ERROR, "eap_proxy: QMI_UIM_EVENT_REG_REQ_V01, "
                   "qmi_err_code: 0x%x wpa_uim[%d].qmi_uim_svc_client_ptr =%p"
                   "Error=0x%x", qmi_err_code, sim_num,
                    wpa_uim[sim_num].qmi_uim_svc_client_ptr,
                    event_resp_msg.resp.error);

        if (qmi_err_code != QMI_NO_ERR ||
            (event_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01 &&
             event_resp_msg.resp.error != QMI_ERR_NO_EFFECT_V01)) {
                wpa_printf(MSG_ERROR,"QMI-ERROR Error for "
                           "QMI_UIM_EVENT_REG_REQ_V01, qmi_err_code=%d"
                           "Error=%d\n", qmi_err_code,
                            event_resp_msg.resp.error);
                return FALSE;
        }

        if(event_resp_msg.event_mask_valid)
        {
                wpa_printf(MSG_ERROR, "eap_proxy: event_resp_msg.event=%d,\n",
                           event_resp_msg.event_mask);

        }

        if (wpa_qmi_read_card_status(sim_num, wpa_uim))
                return TRUE;
        else {
                wpa_printf(MSG_ERROR,"eap_proxy: Error while reading SIM card status\n");
                return FALSE;
        }
}

static Boolean wpa_qmi_read_card_status(int sim_num, wpa_uim_struct_type *wpa_uim)
{
        unsigned int                        i = 0, j = 0;
        Boolean                             card_found = FALSE;
        qmi_client_error_type               qmi_err_code      = 0;
        uim_get_card_status_resp_msg_v01   card_status_resp_msg;

        wpa_printf (MSG_ERROR, "eap_proxy: reading card %d values\n", sim_num+1);
        os_memset(&card_status_resp_msg,
                  0,
                  sizeof(uim_get_card_status_resp_msg_v01));
        qmi_err_code = qmi_client_send_msg_sync(wpa_uim[sim_num].qmi_uim_svc_client_ptr,
                                                QMI_UIM_GET_CARD_STATUS_REQ_V01,
                                                NULL,
                                                0,
                                                (void *)&card_status_resp_msg,
                                                sizeof(uim_get_card_status_resp_msg_v01),
                                                WPA_UIM_QMI_DEFAULT_TIMEOUT);

        if (qmi_err_code != QMI_NO_ERR ||
            card_status_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Error for "
                           "QMI_UIM_GET_CARD_STATUS_REQ_V01, qmi_err_code: 0x%x\n "
                           "resp_err = %d \n", qmi_err_code, card_status_resp_msg.resp.error);
                return FALSE;
        }

        /* Updated global card status if needed */
        if (!card_status_resp_msg.card_status_valid ||
            (card_status_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01)) {
                wpa_printf(MSG_ERROR, "eap_proxy: card_status is not valid !\n");
                return FALSE;
        }
        /* Update global in case of new card state or error code */
        i = sim_num;
        if ( i < QMI_UIM_CARDS_MAX_V01 &&
             i < card_status_resp_msg.card_status.card_info_len ) {
                wpa_printf(MSG_ERROR, "eap_proxy: card_info[i].card_state: 0x%x\n",
                        card_status_resp_msg.card_status.card_info[i].card_state);
                wpa_printf(MSG_ERROR, "eap_proxy: card_info[i].error_code: 0x%x\n",
                        card_status_resp_msg.card_status.card_info[i].error_code);

                wpa_uim[sim_num].card_info[i].card_state =
                        card_status_resp_msg.card_status.card_info[i].card_state;

                wpa_uim[sim_num].card_info[i].card_error_code =
                        card_status_resp_msg.card_status.card_info[i].error_code;
#ifdef CONFIG_EAP_PROXY_DUAL_SIM
            do {
                   if (card_status_resp_msg.card_status.index_gw_pri != 0xFFFF) {
                        slot = (card_status_resp_msg.card_status.index_gw_pri & 0xFF00) >> 8;
                        if (slot == i) {
                            session_type = UIM_SESSION_TYPE_PRIMARY_GW_V01;
                            wpa_printf (MSG_ERROR, "eap_proxy: read_card_status:"
                                        " prime slot = %d\n", slot);
                            break;
                        }
                   }
                   if (card_status_resp_msg.card_status.index_gw_sec != 0xFFFF) {
                        slot = (card_status_resp_msg.card_status.index_gw_sec & 0xFF00) >> 8;
                        if (slot == i) {
                            session_type = UIM_SESSION_TYPE_SECONDARY_GW_V01;
                            wpa_printf (MSG_ERROR, "eap_proxy: read_card_status: "
                                        "second slot = %d\n", slot);
                            break;
                        }
                   }
                   wpa_printf (MSG_ERROR, "eap_proxy: read_card_status: Not GW it's 1x\n");
                   return FALSE;
                }while(0);

                if (slot > 1){
                            wpa_printf (MSG_ERROR, "eap_proxy: read_card_status: "
                                        "INVALID slot = %d and i = %d\n", slot, i);
                        return FALSE;
                }
#endif /* CONFIG_EAP_PROXY_DUAL_SIM */

                if (card_status_resp_msg.card_status.card_info[i].card_state ==
                    UIM_CARD_STATE_PRESENT_V01) {
                        for (j = 0 ; j < QMI_UIM_APPS_MAX_V01 ; j++) {
                                wpa_uim[sim_num].card_info[i].app_type = card_status_resp_msg.
                                        card_status.card_info[i].app_info[j].app_type;

                                wpa_uim[sim_num].card_info[i].app_state = card_status_resp_msg.
                                        card_status.card_info[i].app_info[j].app_state;

                                if (((card_status_resp_msg.card_status.card_info[i].
                                     app_info[j].app_type == 1) || (card_status_resp_msg.
                                     card_status.card_info[i].app_info[j].app_type == 2)) &&
                                    (card_status_resp_msg.card_status.card_info[i].app_info[j].
                                     app_state == UIM_APP_STATE_READY_V01)) {
                                        wpa_printf(MSG_ERROR, "eap_proxy: card READY\n");
                                        wpa_printf(MSG_ERROR, "eap_proxy: card_info[i].app_ty"
                                                "pe: 0x%x\n", card_status_resp_msg.card_status.
                                                card_info[i].app_info[j].app_type);
                                        wpa_printf(MSG_ERROR, "eap_proxy: card_info[i].app_sta"
                                                "te : 0x%x\n", card_status_resp_msg.card_status
                                                .card_info[i].app_info[j].app_state);
                                        card_found = TRUE;
                                        break;
                                }
                        }
                }

                if (card_found) {
                        wpa_printf(MSG_ERROR, "eap_proxy: card found for SIM = %d\n", sim_num+1);
                }
        }

        if ((!card_found) || (i == QMI_UIM_CARDS_MAX_V01) ||
                (j == QMI_UIM_APPS_MAX_V01)) {
                wpa_printf(MSG_ERROR, "eap_proxy: SIM/USIM not ready card_found=%d\n",card_found);
                return FALSE;
        }

        wpa_printf(MSG_ERROR, "eap_proxy: SIM/USIM ready\n");
        wpa_uim[sim_num].card_ready_idx = i;

        return TRUE;
} /* wpa_qmi_read_card_status */

static int check_for_3_digit()
{
        int mcc = 0,i =0;
        /*
        -- 3 digits if MCC belongs to this group: 302, 310, 311, 312, 313, 314, 315,
        316, 334, 348 (decimal)
        -- 2 digits in all other cases
        Note: imsi values are hex characters
        */
        int valid_mcc[] = {302, 310, 311, 312, 313, 314, 315, 316, 334, 348};

        mcc = ((imsi[0]-0x30)*100) + ((imsi[1]-0x30)*10) + (imsi[2]-0x30);

        wpa_printf(MSG_ERROR, "mcc from the SIM is %d\n", mcc);
        for(i = 0; i < sizeof(valid_mcc)/sizeof(valid_mcc[0]); i++)
        {
                if(mcc == valid_mcc[i])
                        return 1;
        }
        return 0;
}

static Boolean wpa_qmi_read_card_imsi(int sim_num, wpa_uim_struct_type *wpa_uim)
{
        int                     length;
        unsigned char           *data;
        int                     src = 0, dst = 0;
        Boolean                 card_found = FALSE,
        qmi_status = TRUE;
        qmi_client_error_type               qmi_err_code = 0;
        uim_read_transparent_req_msg_v01   qmi_read_trans_req;
        uim_read_transparent_resp_msg_v01  read_trans_resp;
        card_mnc_len = -1;


        os_memset(&read_trans_resp, 0,
                  sizeof(uim_read_transparent_resp_msg_v01));
        os_memset(&qmi_read_trans_req, 0,
                        sizeof(uim_read_transparent_req_msg_v01));

        qmi_read_trans_req.read_transparent.length = 0;
        qmi_read_trans_req.read_transparent.offset = 0;
        qmi_read_trans_req.file_id.file_id = 0x6F07;
        qmi_read_trans_req.file_id.path_len = 4;

#ifdef CONFIG_EAP_PROXY_DUAL_SIM
        wpa_printf (MSG_ERROR, "eap_proxy: read_card_imsi: session_type = %d\n", session_type);
        qmi_read_trans_req.session_information.session_type = session_type;
#else
        qmi_read_trans_req.session_information.session_type =
                                UIM_SESSION_TYPE_PRIMARY_GW_V01;
#endif /* CONFIG_EAP_PROXY_DUAL_SIM */
        qmi_read_trans_req.session_information.aid_len = 0;

        /* For USIM*/
        if ((wpa_uim[sim_num].card_info[wpa_uim[sim_num].card_ready_idx].app_type ==
                UIM_APP_TYPE_USIM_V01)) {
                qmi_read_trans_req.file_id.path[0] = 0x00;
                qmi_read_trans_req.file_id.path[1] = 0x3F;
                qmi_read_trans_req.file_id.path[2] = 0xFF;
                qmi_read_trans_req.file_id.path[3] = 0x7F;

        } else /* For SIM*/
        if ((wpa_uim[sim_num].card_info[wpa_uim[sim_num].card_ready_idx].app_type ==
                UIM_APP_TYPE_SIM_V01)) {
                qmi_read_trans_req.file_id.path[0] = 0x00;
                qmi_read_trans_req.file_id.path[1] = 0x3F;
                qmi_read_trans_req.file_id.path[2] = 0x20;
                qmi_read_trans_req.file_id.path[3] = 0x7F;
        }
        else {
                return FALSE;
        }

        qmi_err_code = qmi_client_send_msg_sync(wpa_uim[sim_num].qmi_uim_svc_client_ptr,
                                        QMI_UIM_READ_TRANSPARENT_REQ_V01,
                                        (void *)&qmi_read_trans_req,
                                        sizeof(uim_read_transparent_req_msg_v01),
                                        (void *) &read_trans_resp,
                                        sizeof(uim_read_transparent_resp_msg_v01),
                                        WPA_UIM_QMI_DEFAULT_TIMEOUT);
        if (QMI_NO_ERR != qmi_err_code ||
            read_trans_resp.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Unable to read IMSI from UIM service;"
                           " error_ret=%d; qmi_err=%d\n", qmi_err_code,
                           read_trans_resp.resp.error);
                qmi_status = FALSE;
        }

        if (QMI_NO_ERR == qmi_err_code) {
                if (read_trans_resp.read_result_valid) {
                        length  =
                                read_trans_resp.read_result.content_len;
                        data    =
                                read_trans_resp.read_result.content;
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI SIM content length = %d\n",
                                        length);

                        /* Received IMSI is in the 3GPP format
                                converting it into ascii string */
                        imsi = os_zalloc(2 * length);
                        if (imsi == NULL) {
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: Couldn't allocate memmory for imsi");
                                return FALSE;
                        }
                        for (src = 1, dst = 0;
                                (src < length) && (dst < (length * 2));
                                src++) {
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI read from SIM = %d src %d\n",
                                        data[src], src);
                                if(data[src] == 0xFF) {
                                        break;
                                }
                                if (src > 1) {
                                        imsi[dst] = bin_to_hexchar(data[src] & 0x0F);
                                        dst++;
                                        wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI dst = %d dst %d\n",
                                        imsi[dst-1], dst);
                                }
                                /* Process upper part of byte for all bytes */
                                imsi[dst] = bin_to_hexchar(data[src] >> 4);
                                dst++;
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI dst = %d dst %d\n",
                                        imsi[dst-1], dst);
                        }
                                imsi_len_g = (data[0]*2 - 1); //dst;
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI first digit = %d read length = %d"
                                        "imsi %20s\n", data[0],imsi_len_g, imsi);
                        } else{
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: IMSI read failure read_result_valid = %d\n",
                                        read_trans_resp.read_result_valid);
                                qmi_status = FALSE;
                        }
                }
        /* READ EF_AD */
        /* if qmi_status is FALSE, UIM read for mnc may not be required - To Do */
        qmi_read_trans_req.file_id.file_id = 0x6FAD;
        qmi_err_code = qmi_client_send_msg_sync(wpa_uim[sim_num].qmi_uim_svc_client_ptr,
                                        QMI_UIM_READ_TRANSPARENT_REQ_V01,
                                        (void *)&qmi_read_trans_req,
                                        sizeof(uim_read_transparent_req_msg_v01),
                                        (void *)&read_trans_resp,
                                        sizeof(uim_read_transparent_resp_msg_v01),
                                        WPA_UIM_QMI_DEFAULT_TIMEOUT);
        if (QMI_NO_ERR != qmi_err_code ||
           read_trans_resp.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Unable to read MNC from UIM service;"
                           " error_ret=%d; qmi_err=%d\n", qmi_err_code,
                           read_trans_resp.resp.error);
                qmi_status = FALSE;
        }
        if (QMI_NO_ERR == qmi_err_code) {
                if (read_trans_resp.read_result_valid) {
                        length  =
                                read_trans_resp.read_result.content_len;
                        data    =
                                read_trans_resp.read_result.content;

                        if(length >= 4)
                                card_mnc_len = 0x0f & data[3];
                        if ((card_mnc_len != 2) && (card_mnc_len != 3)) {
                                if(check_for_3_digit())
                                        card_mnc_len = 3;
                                else
                                        card_mnc_len = 2;
                                wpa_printf(MSG_ERROR, "Failed to get MNC length from (U)SIM "
                                "assuming %d as mcc %s to 3 digit mnc group\n",
                                card_mnc_len, card_mnc_len == 3? "belongs":"not belongs");
                        }
                }
        }


        return qmi_status;
} /* wpa_qmi_read_card_imsi */
#endif /* SIM_AKA_IDENTITY_IMSI */

#ifdef CONFIG_EAP_PROXY_MDM_DETECT
static int eap_modem_compatible(struct dev_info *mdm_detect_info)
{
        char args[EAP_PROXY_PROPERTY_BASEBAND_SIZE] = {0};
        int ret = 0;

        /* Get the hardware property */
        ret = property_get(EAP_PROXY_PROPERTY_BASEBAND, args, "");
        if (ret > EAP_PROXY_PROPERTY_BASEBAND_SIZE){
                wpa_printf(MSG_ERROR,"eap_proxy: property [%s] has size [%d] that exceeds max [%d]",
                           EAP_PROXY_PROPERTY_BASEBAND,
                           ret,
                           EAP_PROXY_PROPERTY_BASEBAND_SIZE);
                return FALSE;
        }

        /* This will check for the type of hardware, and if the hardware type
         * needs external modem, it will check if the modem type is external */
        if(!os_strncmp(EAP_PROXY_BASEBAND_VALUE_APQ, args, 3)) {
                for (ret = 0; ret < mdm_detect_info->num_modems; ret++) {
                        if (mdm_detect_info->mdm_list[ret].type == MDM_TYPE_EXTERNAL) {
                                wpa_printf(MSG_INFO, "eap_proxy: hardware supports external modem");
                                return TRUE;
                        }
                }
                wpa_printf(MSG_ERROR, "eap_proxy: hardware does not support external modem");
                return FALSE;
        }
        return TRUE;
}
#endif /* CONFIG_EAP_PROXY_MDM_DETECT */

static void eap_proxy_notifier_cleanup(struct eap_proxy_sm *eap_proxy)
{
        if (eap_proxy->uim_notifier_handle != NULL)
            qmi_client_release(eap_proxy->uim_notifier_handle);

        if (eap_proxy->auth_notifier_handle != NULL)
            qmi_client_release(eap_proxy->auth_notifier_handle);

        eap_proxy->uim_notifier_handle = NULL;
        eap_proxy->auth_notifier_handle = NULL;
        eap_proxy->notifier_cb_initialized = FALSE;
}

void __eap_proxy_notifier_cb(void *eloop_ctx, void *timeout_ctx)
{
        struct qmi_cb_data *cb_data = (struct qmi_cb_data *)eloop_ctx;
        qmi_client_type user_handle = cb_data->userHandle;
        struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)cb_data->userdata;

        // Done with callback data, let's get rid of it.
        dl_list_del(&cb_data->list);
        os_free(cb_data);

        if (user_handle == NULL || eap_proxy == NULL) {
            wpa_printf(MSG_ERROR, "eap_proxy: qmi_client_type or eap_proxy is missing in callback");
            return;
        }

        if (eap_proxy->proxy_state != EAP_PROXY_DISABLED) {
            wpa_printf(MSG_ERROR, "eap_proxy: %s not in disabled state. ignore", __func__);
            return;
        }

        // Check which module indicates UP indication
        if (eap_proxy->uim_notifier_handle == user_handle)
            eap_proxy->modem_state |= EAP_PROXY_MODEM_UIM_UP;
        else if (eap_proxy->auth_notifier_handle == user_handle)
            eap_proxy->modem_state |= EAP_PROXY_MODEM_AUTH_UP;

        wpa_printf(MSG_DEBUG, "eap_proxy: %s Modem state:%d", __func__, eap_proxy->modem_state);

        if (eap_proxy->modem_state == EAP_PROXY_MODEM_FULL_UP) {
            wpa_printf(MSG_DEBUG, "eap_proxy: %s Modem Available for use.", __func__);
            eap_proxy_post_init(eap_proxy);
        }
}

void eap_proxy_notifier_cb
(
    qmi_client_type                user_handle,
    qmi_idl_service_object_type    service_obj,
    qmi_client_notify_event_type   service_event,
    void                           *notify_cb_data
)
{
        struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)notify_cb_data;
        struct qmi_cb_data *cb_data;

        if (user_handle == NULL || eap_proxy == NULL) {
            wpa_printf(MSG_ERROR, "eap_proxy: qmi_client_type or eap_proxy is missing in callback");
            return;
        }
        wpa_printf(MSG_DEBUG, "eap_proxy: %s eap_proxy=%p", __func__, eap_proxy);
        // Check event type
        switch (service_event) {
        case QMI_CLIENT_SERVICE_COUNT_INC:
            wpa_printf(MSG_DEBUG, "eap_proxy: %s Handle QMI_CLIENT_SERVICE_COUNT_INC event",
                       __func__);
            pthread_mutex_lock(&eloop_lock);       // Lock
            cb_data = os_zalloc(sizeof(*cb_data));
            if (cb_data == NULL) {
                    wpa_printf(MSG_ERROR, "eap_proxy: failed to allocate memory");
                    pthread_mutex_unlock(&eloop_lock); // Unlock
                    return;
            }

            cb_data->userHandle = user_handle;
            cb_data->userdata = notify_cb_data;
            dl_list_add(&eap_proxy->callback, &cb_data->list);
            eloop_register_timeout(0, 0, __eap_proxy_notifier_cb, cb_data, NULL);
            pthread_mutex_unlock(&eloop_lock);      // Unlock
            break;

        case QMI_CLIENT_SERVICE_COUNT_DEC:
            // No Need to release again. SSR (service down) is alreayd handled via error_cb.
            wpa_printf(MSG_DEBUG, "eap_proxy: %s Ignore service event QMI_CLIENT_SERVICE_COUNT_DEC",
                       __func__);
            break;

        default:
            wpa_printf(MSG_ERROR, "eap_proxy: %s Ignore unsupported service event %d",
                       __func__, service_event);
            break;
        }
}

static int eap_proxy_register_notify_cb(struct eap_proxy_sm *eap_proxy)
{
        qmi_client_error_type rc = QMI_INTERNAL_ERR;

        if (eap_proxy->notifier_cb_initialized == TRUE) {
            wpa_printf(MSG_DEBUG, "eap_proxy: notification callback already exist. Skip re-init");
            return 0;
        }

        eap_proxy_notifier_cleanup(eap_proxy); // just in case.

        // Register for notification callback for UIM
        os_memset(&eap_proxy->uim_notifier_os_params, 0, sizeof(qmi_client_os_params));
        rc = qmi_client_notifier_init(uim_get_service_object_v01(),
                                      &eap_proxy->uim_notifier_os_params,
                                      &eap_proxy->uim_notifier_handle);
        if (rc != QMI_NO_ERR)
            goto fail;

        rc = qmi_client_register_notify_cb(eap_proxy->uim_notifier_handle,
                                           eap_proxy_notifier_cb,
                                           (void *) eap_proxy);
        if (rc != QMI_NO_ERR)
            goto fail;

        // Register for notification callback for AUTH
        os_memset(&eap_proxy->auth_notifier_os_params, 0, sizeof(qmi_client_os_params));
        rc = qmi_client_notifier_init(auth_get_service_object_v01(),
                                      &eap_proxy->auth_notifier_os_params,
                                      &eap_proxy->auth_notifier_handle);
        if (rc != QMI_NO_ERR)
            goto fail;

        rc = qmi_client_register_notify_cb(eap_proxy->auth_notifier_handle,
                                           eap_proxy_notifier_cb,
                                           (void *) eap_proxy);
        if (rc != QMI_NO_ERR)
            goto fail;

        eap_proxy->notifier_cb_initialized = TRUE;
        wpa_printf(MSG_DEBUG, "eap_proxy: notify_cb initialized.");
        return 0;

fail:
        wpa_printf(MSG_ERROR, "eap_proxy: notify_cb initialization failed.");
        eap_proxy_notifier_cleanup(eap_proxy);
        return -1;
}

void wpa_qmi_register_notification(void *eloop_ctx, void *timeout_ctx)
{
        struct eap_proxy_sm *eap_proxy = eloop_ctx;
        wpa_printf(MSG_ERROR, "eap_proxy: %s", __func__);

        if (eap_proxy == NULL || !eap_proxy->initialized) {
                wpa_printf(MSG_ERROR, "eap_proxy: %s Skip processing SSR (eap_proxy deinitialized)", __func__);
                return;
        }
        eap_proxy_qmi_deinit(eap_proxy);
        // Register and wait for notify_cb to get modem UP indication.
        if (eap_proxy_register_notify_cb(eap_proxy) < 0) {
            wpa_printf(MSG_ERROR, "eap_proxy: %s failed to register for Modem UP indication. Give up", __func__);
            return;
        }
}

void wpa_qmi_handle_ssr(qmi_client_type user_handle, qmi_client_error_type error, void *err_cb_data)
{
        struct eap_proxy_sm *eap_proxy = err_cb_data;
        if (eap_proxy == NULL)
                return;

        pthread_mutex_lock(&eloop_lock);       // Lock
        wpa_printf(MSG_ERROR, "eap_proxy: %s eap_proxy=%p", __func__, eap_proxy);
        eloop_register_timeout(0, 0, wpa_qmi_register_notification, eap_proxy, NULL);
        pthread_mutex_unlock(&eloop_lock);      // Unlock
}

static void eap_proxy_post_init(struct eap_proxy_sm *eap_proxy)
{
        int qmiErrorCode = QMI_NO_ERR;
        qmi_idl_service_object_type qmi_client_service_obj[MAX_NO_OF_SIM_SUPPORTED];
        int index;
        Boolean flag = FALSE;
        int ret = 0;
        wpa_uim_struct_type *wpa_uim = eap_proxy->wpa_uim;
#ifdef CONFIG_EAP_PROXY_MDM_DETECT
        struct dev_info mdm_detect_info;

        /* Call ESOC API to get the number of modems.
         * If the number of modems is not zero, only then proceed
         * with the eap_proxy intialization.
         */
        ret = get_system_info(&mdm_detect_info);
        if (ret > 0)
                wpa_printf(MSG_ERROR, "eap_proxy: Failed to get system info, ret %d", ret);

        if (mdm_detect_info.num_modems == 0) {
                eap_proxy->proxy_state = EAP_PROXY_DISABLED;
                wpa_printf(MSG_ERROR, "eap_proxy: No Modem support for this target"
                           " number of modems is %d", mdm_detect_info.num_modems);
                return;
        }
        wpa_printf(MSG_ERROR, "eap_proxy: num_modems = %d", mdm_detect_info.num_modems);

        if(eap_modem_compatible(&mdm_detect_info) == FALSE) {
                eap_proxy->proxy_state = EAP_PROXY_DISABLED;
                wpa_printf(MSG_ERROR, "eap_proxy: build does not support EAP-SIM feature");
                return;
        }
#endif /* CONFIG_EAP_PROXY_MDM_DETECT */
        eap_proxy->proxy_state = EAP_PROXY_INITIALIZE;
        eap_proxy->qmi_state = QMI_STATE_IDLE;
        eap_proxy->key = NULL;
        eap_proxy->emsk = NULL;
        eap_proxy->session_id = NULL;
        eap_proxy->session_id_len = 0;
        eap_proxy->iskey_valid = FALSE;
        eap_proxy->is_state_changed = FALSE;
        eap_proxy->isEap = FALSE;
        eap_proxy->eap_type = EAP_TYPE_NONE;
        eap_proxy->user_selected_sim = 0;

#ifdef CONFIG_EAP_PROXY_DUAL_SIM
        wpa_printf (MSG_ERROR,
                "eap_proxy: eap_proxy Initializing for DUAL SIM build %d tid %d",
                MAX_NO_OF_SIM_SUPPORTED, gettid());
#else
        wpa_printf (MSG_ERROR,
                "eap_proxy: eap_proxy Initializing for Single SIM build %d tid %d",
                MAX_NO_OF_SIM_SUPPORTED, gettid());
#endif

        for (index = 0; index < MAX_NO_OF_SIM_SUPPORTED; ++index) {
#ifdef SIM_AKA_IDENTITY_IMSI
                if (FALSE == eap_proxy->qmi_uim_svc_client_initialized[index])  {
                        qmi_client_os_params eap_os_params;
                        /* Init QMI_UIM service for EAP-SIM/AKA */
                        os_memset(&eap_os_params, 0, sizeof(qmi_client_os_params));

                        qmiErrorCode = qmi_client_init_instance(
                                        uim_get_service_object_v01(),
                                        QMI_CLIENT_INSTANCE_ANY,
                                        wpa_qmi_client_indication_cb,
                                        eap_proxy, &eap_os_params,
                                        10000,
                                        &wpa_uim[index].qmi_uim_svc_client_ptr);

                        if ((wpa_uim[index].qmi_uim_svc_client_ptr == NULL) || (qmiErrorCode != QMI_NO_ERR)) {
                                wpa_printf(MSG_ERROR, "eap_proxy: Could not register with QMI UIM"
                                        " Service, qmi_uim_svc_client_ptr: %p,qmi_err_code: %d\n",
                                        wpa_uim[index].qmi_uim_svc_client_ptr, qmiErrorCode);
                                wpa_uim[index].qmi_uim_svc_client_ptr = NULL;
                                flag = FALSE;
                                continue;
                        }
                        /* Register the card events with the QMI / UIM */
                        // TODO: Should we treat sim read failure as eap_proxy_init failure ?
                        wpa_qmi_register_events(index, wpa_uim);

                        // register for SSR once per interface.
                        if (flag == FALSE) {
                                qmiErrorCode = qmi_client_register_error_cb(
                                        wpa_uim[index].qmi_uim_svc_client_ptr, wpa_qmi_handle_ssr, eap_proxy);
                                if (qmiErrorCode != QMI_NO_ERR) {
                                        wpa_printf(MSG_ERROR, "eap_proxy: qmi_client_register_error_cb()-"
                                                   " Failed to register callbacks %d\n", qmiErrorCode);
                                        wpa_uim[index].qmi_uim_svc_client_ptr = NULL;
                                        flag = FALSE;
                                        continue;
                                }
                        }
                        eap_proxy->qmi_uim_svc_client_initialized[index] = TRUE;

                        wpa_printf (MSG_ERROR, "eap_proxy: QMI uim service client initialized with"
                                " success tid is %d %p %d\n",
                                gettid(), wpa_uim[index].qmi_uim_svc_client_ptr, qmiErrorCode);
                } else
                        wpa_printf (MSG_ERROR, "eap_proxy: QMI uim service client is already init"
                                "ialized tid is %d \n", gettid());


                qmi_client_os_params eap_os_params;
                os_memset(&eap_os_params, 0, sizeof(qmi_client_os_params));

                qmiErrorCode = qmi_client_init_instance(auth_get_service_object_v01(),
                                                        QMI_CLIENT_INSTANCE_ANY,
                                                        handle_qmi_eap_ind,
                                                        eap_proxy,
                                                        &eap_os_params,
                                                        10000,
                                                        &eap_proxy->qmi_auth_svc_client_ptr[index]);


                if ((eap_proxy->qmi_auth_svc_client_ptr[index] == NULL) || (qmiErrorCode != QMI_NO_ERR)) {
                        wpa_printf(MSG_ERROR, "eap_proxy: Could not register with QMI auth Service "
                                        "qmi_auth_svc_client_ptr: %p,qmi_err_code: %d\n",
                                        eap_proxy->qmi_auth_svc_client_ptr[index], qmiErrorCode);
                        eap_proxy->qmi_auth_svc_client_ptr[index] = NULL;
                        eap_proxy->qmi_uim_svc_client_initialized[index] = FALSE;
                        flag = FALSE;
                        continue;
                }
                wpa_printf (MSG_ERROR, "eap_proxy: QMI auth service client initialized with success"
                        " tid is %d  %p eapol_proxy=%p\n", gettid(),
                                eap_proxy->qmi_auth_svc_client_ptr[index], eap_proxy);
                /* Register for the notifications from QMI / AUTH */
                if (wpa_qmi_register_auth_inds(index, eap_proxy) == FALSE) {
                        eap_proxy->qmi_auth_svc_client_ptr[index] = NULL;
                        eap_proxy->qmi_uim_svc_client_initialized[index] = FALSE;
                        wpa_printf (MSG_ERROR, "eap_proxy: wpa_qmi_register_auth_inds failed");
                        flag = FALSE;
                        continue;
                }
                flag = TRUE;
#endif /* SIM_AKA_IDENTITY_IMSI */
        }

        if ( flag == FALSE ) {
                eap_proxy->proxy_state = EAP_PROXY_DISABLED;
                wpa_printf(MSG_ERROR, "eap_proxy: flag = %d proxy init failed\n", flag);
                return;
        }

        eap_proxy->proxy_state = EAP_PROXY_IDLE;
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapSuccess, FALSE);
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapFail, FALSE);
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapRestart, FALSE);
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapResp, FALSE);
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapNoResp, FALSE);
        wpa_printf (MSG_ERROR, "eap_proxy: Eap_proxy initialized successfully"
                " tid is %d \n", gettid());
        return;

}

int eap_auth_end_eap_session(qmi_client_type qmi_auth_svc_client_ptr)
{
        qmi_client_error_type qmiRetCode = 0;
        auth_end_eap_session_resp_msg_v01 end_eap_session_resp_msg ;

        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_end_eap_session: Ending EAP auth session");


        /* Send QMI_AUTH_END_EAP_SESSION_REQ */

        os_memset(&end_eap_session_resp_msg,
                        0,
                        sizeof(auth_end_eap_session_resp_msg_v01));

        qmiRetCode = qmi_client_send_msg_sync(qmi_auth_svc_client_ptr,
                                              QMI_AUTH_END_EAP_SESSION_REQ_V01,
                                              NULL,
                                              0,
                                              (void *) &end_eap_session_resp_msg,
                                              sizeof(auth_end_eap_session_resp_msg_v01),
                                              WPA_UIM_QMI_DEFAULT_TIMEOUT);

        if (QMI_NO_ERR != qmiRetCode ||
            end_eap_session_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Unable to End the EAP session;"
                                " error_ret=%d; qmi_err=%d\n", qmiRetCode,
                                end_eap_session_resp_msg.resp.error);
                return -1;
        }

        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_end_eap_session:"
                " EAP auth session ended successfuly");

        return 0;
}

struct eap_proxy_sm *
eap_proxy_init(void *eapol_ctx, const struct eapol_callbacks *eapol_cb,
               void *msg_ctx)
{
        struct eap_proxy_sm *eap_proxy;
        int ret;

        wpa_printf(MSG_ERROR, "eap_proxy: %s", __func__);
        eap_proxy = get_next_eap_proxy();
        if (NULL == eap_proxy)
                return NULL;

        os_memset(eap_proxy, 0, sizeof(*eap_proxy));
        eap_proxy->initialized = TRUE;
        eap_proxy->ctx = eapol_ctx;
        eap_proxy->eapol_cb = eapol_cb;
        eap_proxy->msg_ctx = msg_ctx;

        eap_proxy->proxy_state = EAP_PROXY_DISABLED;
        eap_proxy->modem_state = EAP_PROXY_MODEM_UNKNOWN;
        eap_proxy->notifier_cb_initialized = FALSE;
        dl_list_init(&eap_proxy->callback);

        /* delay the qmi client initialization after the eloop_run starts,
        * in order to avoid the case of daemonize enabled, which exits the
        * parent process that created the qmi client context.
        * NOTE: Spawn a new thread to allow eap_proxy initialization.
        */

        // Make note of new thread creation, so that we can take care of joining.
        eap_proxy->qmi_thread_joined = FALSE;

        ret = pthread_create(&eap_proxy->thread_id, NULL, eap_proxy_post_init, eap_proxy);
        if(ret < 0) {
               wpa_printf(MSG_ERROR, "eap_proxy: starting thread is failed %d\n", ret);
               goto fail;
        }

        return eap_proxy;
fail:
        eap_proxy->initialized = FALSE;
        return NULL;
}


static void eap_proxy_qmi_deinit(struct eap_proxy_sm *eap_proxy)
{
        int qmiRetCode;
        int index;
        wpa_uim_struct_type *wpa_uim = NULL;

        if (eap_proxy == NULL || !eap_proxy->initialized)
                return;
        /* Waiting for eap_proxy_post_init to exit normally.
         * The eap_proxy_post_init may wait for QMI responese.
         * Force killing the thread will cause problem in QMI lib.
         * Also, Do not join the thread if it was already joined before.
         */
        if (!eap_proxy->qmi_thread_joined) {
                wpa_printf(MSG_ERROR, "eap_proxy: pthread_join on eap_proxy=%p", eap_proxy);
                pthread_join(eap_proxy->thread_id, NULL);
                eap_proxy->qmi_thread_joined = TRUE;
        }
        eap_proxy->proxy_state = EAP_PROXY_DISABLED;
        wpa_uim = eap_proxy->wpa_uim;

        for (index = 0; index < MAX_NO_OF_SIM_SUPPORTED; ++index) {
                if (TRUE == eap_proxy->eap_auth_session_flag[index]) {

                        /* end the current EAP session */
                        if(eap_auth_end_eap_session(eap_proxy->qmi_auth_svc_client_ptr[index]) < 0 ){
                                wpa_printf(MSG_ERROR, "eap_proxy: Unable to end the EAP session for"
                                                " client %d", index+1);
                        } else {
                                wpa_printf(MSG_ERROR, "eap_proxy: Ended the QMI EAP session for "
                                                "client %d\n",
                                                index+1);
                                eap_proxy->eap_auth_session_flag[index] = FALSE;
                        }
                } else {
                        wpa_printf (MSG_ERROR, "eap_proxy: session not started"
                                " for client = %d\n", index+1);
                }

                if ((TRUE == eap_proxy->qmi_uim_svc_client_initialized[index]))  {
                        qmiRetCode = qmi_client_release(wpa_uim[index].qmi_uim_svc_client_ptr);
                        if (QMI_NO_ERR != qmiRetCode) {
                                wpa_printf (MSG_ERROR, "eap_proxy: Unable to Releas the connection"
                                                " to uim service for client=%d; error_ret=%d\n;",
                                                index+1, qmiRetCode);
                        }
                        wpa_printf(MSG_ERROR, "eap_proxy: Released QMI UIM service client\n");
                        eap_proxy->qmi_uim_svc_client_initialized[index] = FALSE;
                }

                if (NULL != eap_proxy->qmi_auth_svc_client_ptr[index]) {
                        qmiRetCode = qmi_client_release(eap_proxy->qmi_auth_svc_client_ptr[index]);
                        if (QMI_NO_ERR != qmiRetCode) {
                                wpa_printf (MSG_ERROR, "eap_proxy: Unable to Releas the connection"
                                                " to auth service for client=%d; error_ret=%d\n;",
                                                index+1, qmiRetCode);
                        }  else {
                                wpa_printf(MSG_ERROR, "eap_proxy: Released QMI EAP service client\n");
                        }
                }

        }

        if (NULL != eap_proxy->key) {
                os_free(eap_proxy->key);
                eap_proxy->key = NULL;
        }
        if (eap_proxy->emsk) {
                os_free(eap_proxy->emsk);
                eap_proxy->emsk = NULL;
        }
        if (eap_proxy->session_id) {
                os_free(eap_proxy->session_id);
                eap_proxy->session_id = NULL;
                eap_proxy->session_id_len = 0;
        }

        eap_proxy->iskey_valid = FALSE;
        eap_proxy->is_state_changed = FALSE;
        eap_proxy->user_selected_sim = 0;
        eap_proxy->modem_state = EAP_PROXY_MODEM_UNKNOWN;
}

static void eap_proxy_clear_callbacks(struct eap_proxy_sm *eap_proxy)
{
        struct qmi_cb_data *tmp, *prev;
        dl_list_for_each_safe(tmp, prev, &eap_proxy->callback,
                              struct qmi_cb_data, list) {
                eap_proxy_clear_qmi_cb_data(tmp);
        }
}

void eap_proxy_deinit(struct eap_proxy_sm *eap_proxy)
{
        if (eap_proxy == NULL) {
            wpa_printf(MSG_ERROR, "eap_proxy: Not initialized");
            return;
        }

        eap_proxy_qmi_deinit(eap_proxy);
        // clear any pending callback.
        eap_proxy_clear_callbacks(eap_proxy);
        eap_proxy_notifier_cleanup(eap_proxy);
        if (eap_proxy->initialized) {
            eap_proxy->initialized = FALSE;
            wpa_printf(MSG_INFO, "eap_proxy: eap_proxy Deinitialzed\n");
        }
}

void __handle_qmi_eap_ind(void *eloop_ctx, void *timeout_ctx)
{
        qmi_client_error_type qmi_err;
        auth_eap_session_result_ind_msg_v01 eap_session_result;
        memset(&eap_session_result, 0, sizeof(auth_eap_session_result_ind_msg_v01));
        eap_session_result.eap_result = -1;

        struct qmi_cb_data *cb_data = (struct qmi_cb_data *)eloop_ctx;
        struct eap_proxy_sm *sm = (struct eap_proxy_sm *)cb_data->userdata;

        auth_eap_notification_code_ind_msg_v01 eap_notification;
        memset(&eap_notification, 0, sizeof(auth_eap_notification_code_ind_msg_v01));

        wpa_printf(MSG_ERROR, "eap_proxy: %s msgId =%d  sm=%p\n", __func__, cb_data->msg_id, sm);
        /* Decode */

        switch(cb_data->msg_id)
        {
                case QMI_AUTH_EAP_SESSION_RESULT_IND_V01:

                        qmi_err = qmi_client_message_decode(cb_data->userHandle, QMI_IDL_INDICATION,
                                        cb_data->msg_id, (void*)cb_data->buf, cb_data->buflen,
                                        &eap_session_result,
                                        sizeof(auth_eap_session_result_ind_msg_v01));
                        if (qmi_err != QMI_NO_ERR)
                        {
                                wpa_printf(MSG_ERROR, "eap_proxy: Error in qmi_client_message_de"
                                        "code; error_code=%d \n", qmi_err);
                                sm->srvc_result = EAP_PROXY_QMI_SRVC_FAILURE;
                                goto done;
                        }
                        if ((eap_session_result.eap_result == 0) &&
                            (QMI_STATE_RESP_TIME_OUT != sm->qmi_state)) {
                                sm->proxy_state = EAP_PROXY_AUTH_SUCCESS;
                                sm->qmi_state = QMI_STATE_RESP_RECEIVED;
                                wpa_printf(MSG_ERROR, "eap_proxy: %s EAP PROXY AUTH"
                                        " SUCCESS %p set to %d\n", __func__,
                                        (void *)&sm->qmi_state, sm->qmi_state);
                        } else {
                                sm->proxy_state = EAP_PROXY_AUTH_FAILURE;
                                wpa_printf(MSG_ERROR, "eap_proxy: %s EAP PROXY AUTH"
                                        " FAILURE \n", __func__);
                        }
                        sm->srvc_result = EAP_PROXY_QMI_SRVC_SUCCESS;
                        break;

                case QMI_AUTH_EAP_NOTIFICATION_CODE_IND_V01:

                        qmi_err = qmi_client_message_decode(cb_data->userHandle, QMI_IDL_INDICATION,
                                        cb_data->msg_id, (void*)cb_data->buf, cb_data->buflen,
                                        &eap_notification,
                                        sizeof(auth_eap_notification_code_ind_msg_v01));
                        if (qmi_err != QMI_NO_ERR)
                        {
                                wpa_printf(MSG_ERROR, "eap_proxy: Error in qmi_client_"
                                        "message_decode; error_code=%d \n", qmi_err);
                        }
                        sm->notification_code = eap_notification.eap_notification_code;
                        wpa_printf(MSG_ERROR, "eap_proxy: notificatio code is %x\n",
                                        eap_notification.eap_notification_code);
                        break;

                default:
                        wpa_printf(MSG_ERROR, "eap_proxy: An unexpected msg Id=%d"
                                        " is given\n", cb_data->msg_id);
                        break;
        }
done:
        eap_proxy_clear_qmi_cb_data(cb_data);
}

/* Call-back function to process an authentication result indication
*  from QMI EAP service */
static void handle_qmi_eap_ind(qmi_client_type user_handle,
                               unsigned int msg_id,
                               void* ind_buf,
                               unsigned int ind_buf_len,
                               void* ind_cb_data)
{
        struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)ind_cb_data;
        struct qmi_cb_data *cb_data = NULL;

        if (eap_proxy == NULL)
                return;

        pthread_mutex_lock(&eloop_lock);       // Lock
        wpa_printf(MSG_ERROR, "eap_proxy: %s eap_proxy=%p", __func__, eap_proxy);

        cb_data = eap_proxy_prepare_qmi_cb_data(user_handle, msg_id, ind_buf,
                                                ind_buf_len, ind_cb_data);
        if (cb_data == NULL) {
                pthread_mutex_unlock(&eloop_lock);      // Unlock
                return;
        }

        dl_list_add(&eap_proxy->callback, &cb_data->list);

        // eloop is waiting for response. handle in calling thread
        if (eap_proxy != NULL && eap_proxy->qmi_state == QMI_STATE_RESP_PENDING)
             __handle_qmi_eap_ind(cb_data, NULL);
        else
            eloop_register_timeout(0, 0, __handle_qmi_eap_ind, cb_data, NULL);

        pthread_mutex_unlock(&eloop_lock);      // Unlock
}


/* Call-back function to process an EAP response from QMI EAP service */
static void handle_qmi_eap_reply(
                qmi_client_type userHandle, unsigned int msg_id,
                void *resp_c_struct, unsigned int resp_c_struct_len,
                void *userData, qmi_client_error_type sysErrCode)
{
        struct eap_proxy_sm *eap_proxy = (struct eap_proxy_sm *)userData;
        auth_send_eap_packet_resp_msg_v01* rspData =
                (auth_send_eap_packet_resp_msg_v01*)resp_c_struct;

        u8 *resp_data;
        u32 length;

        wpa_printf(MSG_ERROR, "eap_proxy: %s started\n", __func__);
        if (eap_proxy == NULL || !eap_proxy->initialized) {
                wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy is not initialized");
                goto done;
        }
        if (QMI_STATE_RESP_PENDING == eap_proxy->qmi_state) {

                wpa_printf(MSG_ERROR, "eap_proxy: user_selected_sim = %d\n",
                           eap_proxy->user_selected_sim+1);


                if (QMI_NO_ERR != sysErrCode) {
                        wpa_printf(MSG_ERROR, "eap_proxy: An error is encountered with"
                                        " the request: sysErrorCode=%d\n",
                                        sysErrCode);
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        goto done;
                }

                if (NULL == rspData) {
                        wpa_printf(MSG_ERROR, "eap_proxy: Response data is NULL\n");
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        goto done;
                }
                if((QMI_AUTH_SEND_EAP_PACKET_REQ_V01 != msg_id) &&
                   (QMI_AUTH_SEND_EAP_PACKET_EXT_REQ_V01 != msg_id))
                {
                        wpa_printf(MSG_ERROR, "eap_proxy: Invalid msgId =%d\n", msg_id);
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        goto done;
                }

                /* ensure the reply packet exists  */
                if (rspData->eap_response_pkt_len <= 0 ||
                    rspData->eap_response_pkt_len > QMI_AUTH_EAP_RESP_PACKET_EXT_MAX_V01) {
                        wpa_printf(MSG_ERROR, "eap_proxy: Reply packet is of invalid length %d"
                                " error %d result %d\n", rspData->eap_response_pkt_len,
                                rspData->resp.error, rspData->resp.result);
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        goto done;
                }

                length = rspData->eap_response_pkt_len;
                eap_proxy->qmi_resp_data.eap_send_pkt_resp.length = length;
                /* allocate a buffer to store the response data; size is EAP resp len field */
                eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data =
                        os_malloc(rspData->eap_response_pkt_len);

                resp_data =
                        (u8 *)eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data;

                if (NULL == resp_data) {
                        wpa_printf(MSG_ERROR, "eap_proxy: Unable to allocate memory for"
                                        " reply packet\n");
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        goto done;
                }

                /* copy the response data to the allocated buffer */
                os_memcpy(resp_data,
                                rspData->eap_response_pkt, length);
                eap_proxy->qmi_state = QMI_STATE_RESP_RECEIVED;
                wpa_printf(MSG_ERROR, "eap_proxy: **HANDLE_QMI_EAP_REPLY CALLBACK ENDDED **");

                wpa_printf(MSG_ERROR, "eap_proxy: Dump Resp Data len %d\n", length);
                dump_buff(resp_data, length);
        }

done:
        if (rspData != NULL) {
                os_free(rspData);
                rspData = NULL;
        }
        return;
}

static enum eap_proxy_status eap_proxy_process(struct eap_proxy_sm  *eap_proxy,
                                        u8 *eapReqData, int eapReqDataLen, struct eap_sm *eap_sm)
{
        struct eap_hdr *hdr;
        int qmiErrorCode = QMI_NO_ERR;
        enum eap_proxy_status proxy_status = EAP_PROXY_SUCCESS;
        auth_send_eap_packet_req_msg_v01 eap_send_packet_req;
        auth_send_eap_packet_resp_msg_v01 *eap_send_packet_resp = NULL;
        qmi_txn_handle async_txn_hdl = 0;

        auth_send_eap_packet_ext_req_msg_v01 eap_send_packet_ext_req;
        auth_send_eap_packet_ext_resp_msg_v01 *eap_send_packet_ext_resp = NULL;


        hdr = (struct eap_hdr *)eapReqData;
        if ((EAP_CODE_REQUEST == hdr->code) &&
            (EAP_TYPE_IDENTITY == eapReqData[4])) {
                if (eap_proxy_eapol_sm_get_bool(eap_proxy, EAPOL_eapRestart) &&
                    eap_proxy_eapol_sm_get_bool(eap_proxy, EAPOL_portEnabled)) {
                        wpa_printf (MSG_ERROR, "eap_proxy: Already Authenticated."
                                    " Clear all the flags");
                        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapSuccess, FALSE);
                        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapFail, FALSE);
                        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapResp, FALSE);
                        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapNoResp, FALSE);
                        if (eap_proxy->key) {
                                os_free(eap_proxy->key);
                                eap_proxy->key = NULL;
                        }
                        if (eap_proxy->emsk) {
                                os_free(eap_proxy->emsk);
                                eap_proxy->emsk = NULL;
                        }
                        if (eap_proxy->session_id) {
                                os_free(eap_proxy->session_id);
                                eap_proxy->session_id = NULL;
                                eap_proxy->session_id_len = 0;
                        }
                        eap_proxy->iskey_valid = FALSE;
                        eap_proxy->is_state_changed = TRUE;
                }
                eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapRestart, FALSE);

                if(eap_proxy_build_identity(eap_proxy, hdr->identifier, eap_sm)) {
                        eap_proxy->proxy_state = EAP_PROXY_IDENTITY;
                } else {
                        wpa_printf(MSG_ERROR, "eap_proxy: Error in build identity\n");
                        return EAP_PROXY_FAILURE;
                }
        }
        wpa_printf(MSG_ERROR, "eap_proxy: ***********Dump ReqData len %d***********",
                eapReqDataLen);
        dump_buff(eapReqData, eapReqDataLen);

        if ((eapReqDataLen > QMI_AUTH_EAP_REQ_PACKET_MAX_V01) &&
            (eapReqDataLen > QMI_AUTH_EAP_REQ_PACKET_EXT_MAX_V01)) {
                wpa_printf(MSG_ERROR, "eap_proxy: Error in eap_send_packet_req\n");
                return EAP_PROXY_FAILURE;
        }

        wpa_printf(MSG_ERROR, "eap_proxy: SIM selected by User: Selected sim = %d\n",
                eap_proxy->user_selected_sim+1);
        if (eap_proxy->qmi_state != QMI_STATE_IDLE) {
                wpa_printf(MSG_ERROR, "Error in QMI state=%d\n",
                                         eap_proxy->qmi_state);
                return EAP_PROXY_FAILURE;
        }

        wpa_printf (MSG_ERROR, "eap_proxy: In eap_proxy_process case %d\n", hdr->code);
        eap_proxy->qmi_state = QMI_STATE_RESP_PENDING;

        if (eapReqDataLen <= QMI_AUTH_EAP_REQ_PACKET_MAX_V01) {
                os_memset(&eap_send_packet_req, 0, sizeof(auth_send_eap_packet_req_msg_v01));
                eap_send_packet_req.eap_request_pkt_len = eapReqDataLen ;
                memcpy(eap_send_packet_req.eap_request_pkt, eapReqData, eapReqDataLen);

                eap_send_packet_resp = os_zalloc(sizeof(auth_send_eap_packet_resp_msg_v01));
                if (eap_send_packet_resp == NULL) {
                        wpa_printf(MSG_ERROR, "Error allocating memory for eap_packet_resp_msg");
                        goto fail;
                }
        } else if (eapReqDataLen <= QMI_AUTH_EAP_REQ_PACKET_EXT_MAX_V01) {
                os_memset(&eap_send_packet_ext_req, 0,
                        sizeof(auth_send_eap_packet_ext_req_msg_v01));
                eap_send_packet_ext_req.eap_request_ext_pkt_len = eapReqDataLen;
                memcpy(eap_send_packet_ext_req.eap_request_ext_pkt, eapReqData, eapReqDataLen);

                eap_send_packet_ext_resp = os_zalloc(sizeof(auth_send_eap_packet_ext_resp_msg_v01));
                if (eap_send_packet_ext_resp == NULL) {
                        wpa_printf(MSG_ERROR, "Error allocating memory for eap_send_packet_ext_resp");
                        goto fail;
                }
        }

        if(eapReqDataLen <= QMI_AUTH_EAP_REQ_PACKET_MAX_V01) {
                qmiErrorCode = qmi_client_send_msg_async(
                                eap_proxy->qmi_auth_svc_client_ptr[eap_proxy->user_selected_sim],
                                QMI_AUTH_SEND_EAP_PACKET_REQ_V01,
                                (void *) &eap_send_packet_req,
                                sizeof(auth_send_eap_packet_req_msg_v01),
                                (void *) eap_send_packet_resp,
                                sizeof(auth_send_eap_packet_resp_msg_v01),
                                &handle_qmi_eap_reply, eap_proxy,
                                &async_txn_hdl);
        } else if(eapReqDataLen <= QMI_AUTH_EAP_REQ_PACKET_EXT_MAX_V01) {
                qmiErrorCode = qmi_client_send_msg_async(
                                eap_proxy->qmi_auth_svc_client_ptr[eap_proxy->user_selected_sim],
                                QMI_AUTH_SEND_EAP_PACKET_EXT_REQ_V01,
                                (void *) &eap_send_packet_ext_req,
                                sizeof(auth_send_eap_packet_ext_req_msg_v01),
                                (void *) eap_send_packet_ext_resp,
                                sizeof(auth_send_eap_packet_ext_resp_msg_v01),
                                &handle_qmi_eap_reply, eap_proxy,
                                &async_txn_hdl);
        }

        if (QMI_NO_ERR != qmiErrorCode) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Error in sending EAP packet;"
                                " error_code=%d\n", qmiErrorCode);
                goto fail;
        } else {
                wpa_printf (MSG_ERROR, "eap_proxy: In eap_proxy_process case %d\n", hdr->code);
                switch (hdr->code) {
                case EAP_CODE_SUCCESS:
                        if (EAP_PROXY_SUCCESS !=
                                eap_proxy_qmi_response_wait(eap_proxy)) {
                                goto fail;
                        } else if( eap_proxy->proxy_state == EAP_PROXY_AUTH_SUCCESS ) {
                                eap_proxy_get_keys(eap_proxy);
                                eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                 EAPOL_eapSuccess, TRUE);
        /*
         * RFC 4137 does not clear eapReq here, but this seems to be required
         * to avoid processing the same request twice when state machine is
         * initialized.
         */
                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                        EAPOL_eapReq, FALSE);

        /*
         * RFC 4137 does not set eapNoResp here, but this seems to be required
         * to get EAPOL Supplicant backend state machine into SUCCESS state. In
         * addition, either eapResp or eapNoResp is required to be set after
         * processing the received EAP frame.
         */
                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapNoResp, TRUE);

                        wpa_msg(eap_proxy->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
                                "eap_proxy: EAP authentication completed successfully");

                        eap_proxy->is_state_changed = TRUE;

                                /* Retrieve the keys  and store*/
                        } else if( eap_proxy->proxy_state == EAP_PROXY_AUTH_FAILURE ){

                                eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapFail, TRUE);
                                eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapReq, FALSE);
                                eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapNoResp, TRUE);
                                eap_proxy->is_state_changed = TRUE;

                        }

                        break;

                case EAP_CODE_FAILURE:
                        wpa_printf (MSG_ERROR,
                                "eap_proxy: in eap_proxy_process case EAP_CODE_FAILURE\n");
                        eap_proxy->proxy_state = EAP_PROXY_AUTH_FAILURE;
                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapFail, TRUE);

        /*
         * RFC 4137 does not clear eapReq here, but this seems to be required
         * to avoid processing the same request twice when state machine is
         * initialized.
        */
                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapReq, FALSE);

        /*
         * RFC 4137 does not set eapNoResp here. However, either eapResp or
         * eapNoResp is required to be set after processing the received EAP
         * frame.
         */
                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapNoResp, TRUE);

                        wpa_msg(eap_proxy->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE
                                "EAP authentication failed notification code 0x%x",
                                eap_proxy->notification_code);

                        eap_proxy->is_state_changed = TRUE;
                        break;

                case EAP_CODE_REQUEST:
                                        eap_proxy->proxy_state = EAP_PROXY_SEND_RESPONSE;
                        if (EAP_PROXY_SUCCESS !=
                                eap_proxy_qmi_response_wait(eap_proxy)) {
                                goto fail;
                        } else {
                                eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                        EAPOL_eapResp, TRUE);
                                eap_proxy->proxy_state =
                                                EAP_PROXY_SEND_RESPONSE;
                        }

                        eap_proxy_eapol_sm_set_bool(eap_proxy,
                                                EAPOL_eapReq, FALSE);
                        eap_proxy->is_state_changed = TRUE;
                        break;

                default:
                        wpa_printf(MSG_ERROR, "eap_proxy: Error in sending EAP packet;"
                                         " error_code=%d\n", qmiErrorCode);
                        goto fail;
                }
        }

        return EAP_PROXY_SUCCESS;

fail:
        if (eap_send_packet_resp != NULL)
            os_free(eap_send_packet_resp);
        if (eap_send_packet_ext_resp != NULL)
            os_free(eap_send_packet_ext_resp);

        // Reset QMI state to IDLE to process next frame.
        eap_proxy->qmi_state = QMI_STATE_IDLE;

        eap_proxy->proxy_state = EAP_PROXY_DISCARD;
        eap_proxy_eapol_sm_set_bool(eap_proxy, EAPOL_eapNoResp, TRUE);

        return EAP_PROXY_FAILURE;
}



static u8 *eap_proxy_getKey(struct eap_proxy_sm *eap_proxy)
{
        int qmiRetCode;

        auth_get_eap_session_keys_resp_msg_v01 key_resp_msg;
        os_memset(&key_resp_msg, 0, sizeof(auth_get_eap_session_keys_resp_msg_v01));

        qmiRetCode = qmi_client_send_msg_sync(
                        eap_proxy->qmi_auth_svc_client_ptr[eap_proxy->user_selected_sim],
                        QMI_AUTH_GET_EAP_SESSION_KEYS_REQ_V01,
                        NULL,
                        0,
                        (void *) &key_resp_msg,
                        sizeof(auth_get_eap_session_keys_resp_msg_v01),
                        WPA_UIM_QMI_DEFAULT_TIMEOUT);


        /* see if the MSK is acquired successfully */
        if (QMI_NO_ERR != qmiRetCode || key_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, "QMI-ERROR Unable to get session keys;"
                                 " err_code=%d qmiErr=%d\n", qmiRetCode, key_resp_msg.resp.error);
                eap_proxy->key = NULL;
                return NULL;
        }
        wpa_printf(MSG_ERROR, "eap_proxy: %s:session_key_len =%d", __func__,
                key_resp_msg.session_key_len);

        if(key_resp_msg.session_key_len <=0 ||
           key_resp_msg.session_key_len > EAP_PROXY_KEYING_DATA_LEN)
        {
                return NULL;

        }
        eap_proxy->key = os_malloc(EAP_PROXY_KEYING_DATA_LEN);
        if(eap_proxy->key == NULL)
                return NULL;

        memset(eap_proxy->key, 0, EAP_PROXY_KEYING_DATA_LEN);
        memcpy(eap_proxy->key, key_resp_msg.session_key, key_resp_msg.session_key_len);

        eap_proxy->iskey_valid = TRUE;
        eap_proxy->proxy_state = EAP_PROXY_AUTH_SUCCESS;

        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_getkey EAP KEYS ");
        dump_buff(eap_proxy->key, EAP_PROXY_KEYING_DATA_LEN);

        return eap_proxy->key;
}

static u8 * eap_proxy_get_keys(struct eap_proxy_sm *sm)
{
	int qmiRetCode;

	auth_get_eap_auth_credentials_req_msg_v01 key_req_msg;
	auth_get_eap_auth_credentials_resp_msg_v01 key_resp_msg;

	os_memset(&key_req_msg, 0,
		  sizeof(auth_get_eap_auth_credentials_req_msg_v01));
	os_memset(&key_resp_msg, 0,
		  sizeof(auth_get_eap_auth_credentials_resp_msg_v01));

	key_req_msg.cred_request_mask = QMI_AUTH_MASK_EAP_CRED_MSK_V01 |
					QMI_AUTH_MASK_EAP_CRED_EXT_MSK_V01 |
					QMI_AUTH_MASK_EAP_CRED_SESSION_ID_V01;

	qmiRetCode = qmi_client_send_msg_sync(
			sm->qmi_auth_svc_client_ptr[sm->user_selected_sim],
			QMI_AUTH_GET_EAP_AUTH_CREDENTIALS_REQ_V01,
			&key_req_msg,
			sizeof(auth_get_eap_auth_credentials_req_msg_v01),
			&key_resp_msg,
			sizeof(auth_get_eap_auth_credentials_resp_msg_v01),
			WPA_UIM_QMI_DEFAULT_TIMEOUT);

	/* see if the keys are acquired successfully */
	if (QMI_NO_ERR != qmiRetCode ||
	    key_resp_msg.resp.result != QMI_RESULT_SUCCESS_V01) {
	        wpa_printf(MSG_ERROR,
			   "QMI-ERROR Unable to get keys, err_code=%d qmiErr=%d "
			   "Try using msg QMI_AUTH_GET_EAP_SESSION_KEYS_REQ_V01",
			   qmiRetCode, key_resp_msg.resp.error);
	        return eap_proxy_getKey(sm);
	}

	wpa_printf(MSG_ERROR, "eap_proxy: qmi msk_valid:%d emsk_valid:%d session_id_valid:%d",
		   key_resp_msg.msk_valid, key_resp_msg.ext_msk_valid,
		   key_resp_msg.session_id_valid);

	if (key_resp_msg.msk_valid && key_resp_msg.msk_len > 0 &&
	    key_resp_msg.msk_len <= EAP_PROXY_KEYING_DATA_LEN) {
		os_free(sm->key);
		sm->key = os_zalloc(EAP_PROXY_KEYING_DATA_LEN);
		if (sm->key != NULL) {
			os_memcpy(sm->key, key_resp_msg.msk,
				  key_resp_msg.msk_len);
			sm->iskey_valid = TRUE;
			sm->proxy_state = EAP_PROXY_AUTH_SUCCESS;
			wpa_hexdump_key(MSG_DEBUG, "eap_proxy: session key",
					sm->key, EAP_PROXY_KEYING_DATA_LEN);

		}
	}

	if (key_resp_msg.ext_msk_valid && key_resp_msg.ext_msk_len > 0 &&
	    key_resp_msg.ext_msk_len <= EAP_PROXY_KEYING_DATA_LEN) {
		os_free(sm->emsk);
		sm->emsk = os_zalloc(EAP_PROXY_KEYING_DATA_LEN);
		if (sm->emsk != NULL) {
			os_memcpy(sm->emsk, key_resp_msg.ext_msk,
				  key_resp_msg.ext_msk_len);
			wpa_hexdump_key(MSG_DEBUG, "eap_proxy: emsk", sm->emsk,
					EAP_PROXY_KEYING_DATA_LEN);
		}
	}

	if (key_resp_msg.session_id_valid) {
		os_free(sm->session_id);
		sm->session_id = os_zalloc(key_resp_msg.session_id_len);
		if (sm->session_id != NULL) {
			os_memcpy(sm->session_id, key_resp_msg.session_id,
				  key_resp_msg.session_id_len);
			sm->session_id_len = key_resp_msg.session_id_len;
			wpa_hexdump_key(MSG_DEBUG, "eap_proxy: session_id",
					sm->session_id, sm->session_id_len);
		}
	}

	return sm->key;
}

/**
 * eap_key_available - Get key availability (eapKeyAvailable variable)
 * @sm: Pointer to EAP state machine allocated with eap_sm_init()
 * Returns: 1 if EAP keying material is available, 0 if not
 */
int eap_proxy_key_available(struct eap_proxy_sm *sm)
{
        return sm ? sm->iskey_valid : 0;
}


static int eap_proxy_is_state_changed(struct eap_proxy_sm *sm)
{
        if (NULL == sm)
                return 0;

        if (TRUE == sm->is_state_changed) {
                sm->is_state_changed = FALSE;
                return 1;
        } else {
                return 0;
        }
}


/**
 * eap_get_eapKeyData - Get master session key (MSK) from EAP state machine
 * @sm: Pointer to EAP state machine allocated with eap_sm_init()
 * @len: Pointer to variable that will be set to number of bytes in the key
 * Returns: Pointer to the EAP keying data or %NULL on failure
 *
 * Fetch EAP keying material (MSK, eapKeyData) from the EAP state machine. The
 * key is available only after a successful authentication. EAP state machine
 * continues to manage the key data and the caller must not change or free the
 * returned data.
 */
const u8 * eap_proxy_get_eapKeyData(struct eap_proxy_sm *sm, size_t *len)
{
        if (sm == NULL || sm->key == NULL) {
                *len = 0;
                return NULL;
        }

        *len = EAP_PROXY_KEYING_DATA_LEN;
        return sm->key;
}


u8 * eap_proxy_get_eap_session_id(struct eap_proxy_sm *sm, size_t *len)
{
	u8 *id;

	*len = 0;
	if (sm == NULL || sm->session_id == NULL)
		return NULL;

	id = os_malloc(sm->session_id_len);
	if (id == NULL)
		return NULL;

	os_memcpy(id, sm->session_id, sm->session_id_len);
	*len = sm->session_id_len;
	return id;
}


u8 * eap_proxy_get_emsk(struct eap_proxy_sm *sm, size_t *len)
{
	u8 *emsk;

	*len = 0;
	if (sm == NULL || sm->emsk == NULL)
		return NULL;

	emsk = os_malloc(EAP_PROXY_KEYING_DATA_LEN);
	if (emsk == NULL)
		return NULL;

	os_memcpy(emsk, sm->emsk, EAP_PROXY_KEYING_DATA_LEN);
	*len = EAP_PROXY_KEYING_DATA_LEN;
	return emsk;
}


void eap_proxy_sm_abort(struct eap_proxy_sm *sm)
{
	if (sm == NULL)
		return;

	if (sm->key) {
		os_free(sm->key);
		sm->key = NULL;
	}

	if (sm->emsk) {
		os_free(sm->emsk);
		sm->emsk = NULL;
	}

	if (sm->session_id) {
		os_free(sm->session_id);
		sm->session_id = NULL;
		sm->session_id_len = 0;
	}

	sm->iskey_valid = FALSE;
}


/**
 * eap_proxy_get_eapRespData - Get EAP response data
 * @sm: Pointer to EAP state machine allocated with eap_sm_init()
 * @len: Pointer to variable that will be set to the length of the response
 * Returns: Pointer to the EAP response (eapRespData) or %NULL on failure
 *
 * Fetch EAP response (eapRespData) from the EAP state machine. This data is
 * available when EAP state machine has processed an incoming EAP request. The
 * EAP state machine does not maintain a reference to the response after this
 * function is called and the caller is responsible for freeing the data.
 */
struct wpabuf * eap_proxy_get_eapRespData(struct eap_proxy_sm *eap_proxy)
{
        struct wpabuf *resp;
        int len;
        //int i;

        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_get_eapRespData");
        if ((eap_proxy == NULL) || (!eap_proxy->initialized) ||
            (eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data == NULL))
                return NULL;

        len = eap_proxy->qmi_resp_data.eap_send_pkt_resp.length;
        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_get_eapRespData len = %d", len);
        resp = wpabuf_alloc(len);
        if (resp == NULL) {
                wpa_printf(MSG_ERROR, "eap_proxy: buf allocation failed\n");
                return NULL;
        }

        resp->used = len;
        os_memcpy(resp->buf, eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data,
                   len);
        /*
        for (i = 0; i < len; i++) {
                wpa_printf (MSG_ERROR, "%c", resp->buf[i]);
        }
        */
        os_free(eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data);
        eap_proxy->qmi_resp_data.eap_send_pkt_resp.resp_data = NULL;
        eap_proxy->qmi_resp_data.eap_send_pkt_resp.length = 0;

        return resp;
}


static enum eap_proxy_status eap_proxy_qmi_response_wait(struct eap_proxy_sm *eap_proxy)
{

        int count = 0;

        wpa_printf(MSG_ERROR, "eap_proxy_qmi_response_wait: Start blocking "
                   "wait eap_proxy=%p",eap_proxy);
        do {
                count++;
                if (count > QMI_RESP_TIME_OUT / 2) {
                        wpa_printf(MSG_ERROR,
                                   "eap_proxy: eap_proxy_qmi_response_wait "
                                   "!QMI STATE %d TIME_OUT\n",
                                   eap_proxy->qmi_state);
                        eap_proxy->qmi_state = QMI_STATE_RESP_TIME_OUT;
                        break;
                }

                os_sleep(0, 2000);

                if ((QMI_STATE_RESP_RECEIVED == eap_proxy->qmi_state) ||
                   (QMI_STATE_RESP_TIME_OUT == eap_proxy->qmi_state))
                        break;
        } while (1);

        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_qmi_response_wait: Wait done after %d "
                   "iterations: qmi_state=%d", count,
                   eap_proxy->qmi_state);

        if (QMI_STATE_RESP_TIME_OUT == eap_proxy->qmi_state) {
                wpa_printf(MSG_ERROR, "eap_proxy: QMI state Response Time out\n");
                eap_proxy->proxy_state = EAP_PROXY_DISCARD;
                return EAP_PROXY_FAILURE;
        }
        eap_proxy->qmi_state = QMI_STATE_IDLE;

        return EAP_PROXY_SUCCESS;
}


static void eap_proxy_eapol_sm_set_bool(struct eap_proxy_sm *sm,
                        enum eapol_bool_var var, Boolean value)
{
        sm->eapol_cb->set_bool(sm->ctx, var, value);
}


static Boolean eap_proxy_eapol_sm_get_bool(struct eap_proxy_sm *sm,
                         enum eapol_bool_var var)
{
        return  sm->eapol_cb->get_bool(sm->ctx, var);
}


int eap_proxy_sm_step(struct eap_proxy_sm *sm, struct eap_sm *eap_sm)
{
        if ((sm->proxy_state != EAP_PROXY_INITIALIZE) &&
                                 (sm->proxy_state != EAP_PROXY_DISABLED)) {
                if (TRUE == sm->isEap) {
                        if(!eap_proxy_process(sm, sm->eapReqData,
                                                 sm->eapReqDataLen,eap_sm)) {
                                sm->proxy_state = EAP_PROXY_AUTH_FAILURE;
                                eap_proxy_eapol_sm_set_bool(sm, EAPOL_eapRestart, TRUE);
                        }
                        sm->isEap = FALSE;
                }
        }
        return eap_proxy_is_state_changed(sm);
}


enum eap_proxy_status
eap_proxy_packet_update(struct eap_proxy_sm *eap_proxy, u8 *eapReqData,
                        int eapReqDataLen)
{
        eap_proxy->eapReqData = eapReqData;
        eap_proxy->eapReqDataLen = eapReqDataLen;
        eap_proxy->isEap = TRUE;
        return EAP_PROXY_SUCCESS;
}


static void dump_buff(u8 *buff, int len)
{
        wpa_printf(MSG_ERROR, "eap_proxy: ---- EAP Buffer----LEN %d",len);

        while (len > 32) {
                wpa_hexdump(MSG_DEBUG, "eap_proxy:", buff, 32);
                buff += 32;
                len -= 32;
        }
        wpa_hexdump(MSG_DEBUG, "eap_proxy: ", buff, len);
}

static char bin_to_hexchar(u8 ch)
{
        if (ch < 0x0a) {
                return ch + '0';
        }
        return ch + 'a' - 10;
}
static Boolean eap_proxy_build_identity(struct eap_proxy_sm *eap_proxy, u8 id, struct eap_sm *eap_sm)
{
        struct eap_hdr *resp;
        unsigned int len;
        u8 identity_len = 0, ret;
        u8 imsi_id_len = 0;
        int mnc_len = -1;
        u8 *pos;
        int qmiRetCode;
        u8 idx = 0, mcc_idx = 0;
        unsigned char *identity = NULL;
        unsigned char *imsi_identity = NULL;
        auth_start_eap_session_req_msg_v01 eap_auth_start;
        auth_start_eap_session_resp_msg_v01 eap_auth_start_resp;
        auth_set_subscription_binding_req_msg_v01 sub_req_binding;
        auth_set_subscription_binding_resp_msg_v01 sub_resp_binding;

        struct eap_method_type *m;
        eap_identity_format_e identity_format = EAP_IDENTITY_ANNONYMOUS;
        Boolean simEnabled = FALSE, akaEnabled = FALSE;
        struct eap_peer_config *config = eap_get_config(eap_sm);
        const char *realm_3gpp = "@wlan.mnc000.mcc000.3gppnetwork.org";
        int sim_num;

        wpa_printf(MSG_ERROR, "eap_proxy: %s\n", __func__);
        sim_num = config->sim_num - 1;
        os_memset(&eap_auth_start, 0, sizeof(eap_auth_start));
        os_memset(&eap_auth_start_resp, 0, sizeof(eap_auth_start_resp));

        eap_auth_start.user_id_len = 0;
        m = config->eap_methods;

        if (sim_num >= MAX_NO_OF_SIM_SUPPORTED || sim_num < 0) {
                wpa_printf (MSG_ERROR, "eap_proxy: Invalid SIM selected sim by user = %d\n",
                             sim_num+1);
                return FALSE;
        }
        wpa_printf(MSG_ERROR, "eap_proxy: User selected sim = %d\n", sim_num + 1);

        if (m != NULL) {
                for (idx = 0; m[idx].vendor != EAP_VENDOR_IETF ||
                                m[idx].method != EAP_TYPE_NONE; idx++) {
                        if (m[idx].method == EAP_TYPE_AKA) {
                                akaEnabled = TRUE;
                                eap_auth_start.eap_method_mask_valid = 1;
                                eap_auth_start.eap_method_mask |= QMI_AUTH_EAP_METHOD_MASK_AKA_V01;
                                wpa_printf(MSG_ERROR, "eap_proxy: AKA Enabled\n");
                        } else if (m[idx].method == EAP_TYPE_SIM) {
                                simEnabled = TRUE;
                                eap_auth_start.eap_method_mask_valid = 1;
                                eap_auth_start.eap_method_mask |= QMI_AUTH_EAP_METHOD_MASK_SIM_V01;
                                wpa_printf(MSG_ERROR, "eap_proxy: SIM Enabled\n");
#ifdef CONFIG_EAP_PROXY_AKA_PRIME
                        } else if (m[idx].method == EAP_TYPE_AKA_PRIME) {
                                eap_auth_start.eap_method_mask_valid = 1;
                                eap_auth_start.eap_method_mask |=
                                        QMI_AUTH_EAP_METHOD_MASK_AKA_PRIME_V01;
                                wpa_printf(MSG_ERROR, "eap_proxy: AKA Prime Enabled\n");
#endif /* CONFIG_EAP_PROXY_AKA_PRIME */
                        }
                }
        } else {
                wpa_printf(MSG_ERROR, "eap_proxy: eap_methods is NULL!\n");
                return FALSE;
        }

        eap_auth_start.eap_method_mask_valid = 1;

        idx = 0;
#ifdef SIM_AKA_IMSI_RAW_ENABLED

        identity_format = EAP_IDENTITY_IMSI_RAW;
        eap_auth_start.user_id_valid = 1;
        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_IMSI_RAW selected %d \n",
                eap_auth_start.user_id_len);

#else /* SIM_AKA_IMSI_RAW_ENABLED */

#ifdef EAP_PROXY_USE_CONFIG_IDENTITY
        if (config->identity_len && config->identity != NULL) {
                for (idx = 0; idx < config->identity_len; idx++) {
                        if (config->identity[idx] == 64) {
                                wpa_printf(MSG_ERROR, "eap_proxy: @ found \n");
                                mcc_idx = idx;
                                if ((mcc_idx + 18) > config->identity_len)
                                        mcc_idx = 0;
                                else {
                                        /* Looking for mnc and mcc pattern */
                                        if (109 == config->identity[mcc_idx + 6] &&
                                                (110 == config->identity[mcc_idx + 7]) &&
                                                (99 == config->identity[mcc_idx + 8]) &&
                                                (109 == config->identity[mcc_idx + 13]) &&
                                                (99 == config->identity[mcc_idx + 14]) &&
                                                (99 == config->identity[mcc_idx + 15])) {
                                                mcc_idx += 9;
                                        } else
                                                mcc_idx = 0;
                                }
                                break;
                        }
                }

                wpa_printf(MSG_ERROR, "eap_proxy: idx %d\n", idx);
                wpa_printf(MSG_ERROR, "eap_proxy: mcc idx %d\n", mcc_idx);

                if (!idx && (config->identity_len == 1)) {
                        /* config file : @ */
                        config->identity_len = 0;
                        identity_format = EAP_IDENTITY_IMSI_3GPP_REALM;
                        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_IMSI_3GPP_REALM "
                                "selected \n");
                } else if (idx && (idx < config->identity_len) && (config->identity != NULL)) {

                        /* config file : <>@<> or <>@<wlan.mnc000.mcc000.<>.<> */
                        identity_len = config->identity_len;
                        identity = os_malloc(config->identity_len);

                        if (NULL != identity) {
                                os_memset(identity, 0, config->identity_len);
                                os_memcpy(identity, config->identity,
                                                config->identity_len);
                        }

                        /* To Do for 3GPP realm */
                        identity_format = EAP_IDENTITY_CFG_3GPP_REALM;
                        eap_auth_start.user_id_valid = 1;
                        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_CFG_3GPP_REALM "
                                "selected %d \n", eap_auth_start.user_id_len);

                } else if ((idx == config->identity_len) && config->identity_len &&
                                        (config->identity != NULL)) {

                        /* config file : <identity in RAW format >*/
                        identity_len = config->identity_len;
                        identity = os_malloc(config->identity_len);

                        if (NULL != identity) {
                                os_memset(identity, 0, config->identity_len);
                                os_memcpy(identity, config->identity,
                                                config->identity_len);
                        }

                        identity_format = EAP_IDENTITY_CFG_RAW;
                        eap_auth_start.user_id_valid = 1;
                        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_CFG_RAW selected %d \n",
                                eap_auth_start.user_id_len);
                } else if (!idx && mcc_idx) {

                        /* config file: @wlan.mnc000.mcc000.<>.<> */
                        identity_len = config->identity_len;
                        identity = os_malloc(config->identity_len);

                        if (NULL != identity) {
                                os_memset(identity, 0, config->identity_len);
                                os_memcpy(identity, config->identity,
                                         config->identity_len);
                        }

                        identity_format = EAP_IDENTITY_IMSI_3GPP_REALM;
                        eap_auth_start.user_id_valid = 1;
                        wpa_printf(MSG_ERROR, "eap_proxy: config EAP_IDENTITY_IMSI_3GPP_REALM "
                                "selected %d\n", eap_auth_start.user_id_len);
                }
        } else
#endif /* EAP_PROXY_USE_CONFIG_IDENTITY */
        {
                if (config->anonymous_identity_len && config->anonymous_identity != NULL) {

                        eap_auth_start.eap_meta_identity_len = config->anonymous_identity_len;
                        os_memcpy(&eap_auth_start.eap_meta_identity ,
                                                config->anonymous_identity ,
                                                config->anonymous_identity_len);

                        identity_format = EAP_IDENTITY_ANNONYMOUS;
                        eap_auth_start.eap_meta_identity_valid = 1;
                        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_ANNONYMOUS selected user id "
                                "%d, annonymous %d\n", eap_auth_start.user_id_len,
                                eap_auth_start.eap_meta_identity_len);
                } else {
                        /* config file doesn't contain any identity
                                generating IMSI@realm */
                        identity_format = EAP_IDENTITY_IMSI_3GPP_REALM;
                        eap_auth_start.user_id_valid = 1;
                        wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_IMSI_3GPP_REALM id len %d\n",
                                eap_auth_start.user_id_len);
                }
        }
#endif /* SIM_AKA_IMSI_RAW_ENABLED */
        if (identity_format == EAP_IDENTITY_IMSI_3GPP_REALM ||
                identity_format == EAP_IDENTITY_IMSI_RAW || mcc_idx) {

                wpa_printf(MSG_ERROR, "eap_proxy: EAP_IDENTITY_IMSI_3GPP_REALM is selected\n");
                if (!wpa_qmi_read_card_status(sim_num, eap_proxy->wpa_uim)) {
                        wpa_printf(MSG_INFO, "eap_proxy: Read Card Status failed, return\n");
                        if (NULL != identity) {
                                os_free(identity);
                                identity = NULL;
                        }
                        return FALSE;
                }

                if (!wpa_qmi_read_card_imsi(sim_num, eap_proxy->wpa_uim)) {
                        wpa_printf(MSG_INFO, "eap_proxy: Read Card IMSI failed, return\n");
                        if (NULL != identity) {
                                os_free(identity);
                                identity = NULL;
                        }
                        return FALSE;
                }

                if (imsi == NULL) {
                        wpa_printf(MSG_INFO, "eap_proxy: IMSI not available, return\n");
                        if (NULL != identity) {
                                os_free(identity);
                                identity = NULL;
                        }
                        return FALSE;
                } else {
                        wpa_printf(MSG_ERROR, "eap_proxy: IMSI not NULL \n");
                        if (NULL == identity)
                                wpa_printf(MSG_ERROR,
                                        "eap_proxy: config file doesn't contain identity \n");
                        else
                                wpa_printf(MSG_ERROR, "eap_proxy: config file contains identity\n");

                        wpa_printf(MSG_ERROR, "eap_proxy: eap_type: %d\n", eap_proxy->eap_type);

                        if (!idx) {

                                /* IMSI is expected as username */
                                wpa_printf(MSG_ERROR, "eap_proxy:  username is not available in"
                                        " config picking IMSI \n");

                                if (config->identity_len > 1)
                                        /* @realm provided in config */
                                        imsi_identity =
                                                os_malloc(1 + IMSI_LENGTH + config->identity_len);
                                else if (identity_format == EAP_IDENTITY_IMSI_3GPP_REALM)
                                        /* IMSI@realm not provided through config */
                                        imsi_identity =
                                                os_malloc(1 + IMSI_LENGTH + os_strlen(realm_3gpp));
                                else
                                        /* IMSI RAW */
                                        imsi_identity = os_malloc(1 + IMSI_LENGTH);

                                if (NULL == imsi_identity) {
                                        wpa_printf(MSG_ERROR, "eap_proxy: Memory not available\n");
                                        if (NULL != identity) {
                                                os_free(identity);
                                                identity = NULL;
                                        }
                                        return FALSE;
                                } else {
                                        if (config->identity_len > 1)
                                                os_memset(imsi_identity, 0,
                                                        (1 + IMSI_LENGTH + config->identity_len));
                                        else if (identity_format == EAP_IDENTITY_IMSI_3GPP_REALM)
                                                os_memset(imsi_identity, 0,
                                                        (1 + IMSI_LENGTH + os_strlen(realm_3gpp)));
                                        else
                                                os_memset(imsi_identity, 0, (1 + IMSI_LENGTH));

                                        if (eap_proxy->eap_type == EAP_TYPE_SIM)
                                                imsi_identity[0] = '1';
                                        else if (eap_proxy->eap_type == EAP_TYPE_AKA)
                                                imsi_identity[0] = '0';
#ifdef CONFIG_EAP_PROXY_AKA_PRIME
                                        else if (eap_proxy->eap_type == EAP_TYPE_AKA_PRIME)
                                                imsi_identity[0] = '6';
#endif /* CONFIG_EAP_PROXY_AKA_PRIME */
                                        else
                                                /* Default value is set as SIM */
                                                imsi_identity[0] = '1';

                                        /* copying IMSI value */
                                        os_memcpy(imsi_identity + 1 , imsi , imsi_len_g);

                                        if (config->identity_len > 1 && NULL != identity) {
                                                /* copying realm tag */
                                                os_memcpy(imsi_identity + 1 + imsi_len_g , identity,
                                                        config->identity_len);
                                                imsi_id_len = imsi_len_g + 1 + config->identity_len;
                                                os_free(identity);
                                                identity = NULL;
                                        } else if(identity_format == EAP_IDENTITY_IMSI_3GPP_REALM) {
                                                /* realm is not available so append it */
                                                os_memcpy(imsi_identity + 1 + imsi_len_g,
                                                        realm_3gpp, os_strlen(realm_3gpp));
                                                imsi_id_len = imsi_len_g + 1 +
                                                        os_strlen(realm_3gpp);
                                        } else
                                                /* IMSI RAW */
                                                imsi_id_len = imsi_len_g + 1;
                                }
                        } else if (identity) {
                                /* idx is non-zero implies username available */
                                imsi_identity = identity;
                                imsi_id_len = config->identity_len;
                        }
                }

                if (identity_format == EAP_IDENTITY_IMSI_3GPP_REALM || mcc_idx) {

                        if (0 == idx) {
                        /* id = @wlan.mnc000.mcc000.<>.<> realm exist
                                but need to insert mnc and mcc values */
                                idx = imsi_len_g + 1;
                        }

                        if (imsi_identity != NULL) {
                                /* mcc valus */
                                imsi_identity[idx + 16] = imsi[0];
                                imsi_identity[idx + 17] = imsi[1];
                                imsi_identity[idx + 18] = imsi[2];
                        }

                        /* mnc valus */
                        mnc_len = card_mnc_len;
                        wpa_printf(MSG_ERROR, "eap_proxy: card mnc len %d\n", card_mnc_len);

                        if ((mnc_len == 2) && (imsi_identity != NULL)) {
                                imsi_identity[idx + 9]  = '0';
                                imsi_identity[idx + 10] = imsi[3];
                                imsi_identity[idx + 11] = imsi[4];
                        } else if ((mnc_len == 3) && (imsi_identity != NULL)) {
                                imsi_identity[idx + 9]  = imsi[3];
                                imsi_identity[idx + 10] = imsi[4];
                                imsi_identity[idx + 11] = imsi[5];
                        }
                        wpa_printf(MSG_ERROR, "eap_proxy:  Appending 3gpp realm\n ");
                }
                identity = imsi_identity;
                identity_len = imsi_id_len;
                eap_auth_start.user_id_valid = 1;
        }

        eap_auth_start.user_id_len = identity_len;

        if(identity_len >= QMI_AUTH_EAP_IDENTITY_MAX_CHAR_V01)
        {
                wpa_printf(MSG_ERROR, "eap_proxy: Invalid User Identity length =%d",identity_len);
                return FALSE;
        }

        if(identity)
        {
                memcpy(&eap_auth_start.user_id, identity, identity_len);
                eap_auth_start.user_id_valid = 1;
        }

        wpa_printf(MSG_ERROR, "eap_proxy: eap auth user identity  - %20s length-%d\n ",
                    eap_auth_start.user_id, eap_auth_start.user_id_len);

        if ( (sim_num < 0) || (sim_num >= MAX_NO_OF_SIM_SUPPORTED)) {
                wpa_printf(MSG_ERROR, "eap_proxy: SIM: Invalid SIM selected by "
                            "User: Selected sim = %d\n", sim_num+1);
                return FALSE;
        }


        eap_proxy->user_selected_sim = sim_num;
        wpa_printf(MSG_ERROR, "eap_proxy: SIM selected by User: Selected sim = %d\n",
                    eap_proxy->user_selected_sim+1);

        memset(&sub_req_binding, 0, sizeof(auth_set_subscription_binding_req_msg_v01));
        memset(&sub_resp_binding, 0, sizeof(auth_set_subscription_binding_resp_msg_v01));
#ifdef CONFIG_EAP_PROXY_DUAL_SIM
        if (sim_num == 0) {
                sub_req_binding.bind_subs = AUTH_PRIMARY_SUBS_V01;
                qmiRetCode = qmi_client_send_msg_sync(eap_proxy->qmi_auth_svc_client_ptr[sim_num],
                                QMI_AUTH_SET_SUBSCRIPTION_BINDING_REQ_V01,
                                                (void *) &sub_req_binding,
                                                sizeof(auth_set_subscription_binding_req_msg_v01),
                                                (void *) &sub_resp_binding,
                                                sizeof(auth_set_subscription_binding_resp_msg_v01),
                                                WPA_UIM_QMI_DEFAULT_TIMEOUT);

                if ((QMI_NO_ERR != qmiRetCode ||
                     sub_resp_binding.resp.result != QMI_RESULT_SUCCESS_V01 ) &&
                    (QMI_ERR_OP_DEVICE_UNSUPPORTED_V01 != sub_resp_binding.resp.error)) {
                        wpa_printf(MSG_ERROR, "QMI-ERROR Unable to get the qmi_auth_set_subscriptio"
                                "n_binding for sim 1; error_ret=%d; error_code=%d\n", qmiRetCode,
                                sub_resp_binding.resp.error);
                        return FALSE;
                }
                wpa_printf (MSG_ERROR, "eap_proxy: Binded with PRIMARY Subscription\n");
        } else if (sim_num == 1) {
                sub_req_binding.bind_subs = AUTH_SECONDARY_SUBS_V01;
                qmiRetCode = qmi_client_send_msg_sync(eap_proxy->qmi_auth_svc_client_ptr[sim_num],
                                QMI_AUTH_SET_SUBSCRIPTION_BINDING_REQ_V01,
                                                (void *) &sub_req_binding,
                                                sizeof(auth_set_subscription_binding_req_msg_v01),
                                                (void *) &sub_resp_binding,
                                                sizeof(auth_set_subscription_binding_resp_msg_v01),
                                                WPA_UIM_QMI_DEFAULT_TIMEOUT);

                if (QMI_NO_ERR != qmiRetCode ||
                    sub_resp_binding.resp.result != QMI_RESULT_SUCCESS_V01 ) {
                        wpa_printf(MSG_ERROR, "QMI-ERROR Unable to get the qmi_auth_set_subscriptio"
                                "n_binding for sim 2; error_ret=%d; error_code=%d\n", qmiRetCode,
                                sub_resp_binding.resp.error);
                        return FALSE;
                }

                wpa_printf (MSG_ERROR, "eap_proxy: Binded with SECONDARY Subscription\n");
        } else {
                wpa_printf(MSG_ERROR, "eap_proxy: Invalid SIM selected by User: "
                        "Selected sim = %d\n", sim_num+1);
                return FALSE;
        }
#endif
        if (TRUE == eap_proxy->eap_auth_session_flag[sim_num]) {
                if(eap_auth_end_eap_session(eap_proxy->qmi_auth_svc_client_ptr[sim_num]) < 0) {
                        wpa_printf(MSG_ERROR, "eap_proxy: Unable to end the EAP session;"
                                                " sim_num%d;", sim_num);
                        }
                        eap_proxy->eap_auth_session_flag[sim_num] = FALSE;
        }

        if (FALSE == eap_proxy->eap_auth_session_flag[sim_num]) {
                        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_start values\n");
                        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_start.eap_method_mask = %d\n",
                                eap_auth_start.eap_method_mask);
                        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_start.user_id_len = %d\n",
                                eap_auth_start.user_id_len);
                        wpa_printf(MSG_ERROR, "eap_proxy: eap_auth_start.eap_meta_id_len = %d\n",
                                eap_auth_start.eap_meta_identity_len);
                        wpa_printf(MSG_ERROR, "eap_auth_start.eap_sim_aka_algo = %d\n",
                                eap_auth_start.eap_sim_aka_algo);
        qmiRetCode = qmi_client_send_msg_sync(eap_proxy->qmi_auth_svc_client_ptr[sim_num],
                                                QMI_AUTH_START_EAP_SESSION_REQ_V01,
                                                (void *) &eap_auth_start,
                                                sizeof(auth_start_eap_session_req_msg_v01),
                                                (void *) &eap_auth_start_resp,
                                                sizeof(auth_start_eap_session_resp_msg_v01),
                                                WPA_UIM_QMI_DEFAULT_TIMEOUT);
        if (QMI_NO_ERR != qmiRetCode ||
            eap_auth_start_resp.resp.result != QMI_RESULT_SUCCESS_V01) {
                wpa_printf(MSG_ERROR, " QMI-ERROR Unable to start the EAP session;"
                           " error_ret=%d; qmi_err=%d\n", qmiRetCode,
                           eap_auth_start_resp.resp.error);
                if(eap_auth_start.eap_method_mask == QMI_AUTH_EAP_METHOD_MASK_AKA_PRIME_V01 &&
                   eap_auth_start_resp.resp.error == QMI_ERR_INVALID_ARG_V01)
                        wpa_printf(MSG_ERROR, "QMI-ERROR AKA' not supported\n");

                return FALSE;
                }
                eap_proxy->eap_auth_session_flag[sim_num] = TRUE;
                eap_proxy->notification_code = 0;
                eap_proxy->qmi_state = QMI_STATE_IDLE;
                wpa_printf(MSG_ERROR, "eap_proxy: EAP session started"
                           " error_ret=%d; Resp=%d\n", qmiRetCode,
                            eap_auth_start_resp.resp.error);
        }

        return TRUE;
}



#ifdef CONFIG_CTRL_IFACE

/**
 * eap_proxyl_sm_get_status - Get EAP state machine status
 * @sm: Pointer to EAP state machine allocated with eap_sm_init()
 * @buf: Buffer for status information
 * @buflen: Maximum buffer length
 * @verbose: Whether to include verbose status information
 * Returns: Number of bytes written to buf.
 *
 * Query EAP state machine for status information. This function fills in a
 * text area with current status information from the EAPOL state machine. If
 * the buffer (buf) is not large enough, status information will be truncated
 * to fit the buffer.
 */
int eap_proxy_sm_get_status(struct eap_proxy_sm *sm, char *buf, size_t buflen,
                            int verbose)
{
        int len, ret;

        if (sm == NULL)
                return 0;

        len = os_snprintf(buf, buflen, "eap_proxy: EAP state=%s\n",
                          eap_proxy_sm_state_txt(sm->proxy_state));
        if (len < 0 || (size_t)len >= buflen)
                return 0;

        if (sm->eap_type != EAP_TYPE_NONE) {
                char name[8];

                if (sm->eap_type == EAP_TYPE_SIM)
                        os_strlcpy(name, "SIM", 4);
                else if (sm->eap_type == EAP_TYPE_AKA)
                        os_strlcpy(name, "AKA", 4);
                else if (sm->eap_type == EAP_TYPE_AKA_PRIME)
                        os_strlcpy(name, "AKA'", 5);
                else
                        os_strlcpy(name, "Unknown", 8);

                ret = os_snprintf(buf + len, buflen - len,
                                "selectedMethod=%d (EAP-%s)\n",
                                        sm->eap_type, name);
                if (ret < 0 || (size_t)ret >= buflen - len)
                        return len;
                len += ret;
        }

        return len;
}


static const char *eap_proxy_sm_state_txt(int state)
{
        switch (state) {
        case EAP_PROXY_INITIALIZE:
                return "INITIALIZE";
        case EAP_PROXY_DISABLED:
                return "DISABLED";
        case EAP_PROXY_IDLE:
                return "IDLE";
        case EAP_PROXY_RECEIVED:
                return "RECEIVED";
        case EAP_PROXY_GET_METHOD:
                return "GET_METHOD";
        case EAP_PROXY_METHOD:
                return "METHOD";
        case EAP_PROXY_SEND_RESPONSE:
                return "SEND_RESPONSE";
        case EAP_PROXY_DISCARD:
                return "DISCARD";
        case EAP_PROXY_IDENTITY:
                return "IDENTITY";
        case EAP_PROXY_NOTIFICATION:
                return "NOTIFICATION";
        case EAP_PROXY_RETRANSMIT:
                return "RETRANSMIT";
        case EAP_PROXY_AUTH_SUCCESS:
                return "SUCCESS";
        case EAP_PROXY_AUTH_FAILURE:
                return "FAILURE";
        default:
                return "UNKNOWN";
        }
}
#endif /* CONFIG_CTRL_IFACE */


/**
 * eap_proxy_get_imsi - Get IMSI
 * @config_sim_num: sim number for the configuration, -1 if not specified
 * @imsi_buf: Buffer for returning IMSI
 * @imsi_len: Buffer for returning IMSI length
 * Returns: MNC length (2 or 3) or -1 on error
 */
int eap_proxy_get_imsi(struct eap_proxy_sm *eap_proxy, int config_sim_num,
		       char *imsi_buf, size_t *imsi_len)
{
#ifdef SIM_AKA_IDENTITY_IMSI
	int mnc_len;
	int sim_num;

	if (config_sim_num > 0) {
		sim_num = config_sim_num - 1;
		if (sim_num >= MAX_NO_OF_SIM_SUPPORTED) {
			wpa_printf(MSG_ERROR,
				   "eap_proxy: Invalid user sim %d selected",
				   config_sim_num);
			return -1;
		}
	} else {
		sim_num = eap_proxy->user_selected_sim;
	}

	if ((eap_proxy->proxy_state == EAP_PROXY_DISABLED) ||
	    (eap_proxy->proxy_state == EAP_PROXY_INITIALIZE)) {
		wpa_printf(MSG_ERROR,
			   "eap_proxy:%s: Not initialized", __func__);
		return -1;
	}

	if (!wpa_qmi_read_card_status(sim_num, eap_proxy->wpa_uim)) {
		wpa_printf(MSG_INFO, "eap_proxy: Card not ready");
		return -1;
	}

	if (!wpa_qmi_read_card_imsi(sim_num, eap_proxy->wpa_uim) ||
	    imsi == NULL) {
		wpa_printf(MSG_INFO, "eap_proxy: Failed to read card IMSI");
		return -1;
	}

	*imsi_len = os_strlen(imsi);
	os_memcpy(imsi_buf, imsi, *imsi_len + 1);

	mnc_len = card_mnc_len;
	if (mnc_len < 2 || mnc_len > 3)
		mnc_len = 3; /* Default to 3 if MNC length is unknown */

	os_free(imsi);
	imsi = NULL;

	return mnc_len;
#else /* SIM_AKA_IDENTITY_IMSI */
	return -1;
#endif /* SIM_AKA_IDENTITY_IMSI */
}

int eap_proxy_notify_config(struct eap_proxy_sm *eap_proxy,
                            struct eap_peer_config *config)
{
        int ret_val;

        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_notify_config\n");
        if (!eap_proxy) {
                wpa_printf(MSG_ERROR, "eap_proxy: is NULL");
                return FALSE;
        }

        if ((eap_proxy->proxy_state == EAP_PROXY_DISABLED) ||
            (eap_proxy->proxy_state == EAP_PROXY_INITIALIZE)) {
                wpa_printf(MSG_ERROR, "eap_proxy: Not initialized\n");
                return FALSE;
        }

        if ( config && eap_proxy_allowed_method(config, EAP_VENDOR_IETF,
                        EAP_TYPE_SIM)) {
                eap_proxy->eap_type =  EAP_TYPE_SIM;
                ret_val = TRUE;
        } else if ( config && eap_proxy_allowed_method(config, EAP_VENDOR_IETF,
                                EAP_TYPE_AKA)) {
                eap_proxy->eap_type =  EAP_TYPE_AKA;
                ret_val = TRUE;
        } else if ( config && eap_proxy_allowed_method(config, EAP_VENDOR_IETF,
                                EAP_TYPE_AKA_PRIME)) {
                eap_proxy->eap_type =  EAP_TYPE_AKA_PRIME;
                ret_val = TRUE;
        } else
                ret_val = FALSE;

        return ret_val;
}

int eap_proxy_allowed_method(struct eap_peer_config *config, int vendor,
                              u32 method)
{
        int i;
        struct eap_method_type *m;

        wpa_printf(MSG_ERROR, "eap_proxy: eap_proxy_allowed_method");
        if (config == NULL || config->eap_methods == NULL)
                return -1;

        m = config->eap_methods;
        for (i = 0; m[i].vendor != EAP_VENDOR_IETF ||
                     m[i].method != EAP_TYPE_NONE; i++) {
                if (m[i].vendor == vendor && m[i].method == method)
                        return 1;
        }
        return 0;
}

#endif  /* CONFIG_EAP_PROXY */