summaryrefslogtreecommitdiff
path: root/apps/plugins/passmgr/passmgr.c
blob: dc475d1d08065021a73dbfd21bfbd42af08eaa65 (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
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2016 Franklin Wei
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

/* password manager plugin, supports both one-time static passwords */

/* see RFC 4226 and 6238 about the OTP algorithm */

#include "plugin.h"

#include "lib/aes.h"
#include "lib/display_text.h"
#include "lib/pluginlib_actions.h"
#include "lib/pluginlib_exit.h"
#include "lib/sha1.h"

#include "wordlist.h"

/* don't change these if you want to maintain backwards compatibility */
#define MAX_NAME    50
#define SECRET_MAX  256
#define URI_MAX     (MAX_NAME + SECRET_MAX * 2 + 1)
#define ACCT_FILE   PLUGIN_APPS_DATA_DIR "/passmgr.dat"

/* these can be changed without breaking anything */
#define PASS_MAX    128
#define KDF_MIN     5000     /* minimum KDF iterations */
#define KDF_MAX     2500000
#define KDF_DEFAULT (HZ / 4) /* decryption will take about this long by default */
#define KDF_EXPORT  50000    /* encrypted exports use these many iterations */

/* convenience macros */
#define MAX(a, b) (((a)>(b))?(a):(b))
#define assert(x) (!(x)?assert_fail():0)

/* we define these no matter what */
#ifdef PASSMGR_DICEWARE
#define DICEWARE_WORDS 6
#else
#define DICEWARE_WORDS 0
#endif
#define DICEWARE_BUF (16 * DICEWARE_WORDS + 1)

/* this numbering maintans some backwards compatibility: older
 * versions had a bool that would be false (zero) for HOTP
 * accounts, but gcc would pad it to 4 bytes; by using this
 * numbering very little additional logic is needed */
enum { TYPE_HOTP = 0, TYPE_TOTP = 1, TYPE_STATIC = 3};

struct account_t {
    char name[MAX_NAME];

    int32_t type;

    union {
        uint64_t hotp_counter;
        int32_t totp_period;
    };

    uint32_t digits;

    unsigned char secret[SECRET_MAX];
    uint32_t sec_len;
};

/* in plugin buffer */
static struct account_t *accounts = NULL;

/* global variables */

static int max_accts = 0; // dynamic, depends on plugin buffer size
static int next_slot = 0;

static int time_offs = 0; // in seconds
static int kdf_iters = 0; // calculated on first run
static char encrypted = 0; // 0 = off, 1 = password, 2 = diceware

static char enc_password[PASS_MAX + 1]; // encryption password
static char data_buf[MAX(MAX_NAME, MAX(SECRET_MAX * 2, MAX(20, MAX(URI_MAX, MAX(sizeof(struct account_t), MAX(DICEWARE_BUF, PASS_MAX))))))];
static char temp_sec[SECRET_MAX];
static long background_stack[2 * DEFAULT_STACK_SIZE / sizeof(long)];

static void wipe_buf(void *ptr, size_t len)
{
    rb->memset(ptr, 0, len);
    rb->memset(ptr, 0xff, len);
    rb->memset(ptr, 0, len);
}

static void erase_sensitive_info(void)
{
    wipe_buf(accounts, sizeof(struct account_t) * max_accts);
    wipe_buf(enc_password, sizeof(enc_password));
    wipe_buf(temp_sec, sizeof(temp_sec));
    wipe_buf(background_stack, sizeof(background_stack));
}

static void acct_menu(char *title, void (*cb)(int acct));

static void assert_fail(void)
{
    rb->splashf(HZ * 2, "Assertion failed! REPORT ME!");
    exit(0);
}

static int HOTP(unsigned char *secret, size_t sec_len, uint64_t ctr, int digits)
{
    ctr = htobe64(ctr);
    unsigned char hash[20];
    if(hmac_sha1(secret, sec_len, &ctr, 8, hash))
    {
        return -1;
    }

    int offs = hash[19] & 0xF;
    uint32_t code = (hash[offs] & 0x7F) << 24 |
        hash[offs + 1] << 16 |
        hash[offs + 2] << 8  |
        hash[offs + 3];

    int mod = 1;
    for(int i = 0; i < digits; ++i)
        mod *= 10;

    // debug
    // rb->splashf(HZ * 5, "HOTP %*s, %llu, %d: %d", sec_len, secret, htobe64(ctr), digits, code % mod);

    return code % mod;
}

static bool compare_constant_time(volatile const char* p1, volatile const char* p2, size_t n)
{
    volatile char c = 0;
    for (size_t i=0; i<n; ++i)
        c |= p1[i] ^ p2[i];
    return (c == 0);
}

#if CONFIG_RTC
static time_t get_utc(void)
{
    return rb->mktime(rb->get_time()) - time_offs;
}

static int TOTP(unsigned char *secret, size_t sec_len, uint64_t step, int digits)
{
    if(!step)
        return -1;
    uint64_t tm = get_utc() / step;
    return HOTP(secret, sec_len, tm, digits);
}
#endif

/* search the accounts for a duplicate */
static bool acct_exists(const char *name)
{
    for(int i = 0; i < next_slot; ++i)
        if(!rb->strcmp(accounts[i].name, name))
            return true;
    return false;
}

/* diceware-related code */

#ifdef PASSMGR_DICEWARE
/* returns the index of the first element with a matching prefix, assumes sorted list */
static int search_prefix(const char **list, size_t list_len, const char *prefix, int *last)
{
    int l = 0;
    int r = list_len - 1;
    int len = rb->strlen(prefix);
    while(l <= r)
    {
        int m = (l + r) / 2;
        int c = rb->strncmp(list[m], prefix, len);
        if(c < 0)
            l = m + 1;
        else if(c > 0)
            r = m - 1;
        else
        {
            /* we can afford to be a bit slower here with a
             * linear-time algorithm */

            /* search forwards to find the last word with this
             * prefix */

            if(last)
            {
                int old_m = m;
                while((unsigned)m < list_len - 1)
                {
                    if(!rb->strncmp(list[m + 1], prefix, len))
                        m++;
                    else
                        break;
                }
                *last = m;
                m = old_m;
            }

            /* search backwards */
            while(m > 0)
            {
                if(!rb->strncmp(list[m - 1], prefix, len))
                    m--;
                else
                    break;
            }

            return m;
        }
    }
    return -1;
}

static char charlist_items[26][8];

static const char* charlist_cb(int selected_item, void *data,
                               char *buffer, size_t buffer_len)
{
    (void) data;
    char *str = charlist_items[selected_item];
    str[0] = toupper(str[0]);
    rb->snprintf(buffer, buffer_len, "%s-", str);
    str[0] = tolower(str[0]);
    return buffer;
}

static const char* wordlist_cb(int selected_item, void *data,
                               char *buffer, size_t buffer_len)
{
    rb->snprintf(buffer, buffer_len, "%s", word_list[(int)data + selected_item]);
    return buffer;
}

static char choose_letter(char *prefix, char selected, char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    char str[32];
    rb->vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);
    struct gui_synclist list;

    rb->gui_synclist_init(&list, &charlist_cb, NULL, false, 1, NULL);
    rb->gui_synclist_set_icon_callback(&list, NULL);

    int n_items = 0;
    int to_select = 0;
    for(char c = 'a'; c <= 'z'; ++c)
    {
        char temp[8];
        rb->snprintf(temp, sizeof(temp), "%s%c", prefix, c);
        if(search_prefix(word_list, word_list_len, temp, NULL) >= 0)
        {
            rb->strlcpy(charlist_items[n_items], temp, sizeof(charlist_items[n_items]));
            if(selected == c)
                to_select = n_items;
            ++n_items;
        }
    }
    rb->gui_synclist_set_nb_items(&list, n_items);
    rb->gui_synclist_limit_scroll(&list, false);
    rb->gui_synclist_select_item(&list, to_select);

    bool done = false;
    rb->gui_synclist_set_title(&list, str, NOICON);
    while (!done)
    {
        rb->gui_synclist_draw(&list);
        int button = rb->get_action(CONTEXT_LIST, TIMEOUT_BLOCK);
        if(rb->gui_synclist_do_button(&list, &button, LIST_WRAP_ON))
            continue;

        switch (button)
        {
        case ACTION_STD_OK:
        {
            char *str = charlist_items[rb->gui_synclist_get_sel_pos(&list)];
            int len = rb->strlen(str);
            return str[len - 1];
        }
        case ACTION_STD_PREV:
        case ACTION_STD_CANCEL:
        case ACTION_STD_MENU:
            return '\0';
        }
        rb->yield();
    }
    return '\0';
}

/* prompt the user for a word from a list */
/* returns 0 on success, negative on failure */
static int choose_word(char *ret, size_t ret_len, const char **wordlist, size_t wordlist_len, int wordnr)
{
    char prefix[3], ch;

    char first_sel = '\0', second_sel = '\0';

    rb->memset(prefix, 0, sizeof(prefix));

first_letter:

    first_sel = ch = choose_letter(prefix, first_sel, "Choose First Letter of Word #%d", wordnr);
    if(!ch)
        return -1;
    prefix[0] = ch;

    if(search_prefix(wordlist, wordlist_len, prefix, NULL) < 0)
    {
        rb->splash(HZ, "No words with this prefix!");
        prefix[0] = '\0';
        goto first_letter;
    }

second_letter:

    second_sel = ch = choose_letter(prefix, second_sel, "Choose Second Letter of Word #%d", wordnr);
    if(!ch)
    {
        prefix[0] = '\0';
        goto first_letter;
    }
    prefix[1] = ch;

    if(search_prefix(wordlist, wordlist_len, prefix, NULL) < 0)
    {
        rb->splash(HZ, "No words with this prefix!");
        prefix[1] = '\0';
        goto second_letter;
    }

    int start, stop;
    start = search_prefix(wordlist, wordlist_len, prefix, &stop);

    /* now list the words with this prefix */

    struct gui_synclist list;

    rb->gui_synclist_init(&list, &wordlist_cb, (void*)start, false, 1, NULL);
    rb->gui_synclist_set_icon_callback(&list, NULL);
    rb->gui_synclist_set_nb_items(&list, stop - start + 1);
    rb->gui_synclist_limit_scroll(&list, false);
    rb->gui_synclist_select_item(&list, 0);

    bool done = false;
    int wordidx = -1;

    char str[32];
    rb->snprintf(str, sizeof(str), "Choose Word #%d", wordnr);
    rb->gui_synclist_set_title(&list, str, NOICON);
    while (!done)
    {
        rb->gui_synclist_draw(&list);
        int button = rb->get_action(CONTEXT_LIST, TIMEOUT_BLOCK);
        if (rb->gui_synclist_do_button(&list, &button, LIST_WRAP_ON))
            continue;

        switch (button)
        {
        case ACTION_STD_OK:
            wordidx = start + rb->gui_synclist_get_sel_pos(&list);
            done = true;
            break;
        case ACTION_STD_PREV:
        case ACTION_STD_CANCEL:
        case ACTION_STD_MENU:
            prefix[1] = '\0';
            goto second_letter;
        }
        rb->yield();
    }

    rb->strlcpy(ret, word_list[wordidx], ret_len);
    return 0;
}

static int read_diceware_passphrase(char *buf, size_t buflen)
{
    /* assumes that no words are > 15 chars */
    char words[DICEWARE_WORDS][16];

    for(int i = 0; i < DICEWARE_WORDS; ++i)
    {
        int rc = choose_word(words[i], sizeof(words[i]), word_list, word_list_len, i + 1);
        if(rc < 0)
        {
            if(!i)
                return -1; /* failure */
            else
                i -= 2; /* back a word */
        }
    }

    /* copy the words into the passphrase */
    buf[0] = '\0';
    for(int i = 0; i < DICEWARE_WORDS; ++i)
    {
        rb->strlcat(buf, words[i], buflen);
        rb->strlcat(buf, " ", buflen);
    }
    return 0;
}

#endif /* #ifdef PASSMGR_DICEWARE */

// Base32 implementation
//
// Copyright 2010 Google Inc.
// Author: Markus Gutschke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

