summaryrefslogtreecommitdiff
path: root/libdigidoc/DigiDocObj.c
blob: 6dba29f4e4da172206664ddb969cca977fa5b17a (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
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
//==================================================
// FILE:	DigiDocObj.c
// PROJECT:     Digi Doc
// DESCRIPTION: DigiDoc helper routines for accessing dogidoc data
// AUTHOR:  Veiko Sinivee, S|E|B IT Partner Estonia
//==================================================
// Copyright (C) AS Sertifitseerimiskeskus
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// GNU Lesser General Public Licence is available at
// http://www.gnu.org/copyleft/lesser.html
//==========< HISTORY >=============================
//      26.04.2006      Veiko Sinivee
//                      Creation
//==================================================

#include "DigiDocObj.h"
#include "DigiDocGen.h"
#include "DigiDocError.h"
#include "DigiDocConvert.h"
#include "DigiDocDebug.h"
#include "DigiDocCert.h"
#include "DigiDocOCSP.h"
#include "DigiDocConfig.h"
#include "DigiDocError.h"
#include <string.h>
#include <ctype.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#if OPENSSL_VERSION_NUMBER < 0x10010000L
static EVP_MD_CTX *EVP_MD_CTX_new()
{
	return (EVP_MD_CTX*)OPENSSL_malloc(sizeof(EVP_MD_CTX));
}

static void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
{
	OPENSSL_free(ctx);
}

static int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, const ASN1_OCTET_STRING **pid, const X509_NAME **pname)
{
	*pid = NULL;
	*pname = NULL;
	const OCSP_RESPID *rid = bs->tbsResponseData->responderId;
	if (rid->type == V_OCSP_RESPID_NAME)
		*pname = rid->value.byName;
	else if (rid->type == V_OCSP_RESPID_KEY)
		*pid = rid->value.byKey;
	else
		return 0;
	return 1;
}

static const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP* bs)
{
	return bs->tbsResponseData->producedAt;
}

static const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *single)
{
	return single->certId;
}

static const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs)
{
	return bs->signature;
}
#endif

//============================================================
// Sets a string element of a struct to a new value
// dest - element pointer
// value - new value
// valLen - value length (use -1 for null terminated strings)
//============================================================
EXP_OPTION int setString(char** dest, const char* value, int valLen) 
{
  RETURN_IF_NULL_PARAM(dest);
  RETURN_IF_NULL_PARAM(value);

  if(*dest) {
    free(*dest);
    *dest = NULL;
  }
  if(valLen == -1) {
    *dest = (char*)malloc(strlen(value)+1);
    RETURN_IF_BAD_ALLOC(*dest);
    strncpy(*dest, value, strlen(value)+1);
  } else {
    *dest = (char*)malloc(valLen);
    RETURN_IF_BAD_ALLOC(*dest);
    memcpy(*dest, value, valLen);
  }	
  return ERR_OK;
}

//============================================================
// Allocates a new SignedDoc element and initializes it
// format - format name
// version - format version
//============================================================
EXP_OPTION int SignedDoc_new(SignedDoc **pSignedDoc, const char* format, const char* version)
{
  SignedDoc* pSigDoc = NULL;
	
  RETURN_IF_NULL_PARAM(format);
  RETURN_IF_NULL_PARAM(version);
  ddocDebug(3, "SignedDoc_new", "format: %s version: %s", (format ? format : "NULL"), (version ? version : "NULL"));
  pSigDoc = (SignedDoc*)malloc(sizeof(SignedDoc));
  RETURN_IF_BAD_ALLOC(pSigDoc);
  memset(pSigDoc, 0, sizeof(SignedDoc));
  if(!strcmp(format, DIGIDOC_XML_1_1_NAME) && 
     !strcmp(version, DIGIDOC_XML_1_3_VER)) {
    setString(&(pSigDoc->szFormat), format, -1);
    setString(&(pSigDoc->szFormatVer), version, -1);
	setString(&(pSigDoc->szFileName), "", -1);
  } else {
	ddocDebug(3, "SignedDoc_new", "unsupported version");
    SET_LAST_ERROR_RETURN_CODE(ERR_UNSUPPORTED_FORMAT);
  }
  *pSignedDoc = pSigDoc;
  return ERR_OK;
}

//============================================================
// Frees the memory of SignedDoc element
// pSigDoc - element to free
//============================================================
EXP_OPTION void SignedDoc_free(SignedDoc* pSigDoc) 
{
  int i;

  RETURN_VOID_IF_NULL(pSigDoc);
  for(i = 0; (pSigDoc->pDataFiles != NULL) && 
	(i < pSigDoc->nDataFiles); i++) 
    DataFile_free(pSigDoc->pDataFiles[i]);
  if(pSigDoc->pDataFiles)
    free(pSigDoc->pDataFiles);
  for(i = 0; (pSigDoc->pSignatures != NULL) && 
	(i < pSigDoc->nSignatures); i++)
    SignatureInfo_free(pSigDoc->pSignatures[i]);
  if(pSigDoc->pSignatures)
    free(pSigDoc->pSignatures);
  if(pSigDoc->szFormat)
    free(pSigDoc->szFormat);
  if(pSigDoc->szFormatVer)
    free(pSigDoc->szFormatVer);
	if(pSigDoc->szFileName)
		free(pSigDoc->szFileName);
	if(pSigDoc->szProfile)
		free(pSigDoc->szProfile);
  if(pSigDoc)
    free(pSigDoc);
}


//============================================================
// Returns the number of data files
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getCountOfDataFiles(const SignedDoc* pSigDoc)
{
  RETURN_OBJ_IF_NULL(pSigDoc, 0);
  return pSigDoc->nDataFiles;
}

//============================================================
// Returns the next free data file id
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getNextDataFileId(const SignedDoc* pSigDoc)
{
  int id = 0, n, i;

  RETURN_OBJ_IF_NULL(pSigDoc, 0);
  for(i = 0; i < pSigDoc->nDataFiles; i++) {
    DataFile* pDataFile = pSigDoc->pDataFiles[i];
    RETURN_OBJ_IF_NULL(pDataFile, 0);
    RETURN_OBJ_IF_NULL(pDataFile->szId, 0);
    SET_LAST_ERROR_RETURN_IF_NOT(strlen(pDataFile->szId) > 1, ERR_EMPTY_STRING, 0);
    n = atoi(pDataFile->szId+1);
    if(id <= n)
      id = n+1;
  }
  return id;
}

//============================================================
// Returns the desired DataFile object
// pSigDoc - signed doc pointer
// nIdx - DataFile index (starting with 0)
//============================================================
EXP_OPTION DataFile* getDataFile(const SignedDoc* pSigDoc, int nIdx)
{
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx < pSigDoc->nDataFiles, ERR_BAD_DATAFILE_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigDoc->pDataFiles[nIdx], 0);
  return pSigDoc->pDataFiles[nIdx];
}

//============================================================
// Returns the last DataFile object
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION DataFile* ddocGetLastDataFile(const SignedDoc* pSigDoc)
{
  int nIdx;
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  nIdx = pSigDoc->nDataFiles - 1;
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx >= 0, ERR_BAD_DATAFILE_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigDoc->pDataFiles[nIdx], 0);
  return pSigDoc->pDataFiles[nIdx];
}

//============================================================
// Returns the DataFile object with the given id
// pSigDoc - signed doc pointer
// id - DataFile id
//============================================================
EXP_OPTION DataFile* getDataFileWithId(const SignedDoc* pSigDoc, const char* id)
{
  DataFile* pDataFile = NULL;
  int i;
  //AA 12.11.2003
  RETURN_OBJ_IF_NULL(id, NULL);
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  ddocDebug(4, "getDataFileWithId", "id: \'%s\', files: %d", id, pSigDoc->nDataFiles);
  for(i = 0; i < pSigDoc->nDataFiles; i++) {
    RETURN_OBJ_IF_NULL(pSigDoc->pDataFiles[i], NULL);
    RETURN_OBJ_IF_NULL(pSigDoc->pDataFiles[i]->szId, NULL);
    if(!strcmp(pSigDoc->pDataFiles[i]->szId, id)) {
      pDataFile = pSigDoc->pDataFiles[i];
      break;
    }
  }
  return pDataFile;
}


//============================================================
// Adds a new DataFile element to  a SignedDoc element and initializes it
// pSigDoc - signed document
// id - data file id
// filename - filename
// contentType - EMBEDDED or EMBEDDED_BASE64
// mime - mime type
// size - file size
// digType - digestType
// digest - file digest (SHA1)
// digLen - digest length
//============================================================
EXP_OPTION int DataFile_new(DataFile **newDataFile, 
			    SignedDoc* pSigDoc, const char* id,
			    const char* filename, const char* contentType, 
			    const char* mime, long size,
			    const byte* digest, int digLen,
			    const char* digType, const char* szCharset)
{
  char buf1[300];
  int nId = 0, i, j, n;
  DataFile **pDataFiles;
  DataFile *pDataFile;
  FILE* hFile;

  RETURN_IF_NULL_PARAM(newDataFile);
  RETURN_IF_NULL_PARAM(pSigDoc);
  ddocDebug(3, "DataFile_new", "SigDoc ver: %s, file: %s, contentType: %s, mimeType: %s", 
	    (pSigDoc ? pSigDoc->szFormatVer : "NULL"), (filename ? filename : "NULL"), contentType, mime);
  //clearErrors();
  if(!id)
    nId = getNextDataFileId(pSigDoc);
  if(pSigDoc->nDataFiles == 0) {
    SET_LAST_ERROR_RETURN_IF_NOT(!pSigDoc->pDataFiles, ERR_BAD_DATAFILE_COUNT, 0);
    pSigDoc->nDataFiles = 1;
  }
  else
    pSigDoc->nDataFiles++;	
  pDataFiles = (DataFile**)malloc((pSigDoc->nDataFiles) * sizeof(void *));
  
  RETURN_IF_BAD_ALLOC(pDataFiles);
  for(i = 0; i < pSigDoc->nDataFiles-1; i++)
    pDataFiles[i] = pSigDoc->pDataFiles[i];
  pDataFile = (DataFile*)malloc(sizeof(DataFile));
  RETURN_IF_BAD_ALLOC(pDataFile);
  memset(pDataFile, 0, sizeof(DataFile));
  pDataFiles[pSigDoc->nDataFiles-1] = pDataFile;
  if(pSigDoc->pDataFiles)
    free(pSigDoc->pDataFiles);
  pSigDoc->pDataFiles = pDataFiles;
  if(id) {
      j = 0; n = strlen(id);
      if(n < 2 || id[0] != 'D') j = -1;
      if(j == 0 && n >= 2 && !isdigit(id[1]) && id[1] != 'O') j = -1;
      for(i = 2; j == 0 && i < n; i++)
          if(!isdigit(id[i])) j = -1;
      if(j == -1) {
          ddocDebug(1, "DataFile_new", "Invalid DataFile id: %s", id);
          SET_LAST_ERROR(ERR_BAD_PARAM);
      }
    setString(&(pDataFile->szId), id, -1);
  } else {
    snprintf(buf1, sizeof(buf1), "D%d", nId);
    setString(&(pDataFile->szId), buf1, -1);
  }
  if(szCharset)
    setString(&(pDataFile->szCharset), szCharset, -1);
  else
    setString(&(pDataFile->szCharset), CHARSET_ISO_8859_1, -1);
  if(filename) {
    // in versions 1.0, 1.1 and 1.2 we used wrong encoding for OEM windows charset
    setString(&(pDataFile->szFileName), filename, -1);
    if(!strcmp(contentType, CONTENT_EMBEDDED)) {
      if((hFile = fopen(pDataFile->szFileName, "rt")) != NULL) {
	fgets(buf1, sizeof(buf1), hFile);
	if(strstr(buf1, "<?xml")) 
	  SET_LAST_ERROR(ERR_BAD_DATAFILE_XML);
	fclose(hFile);
      }
    }
  }
  if(mime)
    setString(&(pDataFile->szMimeType), mime, -1);
  if((!contentType || strcmp(contentType, CONTENT_EMBEDDED_BASE64)) 
     && !ConfigItem_lookup_bool("EMBEDDED_XML_SUPPORT", 0)) {
    SET_LAST_ERROR(ERR_BAD_DATAFILE_CONTENT_TYPE);
    return ERR_BAD_DATAFILE_CONTENT_TYPE;
  }
  if(contentType)
    setString(&(pDataFile->szContentType), contentType, -1);
  pDataFile->nSize = size;
  if(digType && strlen(digType))
    setString(&(pDataFile->szDigestType), digType, -1);
  if(digest && digLen)
    ddocMemAssignData(&(pDataFile->mbufDigest), (const char*)digest, digLen);
  *newDataFile = pDataFile;
  return ERR_OK;
}


//============================================================
// Removes this DataFile from signed doc and frees it's memory
// pSigDoc - signed doc object
// id - DataFile id to be removed
//============================================================
EXP_OPTION int DataFile_delete(SignedDoc* pSigDoc, const char* id)
{
  int err = ERR_OK, n, i, j;
  DataFile* pDataFile = NULL;
  DataFile** pDataFiles = NULL;

  RETURN_IF_NULL_PARAM(pSigDoc);
  ddocDebug(3, "DataFile_delete", "id: %s", id);
  if(pSigDoc->nSignatures > 0)
    SET_LAST_ERROR_RETURN_CODE(ERR_MODIFY_SIGNED_DOC);	
  if((pDataFile = getDataFileWithId(pSigDoc, id)) != 0) {
    n = pSigDoc->nDataFiles - 1;
    if(n > 0) {
      pDataFiles = (DataFile**)malloc(n * sizeof(void*));
      RETURN_IF_BAD_ALLOC(pDataFiles);
      for(i = j = 0; i < pSigDoc->nDataFiles; i++) {
	if(strcmp(pSigDoc->pDataFiles[i]->szId, id)) 
	  pDataFiles[j++] = pSigDoc->pDataFiles[i];
	else{
	DataFile_free(pSigDoc->pDataFiles[i]);}
      }
      free(pSigDoc->pDataFiles);
      pSigDoc->pDataFiles = pDataFiles;
      pSigDoc->nDataFiles = n;
    } else {
      for(i = 0; i < pSigDoc->nDataFiles; i++){
	DataFile_free(pSigDoc->pDataFiles[i]);}
      free(pSigDoc->pDataFiles);
      pSigDoc->pDataFiles = NULL;
      pSigDoc->nDataFiles = 0;
    }
  }
  else
    err = ERR_BAD_DATAFILE_INDEX;
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}

//============================================================
// Retrieve and convert cached DataFile data if possible
// pSigDoc - signed document object
// szDocId - datafile id
// ppBuf - address of buffer pointer
// pLen - address of lenght of bytes
//============================================================
EXP_OPTION int ddocGetDataFileCachedData(SignedDoc* pSigDoc, const char* szDocId, void** ppBuf, long* pLen)
{
  DataFile* pDf;
  DigiDocMemBuf mbuf1;
  int err1 = 0;
    
  mbuf1.pMem = 0; mbuf1.nLen = 0;
    
  //RETURN_IF_NULL_PARAM(pSigDoc); // if null then don't check for cached data (old logic)
  RETURN_IF_NULL_PARAM(szDocId);
  RETURN_IF_NULL_PARAM(ppBuf);
  RETURN_IF_NULL_PARAM(pLen);
  *ppBuf = 0;
  *pLen = 0;
  if(pSigDoc) {
    pDf = getDataFileWithId(pSigDoc, szDocId);
    if(pDf && pDf->mbufContent.pMem) { // gotcha!
      int len;
      // base64 content, allocate exact length and initialize
      if(!strcmp(pDf->szContentType, CONTENT_EMBEDDED_BASE64)) {
          err1 = ddocMemSetLength(&mbuf1, pDf->mbufContent.nLen);
          if(err1) {
              ddocMemBuf_free(&mbuf1);
              return err1;
          }
	      *ppBuf = mbuf1.pMem;
          *pLen = mbuf1.nLen;
          err1 = ddocDecodeBase64(&(pDf->mbufContent), &mbuf1);
          if(err1) {
              ddocMemBuf_free(&mbuf1);
              return err1;
          }
          mbuf1.pMem = 0; mbuf1.nLen = 0; // release ownership 
      } 
      // simple text content. Make it zero terminated string
      else if(!strcmp(pDf->szContentType, CONTENT_EMBEDDED)) {
          *ppBuf = malloc(pDf->mbufContent.nLen+1);
          RETURN_IF_BAD_ALLOC(*ppBuf);
          *pLen = pDf->mbufContent.nLen;
          memcpy(*ppBuf, pDf->mbufContent.pMem, pDf->mbufContent.nLen);
          ((char*)(*ppBuf))[*pLen] = 0;
      }
    }
  }
  return ERR_OK;
}

//============================================================
// Retrieve and convert DataFile Filename atribute and convert
// to proper UTF-8 if necessary.
// pSigDoc - signed document object
// szDocId - datafile id
// ppBuf - address of buffer pointer. Caller must free the buffer
// pLen - address of lenght of bytes. Will be changed.
//============================================================
EXP_OPTION int ddocGetDataFileFilename(SignedDoc* pSigDoc, const char* szDocId, void** ppBuf, int* pLen)
{
  DataFile* pDf;

  RETURN_IF_NULL_PARAM(pSigDoc);
  RETURN_IF_NULL_PARAM(szDocId);
  RETURN_IF_NULL_PARAM(ppBuf);
  RETURN_IF_NULL_PARAM(pLen);
  *ppBuf = 0;
  *pLen = 0;
  if(pSigDoc) {
    pDf = getDataFileWithId(pSigDoc, szDocId);
    if(pDf && pDf->szFileName) { // gotcha!
      *ppBuf = unescapeXmlsym((const char*)pDf->szFileName);
      *pLen = strlen((const char*)*ppBuf);
      // in version 1.2 and earlier we had bad UTF-8 for some chars
      // check and fix it for newer clients
      if((!strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && !strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) ||
	     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_1_VER) ||
	     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_2_VER)) {
        convWinToFName(pDf->szFileName, (char*)*ppBuf, *pLen+1);
      }
    }
  }
  return ERR_OK;
}

//--------------------------------------------------
// Checks if the size of this DataFile is less than
// max size for memory cache and if so caches the data.
// pDf - DataFile object
// maxLen - max cacheable DataFile size
// value - character values read from file
// len - length of chars ???
// isBase64 - is allready in base64 form or not (1/0)
//--------------------------------------------------
EXP_OPTION void ddocAppendDataFileData(DataFile* pDf, int maxLen, void* data, int len, int isBase64)
{
  DigiDocMemBuf mbuf1, mbuf2;
	
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  ddocDebug(5, "ddocAppendDataFileData", "append: %d, max: %d", len, maxLen);
  if(pDf && pDf->nSize < maxLen) {
    ddocDebug(6, "ddocAppendDataFileData", "DF: %s, size: %d, max: %d", pDf->szId, pDf->nSize, maxLen);
    // original content must be kept in the form it will exist in file
	if(!strcmp(pDf->szContentType, CONTENT_EMBEDDED_BASE64) && !isBase64) {
      mbuf2.pMem = data;
      mbuf2.nLen = len;
	  ddocEncodeBase64(&mbuf2, &mbuf1);
	  ddocMemAppendData(&(pDf->mbufContent), mbuf1.pMem, mbuf1.nLen);
	  ddocMemBuf_free(&mbuf1); 
	}
    else
        ddocMemAppendData(&(pDf->mbufContent), data, len);
  }
}