static int base32_decode(uint8_t *result, int bufSize, const uint8_t *encoded) {
    int buffer = 0;
    int bitsLeft = 0;
    int count = 0;
    for (const uint8_t *ptr = encoded; count < bufSize && *ptr; ++ptr) {
        uint8_t ch = *ptr;
        if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') {
            continue;
        }
        buffer <<= 5;

        // Deal with commonly mistyped characters
        if (ch == '0') {
            ch = 'O';
        } else if (ch == '1') {
            ch = 'L';
        } else if (ch == '8') {
            ch = 'B';
        }

        // Look up one base32 digit
        if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
            ch = (ch & 0x1F) - 1;
        } else if (ch >= '2' && ch <= '7') {
            ch -= '2' - 26;
        } else {
            return -1;
        }

        buffer |= ch;
        bitsLeft += 5;
        if (bitsLeft >= 8) {
            result[count++] = buffer >> (bitsLeft - 8);
            bitsLeft -= 8;
        }
    }
    if (count < bufSize) {
        result[count] = '\000';
    }
    return count;
}

static int base32_encode(const uint8_t *data, int length, uint8_t *result,
                         int bufSize) {
    if (length < 0 || length > (1 << 28)) {
        return -1;
    }
    int count = 0;
    if (length > 0) {
        int buffer = data[0];
        int next = 1;
        int bitsLeft = 8;
        while (count < bufSize && (bitsLeft > 0 || next < length)) {
            if (bitsLeft < 5) {
                if (next < length) {
                    buffer <<= 8;
                    buffer |= data[next++] & 0xFF;
                    bitsLeft += 8;
                } else {
                    int pad = 5 - bitsLeft;
                    buffer <<= pad;
                    bitsLeft += pad;
                }
            }
            int index = 0x1F & (buffer >> (bitsLeft - 5));
            bitsLeft -= 5;
            result[count++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[index];
        }
    }
    if (count < bufSize) {
        result[count] = '\000';
    }
    return count;
}

/***********************************************************************
 * File browser (from rockpaint)
 ***********************************************************************/

static bool browse( char *dst, int dst_size, const char *start )
{
    struct browse_context browse;

    rb->browse_context_init(&browse, SHOW_ALL,
                            BROWSE_SELECTONLY|BROWSE_NO_CONTEXT_MENU,
                            NULL, NOICON, start, NULL);

    browse.buf = dst;
    browse.bufsize = dst_size;

    rb->rockbox_browse(&browse);

    return (browse.flags & BROWSE_SELECTED);
}

#if 0
/* check an entered password/diceware passphrase with the actual
 * one */
/* used as a very weak security measure, and disabled because it
 * doesn't really do anything */
static bool verify_password(void)
{
    char temp_pass[PASS_MAX];

    switch(encrypted)
    {
    case 0:
        return true;
    case 1:
        rb->splash(HZ, "Enter current password:");
        temp_pass[0] = '\0';
        if(rb->kbd_input(temp_pass, sizeof(temp_pass)) < 0)
            return false;
        break;
#ifdef PASSMGR_DICEWARE
    case 2:
        rb->splash(HZ, "Enter current passphrase:");
        if(read_diceware_passphrase(temp_pass, sizeof(temp_pass)) < 0)
            return false;
        break;
#endif
    }
    if(rb->strcmp(enc_password, temp_pass))
    {
        rb->splashf(HZ * 2, "Wrong password!");
        return false;
    }
    return true;
}
#endif

/* a simple AES128-CTR implementation */

struct aes_ctr_ctx {
    char key[16];
    union {
        char bytes[16];
        uint64_t half[2];
    } counter;
    /* one block */
    char keystream[16];
    uint8_t bytes_left;
};

static void aes_ctr_init(struct aes_ctr_ctx *ctx, const char *key, uint64_t nonce)
{
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(true);
#endif
    rb->memcpy(ctx->key, key, 16);
    ctx->counter.half[0] = nonce;
    ctx->counter.half[1] = 0;
    ctx->bytes_left = 0;
}

static void aes_ctr_nextblock(struct aes_ctr_ctx *ctx)
{
    AES128_ECB_encrypt((char*)&ctx->counter, ctx->key, ctx->keystream);
    ctx->counter.half[1]++;
    ctx->bytes_left = 16;
}

/* should be safe to operate in-place */
static void aes_ctr_process(struct aes_ctr_ctx *ctx, const unsigned char *in, unsigned char *out, size_t len)
{
    while(len--)
    {
        if(!ctx->bytes_left)
            aes_ctr_nextblock(ctx);
        *out++ = *in++ ^ ctx->keystream[16 - ctx->bytes_left--];
    }
}

static void aes_ctr_destroy(struct aes_ctr_ctx *ctx)
{
    wipe_buf(ctx, sizeof(*ctx));
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(false);
#endif
}

/* yield after this many HMAC iterations */
#define YIELD_INTERVAL 2500

/* internal PBKDF function */
#if CONFIG_CPU == S5L8702 && !defined(SIMULATOR)

/* hardware-accelerated version */

static void PBKDF2_F(const void *pass, size_t passlen, const void *salt, size_t saltlen,
                     int c, uint32_t blockidx, void *tmp, char *out)
{
    char buf[64 + 20];
    char *last = buf + 64;

    rb->yield();

    rb->memcpy(tmp, salt, saltlen);
    blockidx = htobe32(blockidx);
    rb->memcpy(tmp + saltlen, &blockidx, 4);

    hmac_sha1(pass, passlen, tmp, saltlen + 4, last);
    rb->memcpy(out, last, 20);

    /* begin micro-optimization :P */
    for(int j = 0; j < c / YIELD_INTERVAL; ++j)
    {
        int iters = YIELD_INTERVAL;
        if(c % YIELD_INTERVAL == 0 && j == c / YIELD_INTERVAL - 1)
            iters--;
        for(int i = 0; i < iters; ++i)
        {
            hmac_sha1_hwaccel(pass, passlen, last, 20, last);

            uint32_t *a = (uint32_t*)out;
            const uint32_t *b = (const uint32_t*)last;

            /* out ^= last: */
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
        }
        rb->yield();
    }
    for(int i = 1; i < c % YIELD_INTERVAL; ++i)
    {
        hmac_sha1_hwaccel(pass, passlen, last, 20, last);

        uint32_t *a = (uint32_t*)out;
        const uint32_t *b = (const uint32_t*)last;

        /* out ^= last: */
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
    }
    rb->yield();
}
#else

/* all-software version */

static void PBKDF2_F(const void *pass, size_t passlen, const void *salt, size_t saltlen,
                     int c, uint32_t blockidx, void *tmp, char *out)
{
    char last[20];

    rb->yield();

    rb->memcpy(tmp, salt, saltlen);
    blockidx = htobe32(blockidx);
    rb->memcpy(tmp + saltlen, &blockidx, 4);

    hmac_sha1(pass, passlen, tmp, saltlen + 4, last);
    rb->memcpy(out, last, 20);

    /* begin micro-optimization :P */
    for(int j = 0; j < c / YIELD_INTERVAL; ++j)
    {
        int iters = YIELD_INTERVAL;
        if(c % YIELD_INTERVAL == 0 && j == c / YIELD_INTERVAL - 1)
            iters--;
        for(int i = 0; i < iters; ++i)
        {
            hmac_sha1(pass, passlen, last, 20, last);

            uint32_t *a = (uint32_t*)out;
            const uint32_t *b = (const uint32_t*)last;

            /* out ^= last: */
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
            *a++ ^= *b++;
        }
        rb->yield();
    }
    for(int i = 1; i < c % YIELD_INTERVAL; ++i)
    {
        hmac_sha1(pass, passlen, last, 20, last);

        uint32_t *a = (uint32_t*)out;
        const uint32_t *b = (const uint32_t*)last;

        /* out ^= last: */
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
        *a++ ^= *b++;
    }
    rb->yield();
}
#endif

/* uses HMAC-SHA-1 as the underlying PRF */
/* tmp must be at least saltlen + 4 bytes */
static void PBKDF2(const void *pass, size_t passlen, const void *salt, size_t saltlen,
                   int c, char *dk, size_t dklen, void *tmp)
{
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(true);
#endif
    /* number of blocks */
    unsigned l = dklen / 20;
    if(dklen % 20)
        l += 1; // round up

    /* amount of left-over bytes in the final block */
    unsigned r = dklen - (l - 1) * 20;

    for(uint32_t i = 1; i < l; ++i)
    {
        PBKDF2_F(pass, passlen, salt, saltlen, c, i, tmp, dk);
        dk += 20;
    }
    if(r)
    {
        char temp_block[20];
        PBKDF2_F(pass, passlen, salt, saltlen, c, l, tmp, temp_block);
        rb->memcpy(dk, temp_block, r);
    }
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(false);
#endif
}

/* calculate about how many KDF iterations it takes to make key
 * derivation take a certain time */
static int calc_kdf_iters(long delay)
{
    rb->splash(0, "Please wait...");
    int iters = KDF_MIN;
    long ticks = 0;
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(true);
#endif
    /* calculate how many iterations make PBKDF2 take a certain time */
    while(ticks < 4 && iters <= KDF_MAX)
    {
        char out[20];
        char tmp[4 + 4];
        long start = *rb->current_tick;
        PBKDF2("password", 8, "salt", 4, KDF_MIN, out, 20, tmp);
        long end = *rb->current_tick;
        ticks = end - start;
        if(!ticks)
            iters *= 2;
    }

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(false);
#endif

    if(!ticks)
        return KDF_MAX;

    /* then extrapolate to the desired time */
    int ret = (delay * iters) / ticks;
    rb->lcd_update();
    return ret < KDF_MIN ? KDF_MIN : ret;
}

static int read_password_or_passphrase(char *buf, size_t len)
{
    buf[0] = '\0';
    switch(encrypted)
    {
    case 1: /* plain password */
        rb->splash(HZ, "Enter password:");
        return rb->kbd_input(buf, len);
    case 2: /* passphrase */
#ifdef PASSMGR_DICEWARE
        rb->splash(HZ, "Enter passphrase:");
        return read_diceware_passphrase(buf, len);
#endif
    default:
        return -1;
    }
}

static bool read_accts(void)
{
    int fd = rb->open(ACCT_FILE, O_RDONLY);
    if(fd < 0)
        return false;

    unsigned char buf[4];
    /* two versions to maintain backwards-compatibility */
    const char *magic_old = "OTP1";
    const char *magic = "OTP2";
    rb->read(fd, buf, 4);
    if(rb->memcmp(magic, buf, 4) && rb->memcmp(magic_old, buf, 4))
    {
        rb->splash(HZ * 2, "Corrupt save data!");
        rb->close(fd);
        return false;
    }

    rb->read(fd, &time_offs, sizeof(time_offs));

    if(!rb->memcmp(magic, buf, 4))
    {
        /* version 2 */
        rb->read(fd, &encrypted, sizeof(encrypted));
        rb->read(fd, &kdf_iters, sizeof(kdf_iters));

        if(encrypted)
        {
            uint64_t nonce;
            rb->read(fd, &nonce, sizeof(nonce));

            /* read in the MAC */
            char mac_given[20];
            rb->read(fd, mac_given, 20);

            /* also read the encrypted data into memory */
            while(next_slot < max_accts)
            {
                if(rb->read(fd, accounts + next_slot, sizeof(struct account_t)) != sizeof(struct account_t))
                    break;
                ++next_slot;
            }

            rb->close(fd);

            for(int i = 0; i < 3; ++i)
            {
                if(read_password_or_passphrase(enc_password, sizeof(enc_password)) < 0)
                {
                    rb->close(fd);
                    exit(PLUGIN_ERROR);
                }

                rb->splash(0, "Decrypting...");

                /* derive the key */
                char key[20];
                char tmp[sizeof(nonce) + 4];

                //long start = *rb->current_tick;
                PBKDF2(enc_password, rb->strlen(enc_password), &nonce, sizeof(nonce),
                       kdf_iters, key, sizeof(key), tmp);
                //long end = *rb->current_tick;
                //rb->splashf(HZ, "Key derviation takes %ld ticks", end - start);

#if CONFIG_CPU == S5L8702 && !defined(SIMULATOR)
                /* if we have a hardware AES coprocessor with
                 * device-unique keys, use it to encrypt the key to
                 * tie it to this device */
                rb->s5l8702_hwkeyaes(HWKEYAES_ENCRYPT,
                                     HWKEYAES_UKEY,
                                     key, sizeof(key));
#endif

                /* calculate the MAC of the ciphertext to see if the
                 * password is correct before decrypting note that we
                 * only use 4 bytes of the derived key in calculating
                 * the MAC, this makes an attack more difficult and
                 * prone to false positives, which is good */
                char mac_calculated[20];
                hmac_sha1(key + 16, sizeof(key) - 16, accounts,
                          next_slot * sizeof(struct account_t), mac_calculated);

                if(!compare_constant_time(mac_calculated, mac_given, 20))
                {
                    rb->splash(HZ, "Wrong password!");
                    continue;
                }

                /* decrypt the data with AES128-CTR */
                struct aes_ctr_ctx aes_ctx;

                aes_ctr_init(&aes_ctx, key, nonce);

                aes_ctr_process(&aes_ctx, (const unsigned char*)accounts, (char*)accounts, sizeof(struct account_t) * next_slot);

                aes_ctr_destroy(&aes_ctx);

                /* successful decryption */
                return true;
            }

            exit(PLUGIN_ERROR);
        }
    }

    /* plain, unencrypted format */

    while(next_slot < max_accts)
    {
        if(rb->read(fd, accounts + next_slot, sizeof(struct account_t)) != sizeof(struct account_t))
            break;
        ++next_slot;
    }

    rb->close(fd);
    return true;
}

static struct mutex save_mutex;
static volatile bool quiet_save SHAREDDATA_ATTR = false;

static void save_accts(void)
{
    if(!quiet_save)
        rb->splash(0, "Saving...");
    rb->mutex_lock(&save_mutex);
    int fd = rb->open(ACCT_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0600);

    rb->fdprintf(fd, "OTP2");

    rb->write(fd, &time_offs, sizeof(time_offs));
    rb->write(fd, &encrypted, sizeof(encrypted));

    /* write how many KDF iterations we use even if encryption is disabled */
    rb->write(fd, &kdf_iters, sizeof(kdf_iters));

    assert(sizeof(data_buf) >= sizeof(struct account_t));
    assert(sizeof(data_buf) >= 20); // needs to hold an SHA-1 hash

    if(encrypted)
    {
        /* encrypt the data with AES128-CTR */

        /* generate/write the nonce */
        uint64_t nonce = *rb->current_tick;
#if CONFIG_RTC
        nonce |= (uint64_t)get_utc() << 32;
#endif

        rb->write(fd, &nonce, sizeof(nonce));

        /* placeholder for the MAC */
        off_t mac_offs = rb->lseek(fd, 0, SEEK_CUR);
        rb->memset(data_buf, 0, 20);
        rb->write(fd, data_buf, 20);

        /* use PKCS #5 PBKDF2 to derive a strong key from the password */
        char key[20];
        char tmp[sizeof(nonce) + 4];

        PBKDF2(enc_password, rb->strlen(enc_password), &nonce, sizeof(nonce),
               kdf_iters, key, sizeof(key), tmp);

#if CONFIG_CPU == S5L8702 && !defined(SIMULATOR)
        /* if we have a hardware AES coprocessor with device-unique
         * keys, use it to encrypt the key to tie it to this device */
        rb->s5l8702_hwkeyaes(HWKEYAES_ENCRYPT,
                             HWKEYAES_UKEY,
                             key, sizeof(key));
#endif

        struct aes_ctr_ctx aes_ctx;
        aes_ctr_init(&aes_ctx, key, nonce);

        /* note that in calculating the HMAC we don't use the primary
           key, but instead another part of the PBKDF2 output */

        struct hmac_ctx hmac_ctx;
        /* 16 bytes are used for the encryption key, 4 for verification */
        hmac_sha1_init(&hmac_ctx, key + 16, sizeof(key) - 16);

        for(int i = 0; i < next_slot; ++i)
        {
            /* encrypt */
            aes_ctr_process(&aes_ctx, (unsigned char*)(accounts + i), data_buf, sizeof(struct account_t));

            rb->write(fd, data_buf, sizeof(struct account_t));

            /* then MAC */
            hmac_sha1_process_bytes(&hmac_ctx, data_buf, sizeof(struct account_t));
            rb->yield();
        }

        char mac[20];

        hmac_sha1_finish_ctx(&hmac_ctx, mac);

        rb->lseek(fd, mac_offs, SEEK_SET);
        rb->write(fd, mac, 20);

        /* cleanup */
        aes_ctr_destroy(&aes_ctx);
        wipe_buf(key, sizeof(key));
        wipe_buf(tmp, sizeof(tmp));
    }
    else
        for(int i = 0; i < next_slot; ++i)
            rb->write(fd, accounts + i, sizeof(struct account_t));

    rb->close(fd);
    rb->mutex_unlock(&save_mutex);
    quiet_save = false;
}

/* generate a desired number of random bits */
/* note that len must be a multiple of sizeof(long) and >= 20 */
static void gather_entropy(void *out, size_t len)
{
    assert(len % sizeof(long) == 0);
    assert(len >= 20);
    rb->splash(0, "Gathering entropy... Please press the keys as randomly as possible.");
    /* fill the buffer with a seed */
    char buf[20];
    long *ptr = (long*)buf;

    /* mix in certain filesystem information such as the number of
     * files in the root directory */
    DIR *root = rb->opendir("/");
    int count = 0;
    while(rb->readdir(root))
        count++;

    for(unsigned i = 0; i < len / sizeof(long); ++i)
    {
        *ptr++ = *rb->current_tick ^ count;
        rb->yield();
    }

    ptr = (long*)buf;

    /* now we mix in the system settings and status */
    hmac_sha1(rb->global_settings, sizeof(struct user_settings), ptr, 20, ptr);
    hmac_sha1(rb->global_status, sizeof(struct system_status), ptr, 20, ptr);

    /* mix the keypresses into the pool */
    /* for now just gather a certain number of keypresses and their
     * associated timestamps */
    for(int keys = 0; keys < 80; ++keys)
    {
        uint32_t data = rb->button_get(true) ^ *rb->current_tick;
#ifdef HAVE_WHEEL_POSITION
        if(rb->wheel_status() >= 0)
            data ^= rb->wheel_status();
#endif

        /* XOR in environmental conditions */
        data ^= rb->audio_status() << 8;
        data ^= rb->audio_get_file_pos() << 16;
        data ^= rb->battery_voltage() << 24;

#ifdef USEC_TIMER
        /* we swap because we need more entropy in the high-order bits */
        data ^= SWAP32_CONST(USEC_TIMER);
#endif

        rb->splashf(0, "Data is 0x%lx", data);

        ptr = (long*)buf;

        /* XOR the data in */
        for(unsigned i = 0; i < len / sizeof(long); ++i)
            *ptr++ ^= data;

        long timestamp = *rb->current_tick;

#if CONFIG_RTC
        timestamp ^= get_utc();
#endif

#ifdef USEC_TIMER
        timestamp ^= SWAP32_CONST(USEC_TIMER);
#endif

        /* finally mix it all up with an HMAC */
        hmac_sha1(&timestamp, sizeof(long), ptr, 20, ptr);
        rb->yield();
    }

    /* as a final step we use PBKDF2 to stretch the 20 bytes we have
     * to the desired length */
    long salt = *rb->current_tick;
    char tmp[sizeof(salt) + 4];
    PBKDF2(buf, 20, &salt, sizeof(salt), 1, out, len, tmp);

    /* clear any errant button presses */
    rb->button_clear_queue();
}

static void generate_random_password(char *dest, size_t len)
{
    rb->memset(dest, 0, len);
    const char *charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=!@#$%^&*()_+[]{}\\|,.<>/?`~'\"";
    char seed[20];
    gather_entropy(seed, sizeof(seed));

    unsigned dest_idx = 0;

    /* now, iterate over bytes of the seed and append characters that
     * are in the character set */
    while(dest_idx < len - 1)
    {
        for(unsigned i = 0; i < sizeof(seed) && dest_idx < len - 1; ++i)
        {
            if(rb->strchr(charset, seed[i]) && seed[i])
                dest[dest_idx++] = seed[i];
        }
        sha1_buffer(seed, sizeof(seed), seed);
    }
}

/* 0: manual entry, 1: random pass, -1: fail */
static int static_password_menu(char *passbuf, size_t buflen)
{
    MENUITEM_STRINGLIST(static_type, "Static Password Options", NULL,
                        "Enter Manually",
                        "Generate Randomly",
                        "Cancel");

    while(1)
    {
        switch(rb->do_menu(&static_type, NULL, NULL, false))
        {
        case 0:
            rb->splash(HZ * 2, "Enter account password:");
            return 0;
        case 1:
        {
            rb->splash(HZ * 2, "Enter desired password length:");

            char temp_buf[16];
            temp_buf[0] = '\0';

            if(rb->kbd_input(temp_buf, sizeof(temp_buf)) < 0)
                return -1;

            int len = rb->atoi(temp_buf);
            if(len < 4 || len > (int)buflen)
            {
                rb->splash(HZ, "Password length not in allowed range!");
                return -1;
            }

            generate_random_password(passbuf, len + 1);
            return 1;
        }
        case 2:
        default:
            return -1;
        }
    }
}

static volatile bool kill_background SHAREDDATA_ATTR = false;
static volatile bool want_save SHAREDDATA_ATTR = false;
static int background_id = -1;

static void background_save(void)
{
    want_save = true;
    /* fall back to normal save */
    if(background_id < 0)
        save_accts();
}

static void background_thread(void)
{
    while(1)
    {
        if(want_save)
        {
            quiet_save = true;
            save_accts();
            want_save = false;
        }
        if(kill_background)
            rb->thread_exit();
        rb->sleep(HZ / 25);
    }
}

static int compare_acct(const void *a, const void *b)
{
    const struct account_t *a1 = a, *b1 = b;
    return rb->strcmp(a1->name, b1->name);
}

static void sort_accts(void)
{
    /* don't sort while a save is going on */
    rb->mutex_lock(&save_mutex);
    rb->qsort(accounts, next_slot, sizeof(struct account_t), compare_acct);
    rb->mutex_unlock(&save_mutex);
}

static void add_acct_file(void)
{
    char fname[MAX_PATH];
    rb->splash(HZ * 2, "Please choose the file that contains the account(s).");
    int before = next_slot;
    if(browse(fname, sizeof(fname), "/"))
    {
        int fd = rb->open(fname, O_RDONLY);
        do {
            char *uri_buf = data_buf;
            rb->memset(accounts + next_slot, 0, sizeof(struct account_t));

            accounts[next_slot].digits = 6;

            if(!rb->read_line(fd, uri_buf, URI_MAX))
                break;

            if(next_slot >= max_accts)
            {
                rb->splash(HZ * 2, "Account limit reached: some accounts not added.");
                break;
            }

            char *save;

            /* check for URI prefix */
            if(rb->strncmp(uri_buf, "otpauth://", 10))
            {
                /* see if it could be in the format name:password */
                if(rb->strchr(uri_buf, ':'))
                {
                    char *tok = rb->strtok_r(uri_buf, ":", &save);

                    if(acct_exists(tok))
                    {
                        rb->splashf(HZ * 2, "Not adding account with duplicate name `%s'!", tok);
                        continue;
                    }

                    if(!rb->strlen(tok))
                    {
                        rb->splashf(HZ * 2, "Skipping account with empty name.");
                        continue;
                    }

                    rb->strlcpy(accounts[next_slot].name, tok, sizeof(accounts[next_slot].name));

                    tok = rb->strtok_r(NULL, "", &save);
                    if(rb->strlen(tok) >= SECRET_MAX)
                        rb->splashf(HZ * 2, "Truncating secret for account `%s'", accounts[next_slot].name);
                    rb->strlcpy(accounts[next_slot].secret, tok, sizeof(accounts[next_slot].secret));
                    accounts[next_slot].type = TYPE_STATIC;
                    ++next_slot;
                }
                continue;
            }

            char *tok = rb->strtok_r(uri_buf + 10, "/", &save);
            if(!rb->strcmp(tok, "totp"))
            {
                accounts[next_slot].type = TYPE_TOTP;
                accounts[next_slot].totp_period = 30;
#if !CONFIG_RTC
                rb->splash(2 * HZ, "Skipping TOTP account (not supported).");
                continue;
#endif
            }
            else if(!rb->strcmp(tok, "hotp"))
            {
                accounts[next_slot].type = TYPE_HOTP;
                accounts[next_slot].hotp_counter = 0;
            }

            tok = rb->strtok_r(NULL, "?", &save);
            if(!tok)
                continue;

            if(acct_exists(tok))
            {
                rb->splashf(HZ * 2, "Not adding account with duplicate name `%s'!", tok);
                continue;
            }

            if(!rb->strlen(tok))
            {
                rb->splashf(HZ * 2, "Skipping account with empty name.");
                continue;
            }

            rb->strlcpy(accounts[next_slot].name, tok, sizeof(accounts[next_slot].name));

            bool have_secret = false;

            do {
                tok = rb->strtok_r(NULL, "=", &save);
                if(!tok)
                    continue;

                if(!rb->strcmp(tok, "secret"))
                {
                    if(have_secret)
                    {
                        rb->splashf(HZ * 2, "URI with multiple `secret' parameters found, skipping!");
                        goto fail;
                    }
                    have_secret = true;
                    tok = rb->strtok_r(NULL, "&", &save);
                    if((accounts[next_slot].sec_len = base32_decode(accounts[next_slot].secret, SECRET_MAX, tok)) <= 0)
                        goto fail;
                }
                else if(!rb->strcmp(tok, "counter"))
                {
                    if(accounts[next_slot].type == TYPE_TOTP)
                    {
                        rb->splash(HZ * 2, "Counter parameter specified for TOTP!? Skipping...");
                        goto fail;
                    }
                    tok = rb->strtok_r(NULL, "&", &save);
                    accounts[next_slot].hotp_counter = rb->atoi(tok);
                }
                else if(!rb->strcmp(tok, "period"))
                {
                    if(accounts[next_slot].type == TYPE_HOTP)
                    {
                        rb->splash(HZ * 2, "Period parameter specified for HOTP!? Skipping...");
                        goto fail;
                    }
                    tok = rb->strtok_r(NULL, "&", &save);
                    accounts[next_slot].totp_period = rb->atoi(tok);
                }
                else if(!rb->strcmp(tok, "digits"))
                {
                    tok = rb->strtok_r(NULL, "&", &save);
                    accounts[next_slot].digits = rb->atoi(tok);
                    if(accounts[next_slot].digits < 1 || accounts[next_slot].digits > 9)
                    {
                        rb->splashf(HZ * 2, "Digits parameter not in acceptable range, skipping.");
                        goto fail;
                    }
                }
                else
                    rb->splashf(HZ, "Unnown parameter `%s' ignored.", tok);
            } while(tok);

            if(!have_secret)
            {
                rb->splashf(HZ * 2, "URI with no `secret' parameter found, skipping!");
                goto fail;
            }

            /* wait if a background save is going on */
            rb->mutex_lock(&save_mutex);

            ++next_slot;

            rb->mutex_unlock(&save_mutex);

        fail:

            ;
        } while(1);
        rb->close(fd);
    }
    if(before == next_slot)
        rb->splash(HZ * 2, "No accounts added.");
    else
    {
        rb->splashf(HZ * 2, "Added %d account(s).", next_slot - before);
        sort_accts();
        background_save();
    }
}

static void add_acct_manual(void)
{
    if(next_slot >= max_accts)
    {
        rb->splashf(HZ * 2, "Account limit reached!");
        return;
    }
    rb->memset(accounts + next_slot, 0, sizeof(struct account_t));

    rb->splash(HZ * 1, "Enter account name:");
    if(rb->kbd_input(accounts[next_slot].name, sizeof(accounts[next_slot].name)) < 0)
        return;

    if(acct_exists(accounts[next_slot].name))
    {
        rb->splash(HZ * 2, "Duplicate account name!");
        return;
    }

    MENUITEM_STRINGLIST(type_menu, "Choose Account Type", NULL,
                        "HOTP (event-based)",
#if CONFIG_RTC
                        "TOTP (time-based)",
#endif
                        "Static Password",
                        "Cancel");

    switch(rb->do_menu(&type_menu, NULL, NULL, false))
    {
    case 0:
        accounts[next_slot].type = TYPE_HOTP;
        break;
    case 1:
#if CONFIG_RTC
            accounts[next_slot].type = TYPE_TOTP;
#else
            accounts[next_slot].type = TYPE_STATIC;
#endif
        break;
    case 2:
#if CONFIG_RTC
            accounts[next_slot].type = TYPE_STATIC;
            break;
#else
            return;
#endif
    case 3:
    default:
    case GO_TO_PREVIOUS:
        return;
    }

    char temp_buf[SECRET_MAX * 2];
    rb->memset(temp_buf, 0, sizeof(temp_buf));

    if(accounts[next_slot].type != TYPE_STATIC)
        rb->splash(HZ * 2, "Enter Base32-encoded secret:");
    else
    {
        switch(static_password_menu(accounts[next_slot].secret, SECRET_MAX))
        {
        case 0:
            break;
        case 1:
            goto done;
        case 2:
        default:
            return;
        }
    }

    if(rb->kbd_input(temp_buf, sizeof(temp_buf)) < 0)
        return;

    if(accounts[next_slot].type != TYPE_STATIC)
    {
        if((accounts[next_slot].sec_len = base32_decode(accounts[next_slot].secret, SECRET_MAX, temp_buf)) <= 0)
        {
            rb->splash(HZ * 2, "Invalid Base32 secret!");
            return;
        }
    }
    else
    {
        accounts[next_slot].sec_len = rb->strlen(temp_buf);
        if(accounts[next_slot].sec_len > SECRET_MAX)
        {
                rb->splash(HZ * 2, "Password too long!");
                return;
        }
        rb->strlcpy(accounts[next_slot].secret, temp_buf, SECRET_MAX);
        goto done;
    }

    rb->memset(temp_buf, 0, sizeof(temp_buf));

    if(accounts[next_slot].type == TYPE_HOTP)
    {
        rb->splash(HZ * 2, "Enter HOTP counter (0 is typical):");
        temp_buf[0] = '0';
    }
    else if(accounts[next_slot].type == TYPE_TOTP)
    {
        rb->splash(HZ * 2, "Enter TOTP period (30 is typical):");
        temp_buf[0] = '3';
        temp_buf[1] = '0';
    }

    if(rb->kbd_input(temp_buf, sizeof(temp_buf)) < 0)
        return;

    if(accounts[next_slot].type == TYPE_TOTP)
        accounts[next_slot].hotp_counter = rb->atoi(temp_buf);
    else
        accounts[next_slot].totp_period = rb->atoi(temp_buf);

    rb->splash(HZ * 2, "Enter digit count (6 is typical):");

    rb->memset(temp_buf, 0, sizeof(temp_buf));
    temp_buf[0] = '6';

    if(rb->kbd_input(temp_buf, sizeof(temp_buf)) < 0)
        return;

    accounts[next_slot].digits = rb->atoi(temp_buf);

    if(accounts[next_slot].digits < 1 || accounts[next_slot].digits > 9)
    {
        rb->splash(HZ, "Invalid length!");
        return;
    }

done:

    rb->mutex_lock(&save_mutex);

    ++next_slot;

    rb->mutex_unlock(&save_mutex);

    sort_accts();
    background_save();

    rb->splashf(HZ, "Success.");
}

static void add_acct(void)
{
    MENUITEM_STRINGLIST(menu, "Add Account(s)", NULL,
                        "From URI List or 'username:password' List",
                        "Manual Entry",
                        "Back");
    int sel = 0;
    bool quit = false;
    while(!quit)
    {
        switch(rb->do_menu(&menu, &sel, NULL, false))
        {
        case 0:
            add_acct_file();
            break;
        case 1:
            add_acct_manual();
            break;
        case 2:
        default:
            quit = true;
            break;
        }
    }
}

/* core algorithm, only for OTP accounts */
static int next_code(int acct)
{
    switch(accounts[acct].type)
    {
    case TYPE_HOTP:
    {
        int ret = HOTP(accounts[acct].secret,
                       accounts[acct].sec_len,
                       accounts[acct].hotp_counter,
                       accounts[acct].digits);
        rb->mutex_lock(&save_mutex);
        ++accounts[acct].hotp_counter;
        rb->mutex_unlock(&save_mutex);
        return ret;
    }
#if CONFIG_RTC
    case TYPE_TOTP:
        return TOTP(accounts[acct].secret,
                    accounts[acct].sec_len,
                    accounts[acct].totp_period,
                    accounts[acct].digits);
#endif
    default:
        return -1;
    }
}

static void show_code(int acct)
{
    /* rockbox's printf doesn't support a variable field width afaik */
    char format_buf[64];
    switch(accounts[acct].type)
    {
    case TYPE_HOTP:
        rb->snprintf(format_buf, sizeof(format_buf), "%%0%" PRIu32 "d", accounts[acct].digits);
        rb->splashf(0, format_buf, next_code(acct));
        background_save();
        break;
#if CONFIG_RTC
    case TYPE_TOTP:
        rb->snprintf(format_buf, sizeof(format_buf), "%%0%" PRIu32 "d (%%ld second(s) left)", accounts[acct].digits);
        rb->splashf(0, format_buf, next_code(acct),
                    accounts[acct].totp_period - get_utc() % accounts[acct].totp_period);
        break;
#else
    case TYPE_TOTP:
        rb->splash(0, "TOTP not supported on this device!");
        break;
#endif
    case TYPE_STATIC:
        rb->splashf(0, "%s", accounts[acct].secret);
        break;
    default:
        assert(false);
        break;
    }
    rb->sleep(HZ);
    while(1)
    {
        int button = rb->button_get(true);
        if(button && !(button & BUTTON_REL))
            break;
        rb->yield();
    }

    rb->lcd_update();
}

static void gen_codes(void)
{
    acct_menu("Show Password", show_code);
}

static bool danger_confirm(void)
{
    int sel = 0;
    MENUITEM_STRINGLIST(menu, "Are you REALLY SURE?", NULL,
                        "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        "No",
                        "Yes, DO IT", // 7
                        "No",
                        "No",
                        "No",
                        "No");

    switch(rb->do_menu(&menu, &sel, NULL, false))
    {
    case 7:
        return true;
    default:
        return false;
    }
}

static void acct_type_menu(int acct)
{
    MENUITEM_STRINGLIST(type_menu, "Choose Account Type", NULL,
                        "HOTP (event-based)",
                        "TOTP (time-based)",
                        "Static Password",
                        "Back");
    int sel = 0;
    switch(accounts[acct].type)
    {
    case TYPE_HOTP:
        break;
    case TYPE_TOTP:
        sel = 1;
        break;
    case TYPE_STATIC:
        sel = 2;
        break;
    }

    rb->mutex_lock(&save_mutex);

    if(accounts[acct].type != TYPE_STATIC)
        base32_encode(accounts[acct].secret, accounts[acct].sec_len, accounts[acct].secret, SECRET_MAX);

    bool quit = false;

    while(!quit)
    {
        switch(rb->do_menu(&type_menu, &sel, NULL, false))
        {
        case 0:
            accounts[acct].type = TYPE_HOTP;
            quit = true;
            break;
        case 1:
            accounts[acct].type = TYPE_TOTP;
            quit = true;
            break;
        case 2:
            /* base32 the secret so it's readable */
            if(accounts[acct].type != TYPE_STATIC)
                base32_encode(accounts[acct].secret, accounts[acct].sec_len, accounts[acct].secret, SECRET_MAX);
            accounts[acct].type = TYPE_STATIC;
            quit = true;
            break;
        case 3:
        default:
            quit = true;
            break;
        }
    }

    rb->mutex_unlock(&save_mutex);
}

static void edit_menu(int acct)
{
    /* HACK ALERT */
    /* three different menus, one handling logic */
    MENUITEM_STRINGLIST(menu_hotp, "Edit Account", NULL,
                        "Rename", // 0
                        "Delete", // 1
                        "Change HOTP Counter", // 2
                        "Change Digit Count", // 3
                        "Change Shared Secret", // 4
                        "Change Type", // 5
                        "Back"); // 6

    MENUITEM_STRINGLIST(menu_totp, "Edit Account", NULL,
                        "Rename", // 0
                        "Delete", // 1
                        "Change TOTP Period", // 2
                        "Change Digit Count", // 3
                        "Change Shared Secret", // 4
                        "Change Type", // 5
                        "Back"); // 6

    MENUITEM_STRINGLIST(menu_static, "Edit Account", NULL,
                        "Rename", // 0
                        "Delete", // 1
                        "Change Password", // 2
                        "Change Type", // 3
                        "Back"); // 4

    const struct menu_item_ex *menu = NULL;

    bool save = false;
    bool quit = false;
    int sel = 0;

type_change:

    /* don't want to corrupt a save */
    rb->mutex_lock(&save_mutex);

    switch(accounts[acct].type)
    {
    case TYPE_HOTP:
        menu = &menu_hotp;
        break;
    case TYPE_TOTP:
        menu = &menu_totp;
        break;
    case TYPE_STATIC:
        menu = &menu_static;
        break;
    default:
        break;
    }

    while(!quit)
    {
        switch(rb->do_menu(menu, &sel, NULL, false))
        {
        case 0: // rename
            rb->splash(HZ, "Enter new name:");
            rb->strlcpy(data_buf, accounts[acct].name, sizeof(data_buf));
            if(rb->kbd_input(data_buf, sizeof(data_buf)) < 0)
                break;
            if(acct_exists(data_buf))
            {
                rb->splash(HZ * 2, "Duplicate account name!");
                break;
            }
            rb->strlcpy(accounts[acct].name, data_buf, sizeof(accounts[acct].name));
            sort_accts();
            save = true;
            rb->splash(HZ, "Success.");
            goto done;
        case 1: // delete
            if(danger_confirm())
            {
                rb->memmove(accounts + acct, accounts + acct + 1, (next_slot - acct - 1) * sizeof(struct account_t));
                --next_slot;
                rb->splashf(HZ, "Deleted.");
                save = true;
                goto done;
            }
            else
                rb->splash(HZ, "Not confirmed.");
            break;
        case 2: // HOTP counter OR TOTP period or password
            switch(accounts[acct].type)
            {
            case TYPE_HOTP:
                rb->snprintf(data_buf, sizeof(data_buf), "%u", (unsigned int) accounts[acct].hotp_counter);
                break;
            case TYPE_TOTP:
                rb->snprintf(data_buf, sizeof(data_buf), "%" PRIi32, accounts[acct].totp_period);
                break;
            case TYPE_STATIC:
                switch(static_password_menu(accounts[next_slot].secret, SECRET_MAX))
                {
                case 0:
                    rb->snprintf(data_buf, sizeof(data_buf), "%s", accounts[acct].secret);
                    break;
                case 1:
                    rb->splash(HZ, "Success.");
                    continue;
                case 2:
                default:
                    continue;
                }
            }

            if(rb->kbd_input(data_buf, sizeof(data_buf)) < 0)
                break;

            switch(accounts[acct].type)
            {
            case TYPE_TOTP:
                accounts[acct].totp_period = rb->atoi(data_buf);
                break;
            case TYPE_HOTP:
                accounts[acct].hotp_counter = rb->atoi(data_buf);
                break;
            case TYPE_STATIC:
                rb->strlcpy(accounts[acct].secret, data_buf, SECRET_MAX);
                break;
            }

            save = true;

            rb->splash(HZ, "Success.");
            break;
        case 3: // digits or type
            if(accounts[acct].type == TYPE_STATIC)
            {
                acct_type_menu(acct);
                save = true;
                rb->mutex_unlock(&save_mutex);
                goto type_change;
            }
            else
            {
                rb->snprintf(data_buf, sizeof(data_buf), "%" PRIu32, accounts[acct].digits);
                if(rb->kbd_input(data_buf, sizeof(data_buf)) < 0)
                    break;

                accounts[acct].digits = rb->atoi(data_buf);

                save = true;

                rb->splash(HZ, "Success.");
            }
            break;
        case 4: // secret or back
        {
            if(accounts[acct].type == TYPE_STATIC)
            {
                quit = true;
                break;
            }
            /* save the old secret */
            size_t old_len = accounts[acct].sec_len;
            rb->memcpy(temp_sec, accounts[acct].secret, accounts[acct].sec_len);

            /* encode */
            base32_encode(accounts[acct].secret, accounts[acct].sec_len, data_buf, sizeof(data_buf));

            if(rb->kbd_input(data_buf, sizeof(data_buf)) < 0)
                break;

            int ret = base32_decode(accounts[acct].secret, sizeof(accounts[acct].secret), data_buf);
            if(ret <= 0)
            {
                rb->memcpy(accounts[acct].secret, temp_sec, SECRET_MAX);
                accounts[acct].sec_len = old_len;
                rb->splash(HZ * 2, "Invalid Base32 secret!");
                break;
            }
            accounts[acct].sec_len = ret;

            save = true;

            rb->splash(HZ, "Success.");

            break;
        }
        case 5:
            acct_type_menu(acct);
            save = true;
            rb->mutex_unlock(&save_mutex);
            goto type_change;
        case 6:
            quit = true;
            break;
        default:
            break;
        }
    }
done:

    /* done modifying */
    rb->mutex_unlock(&save_mutex);

    if(save)
        background_save();
}

static void edit_accts(void)
{
    acct_menu("Edit Account", edit_menu);
}

#if CONFIG_RTC
/* label is like this: UTC([+/-]HH:MM ...) */
static int get_time_seconds(const char *label)
{
    if(!rb->strcmp(label, "UTC"))
        return 0;

    char buf[32];

    /* copy the part after "UTC" */
    rb->strlcpy(buf, label + 3, sizeof(buf));

    char *save, *tok;

    tok = rb->strtok_r(buf, ":", &save);
    /* positive or negative: sign left */
    int hr = rb->atoi(tok);

    tok = rb->strtok_r(NULL, ": ", &save);
    int min = rb->atoi(tok);

    return 3600 * hr + 60 * min;
}

/* returns the offset in seconds associated with a time zone */
static int get_time_offs(void)
{
    MENUITEM_STRINGLIST(menu, "Select Time Zone", NULL,
                        "UTC-12:00", // 0
                        "UTC-11:00", // 1
                        "UTC-10:00 (HAST)", // 2
                        "UTC-9:30",  // 3
                        "UTC-9:00 (AKST, HADT)", // 4
                        "UTC-8:00 (PST, AKDT)", // 5
                        "UTC-7:00 (MST, PDT)", // 6
                        "UTC-6:00 (CST, MDT)", // 7
                        "UTC-5:00 (EST, CDT)", // 8
                        "UTC-4:00 (AST, EDT)", // 9
                        "UTC-3:30 (NST)", // 10
                        "UTC-3:00 (ADT)", // 11
                        "UTC-2:30 (NDT)", // 12
                        "UTC-2:00", // 13
                        "UTC-1:00", // 14
                        "UTC",      // 15
                        "UTC+1:00", // 16
                        "UTC+2:00", // 17
                        "UTC+3:00", // 18
                        "UTC+3:30", // 19
                        "UTC+4:00", // 20
                        "UTC+4:30", // 21
                        "UTC+5:00", // 22
                        "UTC+5:30", // 23
                        "UTC+5:45", // 24
                        "UTC+6:00", // 25
                        "UTC+6:30", // 26
                        "UTC+7:00", // 27
                        "UTC+8:00", // 28
                        "UTC+8:30", // 29
                        "UTC+8:45", // 30
                        "UTC+9:00", // 31
                        "UTC+9:30", // 32
                        "UTC+10:00", // 33
                        "UTC+10:30", // 34
                        "UTC+11:00", // 35
                        "UTC+12:00", // 36
                        "UTC+12:45", // 37
                        "UTC+13:00", // 38
                        "UTC+14:00", // 39
        );

    int sel = 15; // UTC
    for(unsigned int i = 0; i < ARRAYLEN(menu_); ++i)
        if(time_offs == get_time_seconds(menu_[i]))
        {
            sel = i;
            break;
        }

again:
    rb->do_menu(&menu, &sel, NULL, false);

    if(0 <= sel && sel < (int)ARRAYLEN(menu_))
    {
        /* see apps/menu.h */
        const char *label = menu_[sel];

        return get_time_seconds(label);
    }
    else
        goto again;

#if 0
    /* kept just in case menu internals change and the above code
     * breaks */
    switch(rb->do_menu(&menu, &sel, NULL, false))
    {
    case 0: case 1: case 2:
        return (sel - 12) * 3600;
    case 3:
        return -9 * 3600 - 30 * 60;
    case 4: case 5: case 6: case 7: case 8: case 9:
        return (sel - 13) * 3600;
    case 10:
        return -3 * 3600 - 30 * 60;
    case 11:
        return -3 * 3600;
    case 12:
        return -3 * 3600 - 30 * 60;
    case 13: case 14: case 15: case 16: case 17: case 18:
        return (sel - 15) * 3600;

    case 19:
        return 3 * 3600 + 30 * 60;
    case 20:
        return 4 * 3600;
    case 21:
        return 4 * 3600 + 30 * 60;
    case 22:
        return 5 * 3600;
    case 23:
        return 5 * 3600 + 30 * 60;
    case 24:
        return 5 * 3600 + 45 * 60;
    case 25:
        return 6 * 3600;
    case 26:
        return 6 * 3600 + 30 * 60;
    case 27: case 28:
        return (sel - 20) * 3600;
    case 29:
        return 8 * 3600 + 30 * 60;
    case 30:
        return 8 * 3600 + 45 * 60;
    case 31:
        return 9 * 3600;
    case 32:
        return 9 * 3600 + 30 * 60;
    case 33:
        return 10 * 3600;
    case 34:
        return 10 * 3600 + 30 * 60;
    case 35: case 36:
        return (sel - 24) * 3600;
    case 37:
        return 12 * 3600 + 45 * 60;
    case 38: case 39:
        return (sel - 25) * 3600;
    default:
        rb->splash(0, "BUG: time zone fall-through: REPORT ME!!!");
        break;
    }
    return 0;
#endif
}
#endif

#define SAVE_HOTP   (1<<0)
#define SAVE_TOTP   (1<<1)
#define SAVE_STATIC (1<<2)
#define SAVE_OTP    (SAVE_HOTP | SAVE_TOTP)
#define SAVE_ALL    (SAVE_OTP | SAVE_STATIC)

static void export_uri_list(int typemask)
{
    static char buf[MAX(MAX_PATH, SECRET_MAX * 2)];
    buf[0] = '/';
    buf[1] = '\0';
    rb->splash(HZ * 2, "Enter output filename:");
    if(rb->kbd_input(buf, sizeof(buf)) < 0)
        return;

    if(rb->file_exists(buf))
    {
        rb->splash(HZ, "File already exists!");
        return;
    }

    int fd = rb->open(buf, O_WRONLY | O_CREAT | O_TRUNC);
    if(fd < 0)
    {
        rb->splashf(HZ, "Couldn't open file.");
        return;
    }

    for(int i = 0; i < next_slot ; ++i)
    {
        if((accounts[i].type + 1) & typemask)
        {
            switch(accounts[i].type)
            {
            case TYPE_TOTP:
            case TYPE_HOTP:
                base32_encode(accounts[i].secret, accounts[i].sec_len, buf, sizeof(buf));
                rb->fdprintf(fd, "otpauth://%s/%s?secret=%s&digits=%" PRIu32, accounts[i].type == TYPE_TOTP ? "totp" : "hotp",
                             accounts[i].name, buf, accounts[i].digits);

                if(accounts[i].type == TYPE_TOTP)
                    rb->fdprintf(fd, "&period=%" PRIi32, accounts[i].totp_period);
            else
                rb->fdprintf(fd, "&counter=%u", (unsigned) accounts[i].hotp_counter);
                rb->fdprintf(fd, "\n");
                break;
            case TYPE_STATIC:
                rb->fdprintf(fd, "%s:%s\n", accounts[i].name, accounts[i].secret);
                break;
            }
        }
    }

    rb->close(fd);

    rb->splash(HZ, "Success.");
}

static void export_encrypted(void)
{
    if(encrypted)
    {
        MENUITEM_STRINGLIST(menu, "Password to Use", NULL,
                            "Current Password/Passphrase",
                            "Enter New Password",
                            "Cancel");
        bool quit = false;
        while(!quit)
        {
            switch(rb->do_menu(&menu, NULL, NULL, false))
            {
            case 0:
                rb->strlcpy(data_buf, enc_password, PASS_MAX);
                goto export;
            case 1:
                quit = true;
                break;
            case 2:
            default:
                return;
            }
        }
    }

    /* we need to read a password */
    rb->splash(HZ, "Enter encryption password:");
    data_buf[0] = '\0';
    if(rb->kbd_input(data_buf, PASS_MAX) < 0)
        return;

    char temp_pass[PASS_MAX];

    rb->splash(HZ, "Re-enter encryption password:");
    temp_pass[0] = '\0';
    if(rb->kbd_input(temp_pass, PASS_MAX) < 0)
        return;

    if(rb->strcmp(temp_pass, data_buf))
    {
        rb->splash(HZ, "Passwords do not match!");
        return;
    }

    char fname[MAX_PATH];

export:

    rb->snprintf(fname, sizeof(fname), "/");
    rb->splash(HZ, "Enter output filename:");
    if(rb->kbd_input(fname, sizeof(fname)) < 0)
        return;

    if(rb->file_exists(fname))
    {
        rb->splash(HZ, "File already exists!");
        return;
    }

    /* begin saving */

    rb->splash(0, "Exporting...");

    /* this format essentially mirrors that of the default save
     * format, but with some slight modifications: */
    /* all values are stored big-endian */
    /* no hardware AES core is used */
    /* a constant 50,000 PBKDF2 iterations are used */

    int fd = rb->open(fname, O_WRONLY | O_CREAT | O_TRUNC);
    if(fd < 0)
    {
        rb->splash(HZ, "Couldn't open file.");
        return;
    }

    rb->mutex_lock(&save_mutex);

    rb->fdprintf(fd, "OTPX");

    /* generate/write the nonce */
    uint64_t nonce = *rb->current_tick;
#if CONFIG_RTC
    nonce |= (uint64_t)get_utc() << 32;
#endif

    rb->write(fd, &nonce, sizeof(nonce));

    /* placeholder for the MAC */
    off_t mac_offs = rb->lseek(fd, 0, SEEK_CUR);
    rb->memset(data_buf, 0, 20);
    rb->write(fd, data_buf, 20);

    char key[20];
    char tmp[sizeof(nonce) + 4];

    PBKDF2(data_buf, rb->strlen(data_buf), &nonce, sizeof(nonce),
           KDF_EXPORT, key, sizeof(key), tmp);

    struct aes_ctr_ctx aes_ctx;
    aes_ctr_init(&aes_ctx, key, nonce);

    /* note that in calculating the HMAC we don't use the primary
       key, but instead another part of the PBKDF2 output */

    struct hmac_ctx hmac_ctx;
    /* 16 bytes are used for the encryption key, 4 for verification */
    hmac_sha1_init(&hmac_ctx, key + 16, sizeof(key) - 16);

    for(int i = 0; i < next_slot; ++i)
    {
        /* we don't need data_buf to store the password anymore */
        rb->memcpy(data_buf, accounts + i, sizeof(struct account_t));
        struct account_t *acct = (struct account_t*)data_buf;

        /* change endianness */
        acct->type         = htobe32(acct->type);
        acct->hotp_counter = htobe64(acct->hotp_counter);
        acct->digits       = htobe32(acct->digits);
        acct->sec_len      = htobe32(acct->sec_len);

        /* encrypt */
        aes_ctr_process(&aes_ctx, data_buf, data_buf, sizeof(struct account_t));

        /* write */
        rb->write(fd, data_buf, sizeof(struct account_t));

        /* and MAC */
        hmac_sha1_process_bytes(&hmac_ctx, data_buf, sizeof(struct account_t));
    }

    /* write the MAC */
    char mac[20];

    hmac_sha1_finish_ctx(&hmac_ctx, mac);

    rb->lseek(fd, mac_offs, SEEK_SET);
    rb->write(fd, mac, 20);

    /* cleanup */
    aes_ctr_destroy(&aes_ctx);
    wipe_buf(key, sizeof(key));
    wipe_buf(tmp, sizeof(tmp));
    wipe_buf(temp_pass, sizeof(temp_pass));

    rb->close(fd);
    rb->mutex_unlock(&save_mutex);
}

static void export_menu(void)
{
    MENUITEM_STRINGLIST(menu, "Export Accounts", NULL,
                        "To Encrypted Backup (all accounts)",
                        "To URI List (static passwords interleaved)",
                        "To URI List (only OTP accounts)",
                        "To 'username:password List' (only static passwords)",
                        "Back");

    int sel = 0;

    bool quit = false;

    while(!quit)
    {
        switch(rb->do_menu(&menu, &sel, NULL, false))
        {
        case 0:
            export_encrypted();
        case 1:
            export_uri_list(SAVE_ALL);
            break;
        case 2:
            export_uri_list(SAVE_OTP);
            break;
        case 3:
            export_uri_list(SAVE_STATIC);
        break;
        default:
            quit = true;
            break;
        }
    }
}

static void kdf_delay_menu(void)
{
    MENUITEM_STRINGLIST(menu, "Change KDF Delay", NULL,
                        "50 ms -- fastest, least secure",            // 0
                        "100 ms",                                    // 1
                        "250 ms -- default",                         // 2
                        "350 ms",                                    // 3
                        "500 ms",                                    // 4
                        "750 ms",                                    // 5
                        "1000 ms",                                   // 6
                        "1500 ms",                                   // 7
                        "2500 ms -- for the extremely paranoid",     // 8
                        "Back");
    int ticks = 0;
    while(!ticks)
    {
        switch(rb->do_menu(&menu, NULL, NULL, false))
        {
        case 0:
            ticks = 5 * HZ / 100;
            break;
        case 1:
            ticks = 10 * HZ / 100;
            break;
        case 2:
            ticks = 25 * HZ / 100;
            break;
        case 3:
            ticks = 35 * HZ / 100;
            break;
        case 4:
            ticks = 50 * HZ / 100;
            break;
        case 5:
            ticks = 75 * HZ / 100;
            break;
        case 6:
            ticks = 100 * HZ / 100;
            break;
        case 7:
            ticks = 150 * HZ / 100;
            break;
        case 8:
            ticks = 250 * HZ / 100;
            break;
        case 9:
            return;
        default:
            break;
        }
    }
    if(ticks)
    {
        rb->mutex_lock(&save_mutex);
        kdf_iters = calc_kdf_iters(ticks);
        rb->mutex_unlock(&save_mutex);
        background_save();
    }
    rb->splashf(HZ, "Using %d PBKDF2 iterations", kdf_iters);
}

/* begin using a password for encryption */
static bool change_password(void)
{
    //if(!verify_password())
    //    return false;
    char temp_pass[sizeof(enc_password)];
    char temp_pass2[sizeof(enc_password)];

    temp_pass[0] = '\0';

    rb->splash(HZ * 2, "Enter new password:");

    if(rb->kbd_input(temp_pass, sizeof(temp_pass)) < 0)
        return false;

    temp_pass2[0] = '\0';

    rb->splash(HZ * 2, "Re-enter new password:");

    if(rb->kbd_input(temp_pass2, sizeof(temp_pass2)) < 0)
        return false;

    if(rb->strcmp(temp_pass, temp_pass2))
    {
        rb->splash(HZ * 2, "Passwords do not match!");
        return false;
    }

    rb->mutex_lock(&save_mutex);

    rb->strlcpy(enc_password, temp_pass, sizeof(enc_password));

    encrypted = 1;

    rb->mutex_unlock(&save_mutex);

    background_save();

    rb->splash(HZ, "Success.");
    return true;
}

#ifdef PASSMGR_DICEWARE
static bool generate_random_passphrase(char *buf, size_t buflen)
{
    char key[20];

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(true);
#endif

    gather_entropy(key, 20);

    /* give the user time to stop pressing keys */
    rb->splash(HZ * 2, "Done.");

    rb->button_clear_queue();

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    rb->cpu_boost(false);
#endif

    assert(DICEWARE_WORDS < 160/16);

    uint16_t *ptr;

    for(int i = 0; i < 10; ++i)
    {
        /* generate a passphrase until the user decides on one or we try 10 times */

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
        rb->cpu_boost(true);
#endif

        ptr = (uint16_t*)key;
        buf[0] = '\0';
        rb->splash(0, "Generating...");
        for(int i = 0; i < DICEWARE_WORDS; ++i)
        {
            uint16_t rnd;
            /* rehash until we get a good value */
            /* this smells awfully like bitcoin mining */
            do {
                rnd = *ptr;
                long timestamp = *rb->current_tick;
                hmac_sha1(&timestamp, sizeof(long), key, 20, key);
            } while(rnd >= word_list_len);

            rb->strlcat(buf, word_list[rnd], buflen);
            rb->strlcat(buf, " ", buflen);
            rb->yield();
        }

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
        rb->cpu_boost(false);
#endif

        rb->backlight_set_timeout(0); /* no timeout */

        struct text_message prompt = { (const char*[]) { "Your generated passphrase is:", buf, "Is this OK?" }, 3 };
        enum yesno_res response = rb->gui_syncyesno_run(&prompt, NULL, NULL);
        if(response == YESNO_NO)
        {
            long timestamp = *rb->current_tick;

            /* mix it with an HMAC */
            hmac_sha1(&timestamp, sizeof(long), key, 20, key);
        }
        else
        {
            struct text_message prompt2 = { (const char*[]) { "Again, your passphrase is:", buf, "Please take time to commit this to memory.", "If you forget it, your data will be irretrievably lost!", "Continue?"}, 5 };
            enum yesno_res response = rb->gui_syncyesno_run(&prompt2, NULL, NULL);
            if(response == YESNO_YES)
                return true;
        }
    }

    return false;
}

/* use a passphrase */
static bool change_passphrase(void)
{
    MENUITEM_STRINGLIST(mode_menu, "Choose Passphase Generation Method", NULL,
                        "Random Generation",
                        "Manual Entry (not recommended)",
                        "Cancel");

    bool done = false;
    while(!done)
    {
        switch(rb->do_menu(&mode_menu, NULL, NULL, false))
        {
        case 0:
        /* we need the data buffer */
            rb->mutex_lock(&save_mutex);
            if(!generate_random_passphrase(data_buf, sizeof(data_buf)))
            {
                rb->mutex_unlock(&save_mutex);
                return false;
            }
            rb->mutex_unlock(&save_mutex);
            done = true;
            break;
        case 1:
            rb->splash(HZ, "Enter new passphrase:");
            rb->mutex_lock(&save_mutex);
            if(read_diceware_passphrase(data_buf, sizeof(data_buf)))
            {
                /* failure */
                rb->mutex_unlock(&save_mutex);
                return false;
            }
            rb->mutex_unlock(&save_mutex);
            done = true;
            break;
        default:
            return false;
        }
    }

    rb->mutex_lock(&save_mutex);

    rb->strlcpy(enc_password, data_buf, sizeof(enc_password));
    encrypted = 2;

    rb->mutex_unlock(&save_mutex);

    background_save();

    rb->splash(HZ, "Success.");

    return true;
}
#endif /* #ifdef PASSMGR_DICEWARE */

static bool disable_encryption(void)
{
    //if(!verify_password())
    //    return false;
    rb->mutex_lock(&save_mutex);
    encrypted = 0;
    rb->mutex_unlock(&save_mutex);
    background_save();
    rb->splash(HZ, "Success.");
    return true;
}

static void encrypt_menu(void)
{
    /* 3 states for the menu */
    MENUITEM_STRINGLIST(encrypt_menu_0, "Encryption", NULL,
                        "Enable",
                        "Back");

    MENUITEM_STRINGLIST(encrypt_menu_1 , "Encryption", NULL,
                        "Change Password",
                        "Change KDF Delay",
#ifdef PASSMGR_DICEWARE
                        "Use a Passphrase",
#endif
                        "Disable",
                        "Back");

#ifdef PASSMGR_DICEWARE
    MENUITEM_STRINGLIST(encrypt_menu_2 , "Encryption", NULL,
                        "Change Passphrase",
                        "Change KDF Delay",
                        "Use a Password",
                        "Disable",
                        "Back");
#endif

    const struct menu_item_ex *menus[] = { &encrypt_menu_0,
                                           &encrypt_menu_1,
#ifdef PASSMGR_DICEWARE
                                           &encrypt_menu_2,
#endif
    };

    const struct menu_item_ex *menu;
state_change:
    menu = menus[(int)encrypted];

    bool done = false;

    while(!done)
    {
        int sel = rb->do_menu(menu, NULL, NULL, false);
        switch(encrypted)
        {
        case 0: /* disabled */
        {
            switch(sel)
            {
            case 0: /* enable, change type */
                change_password();
                goto state_change;
            case 1: /* back */
            default:
                done = true;
                break;
            }
            break;
        }
        case 1: /* using a password */
        {
            switch(sel)
            {
            case 0: /* change password */
                change_password();
                break; /* no state change */
            case 1: /* KDF delay */
                kdf_delay_menu();
                break;
#ifdef PASSMGR_DICEWARE
            case 2: /* use passphrase */
                change_passphrase();
                goto state_change;
            case 3: /* disable */
                disable_encryption();
                goto state_change;
            case 4: /* back */
                done = true;
                break;
#else
            case 2: /* disable */
                disable_encryption();
                goto state_change;
            case 3: /* back */
                done = true;
                break;
#endif
            default:
                break;
            }
            break;
        }
#ifdef PASSMGR_DICEWARE
        case 2: /* we have a passphrase configured */
        {
            switch(sel)
            {
            case 0: /* change passphrase */
                change_passphrase();
                break;
            case 1: /* KDF delay */
                kdf_delay_menu();
                break;
            case 2: /* use a password */
                change_password();
                goto state_change;
            case 3: /* disable */
                disable_encryption();
                goto state_change;
            case 4:
                done = true;
                break;
            default:
                break;
            }
        }
#endif
        default:
            break;
        }
    }
}

static void adv_menu(void)
{
    MENUITEM_STRINGLIST(menu, "Advanced", NULL,
                        "Edit Account",
                        "Export Accounts",
                        "Encryption",
                        "Delete ALL Accounts",
#if CONFIG_RTC
                        "Select Time Zone",
#endif
                        "Back");

    bool quit = false;
    int sel = 0;
    while(!quit)
    {
        switch(rb->do_menu(&menu, &sel, NULL, false))
        {
        case 0:
            edit_accts();
            break;
        case 1:
            export_menu();
            break;
        case 2:
        {
            encrypt_menu();
            break;
        }
        case 3:
            if(danger_confirm())
            {
                rb->mutex_lock(&save_mutex);
                next_slot = 0;
                rb->mutex_unlock(&save_mutex);
                save_accts();
                rb->splash(HZ, "It is done, my master.");
            }
            else
                rb->splash(HZ, "Not confirmed.");
            break;
#if CONFIG_RTC
        case 4:
        {
            int old_offs = time_offs;
            rb->mutex_lock(&save_mutex);
            time_offs = get_time_offs();
            rb->mutex_unlock(&save_mutex);
            if(time_offs != old_offs)
                background_save();
            break;
        }
        case 5:
#else
        case 4:
#endif
            quit = 1;
            break;
        default:
            break;
        }
    }
}

static char *help_text[] = { "Password Manager", "",
                             "",
                             "Introduction", "",
                             "This", "plugin", "allows", "you", "to", "generate", "one-time", "passwords", "as", "a", "second", "factor", "of", "authentication", "for", "online", "services", "which", "support", "it,", "such", "as", "GitHub", "and", "Google.",
                             "This", "plugin", "supports", "both", "counter-based", "(HOTP),", "and", "time-based", "(TOTP)", "password", "schemes.",
                             "It", "also", "supports", "storing", "static", "passwords", "securely.",
                             "",
                             "",
                             "Time Zone Configuration", "",
                             "On", "the", "first", "run", "of", "the", "plugin,", "you", "are", "asked", "for", "the", "time", "zone", "to", "which", "your", "system", "clock", "is", "set.",
                             "If", "you", "need", "to", "change", "this", "setting", "later,", "it", "is", "available", "under", "the", "'Advanced'", "menu", "option.",
                             "",
                             "",
                             "Account Setup", "",
                             "To", "add", "a", "new", "account,", "choose", "the", "'Add", "Account(s)'", "menu", "option.",
                             "There", "are", "two", "ways", "to", "add", "an", "account,", "either", "from", "a", "file", "containing", "account", "information", "in", "URI", "format,", "or", "manual", "entry.",
                             "",
                             "",
                             "URI Import", "",
                             "This", "method", "of", "adding", "an", "account", "reads", "a", "list", "of", "URIs", "from", "a", "file.",
                             "It", "expects", "each", "URI", "to", "be", "on", "a", "line", "by", "itself", "in", "the", "following", "format:", "",
                             "",
                             "otpauth://[hotp", "OR", "totp]/[account", "name]?secret=[Base32", "secret][&counter=X][&period=X][&digits=X]", "",
                             "",
                             "An", "example", "is", "shown", "below,", "provisioning", "a", "TOTP", "key", "for", "an", "account", "called", "``bob'':", "",
                             "",
                             "otpauth://totp/bob?secret=JBSWY3DPEHPK3PXP", "",
                             "",
                             "Any", "other", "URI", "options", "are", "not", "supported", "and", "will", "be", "ignored.",
                             "",
                             "Most", "services", "will", "provide", "a", "scannable", "QR", "code", "that", "encodes", "a", "OTP", "URI.",
                             "In", "order", "to", "use", "those,", "first", "scan", "the", "QR", "code", "separately", "and", "save", "the", "URI", "to", "a", "file", "on", "your", "device.",
                             "If", "necessary,", "rewrite", "the", "URI", "so", "it", "is", "in", "the", "format", "shown", "above.",
                             "For", "example,", "GitHub's", "URI", "has", "a", "slash", "after", "the", "provider.",
                             "In", "order", "for", "this", "URI", "to", "be", "properly", "parsed,", "you", "must", "rewrite", "the", "account", "name", "so", "that", "it", "does", "not", "contain", "a", "slash.",
                             "",
                             "",
                             "Manual Import", "",
                             "If", "direct", "URI", "import", "is", "not", "possible,", "the", "plugin", "supports", "the", "manual", "entry", "of", "data", "associated", "with", "an", "account.",
                             "After", "you", "select", "the", "'Manual", "Entry'", "option,", "it", "will", "prompt", "you", "for", "an", "account", "name.",
                             "You", "may", "type", "anything", "you", "wish,", "but", "it", "should", "be", "memorable.",
                             "It", "will", "then", "prompt", "you", "for", "the", "Base32-encoded", "secret.",
                             "Most", "services", "will", "provide", "this", "to", "you", "directly,", "but", "some", "may", "only", "provide", "you", "with", "a", "QR", "code.",
                             "In", "these", "cases,", "you", "must", "scan", "the", "QR", "code", "separately,", "and", "then", "enter", "the", "string", "following", "the", "'secret='", "parameter", "on", "your", "Rockbox", "device", "manually.",
                             "",
                             "On", "devices", "with", "a", "real-time", "clock,", "the", "plugin", "will", "ask", "whether", "the", "account", "is", "a", "time-based", "account", "(TOTP).",
                             "If", "you", "answer", "'yes'", "to", "this", "question,", "it", "will", "ask", "for", "further", "information", "regarding", "the", "account.",
                             "Usually", "it", "is", "safe", "to", "accept", "the", "defaults", "here.",
                             "However,", "if", "your", "device", "lacks", "a", "real-time", "clock,", "the", "plugin's", "functionality", "will", "be", "restricted", "to", "HMAC-based", "(HOTP)", "accounts", "only.",
                             "If", "this", "is", "the", "case,", "the", "plugin", "will", "prompt", "you", "for", "information", "regarding", "the", "HOTP", "setup.",
                             "Again,", "it", "is", "usually", "safe", "to", "accept", "the", "defaults.",
                             "",
                             "",
                             "Account Export", "",
                             "This", "plugin", "allows", "you", "to", "export", "account", "data", "to", "a", "file", "for", "backup", "and", "transfer", "purposes.",
                             "This", "option", "is", "located", "under", "the", "'Advanced'", "menu.",
                             "It", "will", "prompt", "for", "for", "a", "filename,", "and", "will", "write", "all", "your", "account", "data", "to", "the", "specified", "file.",
                             "This", "file", "can", "be", "imported", "by", "this", "plugin", "using", "the", "'From", "URI", "List'", "option", "when", "importing.",
                             "Please", "note", "that", "you", "should", "not", "attempt", "to", "copy", "the", "'passmgr.dat'", "from", "the", ".rockbox", "directory", "to", "another", "device.",
                             "",
                             "",
                             "Encryption", "",
                             "This", "plugin", "supports", "the", "optional", "encryption", "of", "account", "data", "while", "stored", "on", "disk.",
                             "This", "feature", "is", "located", "under", "the", "'Advanced'", "menu", "option.",
                             "Upon", "enabling", "this", "feature,", "you", "must", "enter", "an", "encryption", "password", "that", "will", "need", "to", "be", "entered", "each", "time", "the", "plugin", "starts", "up.",
                             "It", "is", "recommended", "that", "you", "use", "a", "strong,", "alphanumeric", "password", "of", "at", "least", "8", "characters", "in", "order", "to", "frustrate", "attempts", "to", "guess", "the", "password.",
                             "Be", "sure", "not", "to", "forget", "this", "password.",
                             "In", "the", "event", "that", "the", "password", "is", "lost,", "it", "is", "nearly", "impossible", "to", "recover", "your", "account", "data.",
                             "",
                             "",
                             "Implementation Details", "",
                             "Account", "data", "is", "encrypted", "with", "128-bit", "AES", "encryption", "in", "counter", "mode.",
                             "The", "key", "is", "derived", "from", "the", "your", "password", "and", "a", "nonce", "by", "using", "PBKDF2-HMAC-SHA1,", "with", "a", "variable", "number", "of", "iterations,", "calibrated", "by", "default", "to", "take", "250", "milliseconds.",
                             "This", "parameter", "can", "be", "adjusted", "using", "the", "'Change", "KDF", "Delay'", "option", "under", "the", "'Encryption'", "submenu.",
                             "The", "nonce", "is", "generated", "from", "the", "system's", "current", "tick", "and", "the", "real-time", "clock,", "if", "available,", "making", "collision", "unlikely.",
                             "Some", "later-model", "iPods", "have", "a", "hardware", "AES", "core", "with", "a", "hardcoded,", "device-specific", "key", "that", "cannot", "easily", "be", "extracted.",
                             "When", "available,", "the", "device-specific", "key", "is", "used", "to", "encrypt", "the", "actual", "encryption", "key,", "tying", "the", "ciphertext", "to", "the", "device,", "making", "a", "brute-force", "attack", "more", "difficult.",
                             "One", "should", "note", "that", "this", "does", "not", "rely", "completely", "rely", "on", "the", "hardware", "encryption", "key,", "it", "merely", "utilizes", "it", "as", "part", "of", "defense", "in", "depth.",
                             "",
                             "",
                             "Troubleshooting", "",
                             "If", "time-based", "passwords", "and", "not", "working", "properly,", "ensure", "that", "your", "system", "clock", "is", "accurate", "to", "within", "30", "seconds", "of", "the", "authenticating", "server's", "clock,", "and", "that", "the", "proper", "time", "zone", "is", "configured", "within", "the", "plugin.",
                             "Be", "sure", "to", "account", "for", "Daylight", "Savings", "Time,", "if", "applicable.",
                             "",
                             "",
                             "Supported Features", "",
#if !CONFIG_RTC
                             "This", "device", "lacks", "a", "real-time", "clock,", "and", "thus", "time-based", "(TOTP)", "passwords", "are", "not", "supported.",
                             "",
#endif
#if CONFIG_CPU == S5L8702 && !defined(SIMULATOR)
                             "This", "device", "has", "a", "hardware", "AES", "core", "that", "will", "be", "used", "to", "further", "protect", "your", "data", "by", "tying", "it", "to", "this", "device.",
                             "",
#else
                             "This", "device", "does", "not", "have", "a", "hardware", "AES", "core.",
                             "The", "security", "of", "the", "encryption", "thus", "relies", "solely", "on", "your", "password.",
                             "",
#endif
#ifdef USB_ENABLE_HID
                             "This", "device", "has", "the", "ability", "to", "type", "passwords", "directly", "to", "a", "host", "computer", "over", "the", "USB", "connection.",
                             "",
#endif
};

struct style_text style[] = {
    { 0, TEXT_CENTER | TEXT_UNDERLINE },
    { 3, C_RED },
    { 50, C_RED },
    { 91, C_RED },
    { 127, C_RED },
    { 280, C_RED },
    { 468, C_RED },
    { 548, C_RED },
    { 644, C_RED },
    { 787, C_RED },
    { 835, C_RED },
    LAST_STYLE_ITEM
};


/* displays the help text */
static void show_help(void)
{

#ifdef HAVE_LCD_COLOR
    rb->lcd_set_foreground(LCD_WHITE);
    rb->lcd_set_background(LCD_BLACK);
#endif

#ifdef HAVE_LCD_BITMAP
    rb->lcd_setfont(FONT_UI);
#endif
    display_text(ARRAYLEN(help_text), help_text, style, NULL, true);
}

#ifdef USB_ENABLE_HID

#define FORCE_EXEC_THRES (HZ/3)
#define TYPE_DELAY (HZ / 25)

static bool wait_for_usb(void)
{
    if(!rb->usb_inserted())
    {
        /* wait for a USB connection */

        rb->splash(0, "Waiting for USB, hold any button to abort...");

        int oldbutton = 0;
        int ticks_held = 0;
        long last_tick = 0;
        while(1)
        {
            int button = rb->button_get(true);
            if(button == SYS_USB_CONNECTED)
            {
                break;
            }
            else if(button)
            {
                /* check if a key is being held down */

                if(oldbutton == 0)
                {
                    oldbutton = button;

                    ticks_held = 0;
                    last_tick = *rb->current_tick;
                }
                else if(button == oldbutton || button == (oldbutton | BUTTON_REPEAT))
                {
                    int dt = *rb->current_tick - last_tick;
                    if(dt)
                    {
                        ticks_held += dt;
                        last_tick = *rb->current_tick;
                        if(ticks_held >= FORCE_EXEC_THRES)
                            return false;
                    }
                }
            }
        }

        /* wait a bit to let the host recognize us... */
        rb->sleep(HZ / 2);
    }
    return true;
}

static void send(int status)
{
    rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, status);
}

/* Rockbox's HID driver supports up to 4 keys simultaneously, 1 in each byte */

static void add_key(int *keystate, unsigned *nkeys, int newkey)
{
    *keystate = (*keystate << 8) | newkey;
    if(nkeys)
        (*nkeys)++;
}

struct char_mapping {
    char c;
    int key;
};

static struct char_mapping shift_tab[] = {
    { '~', HID_KEYBOARD_BACKTICK },
    { '!', HID_KEYBOARD_1 },
    { '@', HID_KEYBOARD_2 },
    { '#', HID_KEYBOARD_3 },
    { '$', HID_KEYBOARD_4 },
    { '%', HID_KEYBOARD_5 },
    { '^', HID_KEYBOARD_6 },
    { '&', HID_KEYBOARD_7 },
    { '*', HID_KEYBOARD_8 },
    { '(', HID_KEYBOARD_9 },
    { ')', HID_KEYBOARD_0 },
    { '_', HID_KEYBOARD_HYPHEN },
    { '+', HID_KEYBOARD_EQUAL_SIGN },
    { '}', HID_KEYBOARD_RIGHT_BRACKET },
    { '{', HID_KEYBOARD_LEFT_BRACKET },
    { '|', HID_KEYBOARD_BACKSLASH },
    { '"', HID_KEYBOARD_QUOTE },
    { ':', HID_KEYBOARD_SEMICOLON },
    { '?', HID_KEYBOARD_SLASH },
    { '>', HID_KEYBOARD_DOT },
    { '<', HID_KEYBOARD_COMMA },
};