//--------------------------------------------------
// Creates new DataFile and assigns contet from memory
// ppDataFile address of pointer to return new DataFile object
// pSigDoc - SignedDoc object
// id - new DataFile id. Use NULL for default
// filename - filename
// contentType - content type
// mime - mime type
// pData - address of DataFile content to be assigned
// size - length of data in bytes
// return error code
//--------------------------------------------------
EXP_OPTION int createDataFileInMemory(DataFile **ppDataFile, SignedDoc* pSigDoc, const char* id,
					   const char* filename, const char* contentType, 
					   const char* mime, const char* pData, long size)
{
  int err = ERR_OK;
  DigiDocMemBuf mbuf1;

  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  err = DataFile_new(ppDataFile, pSigDoc, id,
					   filename, contentType, 
					   mime, size, NULL, 0, DIGEST_SHA1_NAME, NULL);
  if(!err && pData) {
      ddocAppendDataFileData(*ppDataFile, size+1, (void*)pData, size, 0);
	  // calculate hash so it can be used in signing
	  err = generateDataFileXML(pSigDoc, *ppDataFile, NULL, NULL, &mbuf1);
	  ddocMemBuf_free(&mbuf1);
  }
  return err;
}

//============================================================
// cleanup DataFile memory
// pDataFile - data file object to be cleaned up
//============================================================
EXP_OPTION void DataFile_free(DataFile* pDataFile)
{
  int i=0;

  RETURN_VOID_IF_NULL(pDataFile);
  if(pDataFile->szId)
    free(pDataFile->szId);
  if(pDataFile->szFileName)
    free(pDataFile->szFileName);
  if(pDataFile->szMimeType)
    free(pDataFile->szMimeType);
  if(pDataFile->szDigestType)
    free(pDataFile->szDigestType);
  ddocMemBuf_free(&(pDataFile->mbufDigest));
  ddocMemBuf_free(&(pDataFile->mbufWrongDigest));
  ddocMemBuf_free(&(pDataFile->mbufDetachedDigest));
  if(pDataFile->szContentType)
    free(pDataFile->szContentType);
  for(i = 0; i < pDataFile->nAttributes; i++) {
    free(pDataFile->pAttNames[i]);
    free(pDataFile->pAttValues[i]);
  }
  if(pDataFile->szCharset)
    free(pDataFile->szCharset);
  if(pDataFile->pAttNames)
    free(pDataFile->pAttNames);
  if(pDataFile->pAttValues)
    free(pDataFile->pAttValues);
  ddocMemBuf_free(&(pDataFile->mbufContent));
  free(pDataFile);
}

//--------------------------------------------------
// Accessor for Digest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocDataFile_GetDigestValue(DataFile* pDataFile)
{
  RETURN_OBJ_IF_NULL(pDataFile, NULL)
  return &(pDataFile->mbufDigest);
}

//--------------------------------------------------
// Mutatoror for Digest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDataFile_SetDigestValue(DataFile* pDataFile, 
					   const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDataFile)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignData(&(pDataFile->mbufDigest), value, len);
  return err;
}


//--------------------------------------------------
// Accessor for DetachedDigest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocDataFile_GetDetachedDigestValue(DataFile* pDataFile)
{
  RETURN_OBJ_IF_NULL(pDataFile, NULL)
  return &(pDataFile->mbufDetachedDigest);
}

//--------------------------------------------------
// Mutatoror for DetachedDigest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDataFile_SetDetachedDigestValue(DataFile* pDataFile, 
					   const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDataFile)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignData(&(pDataFile->mbufDetachedDigest), value, len);
  return err;
}

//--------------------------------------------------
// Accessor for WrongDigest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocDataFile_GetWrongDigestValue(DataFile* pDataFile)
{
  RETURN_OBJ_IF_NULL(pDataFile, NULL)
  return &(pDataFile->mbufWrongDigest);
}

//--------------------------------------------------
// Mutatoror for WrongDigest atribute of DataFile object.
// pDataFile - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDataFile_SetWrongDigestValue(DataFile* pDataFile, 
					   const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDataFile)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignData(&(pDataFile->mbufWrongDigest), value, len);
  return err;
}

//============================================================
// Removes this NotaryInfo from signed doc and frees it's memory
// pSigInfo - signature object
// id - notary id to be removed
//============================================================
EXP_OPTION int NotaryInfo_delete(SignatureInfo* pSigInfo)
{
  RETURN_IF_NULL_PARAM(pSigInfo);
  if(pSigInfo->pNotary) {
    NotaryInfo_free(pSigInfo->pNotary);
    pSigInfo->pNotary = 0;
  }
  return ERR_OK;
}

//============================================================
// Returns number of DataFile attributes
// pDataFile - data file
//============================================================
EXP_OPTION int getCountOfDataFileAttributes(const DataFile* pDataFile)
{
  RETURN_OBJ_IF_NULL(pDataFile, -1);
  return pDataFile->nAttributes;
}

//============================================================
// Adds an attribute to data file
// pDataFile - data file
// name - attribute name
// value - attribute value
//============================================================
// FIXME : Badly in need for a rewrite - memory leaks, when something fails.
int addDataFileAttribute(DataFile* pDataFile, const char* name, const char* value)
{
  char	**pp;
  int i;

  RETURN_IF_NULL_PARAM(pDataFile);
  RETURN_IF_NULL_PARAM(name);
  RETURN_IF_NULL_PARAM(value);
  if(pDataFile->nAttributes == 0) {
    RETURN_IF_NOT(!pDataFile->pAttNames, ERR_BAD_ATTR_COUNT);
    RETURN_IF_NOT(!pDataFile->pAttValues, ERR_BAD_ATTR_COUNT);
    pDataFile->nAttributes = 1;
  }
  else
    pDataFile->nAttributes++;
  // set name
  pp = (char**)malloc((pDataFile->nAttributes) * sizeof(char *));
  RETURN_IF_BAD_ALLOC(pp);
  for(i = 0; i < pDataFile->nAttributes-1; i++)
    pp[i] = pDataFile->pAttNames[i];
  if(pDataFile->pAttNames)
    free(pDataFile->pAttNames);
  pDataFile->pAttNames = pp;
  pp[pDataFile->nAttributes-1] = NULL;
  setString(&(pp[pDataFile->nAttributes-1]), name, -1);
  // set value
  pp = (char**)malloc((pDataFile->nAttributes) * sizeof(char *));
  RETURN_IF_BAD_ALLOC(pp);
  for(i = 0; i < pDataFile->nAttributes-1; i++)
    pp[i] = pDataFile->pAttValues[i];
  if(pDataFile->pAttValues)
    free(pDataFile->pAttValues);
  pDataFile->pAttValues = pp;
  pp[pDataFile->nAttributes-1] = NULL;
  setString(&(pp[pDataFile->nAttributes-1]), value, -1);
  return ERR_OK;
}


//============================================================
// Gets an attribute of a data file
// pDataFile - data file
// name - buffer for attribute name pointer
// value - buffer for attribute value pointer
//============================================================
EXP_OPTION int getDataFileAttribute(DataFile* pDataFile, int idx, char** name, char** value)
{

  RETURN_IF_NULL_PARAM(pDataFile);
  RETURN_IF_NOT(idx < pDataFile->nAttributes, ERR_BAD_ATTR_INDEX);
  RETURN_IF_NULL_PARAM(name);
  RETURN_IF_NULL_PARAM(value);
  *name = pDataFile->pAttNames[idx];
  *value = pDataFile->pAttValues[idx];
  return ERR_OK;
}

//============================================================
// Calculates the file size and digest
// pSigDoc - signed document
// id - data file id
// filename - filename
// digType - digestType (code)
//============================================================
EXP_OPTION int calculateDataFileSizeAndDigest(SignedDoc* pSigDoc, const char* id,
							const char* filename, int digType)
{
  int err = ERR_OK, len1 = 0;
  char buf1[DIGEST_LEN+2];
  long len2 = 0;
  DataFile* pDataFile;

  RETURN_IF_NULL_PARAM(pSigDoc);
  ddocDebug(3, "calculateDataFileSizeAndDigest", "File: %s id: %s", filename, id);
  pDataFile = getDataFileWithId(pSigDoc, id);
  RETURN_IF_NOT(pDataFile, ERR_FILE_READ);
  if(digType == DIGEST_SHA1) {
    // in version 1.0 we use DigestType and DigestValue
    // attrributes of DataFile element and calculate the digest
    // over the original content
    if(!strcmp(pSigDoc->szFormat, SK_XML_1_NAME) && !strcmp(pSigDoc->szFormatVer, SK_XML_1_VER)) {
      len1 = sizeof(buf1);
      err = calculateFileDigest(filename, digType,
				(byte*)buf1, &len1, &len2);
      RETURN_IF_NOT(err == ERR_OK, err);
      ddocDataFile_SetDigestValue(pDataFile, buf1, len1);
      pDataFile->nSize = len2;
    }
    // in version 1.1 we don't use those attributes
    // and we calculate the digest over the whole
    // DataFile element including the tags
    else {
      err = calculateFileSize(filename, &pDataFile->nSize);
      ddocDebug(4, "calculateDataFileSizeAndDigest", "File: %s size: %d", filename, pDataFile->nSize);
      err = generateDataFileXML(pSigDoc, pDataFile, filename, NULL, NULL); 
    }
  } 
  else
    SET_LAST_ERROR_RETURN_CODE(ERR_UNSUPPORTED_DIGEST);
  return err;
}


//=======================< DigestValue >=====================================

//--------------------------------------------------
// "Constructor" of DigestValue object
// ppDigestValue - address of buffer for newly allocated object [REQUIRED]
// szDigestMethod - digest method [OPTIONAL]
// szDigVal/lDigLen - digest value and length [OPTIONAL]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDigestValue_new(DigestValue** ppDigestValue, 
				   const char* szDigestMethod, 
				   void* szDigVal, long lDigLen)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(4, "ddocDigestValue_new", "DigestMethod: %s, dig-len: %ld", 
	    (szDigestMethod ? szDigestMethod : "NULL"), lDigLen);
  RETURN_IF_NULL_PARAM(ppDigestValue);
  *ppDigestValue = 0; // mark as not yet allocated
  // allocate memory for new DigestValue
  *ppDigestValue = (DigestValue*)malloc(sizeof(DigestValue));
  if(!(*ppDigestValue))
    SET_LAST_ERROR_RETURN(ERR_BAD_ALLOC, ERR_BAD_ALLOC)
  memset(*ppDigestValue, 0, sizeof(DigestValue));
  // set optional fields
  if(szDigestMethod) {
    err = ddocMemAssignString((char**)&((*ppDigestValue)->szDigestMethod), szDigestMethod);
    if(err) return err;
  } else { // default is sha1
    err = ddocMemAssignString((char**)&((*ppDigestValue)->szDigestMethod), DIGEST_METHOD_SHA1);
  }
  if(szDigVal && lDigLen) 
    err = ddocMemAssignData(&((*ppDigestValue)->mbufDigestValue), szDigVal, lDigLen);
  return err;
}

//--------------------------------------------------
// "Destructor" of DigestValue object
// pDigestValue - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDigestValue_free(DigestValue* pDigestValue)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDigestValue)
  // cleanup this object
  if(pDigestValue->szDigestMethod)
    free(pDigestValue->szDigestMethod);
  ddocMemBuf_free(&(pDigestValue->mbufDigestValue));
  free(pDigestValue);
  return err;
}

//--------------------------------------------------
// Accessor for DigestMethod atribute of DigestValue object.
// pDigestValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocDigestValue_GetDigestMethod(DigestValue* pDigestValue)
{
  RETURN_OBJ_IF_NULL(pDigestValue, NULL)
  return pDigestValue->szDigestMethod;
}

//--------------------------------------------------
// Mutatoror for DigestMethod atribute of DigestValue object.
// pDigestValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDigestValue_SetDigestMethod(DigestValue* pDigestValue, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDigestValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pDigestValue->szDigestMethod), value);
  return err;
}

//--------------------------------------------------
// Accessor for DigestValue atribute of DigestValue object.
// pDigestValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocDigestValue_GetDigestValue(DigestValue* pDigestValue)
{
  RETURN_OBJ_IF_NULL(pDigestValue, NULL)
  return &(pDigestValue->mbufDigestValue);
}

//--------------------------------------------------
// Mutatoror for DigestValue atribute of DigestValue object.
// pDigestValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocDigestValue_SetDigestValue(DigestValue* pDigestValue, 
					      const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pDigestValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignData(&(pDigestValue->mbufDigestValue), value, len);
  return err;
}

//--------------------------------------------------
// Compares two DigestValue structure on equality
// pDigest1 - address of first digest [REQUIRED]
// pDigest2 - address of second digest [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCompareDigestValues(DigestValue* pDigest1, DigestValue* pDigest2)
{
  RETURN_IF_NULL_PARAM(pDigest1)
  RETURN_IF_NULL_PARAM(pDigest2)
  return compareByteArrays((const byte*)pDigest1->mbufDigestValue.pMem, 
			    pDigest1->mbufDigestValue.nLen,
			    (const byte*)pDigest2->mbufDigestValue.pMem, 
			    pDigest2->mbufDigestValue.nLen);
}

//--------------------------------------------------
// Generates XML for <DigestValue> element
// pSigDoc - signed doc object [REQUIRED]
// pDigestValue - DigestValue object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocDigestValue_toXML(const DigestValue* pDigestValue, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pBuf)
  RETURN_IF_NULL_PARAM(pDigestValue)
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  // DigestMethod
  if(pDigestValue->szDigestMethod) {
    err = ddocGen_startElemBegin(pBuf, "DigestMethod");
    if(err) return err;
    // Algorithm atribute
    err = ddocGen_addAtribute(pBuf, "Algorithm", pDigestValue->szDigestMethod);
    if(err) return err;
    //err = ddocGen_startElemEnd(pBuf);
    //err = ddocGen_endElem(pBuf, "DigestMethod");
    // end of element start tag
    err = ddocMemAppendData(pBuf, "/>\n", -1);
  }
  if(pDigestValue->mbufDigestValue.pMem) {
    err = ddocGen_startElem(pBuf, "DigestValue");
  }

    if(err) return err;
    // digest value
    ddocEncodeBase64(&(pDigestValue->mbufDigestValue), &mbuf1);
    //AM 17.11.08 to remove newline after base64
    if(mbuf1.pMem && ((char*)mbuf1.pMem)[strlen((const char*)mbuf1.pMem)-1] == '\n')
	((char*)mbuf1.pMem)[strlen((const char*)mbuf1.pMem)-1] = 0;
    err = ddocMemAppendData(pBuf, (char*)mbuf1.pMem, -1);
    ddocMemBuf_free(&mbuf1);
    if(err) return err;
    err = ddocGen_endElem(pBuf, "DigestValue");
    err = ddocMemAppendData(pBuf, "\n", -1);
  return err;
}

//======================< SignatureValue >====================================

//--------------------------------------------------
// "Constructor" of SignatureValue object
// ppSignatureValue - address of buffer for newly allocated object [REQUIRED]
// szId - Id atribute value [OPTIONAL]
// szType - signature type [OPTIONAL]
// szDigVal/lDigLen - digest value and length [OPTIONAL]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSignatureValue_new(SignatureValue** ppSignatureValue, 
				      const char* szId, const char* szType,
				      void* szSigVal, long lSigLen)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(4, "ddocSignatureValue_new", "id: %s, type: %s, dig-len: %ld", 
	    (szId ? szId : "NULL"), (szType ? szType : "NULL"), lSigLen);
  RETURN_IF_NULL_PARAM(ppSignatureValue);
  *ppSignatureValue = 0; // mark as not yet allocated
  // allocate memory for new DigestValue
  *ppSignatureValue = (SignatureValue*)malloc(sizeof(SignatureValue));
  if(!(*ppSignatureValue))
    SET_LAST_ERROR_RETURN(ERR_BAD_ALLOC, ERR_BAD_ALLOC)
  memset(*ppSignatureValue, 0, sizeof(SignatureValue));
  // set optional fields
  if(szId) {
    err = ddocMemAssignString((char**)&((*ppSignatureValue)->szId), szId);
    if(err) return err;
  }
  if(szType) {
    err = ddocMemAssignString((char**)&((*ppSignatureValue)->szType), szType);
    if(err) return err;
  }
  if(szSigVal && lSigLen) 
    err = ddocMemAssignData(&((*ppSignatureValue)->mbufSignatureValue), szSigVal, lSigLen);
  return err;
}

//--------------------------------------------------
// "Destructor" of SignatureValue object
// pSignatureValue - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSignatureValue_free(SignatureValue* pSignatureValue)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pSignatureValue)
  // cleanup this object
  if(pSignatureValue->szId)
    free(pSignatureValue->szId);
  if(pSignatureValue->szType)
    free(pSignatureValue->szType);
  ddocMemBuf_free(&(pSignatureValue->mbufSignatureValue));
  free(pSignatureValue);
  return err;
}

//--------------------------------------------------
// Accessor for Id atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocSignatureValue_GetId(const SignatureValue* pSignatureValue)
{
  RETURN_OBJ_IF_NULL(pSignatureValue, NULL)
  return pSignatureValue->szId;
}

//--------------------------------------------------
// Mutatoror for Id atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSignatureValue_SetId(SignatureValue* pSignatureValue, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pSignatureValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pSignatureValue->szId), value);
  return err;
}

//--------------------------------------------------
// Accessor for Type atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocSignatureValue_GetType(const SignatureValue* pSignatureValue)
{
  RETURN_OBJ_IF_NULL(pSignatureValue, NULL)
  return pSignatureValue->szType;
}

//--------------------------------------------------
// Mutatoror for Type atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSignatureValue_SetType(SignatureValue* pSignatureValue, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pSignatureValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pSignatureValue->szType), value);
  return err;
}

//--------------------------------------------------
// Accessor for SignatureValue atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocSignatureValue_GetSignatureValue(const SignatureValue* pSignatureValue)
{
  RETURN_OBJ_IF_NULL(pSignatureValue, NULL)
    return &(((SignatureValue*)pSignatureValue)->mbufSignatureValue);
}

//--------------------------------------------------
// Mutatoror for SignatureValue atribute of SignatureValue object.
// pSignatureValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSignatureValue_SetSignatureValue(SignatureValue* pSignatureValue, 
						    const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pSignatureValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignData(&(pSignatureValue->mbufSignatureValue), value, len);
  return err;
}

//--------------------------------------------------
// Generates XML for <SignatureValue> element
// pSignatureValue - SignatureValue object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocSignatureValue_toXML(const SignatureValue* pSignatureValue, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK;
  char* p;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pBuf)
  //RETURN_IF_NULL_PARAM(pSignatureValue)
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  // start of element
  err = ddocGen_startElemBegin(pBuf, "SignatureValue");
  if(err) return err;
  // Id atribute
  if(pSignatureValue) {
    p = (char*)ddocSignatureValue_GetId(pSignatureValue);
    if(p)
      err = ddocGen_addAtribute(pBuf, "Id", p);
    if(err) return err;
  }
  // end of element start tag
  err = ddocGen_startElemEnd(pBuf);
  //err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // signature value
  if(pSignatureValue) {
    ddocEncodeBase64(ddocSignatureValue_GetSignatureValue(pSignatureValue), &mbuf1);
		//AM 17.11.08 to remove newline after base64
		if(mbuf1.pMem && ((char*)mbuf1.pMem)[strlen((const char*)mbuf1.pMem)-1] == '\n')
			((char*)mbuf1.pMem)[strlen((const char*)mbuf1.pMem)-1] = 0;
    err = ddocMemAppendData(pBuf, (char*)mbuf1.pMem, -1);
    ddocMemBuf_free(&mbuf1);
  }
  err = ddocGen_endElem(pBuf, "SignatureValue");
  err = ddocMemAppendData(pBuf, "\n", -1);
  return err;
}

//======================< CertID >====================================

//--------------------------------------------------
// "Constructor" of CertID object
// ppCertID - address of buffer for newly allocated object [REQUIRED]
// szId - Id atribute value [OPTIONAL]
// nType - certid internal type (signers or responders cert) [REQUIRED]
// szIssuerSerial - issuer serial number [OPTIONAL]
// szIssuerName - issuer DN [OPTIONAL]
// szDigVal/lDigLen - digest value and length [OPTIONAL]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_new(CertID** ppCertID, 
			      int nType, const char* szId,
			      const char* szIssuerSerial, const char* szIssuerName,
			      void* szDigVal, long lDigLen)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(4, "ddocCertID_new", "id: %s, type: %d, issuer-serial: %s issuer-name: %s, dig-len: %ld", 
	    (szId ? szId : "NULL"), nType,
	    (szIssuerSerial ? szIssuerSerial : "NULL"), 
	    (szIssuerName ? szIssuerName : "NULL"), lDigLen);
  RETURN_IF_NULL_PARAM(ppCertID);
  *ppCertID = 0; // mark as not yet allocated
  // allocate memory for new CertID
  *ppCertID = (CertID*)malloc(sizeof(CertID));
  if(!(*ppCertID))
    SET_LAST_ERROR_RETURN(ERR_BAD_ALLOC, ERR_BAD_ALLOC)
  memset(*ppCertID, 0, sizeof(CertID));
  (*ppCertID)->nType = nType;
  // set optional fields
  if(szId) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szId), szId);
    if(err) return err;
  }
  if(szIssuerSerial) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szIssuerSerial), szIssuerSerial);
    if(err) return err;
  }
  if(szIssuerName) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szIssuerName), szIssuerName);
    if(err) return err;
  }
  if(szDigVal && lDigLen) {
    if(!(*ppCertID)->pDigestValue)
      ddocDigestValue_new(&((*ppCertID)->pDigestValue), 0, szDigVal, lDigLen);
    else
      err = ddocDigestValue_SetDigestValue((*ppCertID)->pDigestValue, szDigVal, lDigLen);
  }
  return err;
}
EXP_OPTION int bdocCertID_new(CertID** ppCertID, 
			      int nType, const char* szId,
			      const char* szIssuerSerial, const char* szIssuerName,
			      void* szDigVal, long lDigLen)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(4, "ddocCertID_new", "id: %s, type: %d, issuer-serial: %s issuer-name: %s, dig-len: %ld", 
	    (szId ? szId : "NULL"), nType,
	    (szIssuerSerial ? szIssuerSerial : "NULL"), 
	    (szIssuerName ? szIssuerName : "NULL"), lDigLen);
  RETURN_IF_NULL_PARAM(ppCertID);
  *ppCertID = 0; // mark as not yet allocated
  // allocate memory for new CertID
  *ppCertID = (CertID*)malloc(sizeof(CertID));
  if(!(*ppCertID))
    SET_LAST_ERROR_RETURN(ERR_BAD_ALLOC, ERR_BAD_ALLOC)
  memset(*ppCertID, 0, sizeof(CertID));
  (*ppCertID)->nType = nType;
  // set optional fields
  if(szId) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szId), szId);
    if(err) return err;
  }
  if(szIssuerSerial) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szIssuerSerial), szIssuerSerial);
    if(err) return err;
  }
  if(szIssuerName) {
    err = ddocMemAssignString((char**)&((*ppCertID)->szIssuerName), szIssuerName);
    if(err) return err;
  }
  if(szDigVal && lDigLen) {
    if(!(*ppCertID)->pDigestValue){
      ddocDigestValue_new(&((*ppCertID)->pDigestValue), 0, szDigVal, lDigLen);
    }else
      err = ddocDigestValue_SetDigestValue((*ppCertID)->pDigestValue, szDigVal, lDigLen);
  }
  return err;
}

//--------------------------------------------------
// "Destructor" of CertID object
// pCertID - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_free(CertID* pCertID)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertID)
  // cleanup this object
  if(pCertID->szId)
    free(pCertID->szId);
  if(pCertID->szIssuerSerial)
    free(pCertID->szIssuerSerial);
  if(pCertID->szIssuerName)
    free(pCertID->szIssuerName);
  if(pCertID->pDigestValue)
    ddocDigestValue_free(pCertID->pDigestValue);
	if(pCertID->szDigestType)
		free(pCertID->szDigestType);
  free(pCertID);
  return err;
}

//--------------------------------------------------
// Accessor for IssuerSerial atribute of CertID object.
// pCertID - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocCertID_GetIssuerSerial(const CertID* pCertID)
{
  RETURN_OBJ_IF_NULL(pCertID, NULL)
  return pCertID->szIssuerSerial;
}

//--------------------------------------------------
// Mutatoror for IssuerSerial atribute of CertID object.
// pCertID - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_SetIssuerSerial(CertID* pCertID, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertID)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pCertID->szIssuerSerial), value);
  return err;
}

//--------------------------------------------------
// Accessor for Id atribute of CertID object.
// pCertID - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocCertID_GetId(const CertID* pCertID)
{
  RETURN_OBJ_IF_NULL(pCertID, NULL)
  return pCertID->szId;
}

//--------------------------------------------------
// Mutatoror for Id atribute of CertID object.
// pCertID - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_SetId(CertID* pCertID, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertID)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pCertID->szId), value);
  return err;
}

//--------------------------------------------------
// Accessor for IssuerName atribute of CertID object.
// pCertID - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocCertID_GetIssuerName(const CertID* pCertID)
{
  RETURN_OBJ_IF_NULL(pCertID, NULL)
  return pCertID->szIssuerName;
}

//--------------------------------------------------
// Mutatoror for IssuerName atribute of CertID object.
// pCertID - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_SetIssuerName(CertID* pCertID, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertID)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pCertID->szIssuerName), value);
  return err;
}

//--------------------------------------------------
// Accessor for DigestValue atribute of CertID object.
// pCertID - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION DigiDocMemBuf* ddocCertID_GetDigestValue(const CertID* pCertID)
{
  RETURN_OBJ_IF_NULL(pCertID, NULL)
  return ddocDigestValue_GetDigestValue(pCertID->pDigestValue);
}

//--------------------------------------------------
// Mutatoror for DigestValue atribute of CertID object.
// pCertID - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// len - length of value in bytes [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertID_SetDigestValue(CertID* pCertID, 
					 const char* value, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertID)
  RETURN_IF_NULL_PARAM(value)
  if(!pCertID->pDigestValue)
    err = ddocDigestValue_new(&(pCertID->pDigestValue), 0, (char*)value, len);
  else
    err = ddocDigestValue_SetDigestValue(pCertID->pDigestValue, value, len);
  return err;
}

//--------------------------------------------------
// Generates XML for <Cert> element
// pSigDoc - SignedDoc object [REQUIRED]
// pCertID - CertID object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCertID_toXML(const SignedDoc* pSigDoc, const CertID* pCertID, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK;

  RETURN_IF_NULL_PARAM(pBuf)
  RETURN_IF_NULL_PARAM(pCertID)
  RETURN_IF_NULL_PARAM(pSigDoc)
  // start of element
  err = ddocGen_startElemBegin(pBuf, "Cert");
  if(err) return err;
  // only formats 1.0, 1.1 and 1.2 we use the Id atribute
	//AM 28.10.08 can also have 1.0 version
  if((!strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && !strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) ||
     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_1_VER) ||
     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_2_VER)) {
    // Id atribute
    if(pCertID->szId)
      err = ddocGen_addAtribute(pBuf, "Id", pCertID->szId);
    if(err) return err;
  }
  // end of element start tag
  err = ddocGen_startElemEnd(pBuf);
  // <CertDigest>
  err = ddocGen_startElem(pBuf, "CertDigest");
  if(err) return err;
  ddocDigestValue_toXML(pCertID->pDigestValue, pBuf);
  err = ddocGen_endElem(pBuf, "CertDigest");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  // <IssuerSerial
  err = ddocGen_startElem(pBuf, "IssuerSerial");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  // only formats 1.0, 1.1 and 1.2 we use the IssuerSerial element alone
	//AM 29.10.08 
  if((!strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && !strcmp(pSigDoc->szFormat, SK_XML_1_NAME))||
     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_1_VER) ||
     !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_2_VER)) {
    err = ddocMemAppendData(pBuf, ddocCertID_GetIssuerSerial(pCertID), -1);
  } else { // in 1.3 and 1.4 we use all subelement of <IssuerSerial> 
    err = ddocGen_startElemBegin(pBuf, "X509IssuerName");
    if(err) return err;
    err = ddocGen_addAtribute(pBuf, "xmlns", NAMESPACE_XML_DSIG);
    // end of element start tag
    err = ddocGen_startElemEnd(pBuf);
    if(err) return err;
    err = ddocMemAppendData(pBuf, ddocCertID_GetIssuerName(pCertID), -1);
    if(err) return err;
    err = ddocGen_endElem(pBuf, "X509IssuerName");
    if(err) return err;
    err = ddocMemAppendData(pBuf, "\n", -1);
    err = ddocGen_startElemBegin(pBuf, "X509SerialNumber");
    if(err) return err;
    err = ddocGen_addAtribute(pBuf, "xmlns", NAMESPACE_XML_DSIG);
    // end of element start tag
    err = ddocGen_startElemEnd(pBuf);
    if(err) return err;
    err = ddocMemAppendData(pBuf, ddocCertID_GetIssuerSerial(pCertID), -1);
    if(err) return err;
    err = ddocGen_endElem(pBuf, "X509SerialNumber");
    if(err) return err;
    err = ddocMemAppendData(pBuf, "\n", -1);
  }
  err = ddocGen_endElem(pBuf, "IssuerSerial");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  err = ddocGen_endElem(pBuf, "Cert");
  return err;
}


//--------------------------------------------------
// Generates XML for <CompleteCertificateRefs> element
// pSigDoc - SignedDoc object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCompleteCertificateRefs_toXML(const SignedDoc* pSigDoc, 
				      const SignatureInfo* pSigInfo, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK, i, n;
  CertID* pCertID;

  RETURN_IF_NULL_PARAM(pBuf)
  RETURN_IF_NULL_PARAM(pSigDoc)
  RETURN_IF_NULL_PARAM(pSigInfo)
  RETURN_IF_NULL(pSigInfo->pCertIDs)
  // <CompleteCertificateRefs>
  err = ddocGen_startElemBegin(pBuf, "CompleteCertificateRefs");
  if(err) return err;
  // end of element start tag
  err = ddocGen_startElemEnd(pBuf);
  if(err) return err;
  // <CertRefs> (not used in 1.0, 1.1 and 1.2
  if((strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) &&
     strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_1_VER) &&
     strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_2_VER)) {
    err = ddocGen_startElem(pBuf, "CertRefs");
    if(err) return err;
  }
  n = ddocCertIDList_GetCertIDsCount(pSigInfo->pCertIDs);
  for(i = 0; i < n; i++) {
    pCertID = ddocCertIDList_GetCertID(pSigInfo->pCertIDs, i);
    if(pCertID && pCertID->nType != CERTID_TYPE_SIGNERS_CERTID)
      ddocCertID_toXML(pSigDoc, pCertID, pBuf);
  }
  // </CertRefs> (not used in 1.0, 1.1 and 1.2
	//AM 29.10.08
  if((strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) &&
     strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_1_VER) &&
     strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_2_VER)) {
    err = ddocGen_endElem(pBuf, "CertRefs");
  }
  if(err) return err;
  err = ddocGen_endElem(pBuf, "CompleteCertificateRefs");
  return err;
}

//--------------------------------------------------
// Generates XML for <CompleteRevocationRefs> element
// pSigDoc - SignedDoc object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCompleteRevocationRefs_toXML(const SignedDoc* pSigDoc, 
				     const SignatureInfo* pSigInfo, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK, l1, l2;
	//AM 28.04.04 increased buffer for sha256
  char buf1[80], buf2[80], *p1, *p2;
  const DigiDocMemBuf *pMBuf = 0;

  RETURN_IF_NULL_PARAM(pBuf)
  RETURN_IF_NULL_PARAM(pSigDoc)
  RETURN_IF_NULL_PARAM(pSigInfo)
  RETURN_IF_NULL(pSigInfo->pNotary)
  // <CompleteRevocationRefs>
  err = ddocGen_startElemBegin(pBuf, "CompleteRevocationRefs");
  if(err) return err;
  // end of element start tag
  err = ddocGen_startElemEnd(pBuf);
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <OCSPRefs>
  err = ddocGen_startElem(pBuf, "OCSPRefs");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <OCSPRef>
  err = ddocGen_startElem(pBuf, "OCSPRef");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <OCSPIdentifier>
  err = ddocGen_startElemBegin(pBuf, "OCSPIdentifier");
  if(err) return err;
  snprintf(buf1, sizeof(buf1), "#%s", pSigInfo->pNotary->szId); 
  err = ddocGen_addAtribute(pBuf, "URI", buf1);
  err = ddocGen_startElemEnd(pBuf);
  if(err) return err;
  // <ResponderID>
  err = ddocGen_startElem(pBuf, "ResponderID");
  if(err) return err;
    if(pSigInfo->pNotary->nRespIdType == RESPID_NAME_TYPE) {
      p1 = (char*)ddocNotInfo_GetResponderId_Value(pSigInfo->pNotary);
      RETURN_IF_NULL(p1);
      err = ddocMemAppendData(pBuf, p1, -1);
      if(err) return err;
    } else if(pSigInfo->pNotary->nRespIdType == RESPID_KEY_TYPE) {
      pMBuf = ddocNotInfo_GetResponderId(pSigInfo->pNotary);
      RETURN_IF_NULL(pMBuf);
      l2 = pMBuf->nLen * 2 + 10;
      p2 = (char*)malloc(l2);
      RETURN_IF_NULL(p2);
      memset(p2, 0, l2);
      encode((const byte*)pMBuf->pMem, pMBuf->nLen, (byte*)p2, &l2);
      err = ddocMemAppendData(pBuf, p2, -1);
      if(err) return err;
    } else {
      SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_WRONG_RESPID);
    }
  err = ddocGen_endElem(pBuf, "ResponderID");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <ProducedAt>
  err = ddocGen_startElem(pBuf, "ProducedAt");
  if(err) return err;
  err = ddocMemAppendData(pBuf, pSigInfo->pNotary->timeProduced, -1);
  if(err) return err;
  err = ddocGen_endElem(pBuf, "ProducedAt");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // </OCSPRef>
  err = ddocGen_endElem(pBuf, "OCSPIdentifier");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <DigestAlgAndValue>
  err = ddocGen_startElem(pBuf, "DigestAlgAndValue");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <DigestMethod>
  err = ddocGen_startElemBegin(pBuf, "DigestMethod");
  if(err) return err;
  err = ddocGen_addAtribute(pBuf, "Algorithm", DIGEST_METHOD_SHA1);
  err = ddocGen_startElemEnd(pBuf);
  if(err) return err;
  err = ddocGen_endElem(pBuf, "DigestMethod");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // <DigestValue>
  err = ddocGen_startElem(pBuf, "DigestValue");
  if(err) return err;
  l2 = sizeof(buf2);
  err = calculateNotaryInfoDigest(pSigDoc, pSigInfo->pNotary, (byte*)buf2, &l2);
  l1 = sizeof(buf1);
  encode((const byte*)buf2, l2, (byte*)buf1, &l1);
  err = ddocMemAppendData(pBuf, buf1, -1);
  err = ddocGen_endElem(pBuf, "DigestValue");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // </DigestAlgAndValue>
  err = ddocGen_endElem(pBuf, "DigestAlgAndValue");
  if(err) return err;
  // </OCSPRef>
  err = ddocGen_endElem(pBuf, "OCSPRef");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // </OCSPRefs>
  err = ddocGen_endElem(pBuf, "OCSPRefs");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  if(err) return err;
  // </CompleteRevocationRefs>
  err = ddocGen_endElem(pBuf, "CompleteRevocationRefs");
  if(err) return err;
  err = ddocMemAppendData(pBuf, "\n", -1);
  return err;
}


//==========< CertIDList >====================

//--------------------------------------------------
// "Constructor" of CertIDList object
// ppCertIDList - address of buffer for newly allocated object [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertIDList_new(CertIDList** ppCertIDList)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(3, "ddocCertIDList_new", "Create new certid list");
  RETURN_IF_NULL_PARAM(ppCertIDList);
  *ppCertIDList = (CertIDList*)malloc(sizeof(CertIDList));
  // allocate new object
  RETURN_IF_BAD_ALLOC(*ppCertIDList);
  memset(*ppCertIDList, 0, sizeof(CertIDList));
  return err;
}

//--------------------------------------------------
// "Destructor" of CertIDList object
// pCertIDList - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertIDList_free(CertIDList* pCertIDList)
{
  int i, err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertIDList)
  // free timestamp-infos
  for(i = 0; i < pCertIDList->nCertIDs; i++) {
    if(pCertIDList->pCertIDs[i]) {
      err = ddocCertID_free(pCertIDList->pCertIDs[i]);
      if(err) return err;
    }
  }
  free(pCertIDList->pCertIDs);
  free(pCertIDList);
  return err;
}

//--------------------------------------------------
// Accessor for count of CertIDs subelement of CertIDList object.
// pCertIDList - pointer to CertIDList object [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCertIDList_addCertID(CertIDList* pCertIDList, CertID* pCertID)
{
  CertID** pCertIDs = 0;

  RETURN_IF_NULL_PARAM(pCertIDList)
  RETURN_IF_NULL_PARAM(pCertID)
  pCertIDs = (CertID**)realloc(pCertIDList->pCertIDs, sizeof(CertID*) * (pCertIDList->nCertIDs + 1));
  RETURN_IF_BAD_ALLOC(pCertIDs);
  pCertIDList->pCertIDs = pCertIDs;
  pCertIDList->pCertIDs[pCertIDList->nCertIDs] = pCertID;
  pCertIDList->nCertIDs++;
  ddocDebug(3, "ddocCertIDList_addCertID", "added certid: %s type: %d", pCertID->szId, pCertID->nType);
  return ERR_OK;
}


//--------------------------------------------------
// Accessor for count of CertIDs subelement of CertIDList object.
// pCertIDList - pointer to CertIDList object [REQUIRED]
// returns count or -1 for error. Then use error API to check errors
//--------------------------------------------------
EXP_OPTION int ddocCertIDList_GetCertIDsCount(CertIDList* pCertIDList)
{
  SET_LAST_ERROR_RETURN_IF_NOT(pCertIDList, ERR_NULL_POINTER, -1)
  return pCertIDList->nCertIDs;
}

//--------------------------------------------------
// Accessor for CertIDs subelement of CertIDList object.
// pCertIDList - pointer to CertIDList object [REQUIRED]
// nIdx - index of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocCertIDList_GetCertID(CertIDList* pCertIDList, int nIdx)
{
  RETURN_OBJ_IF_NULL(pCertIDList, NULL)
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx >= 0 && nIdx < pCertIDList->nCertIDs, ERR_BAD_CERTID_IDX, NULL);
  RETURN_OBJ_IF_NULL(pCertIDList->pCertIDs[nIdx], 0);
  return pCertIDList->pCertIDs[nIdx];
}


//--------------------------------------------------
// Accessor for last CertIDs subelement of CertIDList object.
// pCertIDList - pointer to CertIDList object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocCertIDList_GetLastCertID(CertIDList* pCertIDList)
{
  RETURN_OBJ_IF_NULL(pCertIDList, NULL)
  SET_LAST_ERROR_RETURN_IF_NOT(pCertIDList->nCertIDs > 0, ERR_BAD_CERTID_IDX, NULL);
  RETURN_OBJ_IF_NULL(pCertIDList->pCertIDs[pCertIDList->nCertIDs-1], 0);
  return pCertIDList->pCertIDs[pCertIDList->nCertIDs-1];
}