static struct char_mapping char_tab[] = {
    { ' ', HID_KEYBOARD_SPACEBAR },
    { '`', HID_KEYBOARD_BACKTICK },
    { '-', HID_KEYBOARD_HYPHEN },
    { '=', HID_KEYBOARD_EQUAL_SIGN },
    { '[', HID_KEYBOARD_LEFT_BRACKET },
    { ']', HID_KEYBOARD_RIGHT_BRACKET },
    { '\\', HID_KEYBOARD_BACKSLASH },
    { '\'', HID_KEYBOARD_QUOTE },
    { ';', HID_KEYBOARD_SEMICOLON },
    { '/', HID_KEYBOARD_SLASH },
    { ',', HID_KEYBOARD_COMMA },
    { '.', HID_KEYBOARD_DOT },
    { '\t',HID_KEYBOARD_TAB },
};

static void add_char(int *keystate, unsigned *nkeys, char c)
{
    (void) keystate; (void) nkeys; (void) c;
    if('a' <= c && c <= 'z')
    {
        add_key(keystate, nkeys, c - 'a' + HID_KEYBOARD_A);
    }
    else if('A' <= c && c <= 'Z')
    {
        add_key(keystate, nkeys, HID_KEYBOARD_LEFT_SHIFT);
        add_key(keystate, nkeys, c - 'A' + HID_KEYBOARD_A);
    }
    else if('0' <= c && c <= '9')
    {
        if(c == '0')
            add_key(keystate, nkeys, HID_KEYPAD_0_AND_INSERT);
        else
            add_key(keystate, nkeys, c - '1' + HID_KEYPAD_1_AND_END);
    }
    else
    {
        /* search the character table */
        for(unsigned int i = 0; i < ARRAYLEN(char_tab); ++i)
        {
            if(char_tab[i].c == c)
            {
                add_key(keystate, nkeys, char_tab[i].key);
                return;
            }
        }

        /* search the shift-mapping table */
        for(unsigned int i = 0; i < ARRAYLEN(shift_tab); ++i)
        {
            if(shift_tab[i].c == c)
            {
                add_key(keystate, nkeys, HID_KEYBOARD_LEFT_SHIFT);
                add_key(keystate, nkeys, shift_tab[i].key);
                return;
            }
        }

        rb->splashf(HZ, "WARNING: could not type character '%c'!", c);
    }
}