//--------------------------------------------------
// Deletes CertID subelement of CertIDList object.
// pCertIDList - pointer to CertIDList object [REQUIRED]
// nIdx - index of CertID object to be removed [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertIDList_DeleteCertID(CertIDList* pCertIDList, int nIdx)
{
  int err = ERR_OK, i;

  RETURN_IF_NULL_PARAM(pCertIDList)
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx >= 0 && nIdx < pCertIDList->nCertIDs, ERR_BAD_CERTID_IDX, ERR_BAD_CERTID_IDX);
  RETURN_IF_NULL_PARAM(pCertIDList->pCertIDs[nIdx]);
  // delete the given object
  err = ddocCertID_free(pCertIDList->pCertIDs[nIdx]);
  if(err) return err;
  pCertIDList->pCertIDs[nIdx] = 0;
  // move other objects 1 step close to array start
  for(i = nIdx; i < pCertIDList->nCertIDs; i++) 
    pCertIDList->pCertIDs[i] = pCertIDList->pCertIDs[i+1];
  pCertIDList->pCertIDs[pCertIDList->nCertIDs - 1] = 0;
  pCertIDList->nCertIDs--;
  return err;
}

//--------------------------------------------------
// Finds a CertID object with required type
// pCertIDList - pointer to CertIDList object [REQUIRED]
// nType - type of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocCertIDList_GetCertIDOfType(CertIDList* pCertIDList, int nType)
{
  int i;

  RETURN_OBJ_IF_NULL(pCertIDList, NULL)
  ddocDebug(4, "ddocCertIDList_GetCertIDOfType", "find type: %d", nType);
  for(i = 0; i < pCertIDList->nCertIDs; i++) {
    ddocDebug(4, "ddocCertIDList_GetCertIDOfType", "idx: %d type: %d", i, pCertIDList->pCertIDs[i]->nType);
    if(pCertIDList->pCertIDs[i]->nType == nType)
      return pCertIDList->pCertIDs[i];
  }
  return NULL;
}

//--------------------------------------------------
// Finds a CertID object with serial nr
// pCertIDList - pointer to CertIDList object [REQUIRED]
// nType - type of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocCertIDList_GetCertIDOfSerial(CertIDList* pCertIDList, const char* szSerial)
{
  int i;

  RETURN_OBJ_IF_NULL(pCertIDList, NULL)
  RETURN_OBJ_IF_NULL(szSerial, NULL)
    ddocDebug(4, "ddocCertIDList_GetCertIDOfSerial", "find serial: %s", szSerial);
  for(i = 0; i < pCertIDList->nCertIDs; i++) {
		//AM 19.09.08
		if(pCertIDList->pCertIDs[i]->szIssuerSerial){
			if(!strcmp(pCertIDList->pCertIDs[i]->szIssuerSerial, szSerial))
				return pCertIDList->pCertIDs[i];
		}
  }
  return NULL;
}

//--------------------------------------------------
// Finds a CertID object with required type or creates a new one
// pCertIDList - pointer to CertIDList object [REQUIRED]
// nType - type of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocCertIDList_GetOrCreateCertIDOfType(CertIDList* pCertIDList, int nType)
{
  CertID* pCertID = ddocCertIDList_GetCertIDOfType(pCertIDList, nType);
  if(!pCertID) {
    ddocCertID_new(&pCertID, nType, 0, 0, 0, 0, 0);
    if(pCertID)
      ddocCertIDList_addCertID(pCertIDList, pCertID);
  }
  return pCertID;
}

//======================< CertValue >====================================

//--------------------------------------------------
// "Constructor" of CertValue object
// ppCertValue - address of buffer for newly allocated object [REQUIRED]
// szId - Id atribute value [OPTIONAL]
// nType - certid internal type (signers or responders cert) [REQUIRED]
// pCert - certificate itself [OPTIONAL]. Must fill in later. Do not X509_free() param!
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValue_new(CertValue** ppCertValue, 
				 int nType, const char* szId,
				 X509* pCert)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(4, "ddocCertValue_new", "id: %s, type: %d, cert: %s", 
	    (szId ? szId : "NULL"), nType, (pCert ? "OK" : "NULL"));
  RETURN_IF_NULL_PARAM(ppCertValue);
  //RETURN_IF_NULL_PARAM(pCert);
  *ppCertValue = 0; // mark as not yet allocated
  // allocate memory for new CertValue
  *ppCertValue = (CertValue*)malloc(sizeof(CertValue));
  if(!(*ppCertValue))
    SET_LAST_ERROR_RETURN(ERR_BAD_ALLOC, ERR_BAD_ALLOC)
  memset(*ppCertValue, 0, sizeof(CertValue));
  (*ppCertValue)->nType = nType;
  if(pCert)
    (*ppCertValue)->pCert = pCert;
  // set optional fields
  if(szId) {
    err = ddocMemAssignString((char**)&((*ppCertValue)->szId), szId);
    if(err) return err;
  }
  return err;
}

//--------------------------------------------------
// "Destructor" of CertValue object
// pCertValue - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValue_free(CertValue* pCertValue)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertValue)
  // cleanup this object
  if(pCertValue->szId)
    free(pCertValue->szId);
  if(pCertValue->pCert)
    X509_free(pCertValue->pCert);
  free(pCertValue);
  return err;
}

//--------------------------------------------------
// Accessor for Id atribute of CertValue object.
// pCertValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION const char* ddocCertValue_GetId(CertValue* pCertValue)
{
  RETURN_OBJ_IF_NULL(pCertValue, NULL)
  return pCertValue->szId;
}

//--------------------------------------------------
// Mutatoror for Id atribute of CertValue object.
// pCertValue - address of object [REQUIRED]
// value - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValue_SetId(CertValue* pCertValue, const char* value)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertValue)
  RETURN_IF_NULL_PARAM(value)
  err = ddocMemAssignString((char**)&(pCertValue->szId), value);
  return err;
}

//--------------------------------------------------
// Accessor for Cert atribute of CertValue object.
// pCertValue - address of object [REQUIRED]
// returns value of atribute or NULL.
//--------------------------------------------------
EXP_OPTION X509* ddocCertValue_GetCert(CertValue* pCertValue)
{
  RETURN_OBJ_IF_NULL(pCertValue, NULL)
  return pCertValue->pCert;
}

//--------------------------------------------------
// Mutatoror for Cert atribute of CertValue object.
// pCertValue - address of object [REQUIRED]
// pCert - new value for atribute [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValue_SetCert(CertValue* pCertValue, X509* pCert)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertValue)
  RETURN_IF_NULL_PARAM(pCert)
  if(pCertValue->pCert && pCertValue->pCert != pCert) // free old cert
    X509_free(pCertValue->pCert);
  else
    ddocDebug(3, "ddocCertValue_SetCert", "Not freeing old cert");
  pCertValue->pCert = pCert;
  ddocDebug(3, "ddocCertValue_SetCert", "id: %s type: %d cert: %s", pCertValue->szId, pCertValue->nType, (pCert ? "OK" : "NULL"));
  return err;
}

//--------------------------------------------------
// Generates XML for <EncapsulatedX509Certificate> element
// pCertID - CertID object [REQUIRED]
// pBuf - memory buffer for storing xml [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
int ddocCertValue_toXML(const CertValue* pCertValue, DigiDocMemBuf* pBuf)
{
  int err = ERR_OK;
  char *p1 = 0;

  RETURN_IF_NULL_PARAM(pBuf)
  RETURN_IF_NULL_PARAM(pCertValue)
  // start of element
  err = ddocGen_startElemBegin(pBuf, "EncapsulatedX509Certificate");
  if(err) return err;
  if(pCertValue->szId)
    err = ddocGen_addAtribute(pBuf, "Id", pCertValue->szId);
  if(err) return err;
  err = ddocGen_startElemEnd(pBuf);
  if(err) return err;
  //err = ddocMemAppendData(pBuf, "\n", -1);
  if(pCertValue->pCert) {
    err = getCertPEM(pCertValue->pCert, 0, &p1);
    if(p1) {
      err = ddocMemAppendData(pBuf, p1, -1);
      free(p1);
    }
  }
  if(err) return err;
  err = ddocGen_endElem(pBuf, "EncapsulatedX509Certificate");
  return err;
}

//==========< CertValueList >====================

//--------------------------------------------------
// "Constructor" of CertValueList object
// ppCertValueList - address of buffer for newly allocated object [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValueList_new(CertValueList** ppCertValueList)
{
  int err = ERR_OK;

  // check input parameters
  ddocDebug(3, "ddocCertValueList_new", "Create new cerValue list");
  RETURN_IF_NULL_PARAM(ppCertValueList);
  *ppCertValueList = (CertValueList*)malloc(sizeof(CertValueList));
  // allocate new object
  RETURN_IF_BAD_ALLOC(*ppCertValueList);
  memset(*ppCertValueList, 0, sizeof(CertValueList));
  return err;
}

//--------------------------------------------------
// "Destructor" of CertValueList object
// pCertValueList - address of object to be deleted [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValueList_free(CertValueList* pCertValueList)
{
  int i, err = ERR_OK;
  RETURN_IF_NULL_PARAM(pCertValueList)
  // free timestamp-infos
  for(i = 0; i < pCertValueList->nCertValues; i++) {
    if(pCertValueList->pCertValues[i]) {
      err = ddocCertValue_free(pCertValueList->pCertValues[i]);
      if(err) return err;
    }
  }
  free(pCertValueList->pCertValues);
  free(pCertValueList);
  return err;
}

//--------------------------------------------------
// Adds a CertValue element to CertValueList object.
// pCertValueList - pointer to CertValueList object [REQUIRED]
// pCertValue - new object [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValueList_addCertValue(CertValueList* pCertValueList, CertValue* pCertValue)
{
  CertValue** pCertValues = 0;

  RETURN_IF_NULL_PARAM(pCertValueList)
  RETURN_IF_NULL_PARAM(pCertValue)
  pCertValues = (CertValue**)realloc(pCertValueList->pCertValues, sizeof(CertValue*) * (pCertValueList->nCertValues + 1));
  RETURN_IF_BAD_ALLOC(pCertValues);
  pCertValueList->pCertValues = pCertValues;
  pCertValueList->pCertValues[pCertValueList->nCertValues] = pCertValue;
  pCertValueList->nCertValues++;
  ddocDebug(4, "ddocCertValueList_addCertValue", "added cert: %s type: %d", pCertValue->szId, pCertValue->nType);
  return ERR_OK;
}

//--------------------------------------------------
// Accessor for count of CertValues subelement of CertValueList object.
// pCertValueList - pointer to CertValueList object [REQUIRED]
// returns count or -1 for error. Then use error API to check errors
//--------------------------------------------------
EXP_OPTION int ddocCertValueList_GetCertValuesCount(CertValueList* pCertValueList)
{
  SET_LAST_ERROR_RETURN_IF_NOT(pCertValueList, ERR_NULL_POINTER, -1)
  return pCertValueList->nCertValues;
}

//--------------------------------------------------
// Accessor for CertValues subelement of CertValueList object.
// pCertValueList - pointer to CertValueList object [REQUIRED]
// nIdx - index of CertValue object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocCertValueList_GetCertValue(CertValueList* pCertValueList, int nIdx)
{
  RETURN_OBJ_IF_NULL(pCertValueList, NULL)
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx >= 0 && nIdx < pCertValueList->nCertValues, ERR_BAD_CERTVALUE_IDX, NULL);
  RETURN_OBJ_IF_NULL(pCertValueList->pCertValues[nIdx], 0);
  return pCertValueList->pCertValues[nIdx];
}

//--------------------------------------------------
// Deletes CertValue subelement of CertValueList object.
// pCertValueList - pointer to CertValueList object [REQUIRED]
// nIdx - index of CertValue object to be removed [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocCertValueList_DeleteCertValue(CertValueList* pCertValueList, int nIdx)
{
  int err = ERR_OK, i;

  RETURN_IF_NULL_PARAM(pCertValueList)
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx >= 0 && nIdx < pCertValueList->nCertValues, ERR_BAD_CERTVALUE_IDX, ERR_BAD_CERTVALUE_IDX);
  RETURN_IF_NULL_PARAM(pCertValueList->pCertValues[nIdx]);
  // delete the given object
  err = ddocCertValue_free(pCertValueList->pCertValues[nIdx]);
  if(err) return err;
  pCertValueList->pCertValues[nIdx] = 0;
  // move other objects 1 step close to array start
  for(i = nIdx; i < pCertValueList->nCertValues; i++) 
    pCertValueList->pCertValues[i] = pCertValueList->pCertValues[i+1];
  pCertValueList->pCertValues[pCertValueList->nCertValues - 1] = 0;
  pCertValueList->nCertValues--;
  return err;
}

//--------------------------------------------------
// Finds a CertValue object with required type
// pCertValueList - pointer to CertValueList object [REQUIRED]
// nType - type of CertValue object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocCertValueList_GetCertValueOfType(CertValueList* pCertValueList, int nType)
{
  int i;

  RETURN_OBJ_IF_NULL(pCertValueList, NULL)
  ddocDebug(4, "ddocCertValueList_GetCertValueOfType", "find type: %d", nType);
  for(i = 0; i < pCertValueList->nCertValues; i++) {
	ddocDebug(4, "ddocCertValueList_GetCertValueOfType", "idx: %d", i);
    ddocDebug(4, "ddocCertValueList_GetCertValueOfType", "idx: %d type: %d", i, pCertValueList->pCertValues[i]->nType);
    if(pCertValueList->pCertValues[i]->nType == nType){
	  ddocDebug(4, "ddocCertValueList_GetCertValueOfType", "found");
      return pCertValueList->pCertValues[i];}
  }
  return NULL;
}

//--------------------------------------------------
// Finds a CertValue object with required type or creates a new one
// pCertValueList - pointer to CertValueList object [REQUIRED]
// nType - type of CertValue object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocCertValueList_GetOrCreateCertValueOfType(CertValueList* pCertValueList, int nType)
{
  
  CertValue* pCertValue = ddocCertValueList_GetCertValueOfType(pCertValueList, nType);
  if(!pCertValue) {
    ddocCertValue_new(&pCertValue, nType, 0, 0);
    if(pCertValue)
      ddocCertValueList_addCertValue(pCertValueList, pCertValue);
  }
  return pCertValue;
}


//======================< SignatureInfo >====================================

//============================================================
// Returns the number of signatures
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getCountOfSignatures(const SignedDoc* pSigDoc)
{
  RETURN_OBJ_IF_NULL(pSigDoc, -1);
  return pSigDoc->nSignatures;
}

//============================================================
// Returns the next free signature id
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getNextSignatureId(const SignedDoc* pSigDoc)
{
  int id = 0, n, i;

  RETURN_OBJ_IF_NULL(pSigDoc, -1);
  for(i = 0; i < pSigDoc->nSignatures; i++) {
    SignatureInfo* pSignature = pSigDoc->pSignatures[i];
    RETURN_OBJ_IF_NULL(pSignature, -1);
    RETURN_OBJ_IF_NULL(pSignature->szId, -1);
    SET_LAST_ERROR_RETURN_IF_NOT(strlen(pSignature->szId) > 1, ERR_EMPTY_STRING, -1);
    n = atoi(pSignature->szId+1);
    if(id <= n)
      id = n+1;
  }
  return id;
}

//============================================================
// Returns the signature object for the given Notary
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION SignatureInfo* ddocGetSignatureForNotary(const SignedDoc* pSigDoc, 
						    const NotaryInfo* pNotInfo)
{
  int i;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  for(i = 0; i < pSigDoc->nSignatures; i++) {
    SignatureInfo* pSignature = pSigDoc->pSignatures[i];
    RETURN_OBJ_IF_NULL(pSignature, NULL);
    if(pSignature->pNotary == pNotInfo)
      return pSignature;
  }
  return NULL;
}

//============================================================
// Returns the desired SignatureInfo object
// pSigDoc - signed doc pointer
// nIdx - SignatureInfo index (starting with 0)
//============================================================
EXP_OPTION SignatureInfo* getSignature(const SignedDoc* pSigDoc, int nIdx)
{
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx < pSigDoc->nSignatures, ERR_BAD_SIG_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigDoc->pSignatures[nIdx], NULL);
  return pSigDoc->pSignatures[nIdx];
}

//============================================================
// Returns the last SignatureInfo object
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION SignatureInfo* ddocGetLastSignature(const SignedDoc* pSigDoc)
{
  int nIdx;
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  nIdx = pSigDoc->nSignatures - 1;
  SET_LAST_ERROR_RETURN_IF_NOT(nIdx < pSigDoc->nSignatures, ERR_BAD_SIG_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigDoc->pSignatures && pSigDoc->pSignatures[nIdx], NULL);
  return pSigDoc->pSignatures[nIdx];
}

//============================================================
// Returns the SignatureInfo object with the given id
// pSigDoc - signed doc pointer
// id - SignatureInfo id
//============================================================
EXP_OPTION SignatureInfo* getSignatureWithId(const SignedDoc* pSigDoc, const char* id)
{
  SignatureInfo* pSignature = NULL;
  int i;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  RETURN_OBJ_IF_NULL(id, NULL);
  for(i = 0; i < pSigDoc->nSignatures; i++) {
    RETURN_OBJ_IF_NULL(pSigDoc->pSignatures[i], NULL);
    RETURN_OBJ_IF_NULL(pSigDoc->pSignatures[i]->szId, NULL);
    if(!strcmp(pSigDoc->pSignatures[i]->szId, id)) {
      pSignature = pSigDoc->pSignatures[i];
      break;
    }
  }
  return pSignature;
}


//============================================================
// Adds a new SignedInfo element to a SignedDoc element and initializes it
// id - signature id (use NULL for default)
// return the newly created structure 
//============================================================
// FIXME : memory leaks possible..
EXP_OPTION int SignatureInfo_new(SignatureInfo **newSignatureInfo, 
				 SignedDoc* pSigDoc, const char* id)
{
  int i, nId = 0;
  SignatureInfo** pSignatures = NULL;
  SignatureInfo* pSigInfo = NULL;
  char buf[100];

  RETURN_IF_NULL_PARAM(pSigDoc);
  //clearErrors();
  if(hasSignatureWithWrongDataFileHash(pSigDoc)) {
    ddocDebug(1, "SignatureInfo_new", "Cannot add signature in ddoc with invalid DataFile hashes!");
    return ERR_FILE_WRITE;
  }
  if(!id)
    nId = getNextSignatureId(pSigDoc);
  if(pSigDoc->nSignatures == 0) {
    RETURN_IF_NOT(!pSigDoc->pSignatures, ERR_BAD_SIG_COUNT);
    pSigDoc->nSignatures = 1;
  }
  else
    pSigDoc->nSignatures++;
  pSignatures = (SignatureInfo**)malloc((pSigDoc->nSignatures) * sizeof(void *));
  RETURN_IF_BAD_ALLOC(pSignatures);
  for(i = 0; i < pSigDoc->nSignatures-1; i++)
    pSignatures[i] = pSigDoc->pSignatures[i];
  pSigInfo = (SignatureInfo*)malloc(sizeof(SignatureInfo));
  RETURN_IF_BAD_ALLOC(pSigInfo);
  memset(pSigInfo, 0, sizeof(SignatureInfo));
  pSignatures[pSigDoc->nSignatures-1] = pSigInfo;
  if(pSigDoc->pSignatures)
    free(pSigDoc->pSignatures);
  pSigDoc->pSignatures = pSignatures;
  if(id) {
    setString(&(pSigInfo->szId), id, -1);
  } else {
    snprintf(buf, sizeof(buf), "S%d", nId);
    setString(&(pSigInfo->szId), buf, -1);
  }
  // create timestamp
  createTimestamp(pSigDoc, buf, sizeof(buf));
  setString(&(pSigInfo->szTimeStamp), buf, -1);
  *newSignatureInfo = pSigInfo;
  return ERR_OK;
}


//============================================================
// Sets the signature production place info
// pSigInfo - signature info object
// city - city name
// state - state or province name
// zip - postal code
// country - country name
//============================================================
EXP_OPTION int setSignatureProductionPlace(SignatureInfo* pSigInfo,
                                const char* city, const char* state,
                                const char* zip, const char* country)
{
  char* p = 0;
  RETURN_IF_NULL_PARAM(pSigInfo);
  if(city) {
    p = (char*)escape2xmlsym(city);
    if(p) {
      setString(&(pSigInfo->sigProdPlace.szCity), p, -1);
      free(p);
    }
  }
  if(state) {
    p = (char*)escape2xmlsym(state);
    if(p) {
      setString(&(pSigInfo->sigProdPlace.szStateOrProvince), p, -1);
      free(p);
    }
  }
  if(zip) {
    p = (char*)escape2xmlsym(zip);
    if(p) {
      setString(&(pSigInfo->sigProdPlace.szPostalCode), p, -1);
      free(p);
    }
  }
  if(country) {
    p = (char*)escape2xmlsym(country);
    if(p) {
      setString(&(pSigInfo->sigProdPlace.szCountryName), country, -1);
      free(p);
    }
  }
  return ERR_OK;
}



//============================================================
// Adds a signer role 
// pSigInfo - signature info object
// nCertified - certified role? (1/0)
// role - role data
// rLen - role data length
// encode - 1=encode it with Base64, 0=use as is
//============================================================
// FIXME : memory leaks possible...
EXP_OPTION int addSignerRole(SignatureInfo* pSigInfo, int nCertified, 
				   const char* role, int rLen, int enc)
{
  int n, i;
  char **p = NULL, *b = NULL, *p1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  //if(!enc && role && (strchr(role, '<') || strchr(role, '>')))
  //  SET_LAST_ERROR_RETURN(ERR_INVALID_CONTENT, ERR_INVALID_CONTENT);
  
  if(nCertified) {
    n = pSigInfo->signerRole.nCertifiedRoles + 1;
    p = (char**)malloc(n * sizeof(void*));
    RETURN_IF_BAD_ALLOC(p);
    if(pSigInfo->signerRole.nCertifiedRoles) {
      RETURN_IF_NULL(pSigInfo->signerRole.pCertifiedRoles);
      for(i = 0; i < pSigInfo->signerRole.nCertifiedRoles; i++)
	p[i] = pSigInfo->signerRole.pCertifiedRoles[i];
      free(pSigInfo->signerRole.pCertifiedRoles);
    }
    p[n-1] = 0;
    if(enc) {
      b = (char*)malloc(rLen * 2);
      RETURN_IF_BAD_ALLOC(b);
      i = sizeof(b);
      encode((const byte*)role, rLen, (byte*)b, &i);
      b[i] = 0;
      setString(&(p[n-1]), b, i);
    }
    else
      setString(&(p[n-1]), role, rLen);
    pSigInfo->signerRole.pCertifiedRoles = p;
    pSigInfo->signerRole.nCertifiedRoles = n;
  } else {
    n = pSigInfo->signerRole.nClaimedRoles + 1;
    p = (char**)malloc(n * sizeof(void*));
    RETURN_IF_BAD_ALLOC(p);
    if(pSigInfo->signerRole.nClaimedRoles) {
      RETURN_IF_NULL(pSigInfo->signerRole.pClaimedRoles);
      for(i = 0; i < pSigInfo->signerRole.nClaimedRoles; i++)
	p[i] = pSigInfo->signerRole.pClaimedRoles[i];
      free(pSigInfo->signerRole.pClaimedRoles);
    }
    p[n-1] = 0;
    if(enc) {
      b = (char*)malloc(rLen * 2);
      RETURN_IF_BAD_ALLOC(b);
      i = sizeof(b);
      encode((const byte*)role, rLen, (byte*)b, &i);
      b[i] = 0;
      setString(&(p[n-1]), b, i);
    }
    else {
      p1 = (char*)escape2xmlsym(role);
      if(p1) {
	setString(&(p[n-1]), p1, -1);
	free(p1);
      }
    }
    pSigInfo->signerRole.pClaimedRoles = p;
    pSigInfo->signerRole.nClaimedRoles = n;
  }
  return ERR_OK;
}

//============================================================
// Returns the number of signer roles
// pSigInfo - signature info object
// nCertified - certified role? (1/0)
//============================================================
EXP_OPTION int getCountOfSignerRoles(SignatureInfo* pSigInfo, int nCertified)
{
  RETURN_OBJ_IF_NULL(pSigInfo, -1);
  if(nCertified)
    return pSigInfo->signerRole.nCertifiedRoles;
  else
    return pSigInfo->signerRole.nClaimedRoles;
}


//============================================================
// Returns the desired signer role
// pSigInfo - signature info object
// nCertified - certified role? (1/0)
//============================================================
EXP_OPTION const char* getSignerRole(SignatureInfo* pSigInfo, int nCertified, int nIdx)
{
  RETURN_OBJ_IF_NULL(pSigInfo, 0);
  if(nCertified) {
    SET_LAST_ERROR_RETURN_IF_NOT(nIdx < pSigInfo->signerRole.nCertifiedRoles, ERR_BAD_ROLE_INDEX, 0);
    RETURN_OBJ_IF_NULL(pSigInfo->signerRole.pCertifiedRoles[nIdx], 0);
    return pSigInfo->signerRole.pCertifiedRoles[nIdx];
  } else {
    SET_LAST_ERROR_RETURN_IF_NOT(nIdx < pSigInfo->signerRole.nClaimedRoles, ERR_BAD_ROLE_INDEX, 0);
    RETURN_OBJ_IF_NULL(pSigInfo->signerRole.pClaimedRoles[nIdx], 0);
    return pSigInfo->signerRole.pClaimedRoles[nIdx];
  }
}


//============================================================
// Removes this SignatureInfo from signed doc and frees it's memory
// pSigDoc - signed doc object
// id - signature id to be removed
//============================================================
EXP_OPTION int SignatureInfo_delete(SignedDoc* pSigDoc, const char* id)
{
  int n, i, j, err = ERR_OK;
  SignatureInfo* pSignature;
  SignatureInfo** pSignatures;
  
  RETURN_IF_NULL_PARAM(pSigDoc);
  ddocDebug(3, "SignatureInfo_delete", "id: %s", id);
  if(hasSignatureWithWrongDataFileHash(pSigDoc)) {
    ddocDebug(1, "SignatureInfo_delete", "Cannot delete signature in ddoc with invalid DataFile hashes!");
    return ERR_FILE_WRITE;
  }
  if((pSignature = getSignatureWithId(pSigDoc, id)) != NULL) {
    n = pSigDoc->nSignatures - 1;
    if(n > 0) {
      pSignatures = (SignatureInfo**)malloc(n * sizeof(void*));
      RETURN_IF_BAD_ALLOC(pSignatures);
      for(i = j = 0; i < pSigDoc->nSignatures; i++) {
          if(strcmp(pSigDoc->pSignatures[i]->szId, id)) { 
	        pSignatures[j++] = pSigDoc->pSignatures[i];					
	      } else {
		    SignatureInfo_free(pSigDoc->pSignatures[i]);
          }
      }
      free(pSigDoc->pSignatures);
      pSigDoc->pSignatures = pSignatures;
      pSigDoc->nSignatures = j;
    } else {
      for(i = 0; i < pSigDoc->nSignatures; i++){
	SignatureInfo_free(pSigDoc->pSignatures[i]);
      free(pSigDoc->pSignatures);
      pSigDoc->pSignatures = NULL;
      pSigDoc->nSignatures = 0;}
    }
  }
  else
    err = ERR_BAD_SIG_INDEX;
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}


//============================================================
// cleanup SignatureInfo memory
// pSigInfo - object to be cleaned up
//============================================================
EXP_OPTION void SignatureInfo_free(SignatureInfo* pSigInfo)
{
  int i;

  RETURN_VOID_IF_NULL(pSigInfo);
  if(pSigInfo->szId)
    free(pSigInfo->szId);
  if(pSigInfo->szTimeStamp)
    free(pSigInfo->szTimeStamp);
  if(pSigInfo->pSigPropDigest)
    ddocDigestValue_free(pSigInfo->pSigPropDigest);
  if(pSigInfo->pSigPropRealDigest)
    ddocDigestValue_free(pSigInfo->pSigPropRealDigest);
  if(pSigInfo->pSigInfoRealDigest)
    ddocDigestValue_free(pSigInfo->pSigInfoRealDigest);
  if(pSigInfo->pSigValue)
    ddocSignatureValue_free(pSigInfo->pSigValue);
  for(i = 0; i < pSigInfo->nDocs; i++) {
    DocInfo_free(pSigInfo->pDocs[i]);		
  }
  if(pSigInfo->pDocs)
    free(pSigInfo->pDocs);
  // signature production place
  if(pSigInfo->sigProdPlace.szCity)
    free(pSigInfo->sigProdPlace.szCity);
  if(pSigInfo->sigProdPlace.szStateOrProvince)
    free(pSigInfo->sigProdPlace.szStateOrProvince);
  if(pSigInfo->sigProdPlace.szPostalCode)
    free(pSigInfo->sigProdPlace.szPostalCode);
  if(pSigInfo->sigProdPlace.szCountryName)
    free(pSigInfo->sigProdPlace.szCountryName);
  // signer role
  for(i = 0; i < pSigInfo->signerRole.nClaimedRoles; i++) {
    if(pSigInfo->signerRole.pClaimedRoles[i])
      free(pSigInfo->signerRole.pClaimedRoles[i]);    
  }
  if(pSigInfo->signerRole.pClaimedRoles)
    free(pSigInfo->signerRole.pClaimedRoles);
  for(i = 0; i < pSigInfo->signerRole.nCertifiedRoles; i++) {
    if (pSigInfo->signerRole.pCertifiedRoles[i])
      free(pSigInfo->signerRole.pCertifiedRoles[i]);    
  }
  if(pSigInfo->signerRole.pCertifiedRoles)
    free(pSigInfo->signerRole.pCertifiedRoles);
  ddocMemBuf_free(&(pSigInfo->mbufOrigContent));
  if(pSigInfo->pNotary)
    NotaryInfo_free(pSigInfo->pNotary);
  if(pSigInfo->pCertIDs)
    ddocCertIDList_free(pSigInfo->pCertIDs);
  if(pSigInfo->pCertValues)
    ddocCertValueList_free(pSigInfo->pCertValues);
	//AM 23.05.08
  if(pSigInfo->szDigestType)
    free(pSigInfo->szDigestType);
  free(pSigInfo);
}

//============================================================
// Sets signatures signed properties digest
// pSigInfo - signature info object
// value - new binary digest value
// len - length of the value
//============================================================
EXP_OPTION int ddocSigInfo_SetSigPropDigest(SignatureInfo* pSigInfo, const char* value, long len)
{
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  if(!pSigInfo->pSigPropDigest)
    ddocDigestValue_new(&(pSigInfo->pSigPropDigest), 0, 0, 0);
  return ddocDigestValue_SetDigestValue(pSigInfo->pSigPropDigest, value, len);
}

//============================================================
// Sets signatures signed properties real digest as read from file
// pSigInfo - signature info object
// value - new binary digest value
// len - length of the value
//============================================================
EXP_OPTION int ddocSigInfo_SetSigPropRealDigest(SignatureInfo* pSigInfo, const char* value, long len)
{
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  if(!pSigInfo->pSigPropRealDigest)
    ddocDigestValue_new(&(pSigInfo->pSigPropRealDigest), 0, 0, 0);
  return ddocDigestValue_SetDigestValue(pSigInfo->pSigPropRealDigest, value, len);
}

//============================================================
// Sets signatures signed info real digest as read from file
// pSigInfo - signature info object
// value - new binary digest value
// len - length of the value
//============================================================
EXP_OPTION int ddocSigInfo_SetSigInfoRealDigest(SignatureInfo* pSigInfo, const char* value, long len)
{
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  if(!pSigInfo->pSigInfoRealDigest)
    ddocDigestValue_new(&(pSigInfo->pSigInfoRealDigest), 0, 0, 0);
  return ddocDigestValue_SetDigestValue(pSigInfo->pSigInfoRealDigest, value, len);
}

//============================================================
// Returns signatures signed properties digest
// pSigInfo - signature info object
// return digest value as DigiDocMemBuf pointer or NULL
//============================================================
EXP_OPTION DigiDocMemBuf* ddocSigInfo_GetSigPropDigest(SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return ddocDigestValue_GetDigestValue(pSigInfo->pSigPropDigest);
}

//============================================================
// Returns signatures signed properties digest as read from file
// pSigInfo - signature info object
// return digest value as DigiDocMemBuf pointer or NULL
//============================================================
EXP_OPTION DigiDocMemBuf* ddocSigInfo_GetSigPropRealDigest(SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return ddocDigestValue_GetDigestValue(pSigInfo->pSigPropRealDigest);
}

//============================================================
// Returns signatures signed info digest as read from file
// pSigInfo - signature info object
// return digest value as DigiDocMemBuf pointer or NULL
//============================================================
EXP_OPTION DigiDocMemBuf* ddocSigInfo_GetSigInfoRealDigest(SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return ddocDigestValue_GetDigestValue(pSigInfo->pSigInfoRealDigest);
}

//============================================================
// Returns signatures signature-value
// pSigInfo - signature info object
// return signature-value as SignatureValue pointer or NULL
//============================================================
EXP_OPTION SignatureValue* ddocSigInfo_GetSignatureValue(SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return pSigInfo->pSigValue;
}

//============================================================
// Returns signatures signature-value
// pSigInfo - signature info object
// return signature-value as DigiDocMemBuf pointer or NULL
//============================================================
EXP_OPTION DigiDocMemBuf* ddocSigInfo_GetSignatureValue_Value(SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return ddocSignatureValue_GetSignatureValue(pSigInfo->pSigValue);
}

//============================================================
// Sets signatures signature-value
// pSigInfo - signature info object
// value - new binary signature value
// len - length of the value
//============================================================
EXP_OPTION int ddocSigInfo_SetSignatureValue(SignatureInfo* pSigInfo, const char* value, long len)
{
  char buf1[30];

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  snprintf(buf1, sizeof(buf1), "%s-SIG", pSigInfo->szId);
  if(!pSigInfo->pSigValue) 
    ddocSignatureValue_new(&(pSigInfo->pSigValue), 0, 0, 0, 0);
  ddocSignatureValue_SetId(pSigInfo->pSigValue, buf1);
  return ddocSignatureValue_SetSignatureValue(pSigInfo->pSigValue, value, len);
}

//============================================================
// Returns signaers certs - issuer-serial
// pSigInfo - signature info object
// return required atribute value
//============================================================
EXP_OPTION const char* ddocSigInfo_GetSignersCert_IssuerSerial(const SignatureInfo* pSigInfo)
{
  CertID* pCertID = 0;
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  pCertID = ddocCertIDList_GetCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  RETURN_OBJ_IF_NULL(pCertID, NULL);
  return ddocCertID_GetIssuerSerial(pCertID);
}

//============================================================
// Sets signers certs issuer serial
// pSigInfo - signature info object
// value - new value
//============================================================
EXP_OPTION int ddocSigInfo_SetSignersCert_IssuerSerial(SignatureInfo* pSigInfo, const char* value)
{
  CertID* pCertID = 0;
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  pCertID = ddocCertIDList_GetOrCreateCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  return ddocCertID_SetIssuerSerial(pCertID, value);
}

//============================================================
// Returns signaers certs - issuer-name
// pSigInfo - signature info object
// return required atribute value
//============================================================
EXP_OPTION const char* ddocSigInfo_GetSignersCert_IssuerName(const SignatureInfo* pSigInfo)
{
  CertID* pCertID = 0;
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  pCertID = ddocCertIDList_GetCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  RETURN_OBJ_IF_NULL(pCertID, NULL);
  return ddocCertID_GetIssuerName(pCertID);
}

//============================================================
// Returns signaers certs - issuer-name
// pSigInfo - signature info object
// pMbuf - memory buffer to return hash
// return required atribute value
//============================================================
EXP_OPTION const char* ddocSigInfo_GetSignersCert_IssuerNameAndHash(const SignatureInfo* pSigInfo, DigiDocMemBuf *pMbuf)
{
  CertID* pCertID = 0;
  X509* pCert = 0;
/*  DigiDocMemBuf mbuf1, mbuf2, mbuf3;
  
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  mbuf2.pMem = 0;
  mbuf2.nLen = 0;
  mbuf3.pMem = 0;
  mbuf3.nLen = 0;
*/
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  RETURN_OBJ_IF_NULL(pMbuf, NULL);
  pCertID = ddocCertIDList_GetCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  RETURN_OBJ_IF_NULL(pCertID, NULL);
  pCert = ddocSigInfo_GetSignersCert(pSigInfo);
  RETURN_OBJ_IF_NULL(pCert, NULL);
  /*ddocCertGetSubjectCN(pCert, &mbuf1);
  readSubjectKeyIdentifier(pCert, &mbuf2);
  ddocEncodeBase64(&mbuf2, &mbuf3);
  ddocMemBuf_free(&mbuf2);
  readAuthorityKeyIdentifier(pCert, pMbuf);
  ddocEncodeBase64(pMbuf, &mbuf2);
  ddocDebug(3, "ddocSigInfo_GetSignersCert_IssuerNameAndHash", "CN: %s subj-hash: %s issuer-hash: %s", (char*)mbuf1.pMem, (char*)mbuf3.pMem, (char*)mbuf2.pMem);
  ddocMemBuf_free(&mbuf1);
  ddocMemBuf_free(&mbuf2);
  ddocMemBuf_free(&mbuf3);*/
  readAuthorityKeyIdentifier(pCert, pMbuf);
  return ddocCertID_GetIssuerName(pCertID);
}

//============================================================
// Sets signers certs issuer name
// pSigInfo - signature info object
// value - new value
//============================================================
EXP_OPTION int ddocSigInfo_SetSignersCert_IssuerName(SignatureInfo* pSigInfo, const char* value)
{
  CertID* pCertID = 0;
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  pCertID = ddocCertIDList_GetOrCreateCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  return ddocCertID_SetIssuerName(pCertID, value);
}

//============================================================
// Returns signers certs digest as DigiDocMemBuf object
// pSigInfo - signature info object
// return signers certs digest as DigiDocMemBuf pointer or NULL
//============================================================
EXP_OPTION DigiDocMemBuf* ddocSigInfo_GetSignersCert_DigestValue(const SignatureInfo* pSigInfo)
{
  CertID* pCertID = 0;
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  pCertID = ddocCertIDList_GetCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  RETURN_OBJ_IF_NULL(pCertID, NULL);
  return ddocCertID_GetDigestValue(pCertID);
}

//============================================================
// Sets signers certs digest
// pSigInfo - signature info object
// value - new binary signature value
// len - length of the value
//============================================================
EXP_OPTION int ddocSigInfo_SetSignersCert_DigestValue(SignatureInfo* pSigInfo, const char* value, long len)
{
  CertID* pCertID = 0;
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(value);
  pCertID = ddocCertIDList_GetOrCreateCertIDOfType(pSigInfo->pCertIDs, CERTID_TYPE_SIGNERS_CERTID);
  return ddocCertID_SetDigestValue(pCertID, value, len);
}

//--------------------------------------------------
// Finds a CertID object with required type
// pSigInfo - signature info object [REQUIRED]
// nType - type of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocSigInfo_GetCertIDOfType(const SignatureInfo* pSigInfo, int nType)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(pSigInfo->pCertIDs)
    return ddocCertIDList_GetCertIDOfType(pSigInfo->pCertIDs, nType);
  return NULL;
}

//--------------------------------------------------
// Finds last CertID object of this signature
// pSigInfo - signature info object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocSigInfo_GetLastCertID(const SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(pSigInfo->pCertIDs)
    return ddocCertIDList_GetLastCertID(pSigInfo->pCertIDs);
  return NULL;
}