static void send_string(const char *str)
{
    while(*str)
    {
        int string_state = 0;
        if(!*str)
            break;
        add_char(&string_state, NULL, *str);

        send(string_state);

        ++str;

        rb->sleep(TYPE_DELAY);
    }
}

static bool enable_numlock(void)
{
    /* check numlock status */
    bool change_numlock = !(rb->usb_hid_leds() & 0x1);
    if(change_numlock)
        rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, HID_KEYPAD_NUM_LOCK_AND_CLEAR);
    return change_numlock;
}

static void type_code(int acct)
{
    if(!wait_for_usb())
        return;

    rb->splash(0, "Typing...");

    bool change_numlock = enable_numlock();

    switch(accounts[acct].type)
    {
    case TYPE_HOTP:
    case TYPE_TOTP:
    {
        int code = next_code(acct);

        /* hackery to get around the lack of %*d support */
        char fmt_buf[64], buf[64];

        rb->snprintf(fmt_buf, sizeof(fmt_buf), "%%0%" PRIu32 "d", accounts[acct].digits);
        rb->snprintf(buf, sizeof(buf), fmt_buf, code);

        char *ptr = buf;

        while(*ptr)
        {
            char c = *ptr++;
            if(c == '0')
                rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, HID_KEYPAD_0_AND_INSERT);
            else
                rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, c - '1'  + HID_KEYPAD_1_AND_END);
            rb->sleep(TYPE_DELAY);
        }
        if(accounts[acct].type == TYPE_HOTP)
            background_save();
        break;
    }
    case TYPE_STATIC:
        send_string(accounts[acct].secret);
        break;
    default:
        break;
    }

    rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, HID_KEYBOARD_RETURN);

    if(change_numlock)
        rb->usb_hid_send(HID_USAGE_PAGE_KEYBOARD_KEYPAD, HID_KEYPAD_NUM_LOCK_AND_CLEAR);

    rb->splash(0, "Done.");

    /* wait a while to prevent accidental code generation */
    rb->sleep(HZ / 2);
    while(1)
    {
        int button = rb->button_get(true);
        if(button && !(button & BUTTON_REL))
            break;
        rb->yield();
    }

    rb->lcd_update();
}