//--------------------------------------------------
// Finds a CertID object with required type or creates a new one
// pSigInfo - signature info object [REQUIRED]
// nType - type of CertID object [REQUIRED]
// returns CertID pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertID* ddocSigInfo_GetOrCreateCertIDOfType(SignatureInfo* pSigInfo, int nType)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(!pSigInfo->pCertIDs)
    ddocCertIDList_new(&(pSigInfo->pCertIDs));
  RETURN_OBJ_IF_NULL(pSigInfo->pCertIDs, NULL);
  return ddocCertIDList_GetOrCreateCertIDOfType(pSigInfo->pCertIDs, nType);
}

//--------------------------------------------------
// Finds a CertValue object with required type
// pSigInfo - signature info object [REQUIRED]
// nType - type of CertValue object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocSigInfo_GetCertValueOfType(const SignatureInfo* pSigInfo, int nType)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  ddocDebug(9, "ddocSigInfo_GetCertValueOfType", "start");
  if(pSigInfo->pCertValues)
    return ddocCertValueList_GetCertValueOfType(pSigInfo->pCertValues, nType);
  ddocDebug(9, "ddocSigInfo_GetCertValueOfType", "end");
  return NULL;
}

//--------------------------------------------------
// Finds a CertValue object with required type or creates a new one
// pSigInfo - signature info object [REQUIRED]
// nType - type of CertValue object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocSigInfo_GetOrCreateCertValueOfType(SignatureInfo* pSigInfo, int nType)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(!pSigInfo->pCertValues)
    ddocCertValueList_new(&(pSigInfo->pCertValues));
  RETURN_OBJ_IF_NULL(pSigInfo->pCertValues, NULL);
  return ddocCertValueList_GetOrCreateCertValueOfType(pSigInfo->pCertValues, nType);
}

//--------------------------------------------------
// Finds last CertValue
// pSigInfo - signature info object [REQUIRED]
// returns CertValue pointer or NULL for error
//--------------------------------------------------
EXP_OPTION CertValue* ddocSigInfo_GetLastCertValue(const SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(pSigInfo->pCertValues)
    return ddocCertValueList_GetCertValue(pSigInfo->pCertValues, 
		  ddocCertValueList_GetCertValuesCount(pSigInfo->pCertValues) - 1);
  return NULL;
}

//--------------------------------------------------
// Finds the signers certificate
// pSigInfo - signature info object [REQUIRED]
// returns certificate or NULL
//--------------------------------------------------
EXP_OPTION X509* ddocSigInfo_GetSignersCert(const SignatureInfo* pSigInfo)
{
  X509 *pCert = 0;
  CertValue *pCertValue = 0;
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(pSigInfo->pCertValues) {
    pCertValue = ddocSigInfo_GetCertValueOfType(pSigInfo, CERTID_VALUE_SIGNERS_CERT);
    if(pCertValue)
      pCert = pCertValue->pCert;
  }
  return pCert;
}

//--------------------------------------------------
// Sets the signers certificate
// pSigInfo - signature info object [REQUIRED]
// pCert - certificate [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSigInfo_SetSignersCert(SignatureInfo* pSigInfo, X509* pCert)
{
  int err = ERR_OK;
  CertValue *pCertValue = 0;
  char  buf1[50];

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pCert);
  pCertValue = ddocSigInfo_GetOrCreateCertValueOfType(pSigInfo, CERTID_VALUE_SIGNERS_CERT);
  if(pCertValue) {
    snprintf(buf1, sizeof(buf1), "%s-SIGNER_CERT", pSigInfo->szId);
    err = ddocCertValue_SetId(pCertValue, buf1);
    if(!err && pCert)
      err = ddocCertValue_SetCert(pCertValue, pCert);
  }
  return err;
}

//--------------------------------------------------
// Finds the OCSP responders certificate
// pSigInfo - signature info object [REQUIRED]
// returns certificate or NULL
//--------------------------------------------------
EXP_OPTION X509* ddocSigInfo_GetOCSPRespondersCert(const SignatureInfo* pSigInfo)
{
  X509 *pCert = 0;
  CertValue *pCertValue = 0;
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  if(pSigInfo->pCertValues) {
	ddocDebug(5, "ddocSigInfo_GetOCSPRespondersCert", "start");
    pCertValue = ddocSigInfo_GetCertValueOfType(pSigInfo, CERTID_VALUE_RESPONDERS_CERT);
	ddocDebug(5, "ddocSigInfo_GetOCSPRespondersCert", "end");
    if(pCertValue){
      pCert = pCertValue->pCert;
	ddocDebug(5, "ddocSigInfo_GetOCSPRespondersCert", "test");}
  }
  ddocDebug(5, "ddocSigInfo_GetOCSPRespondersCert", "end2");
  if(pCert) ddocDebug(5, "ddocSigInfo_GetOCSPRespondersCert", "pCert exists" );
  return pCert;
}

//--------------------------------------------------
// Sets the OCSP Responders certificate
// pSigInfo - signature info object [REQUIRED]
// pCert - certificate [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSigInfo_SetOCSPRespondersCert(SignatureInfo* pSigInfo, X509* pCert)
{
  int err = ERR_OK;
  CertValue *pCertValue = 0;
  char  buf1[50];

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pCert);
  pCertValue = ddocSigInfo_GetOrCreateCertValueOfType(pSigInfo, CERTID_VALUE_RESPONDERS_CERT);
  if(pCertValue) {
    snprintf(buf1, sizeof(buf1), "%s-RESPONDER_CERT", pSigInfo->szId);
    err = ddocCertValue_SetId(pCertValue, buf1);
    if(!err)
      err = ddocCertValue_SetCert(pCertValue, pCert);
  }
  return err;
}

//============================================================
// Adds a certificate and it's certid to this signature
// pSigInfo - signature info object [REQUIRED]
// pCert - vertificate [REQUIRED]
// nCertIdType - type of cert [REQUIRED]
// return error code or ERR_OK
//============================================================
EXP_OPTION int ddocSigInfo_addCert(SignatureInfo* pSigInfo, X509* pCert, int nCertIdType)
{
  int err = ERR_OK, l1;
  char buf1[100], buf2[200], buf3[300], buf4[100];
  CertID *pCertID = 0;
  DigiDocMemBuf mbuf1;
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pCert);

  RETURN_IF_NOT(err == ERR_OK, err);
  l1 = sizeof(buf1);
  RETURN_IF_NOT(X509_digest(pCert, EVP_sha1(), (unsigned char*)buf1, 
			    (unsigned int*)&l1), ERR_X509_DIGEST);
  if(err) return err;
  err = ReadCertSerialNumber(buf2, sizeof(buf2), pCert);
  memset(buf3, 0, sizeof(buf3));
  err = ddocCertGetIssuerDN(pCert, &mbuf1);
  RETURN_IF_NOT(err == ERR_OK, err);
  // now set all those atributes
  switch(nCertIdType) {
  case CERTID_TYPE_SIGNERS_CERTID:
    err = ddocSigInfo_SetSignersCert(pSigInfo, pCert);
    snprintf(buf4, sizeof(buf4), "%s-CERTINFO", pSigInfo->szId);
    ddocCertID_new(&pCertID, CERTID_TYPE_SIGNERS_CERTID, buf4, buf2, (char*)mbuf1.pMem, buf1, l1);
    break;
  case CERTID_TYPE_RESPONDERS_CERTID:
    err = ddocSigInfo_SetOCSPRespondersCert(pSigInfo, pCert);
    snprintf(buf4, sizeof(buf4), "%s-OCSP_CERTINFO", pSigInfo->szId);
    ddocCertID_new(&pCertID, CERTID_TYPE_RESPONDERS_CERTID, buf4, buf2, (char*)mbuf1.pMem, buf1, l1);
    break;
  }
  RETURN_IF_NOT(pCertID, ERR_BAD_ALLOC);
  if(!pSigInfo->pCertIDs) {
    err = ddocCertIDList_new(&(pSigInfo->pCertIDs));
    //ddocCertID_free(pCertID); // not owner any more!
    SET_LAST_ERROR_IF_NOT(err == ERR_OK, err);
  }
  if(pCertID) {
    ddocCertIDList_addCertID(pSigInfo->pCertIDs, pCertID);
    ddocDebug(3, "ddocSigInfo_addCert", "Added signers cert-id: %s type: %d", pCertID->szId, pCertID->nType);
  }
  ddocMemBuf_free(&mbuf1);
  return err;
}



//======================< DocInfo functions >=========================================


//============================================================
// Adds a new DocInfo element to a SignatureInfo element and initializes it
// pSigInfo - signature info object
// docId - document id (use NULL for default)
// digType - digest type
// digest - documents digest
// digLen - digest length
// mime - mime type
// mimeDig - mime digest
// mimeDigLen - mime digest length
// return the newly created structure 
//============================================================
EXP_OPTION int addDocInfo(DocInfo **newDocInfo, SignatureInfo* pSigInfo, const char* docId,
			   const char* digType, const byte* digest,
			   int digLen, const byte* mimeDig, int mimeDigLen)
{
  DocInfo** pDocInfos = NULL;
  DocInfo* pDocInfo = NULL;
  int i;

  RETURN_IF_NULL_PARAM(pSigInfo);
  if(pSigInfo->nDocs == 0) {
    RETURN_IF_NOT(!pSigInfo->pDocs, ERR_BAD_DOCINFO_COUNT);
    pSigInfo->nDocs = 1;
  }
  else
    pSigInfo->nDocs++;
  pDocInfos = (DocInfo**)malloc((pSigInfo->nDocs) * sizeof(void *));
  RETURN_IF_BAD_ALLOC(pDocInfos);
  for(i = 0; i < pSigInfo->nDocs-1; i++)
    pDocInfos[i] = pSigInfo->pDocs[i];
  pDocInfo = (DocInfo*)malloc(sizeof(DocInfo)); // MEMLEAK: ???
  if (!pDocInfo) {
    free(pDocInfos);
    SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
  }
  memset(pDocInfo, 0, sizeof(DocInfo));
  pDocInfos[pSigInfo->nDocs-1] = pDocInfo;
  // PR. leak found
  if(pSigInfo->pDocs)
	  free(pSigInfo->pDocs);
  pSigInfo->pDocs = pDocInfos;
  if(docId) 
    setString(&(pDocInfo->szDocId), docId, -1);
  if(digType)
    setString(&(pDocInfo->szDigestType), digType, -1);
  if(digest) {
    setString((char**)&(pDocInfo->szDigest), (const char*)digest, digLen);
    pDocInfo->nDigestLen = digLen;
  }
  if(mimeDig && strlen((const char*)mimeDig)) {
    setString((char**)&(pDocInfo->szMimeDigest), (const char*)mimeDig, mimeDigLen);
    pDocInfo->nMimeDigestLen = mimeDigLen;
  }
  *newDocInfo = pDocInfo;
  return ERR_OK;
}

//============================================================
// cleanup DocInfo memory
// pDocInfo - object to be cleaned up
//============================================================
EXP_OPTION void DocInfo_free(DocInfo* pDocInfo)
{
  RETURN_VOID_IF_NULL(pDocInfo);
  //assert(pDocInfo);
  if(pDocInfo->szDocId)
    free(pDocInfo->szDocId);
  if(pDocInfo->szDigestType)
    free(pDocInfo->szDigestType);
  if(pDocInfo->szDigest)
    free(pDocInfo->szDigest);
  if(pDocInfo->szMimeDigest)
    free(pDocInfo->szMimeDigest);
  // free the object itself
  free(pDocInfo);
}

//============================================================
// Returns number of DocInfos 
// pSigInfo - signature info pointer
//============================================================
EXP_OPTION int getCountOfDocInfos(const SignatureInfo* pSigInfo)
{
  RETURN_OBJ_IF_NULL(pSigInfo, -1);
  return pSigInfo->nDocs;
}

//============================================================
// Returns the desired DocInfo
// pSigInfo - signature info pointer
// idx - DocInfo index
//============================================================
EXP_OPTION DocInfo* getDocInfo(const SignatureInfo* pSigInfo, int idx)
{
  ddocDebug(3, "getDocInfo", "Idx: %d, Docs: %d", idx, pSigInfo->nDocs);
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  SET_LAST_ERROR_RETURN_IF_NOT(idx < pSigInfo->nDocs, ERR_BAD_DOCINFO_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigInfo->pDocs, NULL);
  RETURN_OBJ_IF_NULL(pSigInfo->pDocs[idx], NULL);
  return pSigInfo->pDocs[idx];
}

//============================================================
// Returns the last DocInfo
// pSigInfo - signature info pointer
// idx - DocInfo index
//============================================================
EXP_OPTION DocInfo* ddocGetLastDocInfo(const SignatureInfo* pSigInfo)
{
  int idx;

  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  idx = pSigInfo->nDocs - 1;
  SET_LAST_ERROR_RETURN_IF_NOT(idx < pSigInfo->nDocs, ERR_BAD_DOCINFO_INDEX, NULL);
  RETURN_OBJ_IF_NULL(pSigInfo->pDocs, NULL);
  RETURN_OBJ_IF_NULL(pSigInfo->pDocs[idx], NULL);
  return pSigInfo->pDocs[idx];
}

//============================================================
// Returns the DocInfo object with the given id
// pSigInfo - signature info pointer
// id - SignatureInfo id
//============================================================
EXP_OPTION DocInfo* getDocInfoWithId(const SignatureInfo* pSigInfo, const char* id)
{
  DocInfo* pDocInfo = NULL;
  int i;

  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  //RETURN_OBJ_IF_NULL(id, NULL);
  for(i = 0; i < pSigInfo->nDocs; i++) {
    RETURN_OBJ_IF_NULL(pSigInfo->pDocs[i], NULL);
    RETURN_OBJ_IF_NULL(pSigInfo->pDocs[i]->szDocId, NULL);
    if((id && !strcmp(pSigInfo->pDocs[i]->szDocId, id)) || !id) {
      pDocInfo = pSigInfo->pDocs[i];
      break;
    }
  }
  return pDocInfo;
}

//============================================================
// Sets the DocInfo objects document digest and digest type
// pDocInfo - document info pointer
// digest - digest value
// digLen - digest value length
// digType - digest type
//============================================================
EXP_OPTION void setDocInfoDigest(DocInfo* pDocInfo, const byte* digest, 
					  int digLen, const char* digType)
{
  RETURN_VOID_IF_NULL(pDocInfo);
  if(digType)
    setString(&(pDocInfo->szDigestType), digType, -1);
  if(digest) {
    setString((char**)&(pDocInfo->szDigest), (const char*)digest, digLen);
    pDocInfo->nDigestLen = digLen;
  }
}

//============================================================
// Sets the DocInfo objects mime digest and mime type
// pDocInfo - document info pointer
// mimeDig - mime digest value
// mimeDigLen - mime digest value length
//============================================================
EXP_OPTION void setDocInfoMimeDigest(DocInfo* pDocInfo, const byte* mimeDig, 
					  int mimeDigLen)
{
  RETURN_VOID_IF_NULL(pDocInfo);
  if(mimeDig) {
    setString((char**)&(pDocInfo->szMimeDigest), (const char*)mimeDig, mimeDigLen);
    pDocInfo->nMimeDigestLen = mimeDigLen;
  }
}

//============================================================
// Adds all DocInfo elements in this file to a SignatureInfo element
// pSigInfo - signature info object
// pSigDoc - signed document
//============================================================
EXP_OPTION int addAllDocInfos(SignedDoc* pSigDoc, SignatureInfo* pSigInfo)
{
  int i, c, l2;
  int len = 0;
  //Added by AA 28/10/2003 - not defined len value
  DataFile *pDf = NULL;
  DocInfo  *pDocInfo = NULL;
  byte buf[DIGEST_LEN+2], buf2[50];
  
  RETURN_IF_NULL_PARAM(pSigDoc);
  RETURN_IF_NULL_PARAM(pSigInfo);
  c = getCountOfDataFiles(pSigDoc);
  for(i = 0; i < c; i++ ) {
    pDf = getDataFile(pSigDoc, i);
    RETURN_IF_NULL(pDf);
    buf[0] = 0;
    // in version 1.0 we use mime digest
    if(!strcmp(pSigDoc->szFormatVer, SK_XML_1_VER) && !strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) {
      len = sizeof(buf);
      calculateDigest((const byte*)pDf->szMimeType, strlen(pDf->szMimeType), 
		      DIGEST_SHA1, buf, &len);
    }
    // in 1.1 we don't use mime digest
	memset(buf2, 0, sizeof(buf2));
    l2 = 0;
    encode((const byte*)pDf->mbufDigest.pMem, pDf->mbufDigest.nLen, (byte*)buf2, &l2);
	ddocDebug(3, "addAllDocInfos", "DF: %s digest \'%s\'", pDf->szId, buf2);
    addDocInfo(&pDocInfo, pSigInfo, pDf->szId,
	       pDf->szDigestType, (byte*)pDf->mbufDigest.pMem,
	       pDf->mbufDigest.nLen, buf, len);
  }
  return ERR_OK;
}

//============================================================
// Calculates and stores a signature for this SignatureInfo object
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSigInfoSignature(const SignedDoc* pSigDoc, 
					 SignatureInfo* pSigInfo, int nSigType, 
					 const char* keyfile, const char* passwd, 
					 const char* certfile)
{
  int err = ERR_OK;
  char buf2[SIGNATURE_LEN], *buf1 = NULL;
  int l2, l1;
  X509 *pCert = 0;

  RETURN_IF_NULL_PARAM(pSigInfo);
  clearErrors();
  if(nSigType == SIGNATURE_RSA) {
    err = ddocSignatureValue_new(&(pSigInfo->pSigValue), 0, SIGN_RSA_NAME, 0, 0);
    if(err) return err;

    err = ReadCertificate(&pCert, certfile);
    if(!err && pCert)
      err = ddocSigInfo_SetSignersCert(pSigInfo, pCert);
    RETURN_IF_NOT(err == ERR_OK, ERR_CERT_READ);
    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    RETURN_IF_NULL(buf1);
    l1 = strlen(buf1);
    l2 = sizeof(buf2);
    calculateDigest((const byte*)buf1, l1, DIGEST_SHA1, (byte*)buf2, &l2);
    free(buf1);
    err = ddocSigInfo_SetSigPropDigest(pSigInfo, buf2, l2);
    // SignedInfo digest
    buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);
    RETURN_IF_NULL(buf1);
    l2 = sizeof(buf2);
    err = signData((const byte*)buf1, strlen(buf1), (byte*)buf2, &l2, DIGEST_SHA1,
		   keyfile, passwd);
    free(buf1);
    err = ddocSigInfo_SetSignatureValue(pSigInfo, buf2, l2);
  } else
    err = ERR_UNSUPPORTED_SIGNATURE;
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}

//============================================================
// Calculates <SignedProperties> digest
// pSigInfo - signature info object
//============================================================
EXP_OPTION int calculateSignedPropertiesDigest(SignedDoc* pSigDoc, SignatureInfo* pSigInfo)
{
  int err = ERR_OK, l1, l2;
  byte buf1[DIGEST_LEN256+2], *buf2 = 0, *buf3 = 0;

  RETURN_IF_NULL_PARAM(pSigInfo);
  /* P.R 0->1 */
  buf2 = (byte*)createXMLSignedProperties(pSigDoc, pSigInfo, 1);
  RETURN_IF_NULL(buf2);
  buf3 = canonicalizeXML((char*)buf2, strlen((const char*)buf2));
  //dumpInFile("sigprop-sig1.txt", buf2);
  l2 = (int)strlen((const char*)buf3);
  l1 = (int)sizeof(buf1);
  calculateDigest(buf3, l2, DIGEST_SHA1, buf1, &l1);
  free(buf2);
  free(buf3);
  err = ddocSigInfo_SetSigPropDigest(pSigInfo, (char*)buf1, l1);
  return err;
}