static void type_codes(void)
{
    if(!rb->global_settings->usb_hid)
    {
        rb->splashf(HZ * 4, "Please enable USB HID in the system settings.");
    }
    acct_menu("Type Password", type_code);
}
#endif

/* based on keybox */

static const char* list_cb(int selected_item, void *data,
                           char *buffer, size_t buffer_len)
{
    (void) data;
    rb->snprintf(buffer, buffer_len, "%s", accounts[selected_item].name);
    return buffer;
}

static void acct_menu(char *title, void (*cb)(int acct))
{
    struct gui_synclist list;

    rb->gui_synclist_init(&list, &list_cb, NULL, false, 1, NULL);
    rb->gui_synclist_set_title(&list, title, NOICON);
    rb->gui_synclist_set_icon_callback(&list, NULL);
    rb->gui_synclist_set_nb_items(&list, next_slot);
    rb->gui_synclist_limit_scroll(&list, false);
    rb->gui_synclist_select_item(&list, 0);

    bool done = false;

    while (!done)
    {
        rb->gui_synclist_draw(&list);
        int button = rb->get_action(CONTEXT_LIST, TIMEOUT_BLOCK);

#ifdef USB_ENABLE_HID
        /* ignore USB connections when in USB mode */
        if(cb != type_code || button != SYS_USB_CONNECTED)
#endif
            if (rb->gui_synclist_do_button(&list, &button, LIST_WRAP_ON))
                continue;

        switch (button)
        {
        case ACTION_STD_OK:
            cb(rb->gui_synclist_get_sel_pos(&list));
            rb->gui_synclist_set_nb_items(&list, next_slot);
            if(rb->gui_synclist_get_sel_pos(&list) >= next_slot)
                rb->gui_synclist_select_item(&list, next_slot - 1);
            break;
        case ACTION_STD_CONTEXT:
            if(cb != edit_menu)
                edit_menu(rb->gui_synclist_get_sel_pos(&list));
            rb->gui_synclist_set_nb_items(&list, next_slot);
            if(rb->gui_synclist_get_sel_pos(&list) >= next_slot)
                rb->gui_synclist_select_item(&list, next_slot - 1);
            break;
        case ACTION_STD_CANCEL:
            done = true;
            break;
        }
        rb->yield();
    }

    return;

    rb->lcd_clear_display();
    /* native menus don't seem to support dynamic names easily, so we
     * roll our own */
    static const struct button_mapping *plugin_contexts[] = { pla_main_ctx };
    int idx = 0;
    if(next_slot > 0)
    {
        rb->lcd_puts(0, 0, title);
        rb->lcd_putsf(0, 1, "%s", accounts[0].name);
        rb->lcd_update();
    }
    else
    {
        rb->splash(HZ * 2, "No accounts configured!");
        return;
    }
    while(1)
    {
        int button = pluginlib_getaction(-1, plugin_contexts, ARRAYLEN(plugin_contexts));
        switch(button)
        {
        case PLA_LEFT:
            --idx;
            if(idx < 0)
                idx = next_slot - 1;
            break;
        case PLA_RIGHT:
            ++idx;
            if(idx >= next_slot)
                idx = 0;
            break;
        case PLA_SELECT:
            cb(idx);
            if(idx >= next_slot)
                idx = 0;
            if(next_slot == 0)
                return;
            break;
        case PLA_UP:
        case PLA_CANCEL:
        case PLA_EXIT:
            return;
        default:
#ifdef USB_ENABLE_HID
            if(cb != type_code)
#endif
                exit_on_usb(button);
            break;
        }
        rb->lcd_clear_display();
        rb->lcd_puts(0, 0, title);
        rb->lcd_putsf(0, 1, "%s", accounts[idx].name);
        rb->lcd_update();
        rb->yield();
    }
}

static bool self_check(void)
{
    /* RFC 4226 */
    if(HOTP("12345678901234567890", rb->strlen("12345678901234567890"), 1, 6) != 287082)
        return false;

    /* do a 2-byte KDF just to check that I didn't break TOO many things :P */

    unsigned char out[2];
    char tmp[4 + 4];

    PBKDF2("password", 8, "salt", 4, 2, out, 2, tmp);

    if(out[0] != 0xea || out[1] != 0x6c)
        return false;

    return true;
}

/* this is the plugin entry point */
enum plugin_status plugin_start(const void* parameter)
{
    (void)parameter;

    if(!self_check())
    {
        rb->splash(HZ * 4, "Self-test failed! REPORT ME!");
        return PLUGIN_ERROR;
    }

    size_t bufsz;
    accounts = rb->plugin_get_buffer(&bufsz);
    max_accts = bufsz / sizeof(struct account_t);

    atexit(erase_sensitive_info);

    if(!read_accts())
    {
#if CONFIG_RTC
        /* first-run config */
        time_offs = get_time_offs();
#endif
        kdf_iters = calc_kdf_iters(KDF_DEFAULT);
    }

    /* initialize background saving thread */
    rb->mutex_init(&save_mutex);
    background_id = rb->create_thread(background_thread, background_stack,
                                      sizeof(background_stack), 0,
                                      "background_save" IF_PRIO(, PRIORITY_BACKGROUND) IF_COP(, COP));