//============================================================
// Returns 1 if this signature has 1 reference that was verified
// by wrong DataFile hash calculated not using xmlns atribute
// pSigInfo - signature info pointer
//============================================================
EXP_OPTION int verifiedByWrongDataFileHash(const SignatureInfo* pSigInfo)
{
    int i;
    
    RETURN_IF_NULL_PARAM(pSigInfo);
    for(i = 0; i < pSigInfo->nDocs; i++) {
        RETURN_IF_NULL_PARAM(pSigInfo->pDocs[i]);
        if(pSigInfo->pDocs[i] && pSigInfo->pDocs[i]->szDigestType &&
           !strcmp(pSigInfo->pDocs[i]->szDigestType, DIGEST_SHA1_WRONG))
            return 1;
    }
    return 0;
}

//============================================================
// Returns 1 if one signature has 1 reference that was verified
// by wrong DataFile hash calculated not using xmlns atribute
// pSigDoc - signed doc container pointer
//============================================================
EXP_OPTION int hasSignatureWithWrongDataFileHash(const SignedDoc* pSigDoc)
{
    int i, d, j;
    SignatureInfo *pSigInfo = 0;
    
    RETURN_IF_NULL_PARAM(pSigDoc);
    d = getCountOfSignatures(pSigDoc);
    for(i = 0; i < d; i++) {
        pSigInfo = getSignature(pSigDoc, i);
        j = verifiedByWrongDataFileHash(pSigInfo);
        if(j) return j;
    }
    return 0;
}

//============================================================
// Calculates <SignedInfo> digest
// pSigInfo - signature info object
// digBuf - buffer for digest value
// digLen - address of buffer length. Must be initialized
// with buf max len, will be changed to actual length
//============================================================
EXP_OPTION int calculateSignedInfoDigest(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, byte* digBuf, int* digLen)
{
  int err = ERR_OK, l2;
  byte *buf2 = NULL;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(digBuf);
  buf2 = (byte*)createXMLSignedInfo(pSigDoc, pSigInfo);      
  RETURN_IF_NULL(buf2);
  l2 = strlen((const char*)buf2);
	calculateDigest(buf2, l2, DIGEST_SHA1, digBuf, digLen);
  free(buf2);
  return err;
}

//============================================================
// Sets the signature value from a file that contains
// the base64 encoded signature value
// pSigInfo - signature info object
// szSigFile - filename
//============================================================
EXP_OPTION int setSignatureValueFromFile(SignatureInfo* pSigInfo, char* szSigFile)
{
  int err = ERR_OK, i, j, slen;
  FILE* hFile = 0;
  byte buf[FILE_BUFSIZE], sbuf[300], buf1[30];
  DigiDocMemBuf mbuf1;
  char *p1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(szSigFile);
  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  ddocDebug(3, "setSignatureValueFromFile", "reading: %s", szSigFile);
  if((hFile = fopen(szSigFile, "rb")) != NULL) {
    slen = 0;
    memset(sbuf, 0, sizeof(sbuf));
    // collect all hex chars to sbuf
    while((i = fread(buf, sizeof(char), FILE_BUFSIZE, hFile)) > 0) {
		ddocDebug(3, "setSignatureValueFromFile", "read: %d", i);
      for(j = 0; j < i; j++) {
        if(isxdigit(buf[j])) {
          if(isdigit(buf[j])) {
	    sbuf[slen++] = buf[j];
          } else {
            sbuf[slen++] = toupper(buf[j]);
	  } // else
	} // if
      } // for
    }
    ddocDebug(3, "setSignatureValueFromFile", "input: %d - \'%s\'", slen, sbuf);
    // decode hex
    memset(buf, 0, sizeof(buf));
    j = 0;
    hex2bin((const char*)sbuf, (byte*)buf, &j);
	ddocDebug(3, "setSignatureValueFromFile", "decoded: %d", j);
    // encode in base64 again as we need it this way for signature value
    memset(sbuf, 0, sizeof(sbuf));
    slen = 0;
    encode((const byte*)buf, j, (byte*)sbuf, &slen);
	ddocDebug(3, "setSignatureValueFromFile", "encoded: %d - \'%s\'", slen, sbuf);
    if(j == SIGNATURE_LEN) {
      snprintf((char*)buf1, sizeof(buf1), "#%s-SIG", pSigInfo->szId);
      ddocSignatureValue_new(&(pSigInfo->pSigValue), (char*)buf1, SIGN_RSA_NAME, (char*)buf, j);
      //ddocMemBuf_free(&(pSigInfo->mbufOrigContent));
      if(pSigInfo->mbufOrigContent.pMem) {
        p1 = strstr((char*)pSigInfo->mbufOrigContent.pMem, "<SignatureValue");
        if(p1) p1 = strchr(p1, '>');
        if(p1) p1++;
        if(p1) *p1 = 0;
        if(p1) {
          ddocMemAssignData(&mbuf1, (char*)pSigInfo->mbufOrigContent.pMem, -1);
          ddocMemAppendData(&mbuf1, (char*)sbuf, -1);
          p1++;
		  //ddocDebug(3, "setSignatureValueFromFile", "add: %s", p1);
          ddocMemAppendData(&mbuf1, p1, -1);
        }
        ddocMemAssignData(&(pSigInfo->mbufOrigContent), (const char*)mbuf1.pMem, mbuf1.nLen);
        ddocMemBuf_free(&mbuf1);
      }
    }
    else
      err = ERR_SIGNATURE;
    fclose(hFile);
  }
  else
    err = ERR_FILE_READ;
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}

//============================================================
// Sets the signature value 
// pSigInfo - signature info object
// szSignature - signature value
// sigLen - signature length
//============================================================
EXP_OPTION int setSignatureValue(SignatureInfo* pSigInfo, byte* szSignature, int sigLen)
{
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(szSignature);
	
  //clearErrors();
  // VS: not quite sure if there's not a second constant to use instead of removing the check
  //RETURN_IF_NOT(sigLen == SIGNATURE_LEN, ERR_SIGNATURE);
  ddocSignatureValue_new(&(pSigInfo->pSigValue), 0, SIGN_RSA_NAME, szSignature, sigLen);
  ddocMemBuf_free(&(pSigInfo->mbufOrigContent));
  return ERR_OK;
}


//=====================< NotaryInfo >======================================


//============================================================
// Returns the number of notary infos
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getCountOfNotaryInfos(const SignedDoc* pSigDoc)
{
  int n = 0, i = 0;
  SignatureInfo* pSigInfo = 0;
  RETURN_OBJ_IF_NULL(pSigDoc, -1);
  for(i = 0; i < getCountOfSignatures(pSigDoc); i++) {
    pSigInfo = getSignature(pSigDoc, i);
    if(pSigInfo->pNotary)
      n++;
  }
  return n;
}

//============================================================
// Returns the next free notary id
// pSigDoc - signed doc pointer
//============================================================
EXP_OPTION int getNextNotaryId(const SignedDoc* pSigDoc)
{
  int id = 0, n, i;
  SignatureInfo* pSigInfo = 0;
  
  RETURN_OBJ_IF_NULL(pSigDoc, -1);
  for(i = 0; i < getCountOfSignatures(pSigDoc); i++) {
    pSigInfo = getSignature(pSigDoc, i);
    if(pSigInfo->pNotary && pSigInfo->pNotary->szId) {
      n = atoi(pSigInfo->pNotary->szId+1);
      if(id <= n)
	id = n+1;
    }
  }
  return id;
}

//============================================================
// Returns the desired NotaryInfo object
// pSigDoc - signed doc pointer
// nIdx - NotaryInfo index (starting with 0)
//============================================================
EXP_OPTION NotaryInfo* getNotaryInfo(const SignedDoc* pSigDoc, int nIdx)
{
  SignatureInfo* pSigInfo = 0;
  NotaryInfo* pNotInfo = 0;
  int n = 0, i = 0;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  for(i = 0; i < getCountOfSignatures(pSigDoc); i++) {
    pSigInfo = getSignature(pSigDoc, i);
    if(pSigInfo->pNotary) {
      n++;
      if(n == nIdx) {
	pNotInfo = pSigInfo->pNotary;
	break;
      }
    }
  }
  return pNotInfo;
}

//============================================================
// Returns the last NotaryInfo object
// pSigDoc - signed doc pointer
// nIdx - NotaryInfo index (starting with 0)
//============================================================
EXP_OPTION NotaryInfo* ddocGetLastNotaryInfo(const SignedDoc* pSigDoc)
{
  SignatureInfo* pSigInfo;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  pSigInfo = ddocGetLastSignature(pSigDoc);
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return pSigInfo->pNotary;
}

//============================================================
// Returns the NotaryInfo object with the given id
// pSigDoc - signed doc pointer
// id - NotaryInfo id
//============================================================
EXP_OPTION NotaryInfo* getNotaryWithId(const SignedDoc* pSigDoc, const char* id)
{
  SignatureInfo* pSigInfo = 0;
  int i = 0;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  for(i = 0; i < getCountOfSignatures(pSigDoc); i++) {
    pSigInfo = getSignature(pSigDoc, i);
    if(pSigInfo->pNotary && pSigInfo->pNotary->szId &&
       !strcmp(pSigInfo->pNotary->szId, id)) {
      return pSigInfo->pNotary;
    }
  }
  return NULL;
}

//============================================================
// Returns the NotaryInfo object that corresponds to the given signature
// pSigDoc - signed doc pointer
// id - NotaryInfo id
//============================================================
NotaryInfo* getNotaryWithSigId(const SignedDoc* pSigDoc, const char* sigId)
{
  SignatureInfo* pSigInfo = NULL;

  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  RETURN_OBJ_IF_NULL(sigId, NULL);
  pSigInfo = getSignatureWithId(pSigDoc, sigId);
  RETURN_OBJ_IF_NULL(pSigInfo, NULL);
  return pSigInfo->pNotary;
}

//============================================================
// Returns the NotaryInfo object that corresponds to the given signature
// ore creates a new one
// pSigDoc - signed doc pointer
// id - SignatureInfo id
//============================================================
NotaryInfo* getOrCreateNotaryWithSigId(SignedDoc* pSigDoc, const char* sigId)
{
  NotaryInfo* pNotary = 0;
  SignatureInfo* pSigInfo = 0;
  RETURN_OBJ_IF_NULL(pSigDoc, NULL);
  RETURN_OBJ_IF_NULL(sigId, NULL);
  pNotary = getNotaryWithSigId(pSigDoc, sigId);
  if(!pNotary) {
    pSigInfo = getSignatureWithId(pSigDoc, sigId);
    RETURN_OBJ_IF_NULL(pSigInfo, NULL);
    NotaryInfo_new(&pNotary, pSigDoc, pSigInfo);
  }
  return pNotary;
}


//============================================================
// Adds a new Notary element to a SignedDoc element and 
// initializes it partly
// pSigInfo - signature object to be verified by this notary
// return the newly created structure
//============================================================
EXP_OPTION int NotaryInfo_new(NotaryInfo **newNotaryInfo, SignedDoc* pSigDoc, SignatureInfo* pSigInfo)
{
  int n;
  char buf[10];

  RETURN_IF_NULL_PARAM(pSigDoc);
  RETURN_IF_NULL_PARAM(pSigInfo);
  // get next notary id
  if (pSigInfo) {
    strncpy(buf, pSigInfo->szId, sizeof(buf));
    buf[0] = 'N';
    // make sure we reset the szOrigContent on this signature
    // otherwise the new confirmation will not be written to file!
    ddocMemBuf_free(&(pSigInfo->mbufOrigContent));
  } else {
    n = getNextNotaryId(pSigDoc);
    RETURN_IF_NOT(n >= 0, ERR_BAD_NOTARY_ID);
    snprintf(buf, sizeof(buf), "N%d", n);
  }
  // memory management
  pSigInfo->pNotary = (NotaryInfo*)malloc(sizeof(NotaryInfo));  // MEMLEAK:  ???
  if (!pSigInfo->pNotary)
    RETURN_IF_BAD_ALLOC(pSigInfo->pNotary);
  memset(pSigInfo->pNotary, 0, sizeof(NotaryInfo));
  // set id	
  setString(&(pSigInfo->pNotary->szId), buf, -1);
  // version
  setString(&(pSigInfo->pNotary->szNotType), SK_NOT_VERSION, -1);
  
  *newNotaryInfo = pSigInfo->pNotary;
  return ERR_OK;
}

//============================================================
// cleanup NotaryInfo memory
// pNotary - object to be cleaned up
//============================================================
EXP_OPTION void NotaryInfo_free(NotaryInfo* pNotary)
{
  RETURN_VOID_IF_NULL(pNotary);
  //assert(pNotary);
  if(pNotary->szId)
    free(pNotary->szId);
  if(pNotary->szNotType)
    free(pNotary->szNotType);
  if(pNotary->timeProduced)
    free(pNotary->timeProduced);
  if(pNotary->szProducedAt)
    free(pNotary->szProducedAt);
  ddocMemBuf_free(&(pNotary->mbufRespId));
  if(pNotary->szDigestType)
    free(pNotary->szDigestType);
  if(pNotary->szSigType)
    free(pNotary->szSigType);
  ddocMemBuf_free(&(pNotary->mbufOcspDigest));
  ddocMemBuf_free(&(pNotary->mbufOcspResponse));
  // free the object itself
  free(pNotary);
}

//============================================================
// Returns OCSP responders id as in XML document
// pNotary - Notary info
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
EXP_OPTION const DigiDocMemBuf* ddocNotInfo_GetResponderId(const NotaryInfo* pNotary)
{
  RETURN_OBJ_IF_NULL(pNotary, NULL);
  return &(pNotary->mbufRespId);
}

//============================================================
// Returns OCSP responders id value as string
// pNotary - Notary info
// return responder id value or NULL
//============================================================
EXP_OPTION const char* ddocNotInfo_GetResponderId_Value(const NotaryInfo* pNotary)
{
  RETURN_OBJ_IF_NULL(pNotary, NULL);
  return (const char*)pNotary->mbufRespId.pMem;
}

//============================================================
// Sets OCSP responders id as in XML document
// pNotary - Notary info
// data - new responder id value
// len - length of value
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
int ddocNotInfo_SetResponderId(NotaryInfo* pNotary, const char* data, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(data);
  err = ddocMemAssignData(&(pNotary->mbufRespId), data, len);
  return err;
}

//============================================================
// Returns OCSP response as memory buffer
// pNotary - Notary info
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
const DigiDocMemBuf* ddocNotInfo_GetOCSPResponse(const NotaryInfo* pNotary)
{
  RETURN_OBJ_IF_NULL(pNotary, NULL);
  return &(pNotary->mbufOcspResponse);
}

//============================================================
// Retrieves OCSP responses responder id type and value
// pResp - OCSP response
// pType - buffer for type
// pMbufRespId - responder id
// returns error code or ERR_OK
//============================================================
int ddocGetOcspRespIdTypeAndValue(OCSP_RESPONSE* pResp, 
				int *pType, DigiDocMemBuf* pMbufRespId)
{
  int err = ERR_OK;
  OCSP_BASICRESP *br = NULL;
  
  const X509_NAME *name = NULL;
  const ASN1_OCTET_STRING *id = NULL;
  RETURN_IF_NULL_PARAM(pResp);
  RETURN_IF_NULL_PARAM(pType);
  RETURN_IF_NULL_PARAM(pMbufRespId);
  if((br = OCSP_response_get1_basic(pResp)) == NULL) 
    SET_LAST_ERROR_RETURN_CODE(ERR_OCSP_NO_BASIC_RESP);
  if(!err && br) {
	OCSP_resp_get0_id(br, &id, &name);
	if(name) {
	  *pType = RESPID_NAME_TYPE;
	  ddocMemSetLength(pMbufRespId, 300);
        //X509_NAME_oneline(br->tbsResponseData->responderId->value.byName, (char*)pMbufRespId->pMem, pMbufRespId->nLen);
		//AM 26.09.08
		err = ddocCertGetDNFromName((X509_NAME*)name, pMbufRespId);
		//RETURN_IF_NOT(err == ERR_OK, err);
	} else if(id) {
	  *pType = RESPID_KEY_TYPE;
	  err = ddocMemAssignData(pMbufRespId, (const char*)id->data, id->length);
	} else {
        SET_LAST_ERROR(ERR_OCSP_WRONG_RESPID);
    }
  }
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Sets OCSP respondese value as in XML document. Must pass in
// binary DER data!
// pNotary - Notary info
// data - new responder id value
// len - length of value
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
int ddocNotInfo_SetOCSPResponse(NotaryInfo* pNotary, const char* data, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(data);
  err = ddocMemAssignData(&(pNotary->mbufOcspResponse), data, len);
  return err;
}

//============================================================
// Returns OCSP response value
// pNotary - Notary info
// return OCSP_RESPONSE pointer or NULL for error. Caller must
//    use OCSP_RESPONSE_free() to release it.
//============================================================
OCSP_RESPONSE* ddocNotInfo_GetOCSPResponse_Value(const NotaryInfo* pNotary)
{
  OCSP_RESPONSE* pResp = NULL;

  RETURN_OBJ_IF_NULL(pNotary, NULL);
  RETURN_OBJ_IF_NULL(pNotary->mbufOcspResponse.pMem, NULL);
  ddocOcspReadOcspResp(&pResp, (DigiDocMemBuf*)&(pNotary->mbufOcspResponse));
  return pResp;
}

//============================================================
// Sets OCSP respondese value. Must pass in real OCSP_RESPONSE
// pNotary - Notary info
// data - new responder id value
// len - length of value
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
int ddocNotInfo_SetOCSPResponse_Value(NotaryInfo* pNotary, OCSP_RESPONSE* pResp)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pResp);
  err = ddocOcspWriteOcspResp(pResp, (DigiDocMemBuf*)&(pNotary->mbufOcspResponse));
  return err;
}

//============================================================
// Helper function to get OCSP response parts
// pNotary - notary object
// ppResp - adr for OCSP_RESPONSE - must free!
// ppBasResp - adr for OCSP_BASICRESP - don't free
// ppSingle - optional adr for OCSP_SINGLERESP - don't free
//============================================================
int ddocNotInfo_GetBasicResp(const NotaryInfo* pNotary, OCSP_RESPONSE **ppResp,
			     OCSP_BASICRESP **ppBasResp, OCSP_SINGLERESP **ppSingle)
{
  int err = ERR_OK;

  // check input
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(ppResp);
  RETURN_IF_NULL_PARAM(ppBasResp);
  // single response retrieval is optional - don't check it
  *ppResp = ddocNotInfo_GetOCSPResponse_Value(pNotary);
  if(*ppResp && ppBasResp) {
    *ppBasResp = OCSP_response_get1_basic(*ppResp);
    if(*ppBasResp) {
	  if(ppSingle)
		*ppSingle = OCSP_resp_get0(*ppBasResp, 0);
    }
    else
      return ERR_OCSP_NO_BASIC_RESP;
  }
  return err;
}

//============================================================
// Returns OCSP responders id type as string
// pNotary - Notary info
// return responder id type or NULL. DO NOT free() it!
//============================================================
EXP_OPTION const char* ddocNotInfo_GetResponderId_Type(const NotaryInfo* pNotary)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  const ASN1_OCTET_STRING *id = NULL;
  const X509_NAME *name = NULL;
  char *p1 = RESPID_NAME_VALUE; // default value is name - usefull in format 1.0 where we had no good OCSP response

  RETURN_OBJ_IF_NULL(pNotary, NULL);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, NULL);
  if(!err && br) {
	OCSP_resp_get0_id(br, &id, &name);
	if(name)
		p1 = RESPID_NAME_VALUE;
	else if(id)
		p1 = RESPID_KEY_VALUE;
	else
      SET_LAST_ERROR(ERR_OCSP_WRONG_RESPID);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return p1;
}

//============================================================
// Returns OCSP responses thisUpdate atribute as string
// pNotary - Notary info
// pMBuf - buffer for thisUpdate value
// return error code OR ERR_OK.
//============================================================
EXP_OPTION int ddocNotInfo_GetThisUpdate(const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  ASN1_GENERALIZEDTIME *thisUpdate = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);
  if(!err && br && single) {
    err = ddocMemSetLength(pMBuf, 50);
	OCSP_single_get0_status(single, NULL, NULL, &thisUpdate, NULL);
	ddocDebug(3, "ddocNotInfo_GetThisUpdate", "This update: %s", thisUpdate);
	if(!err && thisUpdate)
	  err = asn1time2str(NULL, thisUpdate, (char*)pMBuf->pMem, pMBuf->nLen);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}


//============================================================
// Returns OCSP responses thisUpdate atribute as time_t
// pNotary - Notary info
// pTime - address of time_t variable
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetThisUpdate_timet(const NotaryInfo* pNotary, time_t* pTime)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  ASN1_GENERALIZEDTIME *thisUpdate = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pTime);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);
  if(!err && br && single) {
	OCSP_single_get0_status(single, NULL, NULL, &thisUpdate, NULL);
	if(!err && thisUpdate)
	  err = asn1time2time_t_local(thisUpdate, pTime);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP responses producedAt atribute as time_t
// pNotary - Notary info
// pTime - address of time_t variable
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetProducedAt_timet(const NotaryInfo* pNotary, time_t* pTime)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  const ASN1_GENERALIZEDTIME *producedAt = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pTime);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, NULL);
  producedAt = OCSP_resp_get0_produced_at(br);
  if(!err && br && producedAt) {
	err = asn1time2time_t_local((ASN1_GENERALIZEDTIME*)producedAt, pTime);
  }
	//AM 22.06.08 lets free br too
	if(br)
		OCSP_BASICRESP_free(br);
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  return err;
}

//============================================================
// Returns OCSP responses producedAt from xml as time_t
// pNotary - Notary info
// pTime - address of time_t variable
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetProducedAtXml_timet(const NotaryInfo* pNotary, time_t* pTime)
{
  int err = ERR_OK;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pTime);
  if(!err && pNotary->szProducedAt) {
    err = str2time_t(pNotary->szProducedAt, pTime);
  }
  return err;
}

//============================================================
// Returns OCSP responses nextUpdate atribute as string
// pNotary - Notary info
// pMBuf - buffer for nextUpdate value
// return error code OR ERR_OK.
//============================================================
EXP_OPTION int ddocNotInfo_GetNextUpdate(const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  ASN1_GENERALIZEDTIME *nextUpdate = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);
  if(!err && br && single) {
    err = ddocMemSetLength(pMBuf, 50);
	OCSP_single_get0_status(single, NULL, NULL, NULL, &nextUpdate);
	if(!err && nextUpdate)
	  err = asn1time2str(NULL, nextUpdate, (char*)pMBuf->pMem, pMBuf->nLen);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP responses IssuerNameHash atribute
// pNotary - Notary info
// pMBuf - buffer for IssuerNameHash value
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetIssuerNameHash(const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  ASN1_OCTET_STRING *issuerNameHash = NULL;
  const OCSP_CERTID *cid = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);
  if(!err && br) {
	cid = OCSP_SINGLERESP_get0_id(OCSP_resp_get0(br, 0));
	OCSP_id_get0_info(&issuerNameHash, NULL, NULL, NULL, (OCSP_CERTID*)cid);
	err = ddocMemAssignData(pMBuf, (const char*)issuerNameHash->data,
				issuerNameHash->length);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP responses IssuerKeyHash atribute
// pNotary - Notary info
// pMBuf - buffer for IssuerKeyHash value
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetIssuerKeyHash(const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  ASN1_OCTET_STRING *issuerKeyHash = NULL;
  const OCSP_CERTID *cid = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);

  if(!err && br) {
	cid = OCSP_SINGLERESP_get0_id(OCSP_resp_get0(br, 0));
	OCSP_id_get0_info(NULL, NULL, &issuerKeyHash, NULL, (OCSP_CERTID*)cid);
	err = ddocMemAssignData(pMBuf, (const char*)issuerKeyHash->data,
				issuerKeyHash->length);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP responses real digest from response data
// pNotary - Notary info
// pMBuf - buffer for digest value
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetOcspRealDigest(const SignedDoc* pSigDoc, const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK, nIdx = 0, l1 = 0, l2 = 0, nCheckOcspLen = 0;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  OCSP_SINGLERESP *single = NULL;
  X509_EXTENSION *ext = NULL;
  ASN1_OCTET_STRING *value = NULL;
  byte* p = 0, buf2[DIGEST_LEN256 * 2 + 2];
    
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, &single);
  nCheckOcspLen = ConfigItem_lookup_bool("CHECK_OCSP_NONCE", 0);
  if(!err && br) {
    nIdx = OCSP_BASICRESP_get_ext_by_NID(br, NID_id_pkix_OCSP_Nonce, -1);
    if(nIdx >= 0) {
        ext = OCSP_BASICRESP_get_ext(br, nIdx);
        if(ext != NULL) {
			value = X509_EXTENSION_get_data(ext);
			int l1 = ASN1_STRING_length(value);
			p = ASN1_STRING_data(value);
            if(l1 > 20 && p[0] == V_ASN1_OCTET_STRING && p[1] == l1-2)
              err = ddocMemAssignData(pMBuf, (const char*)p+2, l1-2);
            else
              err = ddocMemAssignData(pMBuf, (const char*)p, l1);
            // debug
            l2 = sizeof(buf2);
            memset(buf2, 0, l2);
            if(l1 <= DIGEST_LEN256) {
               bin2hex((const byte*)p, l1, (byte*)buf2, &l2);  
               ddocDebug(3, "ddocNotInfo_GetOcspRealDigest", "Not: %s nonce: %s len: %d err: %d", 
                          pNotary->szId, buf2, l1, err);
            }
            if(l1 != 22 && nCheckOcspLen && pSigDoc && strcmp(pSigDoc->szFormat, SK_XML_1_NAME)) {
                ddocDebug(1, "ddocNotInfo_GetOcspRealDigest", "Not: %s invalid nonce: %s len: %d err: %d", 
                          pNotary->szId, buf2, l1, err);
                err = ERR_OCSP_NONCE_INVALID;
            }
        }
    }
    else
      err = ERR_OCSP_NO_NONCE;
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP responses signature value
// pNotary - Notary info
// pMBuf - buffer for signature value
// return error code OR ERR_OK.
//============================================================
int ddocNotInfo_GetOcspSignatureValue(const NotaryInfo* pNotary, DigiDocMemBuf* pMBuf)
{
  int err = ERR_OK;
  OCSP_RESPONSE *pResp = 0;
  OCSP_BASICRESP *br = NULL;
  const ASN1_OCTET_STRING *signature = NULL;

  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(pMBuf);
  err = ddocNotInfo_GetBasicResp(pNotary, &pResp, &br, NULL);
  if(!err && br) {
	signature = OCSP_resp_get0_signature(br);
	err = ddocMemAssignData(pMBuf, (const char*)signature->data,
				signature->length);
  }
  if(pResp)
    OCSP_RESPONSE_free(pResp);
  // PR. leak found
  if(br)
    OCSP_BASICRESP_free(br);
  return err;
}

//============================================================
// Returns OCSP response digest as in XML document
// pNotary - Notary info
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
EXP_OPTION const DigiDocMemBuf* ddocNotInfo_GetOcspDigest(const NotaryInfo* pNotary)
{
  RETURN_OBJ_IF_NULL(pNotary, NULL);
  return &(pNotary->mbufOcspDigest);
}

//============================================================
// Sets OCSP response digest id as in XML document
// pNotary - Notary info
// data - new digest value
// len - length of value
// return DigiDocMemBuf buffer pointer or NULL for error
//============================================================
int ddocNotInfo_SetOcspDigest(NotaryInfo* pNotary, const char* data, long len)
{
  int err = ERR_OK;
  RETURN_IF_NULL_PARAM(pNotary);
  RETURN_IF_NULL_PARAM(data);
  err = ddocMemAssignData(&(pNotary->mbufOcspDigest), data, len);
  return err;
}



//============================================================
// Adds a certificate to Notary and initializes Notary
// pNotary - Notary info
// cert - responders certificate
// return error code
//============================================================
int addNotaryInfoCert(SignedDoc *pSigDoc, NotaryInfo *pNotary, X509 *cert)
{
  int err = ERR_OK, n;
  char buf[300];
  CertID* pCertID = 0;
  SignatureInfo* pSigInfo = 0;
  DigiDocMemBuf mbuf1;

  mbuf1.pMem = 0;
  mbuf1.nLen = 0;
  ddocDebug(3, "addNotaryInfoCert", "adding cert: %s to notary: %s", (cert ? "OK" : "NULL"), pNotary->szId);
  RETURN_IF_NULL_PARAM(pNotary);
  pSigInfo = ddocGetSignatureForNotary(pSigDoc, pNotary);
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(cert);
  RETURN_IF_NOT(err == ERR_OK, err);
  if(!ddocSigInfo_GetOCSPRespondersCert(pSigInfo))
	err = ddocSigInfo_SetOCSPRespondersCert(pSigInfo, cert);
  buf[0] = 0;
  err = ReadCertSerialNumber(buf, sizeof(buf), cert);
  if(strlen(buf)){
    pCertID = ddocCertIDList_GetCertIDOfSerial(pSigInfo->pCertIDs, buf);
  }
  if(!pCertID)
    pCertID = ddocSigInfo_GetOrCreateCertIDOfType(pSigInfo, CERTID_TYPE_RESPONDERS_CERTID);
  else //AM quick fix for smartlink bdoc
	if(pCertID->nType==0)pCertID->nType = CERTID_TYPE_RESPONDERS_CERTID;
  RETURN_IF_NULL(pCertID);
  ddocCertID_SetIssuerSerial(pCertID, buf);
  n = sizeof(buf);
  memset(buf, 0, sizeof(buf));
  n = 40;
  RETURN_IF_NOT(X509_digest(cert, EVP_sha1(), (unsigned char*)buf, (unsigned int*)&n), ERR_X509_DIGEST);
  if(!pCertID->pDigestValue)
    ddocCertID_SetDigestValue(pCertID, (const char*)buf, n);
  ddocCertGetSubjectDN(cert, &mbuf1);
  ddocCertID_SetIssuerName(pCertID, (char*)mbuf1.pMem);
  ddocMemBuf_free(&mbuf1);
  snprintf(buf, sizeof(buf), "%s-RESPONDER_CERTINFO", pSigInfo->szId);
  ddocCertID_SetId(pCertID, buf);
  ddocDebug(4, "addNotaryInfoCert", "cert: %s to notary: %s", (cert ? "OK" : "NULL"), pNotary->szId, err);
  return err;
}


//============================================================
// Removes Notary cert value and id after unsucessful verification attempt
// pSigInfo - signature info [REQUIRED]
// return error code
//============================================================
int removeNotaryInfoCert(SignatureInfo* pSigInfo)
{
  CertID* pCertID;
  CertValue* pCertVal;
  int i;

  RETURN_IF_NULL_PARAM(pSigInfo);
  // remove cert values of type responder
  for(i = 0; i < ddocCertValueList_GetCertValuesCount(pSigInfo->pCertValues); i++) {
	  pCertVal = ddocCertValueList_GetCertValue(pSigInfo->pCertValues, i);
	  if(pCertVal && pCertVal->nType == CERTID_VALUE_RESPONDERS_CERT)
        ddocCertValueList_DeleteCertValue(pSigInfo->pCertValues, i);
  }
  // remove cert ids of type responder
  for(i = 0; i < ddocCertIDList_GetCertIDsCount(pSigInfo->pCertIDs); i++) {
	  pCertID = ddocCertIDList_GetCertID(pSigInfo->pCertIDs, i);
	  if(pCertID && pCertID->nType == CERTID_TYPE_RESPONDERS_CERTID)
        ddocCertIDList_DeleteCertID(pSigInfo->pCertIDs, i);
  }
  return ERR_OK;
}

//============================================================
// Adds a new Notary SignedInfo element to a SignedDoc 
//   element and initializes it
// newNotaryInfo - newly created structure
// pSigDoc - signed doc data
// pSigInfo - signature object to be verified by this notary
// ocspRespFile - OCSP response file name
// notaryCertFile - Notary cert file name
// returns error code or ERR_OK if no error.
//============================================================
// FIXME : What to do if initializeNotaryInfoWithOCSP fails?
EXP_OPTION int NotaryInfo_new_file(NotaryInfo **newNotaryInfo, SignedDoc *pSigDoc,
					 const SignatureInfo *pSigInfo, const char *ocspRespFile,
					 const char *notaryCertFile)

{
  OCSP_RESPONSE* resp;
  X509* notCert;
  NotaryInfo* pNotInf = NULL;
  int err = ERR_OK;
	
  RETURN_IF_NULL_PARAM(pSigDoc);
  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(ocspRespFile);
  RETURN_IF_NULL_PARAM(notaryCertFile);
  err = ReadOCSPResponse(&resp, ocspRespFile);
  RETURN_IF_NOT(err == ERR_OK, ERR_FILE_READ);
  err = ReadCertificate(&notCert, notaryCertFile);
  RETURN_IF_NOT(err == ERR_OK, ERR_CERT_READ);
  err = NotaryInfo_new(&pNotInf, pSigDoc, (SignatureInfo*)pSigInfo);
  RETURN_IF_NOT(err == ERR_OK, err);
  *newNotaryInfo = pNotInf;
  err = initializeNotaryInfoWithOCSP(pSigDoc, pNotInf, resp, notCert, 1);
  RETURN_IF_NOT(err == ERR_OK, err);
  return ERR_OK;
}

// forward deklaratsioon
int notary2ocspBasResp(const SignedDoc* pSigDoc, const NotaryInfo* pNotInfo, X509* notCert, OCSP_BASICRESP** pBasResp);
int calculateOcspBasicResponseDigest(OCSP_BASICRESP* pBsResp, byte* digBuf, int* digLen);

//============================================================
// Calculates the digest of NotaryInfo
// pSigDoc - signed document pointer
// pNotInfo - notary signature info 
// digBuf - signature buffer
// digLen - signature buffer length
// returns error code
//============================================================
EXP_OPTION int calculateNotaryInfoDigest(const SignedDoc* pSigDoc, 
	const NotaryInfo* pNotInfo, byte* digBuf, int* digLen)
{
  SignatureInfo* pSigInfo;
  int err = ERR_OK;
  const DigiDocMemBuf *pMBuf = 0;

  pMBuf = ddocNotInfo_GetOCSPResponse(pNotInfo);
  RETURN_IF_NULL(pMBuf);
  pSigInfo = ddocGetSignatureForNotary(pSigDoc, pNotInfo);
  RETURN_IF_NULL_PARAM(pSigInfo);
  if(!strcmp(pNotInfo->szDigestType,DIGEST_SHA256_NAME))
    err = calculateDigest((const byte*)pMBuf->pMem, pMBuf->nLen, DIGEST_SHA256, digBuf, digLen);
  else
    err = calculateDigest((const byte*)pMBuf->pMem, pMBuf->nLen, DIGEST_SHA1, digBuf, digLen);
  if (err != ERR_OK) SET_LAST_ERROR(err);
  return err;
}

//AM 12.03.08
//--------------------------------------------------
// Sets the CA Responders certificate
// pSigInfo - signature info object [REQUIRED]
// pCert - certificate [REQUIRED]
// returns error code or ERR_OK
//--------------------------------------------------
EXP_OPTION int ddocSigInfo_SetCACert(SignatureInfo* pSigInfo, X509* pCert)
{
  int err = ERR_OK;
  CertValue *pCertValue = 0;
  char  buf1[50];

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pCert);
  pCertValue = ddocSigInfo_GetOrCreateCertValueOfType(pSigInfo, CERTID_VALUE_CA_CERT);
  if(pCertValue) {
    snprintf(buf1, sizeof(buf1), "%s-CA_CERT", pSigInfo->szId);
    err = ddocCertValue_SetId(pCertValue, buf1);
    if(!err)
      err = ddocCertValue_SetCert(pCertValue, pCert);
  }
  return err;
}

//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses PKCS#12 file to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// szPkcs12File - PKCS#12 file
// passwd - key password
//============================================================
EXP_OPTION int calculateSignatureWithPkcs12(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    const char* szPkcs12File, const char* passwd)
{
  int err = ERR_OK;
  int sigLen;
  char sigDig[100];
  char signature[256];
  char* buf1;
  int l2;
  EVP_PKEY *pkey = 0;
  X509* x509 = 0;
  EVP_MD_CTX *ctx;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  RETURN_IF_NULL_PARAM(szPkcs12File);
  ddocDebug(3, "calculateSignatureWithPkcs12", "Keystore: %s passwd-len: %d", 
	    szPkcs12File, (passwd ? strlen(passwd) : 0));
  // read pkcs12 file
  err = ReadCertificateByPKCS12(&x509, szPkcs12File, passwd, &pkey);
  RETURN_IF_NOT(err == ERR_OK, err);
  // try key-usage check
  if(ConfigItem_lookup_int("KEY_USAGE_CHECK", 1) && x509) {
	if(!ddocCertCheckKeyUsage(x509, KUIDX_NON_REPUDIATION)) {
		X509_free(x509);
		EVP_PKEY_free(pkey);
    	SET_LAST_ERROR(ERR_SIGNERS_CERT_NON_REPU);
        return ERR_SIGNERS_CERT_NON_REPU;
	}
  }
  // set signers cert
  setSignatureCert(pSigInfo, x509);
  // create signing timestamp
  createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
  setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);
  // Signed properties digest
  buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
  mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
  mbuf1.nLen = strlen((const char*)mbuf1.pMem);
  ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
  l2 = sizeof(sigDig);
  err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
  free(buf1);
  ddocMemBuf_free(&mbuf1);
  if (err != ERR_OK) {
    SET_LAST_ERROR(err);			
    return err;
  }
  ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
  ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
  // create signed info
  buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
  if (!buf1) {
    err = ERR_NULL_POINTER;
    SET_LAST_ERROR(err);
    return err ;
  }
  mbuf1.pMem = buf1; //canonicalizeXML((char*)buf1, strlen(buf1));
  mbuf1.nLen = strlen((const char*)mbuf1.pMem);
  //ddocDebugWriteFile(4, "siginf-signed.txt", &mbuf1);
  // get digest
  l2 = sizeof(sigDig);
  err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, (byte*)sigDig, &l2);
  // debug
  sigLen = sizeof(signature);
  bin2hex((const byte*)sigDig, l2, (char*)signature, &sigLen);
  sigLen = sizeof(signature);
  encode((const byte*)sigDig, l2, (char*)signature, &sigLen);
  ddocDebug(3, "calculateSignatureWithPkcs12", "Sig-inf hash b64: %s", signature);
  if (err != ERR_OK) {
    err = ERR_NULL_POINTER;
    SET_LAST_ERROR(err);
    return err;
  } 
  ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
  // sign data
  sigLen = sizeof(signature);
  memset(signature, 0, sizeof(signature));
  // sign data
  ctx = EVP_MD_CTX_new();
  EVP_SignInit(ctx, EVP_sha1());
  EVP_SignUpdate(ctx, buf1, (unsigned long)strlen(buf1));
  err = EVP_SignFinal(ctx, signature, &sigLen, pkey);
  EVP_MD_CTX_free(ctx);
  free(buf1);
  if(err == ERR_LIB_NONE)
	err = ERR_OK;
  // set signature value
  ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
  ddocDebug(3, "calculateSignatureWithPkcs12", "Sig-len: %ld", sigLen);
  //X509_free(x509);
  EVP_PKEY_free(pkey);
 
  return err;
}