    MENUITEM_STRINGLIST(menu, "Password Manager", NULL,
                        "Show Password", // 0
#ifdef USB_ENABLE_HID
                        "Type Password", // 1
#endif
                        "Add Account(s)", // 1,2
                        "Help", // 2,3
                        "Advanced", // 3,4
                        "Quit"); // 4,5

    bool quit = false;
    int sel = 0;
    while(!quit)
    {
        switch(rb->do_menu(&menu, &sel, NULL, false))
        {
        case 0:
            gen_codes();
            break;
#ifdef USB_ENABLE_HID
        case 1:
            type_codes();
            break;
        case 2:
            add_acct();
            break;
        case 3:
            show_help();
            break;
        case 4:
            adv_menu();
            break;
        case 5:
            quit = 1;
            break;
#else
        case 1:
            add_acct();
            break;
        case 2:
            show_help();
            break;
        case 3:
            adv_menu();
            break;
        case 4:
            quit = 1;
            break;
#endif
        default:
            break;
        }
    }

    rb->mutex_lock(&save_mutex); // make sure we aren't saving

    /* kill the background thread */
    kill_background = true;
    if(background_id >= 0)
        rb->thread_wait(background_id);

    /* save to disk */
    save_accts();

    /* tell Rockbox that we have completed successfully */
    return PLUGIN_OK;
}