aboutsummaryrefslogtreecommitdiffstats
path: root/URPM.xs
blob: a68500922b61c5b69ee39a2e8048c11d885d8137 (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
/* Copyright (c) 2002, 2003, 2004, 2005 MandrakeSoft SA
 * Copyright (c) 2005, 2006, 2007, 2008 Mandriva SA
 *
 * All rights reserved.
 * This program is free software; you can redistribute it and/or
 * modify it under the same terms as Perl itself.
 *
 * $Id: URPM.xs 259125 2009-08-10 14:37:07Z cfergeau $
 * 
 */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#include <sys/utsname.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <libintl.h>

#undef Fflush
#undef Mkdir
#undef Stat
#undef Fstat

static inline void *_free(const void * p) { 
  if (p != NULL) free((void *)p); 
  return NULL;
}
typedef struct rpmSpec_s * Spec;

#include <rpm/rpmio.h>
#include <rpm/rpmdb.h>
#include <rpm/rpmts.h>
#include <rpm/rpmte.h>
#include <rpm/rpmps.h>
#include <rpm/rpmpgp.h>
#include <rpm/rpmcli.h>
#include <rpm/rpmbuild.h>
#include <rpm/rpmlog.h>

struct s_Package {
  Header h;
  int  filesize;
  unsigned flag;
  char *info;
  char *requires;
  char *suggests;
  char *obsoletes;
  char *conflicts;
  char *provides;
  char *rflags;
  char *summary;
};

struct s_Transaction {
  rpmts ts;
  int count;
};

struct s_TransactionData {
  SV* callback_open;
  SV* callback_close;
  SV* callback_trans;
  SV* callback_uninst;
  SV* callback_inst;
  long min_delta;
  SV *data; /* chain with another data user provided */
};

typedef struct s_Transaction* URPM__DB;
typedef struct s_Transaction* URPM__Transaction;
typedef struct s_Package* URPM__Package;

#define FLAG_ID               0x001fffffU
#define FLAG_RATE             0x00e00000U
#define FLAG_BASE             0x01000000U
#define FLAG_SKIP             0x02000000U
#define FLAG_DISABLE_OBSOLETE 0x04000000U
#define FLAG_INSTALLED        0x08000000U
#define FLAG_REQUESTED        0x10000000U
#define FLAG_REQUIRED         0x20000000U
#define FLAG_UPGRADE          0x40000000U
#define FLAG_NO_HEADER_FREE   0x80000000U

#define FLAG_ID_MAX           0x001ffffe
#define FLAG_ID_INVALID       0x001fffff

#define FLAG_RATE_POS         21
#define FLAG_RATE_MAX         5
#define FLAG_RATE_INVALID     0


#define FILTER_MODE_ALL_FILES     0
#define FILTER_MODE_CONF_FILES    2

static ssize_t write_nocheck(int fd, const void *buf, size_t count) {
  return write(fd, buf, count);
}
static const void* unused_variable(const void *p) {
  return p;
}

static int rpmError_callback_data;

int rpmError_callback() {
  write_nocheck(rpmError_callback_data, rpmlogMessage(), strlen(rpmlogMessage()));
  return RPMLOG_DEFAULT;
}

static int rpm_codeset_is_utf8 = 0;

static SV*
newSVpv_utf8(const char *s, STRLEN len)
{
  SV *sv = newSVpv(s, len);
  SvUTF8_on(sv);
  return sv;
}

static void
get_fullname_parts(URPM__Package pkg, char **name, char **version, char **release, char **arch, char **eos) {
  char *_version = NULL, *_release = NULL, *_arch = NULL, *_eos = NULL;

  if ((_eos = strchr(pkg->info, '@')) != NULL) {
    *_eos = 0; /* mark end of string to enable searching backwards */
    if ((_arch = strrchr(pkg->info, '.')) != NULL) {
      *_arch = 0;
      if ((release != NULL || version != NULL || name != NULL) && (_release = strrchr(pkg->info, '-')) != NULL) {
	*_release = 0;
	if ((version != NULL || name != NULL) && (_version = strrchr(pkg->info, '-')) != NULL) {
	  if (name != NULL) *name = pkg->info;
	  if (version != NULL) *version = _version + 1;
	}
	if (release != NULL) *release = _release + 1;
	*_release = '-';
      }
      if (arch != NULL) *arch = _arch + 1;
      *_arch = '.';
    }
    if (eos != NULL) *eos = _eos;
    *_eos = '@';
  }
}

static char *
get_name(Header header, int32_t tag) {
  struct rpmtd_s val;

  headerGet(header, tag, &val, HEADERGET_MINMEM);
  char *name = (char *) rpmtdGetString(&val);
  return name ? name : "";
}

static char*
get_arch(Header header) {
     return headerIsEntry(header, RPMTAG_SOURCERPM) ? get_name(header, RPMTAG_ARCH) : "src";
}

static int
get_int(Header header, int32_t tag) {
  struct rpmtd_s val;

  headerGet(header, tag, &val, HEADERGET_DEFAULT);
  uint32_t *ep = rpmtdGetUint32(&val);
  return ep ? *ep : 0;
}

static size_t
get_filesize(const Header h) {
  return headerGetNumber(h, RPMTAG_SIGSIZE) + 440; /* 440 is the rpm header size (?) empirical, but works */
}

static int
print_list_entry(char *buff, int sz, const char *name, uint32_t flags, const char *evr) {
  int len = strlen(name);
  char *p = buff;

  if (len >= sz || !strncmp(name, "rpmlib(", 7)) return -1;
  memcpy(p, name, len); p += len;

  if (flags & (RPMSENSE_PREREQ|RPMSENSE_SCRIPT_PREUN|RPMSENSE_SCRIPT_PRE|RPMSENSE_SCRIPT_POSTUN|RPMSENSE_SCRIPT_POST)) {
    if (p - buff + 3 >= sz) return -1;
    memcpy(p, "[*]", 4); p += 3;
  }
  if (evr != NULL) {
    len = strlen(evr);
    if (len > 0) {
      if (p - buff + 6 + len >= sz) return -1;
      *p++ = '[';
      if (flags & RPMSENSE_LESS) *p++ = '<';
      if (flags & RPMSENSE_GREATER) *p++ = '>';
      if (flags & RPMSENSE_EQUAL) *p++ = '=';
      if ((flags & (RPMSENSE_LESS|RPMSENSE_EQUAL|RPMSENSE_GREATER)) == RPMSENSE_EQUAL) *p++ = '=';
      *p++ = ' ';
      memcpy(p, evr, len); p+= len;
      *p++ = ']';
    }
  }
  *p = 0; /* make sure to mark null char, Is it really necessary ? */

  return p - buff;
}

static int
ranges_overlap(uint32_t aflags, char *sa, uint32_t bflags, char *sb, int b_nopromote) {
  if (!aflags || !bflags)
    return 1; /* really faster to test it there instead of later */
  else {
    int sense = 0;
    char *eosa = strchr(sa, ']');
    char *eosb = strchr(sb, ']');
    char *ea, *va, *ra, *eb, *vb, *rb;

    if (eosa) *eosa = 0;
    if (eosb) *eosb = 0;
    /* parse sa as an [epoch:]version[-release] */
    for (ea = sa; *sa >= '0' && *sa <= '9'; ++sa);
    if (*sa == ':') {
      *sa++ = 0; /* ea could be an empty string (should be interpreted as 0) */
      va = sa;
    } else {
      va = ea; /* no epoch */
      ea = NULL;
    }
    if ((ra = strrchr(sa, '-'))) *ra++ = 0;
    /* parse sb as an [epoch:]version[-release] */
    for (eb = sb; *sb >= '0' && *sb <= '9'; ++sb);
    if (*sb == ':') {
      *sb++ = 0; /* ea could be an empty string (should be interpreted as 0) */
      vb = sb;
    } else {
      vb = eb; /* no epoch */
      eb = NULL;
    }
    if ((rb = strrchr(sb, '-'))) *rb++ = 0;
    /* now compare epoch */
    if (ea && eb)
      sense = rpmvercmp(*ea ? ea : "0", *eb ? eb : "0");
    else if (ea && *ea && atol(ea) > 0)
      sense = b_nopromote ? 1 : 0;
    else if (eb && *eb && atol(eb) > 0)
      sense = -1;
    /* now compare version and release if epoch has not been enough */
    if (sense == 0) {
      sense = rpmvercmp(va, vb);
      if (sense == 0 && ra && *ra && rb && *rb)
	sense = rpmvercmp(ra, rb);
    }
    /* restore all character that have been modified inline */
    if (rb) rb[-1] = '-';
    if (ra) ra[-1] = '-';
    if (eb) vb[-1] = ':';
    if (ea) va[-1] = ':';
    if (eosb) *eosb = ']';
    if (eosa) *eosa = ']';
    /* finish the overlap computation */
    if (sense < 0 && ((aflags & RPMSENSE_GREATER) || (bflags & RPMSENSE_LESS)))
      return 1;
    else if (sense > 0 && ((aflags & RPMSENSE_LESS) || (bflags & RPMSENSE_GREATER)))
      return 1;
    else if (sense == 0 && (((aflags & RPMSENSE_EQUAL) && (bflags & RPMSENSE_EQUAL)) ||
			    ((aflags & RPMSENSE_LESS) && (bflags & RPMSENSE_LESS)) ||
			    ((aflags & RPMSENSE_GREATER) && (bflags & RPMSENSE_GREATER))))
      return 1;
    else
      return 0;
  }
}

static int has_old_suggests;
int32_t is_old_suggests(int32_t flags) { 
  int is = flags & RPMSENSE_MISSINGOK;
  if (is) has_old_suggests = is;
  return is;
}
int32_t is_not_old_suggests(int32_t flags) {
  return !is_old_suggests(flags);
}

typedef int (*callback_list_str)(char *s, int slen, const char *name, const uint32_t flags, const char *evr, void *param);

static int
callback_list_str_xpush(char *s, int slen, const char *name, uint32_t flags, const char *evr, __attribute__((unused)) void *param) {
  dSP;
  if (s)
    mXPUSHs(newSVpv(s, slen));
  else {
    char buff[4096];
    int len = print_list_entry(buff, sizeof(buff)-1, name, flags, evr);
    if (len >= 0)
      mXPUSHs(newSVpv(buff, len));
  }
  PUTBACK;
  /* returning zero indicates to continue processing */
  return 0;
}
static int
callback_list_str_xpush_requires(char *s, int slen, const char *name, const uint32_t flags, const char *evr, __attribute__((unused)) void *param) {
  dSP;
  if (s)
    mXPUSHs(newSVpv(s, slen));
  else if (is_not_old_suggests(flags)) {
    char buff[4096];
    int len = print_list_entry(buff, sizeof(buff)-1, name, flags, evr);
    if (len >= 0)
      mXPUSHs(newSVpv(buff, len));
  }
  PUTBACK;
  /* returning zero indicates to continue processing */
  return 0;
}
static int
callback_list_str_xpush_old_suggests(char *s, int slen, const char *name, uint32_t flags, const char *evr, __attribute__((unused)) void *param) {
  dSP;
  if (s)
    mXPUSHs(newSVpv(s, slen));
  else if (is_old_suggests(flags)) {
    char buff[4096];
    int len = print_list_entry(buff, sizeof(buff)-1, name, flags, evr);
    if (len >= 0)
      mXPUSHs(newSVpv(buff, len));
  }
  PUTBACK;
  /* returning zero indicates to continue processing */
  return 0;
}

struct cb_overlap_s {
  char *name;
  int32_t flags;
  char *evr;
  int direction; /* indicate to compare the above at left or right to the iteration element */
  int b_nopromote;
};

static int
callback_list_str_overlap(char *s, int slen, const char *name, uint32_t flags, const char *evr, void *param) {
  struct cb_overlap_s *os = (struct cb_overlap_s *)param;
  int result = 0;
  char *eos = NULL;
  char *eon = NULL;
  char eosc = '\0';
  char eonc = '\0';

  /* we need to extract name, flags and evr from a full sense information, store result in local copy */
  if (s) {
    if (slen) { eos = s + slen; eosc = *eos; *eos = 0; }
    name = s;
    while (*s && *s != ' ' && *s != '[' && *s != '<' && *s != '>' && *s != '=') ++s;
    if (*s) {
      eon = s;
      while (*s) {
	if (*s == ' ' || *s == '[' || *s == '*' || *s == ']');
	else if (*s == '<') flags |= RPMSENSE_LESS;
	else if (*s == '>') flags |= RPMSENSE_GREATER;
	else if (*s == '=') flags |= RPMSENSE_EQUAL;
	else break;
	++s;
      }
      evr = s;
    } else
      evr = "";
  }

  /* mark end of name */
  if (eon) { eonc = *eon; *eon = 0; }
  /* names should be equal, else it will not overlap */
  if (!strcmp(name, os->name)) {
    /* perform overlap according to direction needed, negative for left */
    if (os->direction < 0)
      result = ranges_overlap(os->flags, os->evr, flags, (char *) evr, os->b_nopromote);
    else
      result = ranges_overlap(flags, (char *) evr, os->flags, os->evr, os->b_nopromote);
  }

  /* fprintf(stderr, "cb_list_str_overlap result=%d, os->direction=%d, os->name=%s, os->evr=%s, name=%s, evr=%s\n",
     result, os->direction, os->name, os->evr, name, evr); */

  /* restore s if needed */
  if (eon) *eon = eonc;
  if (eos) *eos = eosc;

  return result;
}

static int
return_list_str(char *s, Header header, int32_t tag_name, int32_t tag_flags, int32_t tag_version, callback_list_str f, void *param) {
  int count = 0;

  if (s != NULL) {
    char *ps = strchr(s, '@');
    if (tag_flags && tag_version) {
      while(ps != NULL) {
	++count;
	if (f(s, ps-s, NULL, 0, NULL, param)) return -count;
	s = ps + 1; ps = strchr(s, '@');
      }
      ++count;
      if (f(s, 0, NULL, 0, NULL, param)) return -count;
    } else {
      char *eos;
      while(ps != NULL) {
	*ps = 0; eos = strchr(s, '['); if (!eos) eos = strchr(s, ' ');
	++count;
	if (f(s, eos ? eos-s : ps-s, NULL, 0, NULL, param)) { *ps = '@'; return -count; }
	*ps = '@'; /* restore in memory modified char */
	s = ps + 1; ps = strchr(s, '@');
      }
      eos = strchr(s, '['); if (!eos) eos = strchr(s, ' ');
      ++count;
      if (f(s, eos ? eos-s : 0, NULL, 0, NULL, param)) return -count;
    }
  } else if (header) {
    struct rpmtd_s list, flags, list_evr;

    if (headerGet(header, tag_name, &list, HEADERGET_DEFAULT)) {
      memset((void*)&flags, 0, sizeof(flags));
      memset((void*)&list_evr, 0, sizeof(list_evr));
      if (tag_flags) headerGet(header, tag_flags, &flags, HEADERGET_DEFAULT);
      if (tag_version) headerGet(header, tag_version, &list_evr, HEADERGET_DEFAULT);
      while (rpmtdNext(&list) >= 0) {
	++count;
	uint32_t *flag = rpmtdNextUint32(&flags);
	if (f(NULL, 0, rpmtdGetString(&list), flag ? *flag : 0, 
	      rpmtdNextString(&list_evr), param)) {
	  rpmtdFreeData(&list);
	  if (tag_flags) rpmtdFreeData(&flags);
	  if (tag_version) rpmtdFreeData(&list_evr);
	  return -count;
	}
      }
      rpmtdFreeData(&list);
      if (tag_flags) rpmtdFreeData(&flags);
      if (tag_version) rpmtdFreeData(&list_evr);
    }
  }
  return count;
}

static int
xpush_simple_list_str(Header header, int32_t tag_name) {
  dSP;
  if (header) {
    struct rpmtd_s list;
    const char *val;
    int size;

    if (!headerGet(header, tag_name, &list, HEADERGET_DEFAULT)) return 0;
    size = rpmtdCount(&list);

    while ((val = rpmtdNextString(&list))) {
        mXPUSHs(newSVpv(val, 0));
    }
    rpmtdFreeData(&list);
    PUTBACK;
    return size;
  } else return 0;
}

void
return_list_int32_t(Header header, int32_t tag_name) {
  dSP;
  if (header) {
    struct rpmtd_s list;

    if (headerGet(header, tag_name, &list, HEADERGET_DEFAULT)) {
      uint32_t *val;
      while ((val = rpmtdNextUint32(&list)))
	mXPUSHs(newSViv(*val));
      rpmtdFreeData(&list);
    }
  }
  PUTBACK;
}

void
return_list_uint_16(Header header, int32_t tag_name) {
  dSP;
  if (header) {
    struct rpmtd_s list;
    if (headerGet(header, tag_name, &list, HEADERGET_DEFAULT)) {
      int count = rpmtdCount(&list);
      int i;
      uint16_t *list_ = list.data;
      for(i = 0; i < count; i++) {
	mXPUSHs(newSViv(list_[i]));
      }
      rpmtdFreeData(&list);
    }
  }
  PUTBACK;
}

void
return_list_tag_modifier(Header header, int32_t tag_name) {
  dSP;
  int i;
  struct rpmtd_s td;
  if (!headerGet(header, tag_name, &td, HEADERGET_DEFAULT)) return;
  int count = rpmtdCount(&td);
  int32_t *list = td.data;

  for (i = 0; i < count; i++) {
    char buff[15];
    char *s = buff;
    switch (tag_name) {
    case RPMTAG_FILEFLAGS:
      if (list[i] & RPMFILE_CONFIG)    *s++ = 'c';
      if (list[i] & RPMFILE_DOC)       *s++ = 'd';
      if (list[i] & RPMFILE_GHOST)     *s++ = 'g';
      if (list[i] & RPMFILE_LICENSE)   *s++ = 'l';
      if (list[i] & RPMFILE_MISSINGOK) *s++ = 'm';
      if (list[i] & RPMFILE_NOREPLACE) *s++ = 'n';
      if (list[i] & RPMFILE_SPECFILE)  *s++ = 'S';
      if (list[i] & RPMFILE_README)    *s++ = 'R';
      if (list[i] & RPMFILE_EXCLUDE)   *s++ = 'e';
      if (list[i] & RPMFILE_ICON)      *s++ = 'i';
      if (list[i] & RPMFILE_UNPATCHED) *s++ = 'u';
      if (list[i] & RPMFILE_PUBKEY)    *s++ = 'p';
    break;
    default:
      rpmtdFreeData(&td);
      return;  
    }
    *s = '\0';
    mXPUSHs(newSVpv(buff, strlen(buff)));
  }
  rpmtdFreeData(&td);
  PUTBACK;
}

void
return_list_tag(URPM__Package pkg, int32_t tag_name) {
  dSP;
  if (pkg->h != NULL) {
    struct rpmtd_s td;
    if (headerGet(pkg->h, tag_name, &td, HEADERGET_DEFAULT)) {
      void *list = td.data;
      int32_t count = rpmtdCount(&td);
      if (tag_name == RPMTAG_ARCH)
	mXPUSHs(newSVpv(headerIsEntry(pkg->h, RPMTAG_SOURCERPM) ? (char *) list : "src", 0));
      else
	switch (rpmtdType(&td)) {
	  case RPM_NULL_TYPE:
	    break;
	  case RPM_CHAR_TYPE:
	  case RPM_INT8_TYPE:
	  case RPM_INT16_TYPE:
	  case RPM_INT32_TYPE:
	    {
	      int i;
	      int *r;
	      r = (int *)list;
	      for (i=0; i < count; i++) {
		mXPUSHs(newSViv(r[i]));
	      }
	    }
	    break;
	  case RPM_STRING_TYPE:
	    mXPUSHs(newSVpv((char *) list, 0));
	    break;
	  case RPM_BIN_TYPE:
	    break;
	  case RPM_STRING_ARRAY_TYPE:
	    {
	      int i;
	      char **s;

	      s = (char **)list;
	      for (i = 0; i < count; i++) {
		mXPUSHs(newSVpv(s[i], 0));
	      }
	    }
	    break;
	  case RPM_I18NSTRING_TYPE:
	    break;
	  case RPM_INT64_TYPE:
	    break;
	}
    }
  } else {
    char *name;
    char *version;
    char *release;
    char *arch;
    char *eos;
    switch (tag_name) {
      case RPMTAG_NAME:
	{
	  get_fullname_parts(pkg, &name, &version, &release, &arch, &eos);
	  if (version - name < 1) croak("invalid fullname");
	  mXPUSHs(newSVpv(name, version-name - 1));
	}
	break;
      case RPMTAG_VERSION:
	{
	  get_fullname_parts(pkg, &name, &version, &release, &arch, &eos);
	  if (release - version < 1) croak("invalid fullname");
	  mXPUSHs(newSVpv(version, release-version - 1));
	}
	break;
      case RPMTAG_RELEASE:
	{
	  get_fullname_parts(pkg, &name, &version, &release, &arch, &eos);
	  if (arch - release < 1) croak("invalid fullname");
	  mXPUSHs(newSVpv(release, arch-release - 1));
	}
	break;
      case RPMTAG_ARCH:
	{
	  get_fullname_parts(pkg, &name, &version, &release, &arch, &eos);
	  mXPUSHs(newSVpv(arch, eos-arch));
	}
	break;
      case RPMTAG_SUMMARY:
	mXPUSHs(newSVpv(pkg->summary, 0));
	break;
    }
  }
  PUTBACK;
}


void
return_files(Header header, int filter_mode) {
  dSP;
  if (header) {
    char buff[4096];
    char *p, *s;
    STRLEN len;
    unsigned int i;

    struct rpmtd_s td_flags, td_fmodes;
    int32_t *flags = NULL;
    if (filter_mode) {
      headerGet(header, RPMTAG_FILEFLAGS, &td_flags, HEADERGET_DEFAULT);
      headerGet(header, RPMTAG_FILEMODES, &td_fmodes, HEADERGET_DEFAULT);
      flags = td_flags.data;
    }

    struct rpmtd_s td_baseNames, td_dirIndexes, td_dirNames, td_list;
    headerGet(header, RPMTAG_BASENAMES, &td_baseNames, HEADERGET_DEFAULT);
    headerGet(header, RPMTAG_DIRINDEXES, &td_dirIndexes, HEADERGET_DEFAULT);
    headerGet(header, RPMTAG_DIRNAMES, &td_dirNames, HEADERGET_DEFAULT);

    char **baseNames = td_baseNames.data;
    char **dirNames = td_dirNames.data;
    int32_t *dirIndexes = td_dirIndexes.data;

    char **list = NULL;
    if (!baseNames || !dirNames || !dirIndexes) {
      if (!headerGet(header, RPMTAG_OLDFILENAMES, &td_list, HEADERGET_DEFAULT)) return;
      list = td_list.data;
    }

    for(i = 0; i < rpmtdCount(&td_baseNames); i++) {
      if (list) {
	s = list[i];
	len = strlen(list[i]);
      } else {
	len = strlen(dirNames[dirIndexes[i]]);
	if (len >= sizeof(buff)) continue;
	memcpy(p = buff, dirNames[dirIndexes[i]], len + 1); p += len;
	len = strlen(baseNames[i]);
	if (p - buff + len >= sizeof(buff)) continue;
	memcpy(p, baseNames[i], len + 1); p += len;
	s = buff;
	len = p-buff;
      }

      if (filter_mode) {
	if ((filter_mode & FILTER_MODE_CONF_FILES) && flags && (flags[i] & RPMFILE_CONFIG) == 0) continue;
      }

      mXPUSHs(newSVpv(s, len));
    }

    free(baseNames);
    free(dirNames);
    free(list);
  }
  PUTBACK;
}

void
return_problems(rpmps ps, int translate_message, int raw_message) {
  dSP;
  if (ps && rpmpsNumProblems(ps) > 0) {
    rpmpsi iterator = rpmpsInitIterator(ps);
    while (rpmpsNextIterator(iterator) >= 0) {
      rpmProblem p = rpmpsGetProblem(iterator);

      if (translate_message) {
	/* translate error using rpm localization */
	const char *buf = rpmProblemString(p);
	SV *sv = newSVpv(buf, 0);
	if (rpm_codeset_is_utf8) SvUTF8_on(sv);
	mXPUSHs(sv);
	_free(buf);
      }
      if (raw_message) {
	const char *pkgNEVR = rpmProblemGetPkgNEVR(p) ? rpmProblemGetPkgNEVR(p) : "";
	const char *altNEVR = rpmProblemGetAltNEVR(p) ? rpmProblemGetAltNEVR(p) : "";
	const char *s = rpmProblemGetStr(p) ? rpmProblemGetStr(p) : "";
	SV *sv;

	switch (rpmProblemGetType(p)) {
	case RPMPROB_BADARCH:
	  sv = newSVpvf("badarch@%s", pkgNEVR); break;

	case RPMPROB_BADOS:
	  sv = newSVpvf("bados@%s", pkgNEVR); break;

	case RPMPROB_PKG_INSTALLED:
	  sv = newSVpvf("installed@%s", pkgNEVR); break;

	case RPMPROB_BADRELOCATE:
	  sv = newSVpvf("badrelocate@%s@%s", pkgNEVR, s); break;

	case RPMPROB_NEW_FILE_CONFLICT:
	case RPMPROB_FILE_CONFLICT:
	  sv = newSVpvf("conflicts@%s@%s@%s", pkgNEVR, altNEVR, s); break;

	case RPMPROB_OLDPACKAGE:
	  sv = newSVpvf("installed@%s@%s", pkgNEVR, altNEVR); break;

	case RPMPROB_DISKSPACE:
	  sv = newSVpvf("diskspace@%s@%s@%lld", pkgNEVR, s, (long long)rpmProblemGetDiskNeed(p)); break;
	case RPMPROB_DISKNODES:
	  sv = newSVpvf("disknodes@%s@%s@%lld", pkgNEVR, s, (long long)rpmProblemGetDiskNeed(p)); break;
	case RPMPROB_REQUIRES:
	  sv = newSVpvf("requires@%s@%s", pkgNEVR, altNEVR+2); break;

	case RPMPROB_CONFLICT:
	  sv = newSVpvf("conflicts@%s@%s", pkgNEVR, altNEVR+2); break;

	default:
	  sv = newSVpvf("unknown@%s", pkgNEVR); break;
	}
	mXPUSHs(sv);
      }
    }
    rpmpsFreeIterator(iterator);
  }
  PUTBACK;
}

static char *
pack_list(Header header, int32_t tag_name, int32_t tag_flags, int32_t tag_version, int32_t (*check_flag)(int32_t)) {
  char buff[65536];
  int32_t *flags = NULL;
  char **list_evr = NULL;
  unsigned int i;
  char *p = buff;

  struct rpmtd_s td;
  if (headerGet(header, tag_name, &td, HEADERGET_DEFAULT)) {
    char **list = td.data;
    
    struct rpmtd_s td_flags, td_list_evr;
    if (tag_flags   && headerGet(header, tag_flags,   &td_flags, HEADERGET_DEFAULT))    flags    = td_flags.data;
    if (tag_version && headerGet(header, tag_version, &td_list_evr, HEADERGET_DEFAULT)) list_evr = td_list_evr.data;
    for(i = 0; i < rpmtdCount(&td); i++) {
      if (check_flag && !check_flag(flags[i])) continue;
      int len = print_list_entry(p, sizeof(buff)-(p-buff)-1, list[i], flags ? flags[i] : 0, list_evr ? list_evr[i] : NULL);
      if (len < 0) continue;
      p += len;
      *p++ = '@';
    }
    if (p > buff) p[-1] = 0;

    free(list);
    free(list_evr);
  }

  return p > buff ? memcpy(malloc(p-buff), buff, p-buff) : NULL;
}

static void
pack_header(URPM__Package pkg) {
  if (pkg->h) {
    if (pkg->info == NULL) {
      char buff[1024];
      char *p = buff;
      char *name = get_name(pkg->h, RPMTAG_NAME);
      char *version = get_name(pkg->h, RPMTAG_VERSION);
      char *release = get_name(pkg->h, RPMTAG_RELEASE);
      char *arch = get_arch(pkg->h);

      p += 1 + snprintf(buff, sizeof(buff), "%s-%s-%s.%s@%d@%d@%s", name, version, release, arch,
		    get_int(pkg->h, RPMTAG_EPOCH), get_int(pkg->h, RPMTAG_SIZE), 
		    get_name(pkg->h, RPMTAG_GROUP));
      pkg->info = memcpy(malloc(p-buff), buff, p-buff);
    }
    if (pkg->filesize == 0) pkg->filesize = get_filesize(pkg->h);
    if (pkg->requires == NULL && pkg->suggests == NULL)
      has_old_suggests = 0;
      pkg->requires = pack_list(pkg->h, RPMTAG_REQUIRENAME, RPMTAG_REQUIREFLAGS, RPMTAG_REQUIREVERSION, is_not_old_suggests);
      if (has_old_suggests)
      pkg->suggests = pack_list(pkg->h, RPMTAG_REQUIRENAME, RPMTAG_REQUIREFLAGS, RPMTAG_REQUIREVERSION, is_old_suggests);
      else
        pkg->suggests = pack_list(pkg->h, RPMTAG_SUGGESTSNAME, 0, 0, NULL);
    if (pkg->obsoletes == NULL)
      pkg->obsoletes = pack_list(pkg->h, RPMTAG_OBSOLETENAME, RPMTAG_OBSOLETEFLAGS, RPMTAG_OBSOLETEVERSION, NULL);
    if (pkg->conflicts == NULL)
      pkg->conflicts = pack_list(pkg->h, RPMTAG_CONFLICTNAME, RPMTAG_CONFLICTFLAGS, RPMTAG_CONFLICTVERSION, NULL);
    if (pkg->provides == NULL)
      pkg->provides = pack_list(pkg->h, RPMTAG_PROVIDENAME, RPMTAG_PROVIDEFLAGS, RPMTAG_PROVIDEVERSION, NULL);
    if (pkg->summary == NULL) {
      char *summary = get_name(pkg->h, RPMTAG_SUMMARY);
      int len = 1 + strlen(summary);

      pkg->summary = memcpy(malloc(len), summary, len);
    }

    if (!(pkg->flag & FLAG_NO_HEADER_FREE)) pkg->h =headerFree(pkg->h);
    pkg->h = NULL;
  }
}

static void
update_hash_entry(HV *hash, char *name, STRLEN len, int force, IV use_sense, URPM__Package pkg) {
  SV** isv;

  if (!len) len = strlen(name);
  if ((isv = hv_fetch(hash, name, len, force))) {
    /* check if an entry has been found or created, it should so be updated */
    if (!SvROK(*isv) || SvTYPE(SvRV(*isv)) != SVt_PVHV) {
      SV* choice_set = (SV*)newHV();
      if (choice_set) {
	SvREFCNT_dec(*isv); /* drop the old as we are changing it */
	if (!(*isv = newRV_noinc(choice_set))) {
	  SvREFCNT_dec(choice_set);
	  *isv = &PL_sv_undef;
	}
      }
    }
    if (isv && *isv != &PL_sv_undef) {
      char id[8];
      STRLEN id_len = snprintf(id, sizeof(id), "%d", pkg->flag & FLAG_ID);
      SV **sense = hv_fetch((HV*)SvRV(*isv), id, id_len, 1);
      if (sense && use_sense) sv_setiv(*sense, use_sense);
    }
  }
}

static void
update_provide_entry(char *name, STRLEN len, int force, IV use_sense, URPM__Package pkg, HV *provides) {
  update_hash_entry(provides, name, len, force, use_sense, pkg);
}

static void
update_provides(URPM__Package pkg, HV *provides) {
  if (pkg->h) {
    int len;
    struct rpmtd_s td, td_flags;
    int32_t *flags = NULL;
    unsigned int i;

    /* examine requires for files which need to be marked in provides */
    if (headerGet(pkg->h, RPMTAG_REQUIRENAME, &td, HEADERGET_DEFAULT)) {
      char **list = td.data;
      for (i = 0; i < rpmtdCount(&td); ++i) {
	len = strlen(list[i]);
	if (list[i][0] == '/') (void)hv_fetch(provides, list[i], len, 1);
      }
    }

    /* update all provides */
    if (headerGet(pkg->h, RPMTAG_PROVIDENAME, &td, HEADERGET_DEFAULT)) {
      char **list = td.data;
      if (headerGet(pkg->h, RPMTAG_PROVIDEFLAGS, &td_flags, HEADERGET_DEFAULT))
	flags = td_flags.data;
      for (i = 0; i < rpmtdCount(&td); ++i) {
	len = strlen(list[i]);
	if (!strncmp(list[i], "rpmlib(", 7)) continue;
	update_provide_entry(list[i], len, 1, flags && flags[i] & (RPMSENSE_PREREQ|RPMSENSE_SCRIPT_PREUN|RPMSENSE_SCRIPT_PRE|RPMSENSE_SCRIPT_POSTUN|RPMSENSE_SCRIPT_POST|RPMSENSE_LESS|RPMSENSE_EQUAL|RPMSENSE_GREATER),
			     pkg, provides);
      }
    }
  } else {
    char *ps, *s, *es;

    if ((s = pkg->requires) != NULL && *s != 0) {
      ps = strchr(s, '@');
      while(ps != NULL) {
	if (s[0] == '/') {
	  *ps = 0; es = strchr(s, '['); if (!es) es = strchr(s, ' '); *ps = '@';
	  (void)hv_fetch(provides, s, es != NULL ? es-s : ps-s, 1);
	}
	s = ps + 1; ps = strchr(s, '@');
      }
      if (s[0] == '/') {
      es = strchr(s, '['); if (!es) es = strchr(s, ' ');
	(void)hv_fetch(provides, s, es != NULL ? (U32)(es-s) : strlen(s), 1);
      }
    }

    if ((s = pkg->provides) != NULL && *s != 0) {
      char *es;

      ps = strchr(s, '@');
      while(ps != NULL) {
	*ps = 0; es = strchr(s, '['); if (!es) es = strchr(s, ' '); *ps = '@';
	update_provide_entry(s, es != NULL ? es-s : ps-s, 1, es != NULL, pkg, provides);
	s = ps + 1; ps = strchr(s, '@');
      }
      es = strchr(s, '['); if (!es) es = strchr(s, ' ');
      update_provide_entry(s, es != NULL ? es-s : 0, 1, es != NULL, pkg, provides);
    }
  }
}

static void
update_obsoletes(URPM__Package pkg, HV *obsoletes) {
  if (pkg->h) {
    struct rpmtd_s td;

    /* update all provides */
    if (headerGet(pkg->h, RPMTAG_OBSOLETENAME, &td, HEADERGET_DEFAULT)) {
      char **list = td.data;
      unsigned int i;
      for (i = 0; i < rpmtdCount(&td); ++i)
	update_hash_entry(obsoletes, list[i], 0, 1, 0, pkg);
    }
  } else {
    char *ps, *s;

    if ((s = pkg->obsoletes) != NULL && *s != 0) {
      char *es;

      ps = strchr(s, '@');
      while(ps != NULL) {
	*ps = 0; es = strchr(s, '['); if (!es) es = strchr(s, ' '); *ps = '@';
	update_hash_entry(obsoletes, s, es != NULL ? es-s : ps-s, 1, 0, pkg);
	s = ps + 1; ps = strchr(s, '@');
      }
      es = strchr(s, '['); if (!es) es = strchr(s, ' ');
      update_hash_entry(obsoletes, s, es != NULL ? es-s : 0, 1, 0, pkg);
    }
  }
}

static void
update_provides_files(URPM__Package pkg, HV *provides) {
  if (pkg->h) {
    STRLEN len;
    char **list = NULL;
    unsigned int i;

    struct rpmtd_s td_baseNames, td_dirIndexes, td_dirNames;
    if (headerGet(pkg->h, RPMTAG_BASENAMES, &td_baseNames, HEADERGET_DEFAULT) &&
	headerGet(pkg->h, RPMTAG_DIRINDEXES, &td_dirIndexes, HEADERGET_DEFAULT) &&
	headerGet(pkg->h, RPMTAG_DIRNAMES, &td_dirNames, HEADERGET_DEFAULT)) {

      char **baseNames = td_baseNames.data;
      char **dirNames = td_dirNames.data;
      int32_t *dirIndexes = td_dirIndexes.data;

      char buff[4096];
      char *p;

      for(i = 0; i < rpmtdCount(&td_baseNames); i++) {
	len = strlen(dirNames[dirIndexes[i]]);
	if (len >= sizeof(buff)) continue;
	memcpy(p = buff, dirNames[dirIndexes[i]], len + 1); p += len;
	len = strlen(baseNames[i]);
	if (p - buff + len >= sizeof(buff)) continue;
	memcpy(p, baseNames[i], len + 1); p += len;

	update_provide_entry(buff, p-buff, 0, 0, pkg, provides);
      }

      free(baseNames);
      free(dirNames);
    } else {
      struct rpmtd_s td;
      headerGet(pkg->h, RPMTAG_OLDFILENAMES, &td, HEADERGET_DEFAULT);
      if (list) {
	for (i = 0; i < rpmtdCount(&td); i++) {
	  len = strlen(list[i]);

	  update_provide_entry(list[i], len, 0, 0, pkg, provides);
	}

	free(list);
      }
    }
  }
}

FD_t
open_archive(char *filename, int *empty_archive) {
  int fd;
  FD_t rfd = NULL;
  struct {
    char header[4];
    char toc_d_count[4];
    char toc_l_count[4];
    char toc_f_count[4];
    char toc_str_size[4];
    char uncompress[40];
    char trailer[4];
  } buf;

  fd = open(filename, O_RDONLY);
  if (fd >= 0) {
    int pos = lseek(fd, -(int)sizeof(buf), SEEK_END);
    if (read(fd, &buf, sizeof(buf)) != sizeof(buf) || strncmp(buf.header, "cz[0", 4) || strncmp(buf.trailer, "0]cz", 4)) {
      /* this is not an archive, open it without magic, but first rewind at begin of file */
      lseek(fd, 0, SEEK_SET);
      return fdDup(fd);
    } else if (pos == 0) {
      *empty_archive = 1;
    } else {
      /* this is an archive, prepare for reading with uncompress defined inside */
      rfd = Fopen(filename, "r.fdio");
      if (strcmp(buf.uncompress, "gzip"))
           rfd = Fdopen(rfd, "r.gzip");
      else if (strcmp(buf.uncompress, "bzip"))
           rfd = Fdopen(rfd, "r.bzip2");
      else if (strcmp(buf.uncompress, "xz") || strcmp(buf.uncompress, "lzma"))
           rfd = Fdopen(rfd, "r.xz");
      else {
           free(rfd);
           rfd = NULL;
      }
    }
  }
  close(fd);
  return rfd;
}

static int
call_package_callback(SV *urpm, SV *sv_pkg, SV *callback) {
  if (sv_pkg != NULL && callback != NULL) {
    int count;

    /* now, a callback will be called for sure */
    dSP;
    PUSHMARK(SP);
    XPUSHs(urpm);
    XPUSHs(sv_pkg);
    PUTBACK;
    count = call_sv(callback, G_SCALAR);
    SPAGAIN;
    if (count == 1 && !POPi) {
      /* package should not be added in depslist, so we free it */
      SvREFCNT_dec(sv_pkg);
      sv_pkg = NULL;
    }
    PUTBACK;
  }

  return sv_pkg != NULL;
}

static int
parse_line(AV *depslist, HV *provides, HV *obsoletes, URPM__Package pkg, char *buff, SV *urpm, SV *callback) {
  SV *sv_pkg;
  URPM__Package _pkg;
  char *tag, *data;
  int data_len;

  if (buff[0] == 0)
    return 1;
  else if ((tag = buff)[0] == '@' && (data = strchr(tag+1, '@')) != NULL) {
    *tag++ = *data++ = 0;
    data_len = 1+strlen(data);
    if (!strcmp(tag, "info")) {
      pkg->info = memcpy(malloc(data_len), data, data_len);
      pkg->flag &= ~FLAG_ID;
      pkg->flag |= 1 + av_len(depslist);
      sv_pkg = sv_setref_pv(newSVpv("", 0), "URPM::Package",
			    _pkg = memcpy(malloc(sizeof(struct s_Package)), pkg, sizeof(struct s_Package)));
      if (call_package_callback(urpm, sv_pkg, callback)) {
	if (provides) update_provides(_pkg, provides);
	if (obsoletes) update_obsoletes(_pkg, obsoletes);
	av_push(depslist, sv_pkg);
      }
      memset(pkg, 0, sizeof(struct s_Package));
    } else if (!strcmp(tag, "filesize"))
      pkg->filesize = atoi(data);
    else if (!strcmp(tag, "requires"))
      free(pkg->requires), pkg->requires = memcpy(malloc(data_len), data, data_len);
    else if (!strcmp(tag, "suggests"))
      free(pkg->suggests), pkg->suggests = memcpy(malloc(data_len), data, data_len);
    else if (!strcmp(tag, "obsoletes"))
      free(pkg->obsoletes), pkg->obsoletes = memcpy(malloc(data_len), data, data_len);
    else if (!strcmp(tag, "conflicts"))
      free(pkg->conflicts), pkg->conflicts = memcpy(malloc(data_len), data, data_len);
    else if (!strcmp(tag, "provides"))
      free(pkg->provides), pkg->provides = memcpy(malloc(data_len), data, data_len);
    else if (!strcmp(tag, "summary"))
      free(pkg->summary), pkg->summary = memcpy(malloc(data_len), data, data_len);

    return 1;
  } else {
    fprintf(stderr, "bad line <%s>\n", buff);
    return 0;
  }
}

#if 0
/*
 * this code is unused since August 2007 and hasn't work since MDK8.1 and rpm 4 (2001!!!).
 */
static void pack_rpm_header(Header *h) {
  Header packed = headerNew();

  HeaderIterator hi = headerInitIterator(*h);
  struct rpmtd_s td;
  while (headerNext(hi, &td)) {
      // fprintf(stderr, "adding %s %d\n", tagname(tag), c);
      headerPut(packed, &td, HEADERPUT_DEFAULT);
      rpmtdFreeData(&td);
  }

  headerFreeIterator(hi);
  *h = headerFree(*h);

  *h = packed;
}

static void drop_tags(Header *h) {
  headerDel(*h, RPMTAG_FILEUSERNAME); /* user ownership is correct */
  headerDel(*h, RPMTAG_FILEGROUPNAME); /* group ownership is correct */
  headerDel(*h, RPMTAG_FILEMTIMES); /* correct time without it */
  headerDel(*h, RPMTAG_FILEINODES); /* hardlinks work without it */
  headerDel(*h, RPMTAG_FILEDEVICES); /* it is the same number for every file */
  headerDel(*h, RPMTAG_FILESIZES); /* ? */
  headerDel(*h, RPMTAG_FILERDEVS); /* it seems unused. always empty */
  headerDel(*h, RPMTAG_FILEVERIFYFLAGS); /* only used for -V */
  headerDel(*h, RPMTAG_FILEDIGESTALGOS); /* only used for -V */
  headerDel(*h, RPMTAG_FILEDIGESTS); /* only used for -V */ /* alias: RPMTAG_FILEMD5S */ 
  /* keep RPMTAG_FILEFLAGS for %config (rpmnew) to work */
  /* keep RPMTAG_FILELANGS for %lang (_install_langs) to work */
  /* keep RPMTAG_FILELINKTOS for checking conflicts between symlinks */
  /* keep RPMTAG_FILEMODES otherwise it segfaults with excludepath */

  /* keep RPMTAG_POSTIN RPMTAG_POSTUN RPMTAG_PREIN RPMTAG_PREUN */
  /* keep RPMTAG_TRIGGERSCRIPTS RPMTAG_TRIGGERVERSION RPMTAG_TRIGGERFLAGS RPMTAG_TRIGGERNAME */
  /* small enough, and only in some packages. not needed per se */

  headerDel(*h, RPMTAG_ICON);
  headerDel(*h, RPMTAG_GIF);
  headerDel(*h, RPMTAG_EXCLUDE);
  headerDel(*h, RPMTAG_EXCLUSIVE);
  headerDel(*h, RPMTAG_COOKIE);
  headerDel(*h, RPMTAG_VERIFYSCRIPT);

  /* always the same for our packages */
  headerDel(*h, RPMTAG_VENDOR);
  headerDel(*h, RPMTAG_DISTRIBUTION);

  /* keep RPMTAG_SIGSIZE, useful to tell the size of the rpm file (+440) */

  headerDel(*h, RPMTAG_DSAHEADER);
  headerDel(*h, RPMTAG_SHA1HEADER);
  headerDel(*h, RPMTAG_SIGMD5);
  headerDel(*h, RPMTAG_SIGGPG);

  pack_rpm_header(h);
}
#endif

static int
update_header(char *filename, URPM__Package pkg, __attribute__((unused)) int keep_all_tags, int vsflags) {
  int d = open(filename, O_RDONLY);

  if (d >= 0) {
    unsigned char sig[4];

    if (read(d, &sig, sizeof(sig)) == sizeof(sig)) {
      lseek(d, 0, SEEK_SET);
      // Is it RPM lead?
      if (sig[0] == 0xed && sig[1] == 0xab && sig[2] == 0xee && sig[3] == 0xdb) {
	FD_t fd = fdDup(d);
	Header header;
	rpmts ts;
	pkg->filesize = fdSize(fd);

	close(d);
	ts = rpmtsCreate();
	rpmtsSetVSFlags(ts, _RPMVSF_NOSIGNATURES | vsflags);
	if (fd != NULL && rpmReadPackageFile(ts, fd, filename, &header) == 0 && header) {
	  Fclose(fd);

	  if (pkg->h && !(pkg->flag & FLAG_NO_HEADER_FREE)) pkg->h = headerFree(pkg->h);
	  pkg->h = header;
	  pkg->flag &= ~FLAG_NO_HEADER_FREE;

	  /*if (!keep_all_tags) drop_tags(&pkg->h);*/
	  (void)rpmtsFree(ts);
	  return 1;
	}
	(void)rpmtsFree(ts);
      } else if (sig[0] == 0x8e && sig[1] == 0xad && sig[2] == 0xe8 && sig[3] == 0x01) {
	// or is it RPM header magic?
	FD_t fd = fdDup(d);

	close(d);
	if (fd != NULL) {
	  if (pkg->h && !(pkg->flag & FLAG_NO_HEADER_FREE)) pkg->h = headerFree(pkg->h);
	  pkg->h = headerRead(fd, HEADER_MAGIC_YES);
	  pkg->flag &= ~FLAG_NO_HEADER_FREE;
	  Fclose(fd);
	  return 1;
	}
      }
    }
  }
  return 0;
}

static int
read_config_files(int force) {
  static int already = 0;
  int rc = 0;

  if (!already || force) {
    rc = rpmReadConfigFiles(NULL, NULL);
    already = (rc == 0); /* set config as load only if it succeed */
  }
  return rc;
}

static void
ts_nosignature(rpmts ts) {
  rpmtsSetVSFlags(ts, _RPMVSF_NODIGESTS | _RPMVSF_NOSIGNATURES);
}

static void *rpmRunTransactions_callback(__attribute__((unused)) const void *h,
					 const rpmCallbackType what, 
					 const rpm_loff_t amount, 
					 const rpm_loff_t total,
					 fnpyKey pkgKey,
					 rpmCallbackData data) {
  static struct timeval tprev;
  static struct timeval tcurr;
  static FD_t fd = NULL;
  long delta;
  int i;
  struct s_TransactionData *td = data;
  SV *callback = NULL;
  char *callback_type = NULL;
  char *callback_subtype = NULL;

  if (!td)
    return NULL;

  switch (what) {
    case RPMCALLBACK_INST_OPEN_FILE:
      callback = td->callback_open;
      callback_type = "open";
      break;
    case RPMCALLBACK_INST_CLOSE_FILE:
      callback = td->callback_close;
      callback_type = "close";
      break;
    case RPMCALLBACK_TRANS_START:
    case RPMCALLBACK_TRANS_PROGRESS:
    case RPMCALLBACK_TRANS_STOP:
      callback = td->callback_trans;
      callback_type = "trans";
      break;
    case RPMCALLBACK_UNINST_START:
    case RPMCALLBACK_UNINST_PROGRESS:
    case RPMCALLBACK_UNINST_STOP:
      callback = td->callback_uninst;
      callback_type = "uninst";
      break;
    case RPMCALLBACK_INST_START:
    case RPMCALLBACK_INST_PROGRESS:
      callback = td->callback_inst;
      callback_type = "inst";
      break;
    default:
      break;
  }

  if (callback != NULL) {
    switch (what) {
      case RPMCALLBACK_TRANS_START:
      case RPMCALLBACK_UNINST_START:
      case RPMCALLBACK_INST_START:
	callback_subtype = "start";
	gettimeofday(&tprev, NULL);
	break;
      case RPMCALLBACK_TRANS_PROGRESS:
      case RPMCALLBACK_UNINST_PROGRESS:
      case RPMCALLBACK_INST_PROGRESS:
	callback_subtype = "progress";
	gettimeofday(&tcurr, NULL);
	delta = 1000000 * (tcurr.tv_sec - tprev.tv_sec) + (tcurr.tv_usec - tprev.tv_usec);
	if (delta < td->min_delta && amount < total - 1)
	  callback = NULL; /* avoid calling too often a given callback */
	else
	  tprev = tcurr;
	break;
      case RPMCALLBACK_TRANS_STOP:
      case RPMCALLBACK_UNINST_STOP:
	callback_subtype = "stop";
	break;
      default:
	break;
    }

    if (callback != NULL) {
      /* now, a callback will be called for sure */
      dSP;
      ENTER;
      SAVETMPS;
      PUSHMARK(SP);
      XPUSHs(td->data);
      mXPUSHs(newSVpv(callback_type, 0));
      XPUSHs(pkgKey != NULL ? sv_2mortal(newSViv((long)pkgKey - 1)) : &PL_sv_undef);
      if (callback_subtype != NULL) {
	mXPUSHs(newSVpv(callback_subtype, 0));
	mXPUSHs(newSViv(amount));
	mXPUSHs(newSViv(total));
      }
      PUTBACK;
      i = call_sv(callback, callback == td->callback_open ? G_SCALAR : G_DISCARD);
      SPAGAIN;
      if (callback == td->callback_open) {
	if (i != 1) croak("callback_open should return a file handle");
	i = POPi;
	fd = fdDup(i);
	if (fd) {
	  fd = fdLink(fd);
	  Fcntl(fd, F_SETFD, (void *)1); /* necessary to avoid forked/execed process to lock removable */
	}
	PUTBACK;
      } else if (callback == td->callback_close) {
	fd = fdFree(fd);
	if (fd) {
	  Fclose(fd);
	  fd = NULL;
	}
      }
      FREETMPS;
      LEAVE;
    }
  }
  return callback == td->callback_open ? fd : NULL;
}

int rpmtag_from_string(char *tag)
{
    if (!strcmp(tag, "name"))
      return RPMTAG_NAME;
    else if (!strcmp(tag, "whatprovides"))
      return RPMTAG_PROVIDENAME;
    else if (!strcmp(tag, "whatrequires"))
      return RPMTAG_REQUIRENAME;
    else if (!strcmp(tag, "whatconflicts"))
      return RPMTAG_CONFLICTNAME;
    else if (!strcmp(tag, "group"))
      return RPMTAG_GROUP;
    else if (!strcmp(tag, "triggeredby"))
      return RPMTAG_TRIGGERNAME;
    else if (!strcmp(tag, "path"))
      return RPMTAG_BASENAMES;
    else if (!strcmp(tag, "nvra"))
      return RPMTAG_NVRA;
    else croak("unknown tag [%s]", tag);
}

MODULE = URPM            PACKAGE = URPM::Package       PREFIX = Pkg_

void
Pkg_DESTROY(pkg)
  URPM::Package pkg
  CODE:
  free(pkg->info);
  free(pkg->requires);
  free(pkg->suggests);
  free(pkg->obsoletes);
  free(pkg->conflicts);
  free(pkg->provides);
  free(pkg->rflags);
  free(pkg->summary);
  if (pkg->h && !(pkg->flag & FLAG_NO_HEADER_FREE)) pkg->h = headerFree(pkg->h);
  free(pkg);

void
Pkg_name(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *name;
    char *version;

    get_fullname_parts(pkg, &name, &version, NULL, NULL, NULL);
    if (version - name < 1) croak("invalid fullname");
    mXPUSHs(newSVpv(name, version-name-1));
  } else if (pkg->h) {
    mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_NAME), 0));
  }

void
Pkg_version(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *version;
    char *release;

    get_fullname_parts(pkg, NULL, &version, &release, NULL, NULL);
    if (release - version < 1) croak("invalid fullname");
    mXPUSHs(newSVpv(version, release-version-1));
  } else if (pkg->h) {
    mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_VERSION), 0));
  }

void
Pkg_release(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *release;
    char *arch;

    get_fullname_parts(pkg, NULL, NULL, &release, &arch, NULL);
    if (arch - release < 1) croak("invalid fullname");
    mXPUSHs(newSVpv(release, arch-release-1));
  } else if (pkg->h) {
    mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_RELEASE), 0));
  }

void
Pkg_arch(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *arch;
    char *eos;

    get_fullname_parts(pkg, NULL, NULL, NULL, &arch, &eos);
    mXPUSHs(newSVpv(arch, eos-arch));
  } else if (pkg->h) {
    mXPUSHs(newSVpv(get_arch(pkg->h), 0));
  }

int
Pkg_is_arch_compat__XS(pkg)
  URPM::Package pkg
  INIT:
  CODE:
  read_config_files(0);
  if (pkg->info) {
    char *arch;
    char *eos;

    get_fullname_parts(pkg, NULL, NULL, NULL, &arch, &eos);
    *eos = 0;
    RETVAL = rpmMachineScore(RPM_MACHTABLE_INSTARCH, arch);
    *eos = '@';
  } else if (pkg->h && headerIsEntry(pkg->h, RPMTAG_SOURCERPM)) {
    char *arch = get_name(pkg->h, RPMTAG_ARCH);
    RETVAL = rpmMachineScore(RPM_MACHTABLE_INSTARCH, arch);
  } else {
    RETVAL = 0;
  }
  OUTPUT:
  RETVAL

void
Pkg_summary(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->summary) {
    mXPUSHs(newSVpv_utf8(pkg->summary, 0));
  } else if (pkg->h) {
    mXPUSHs(newSVpv_utf8(get_name(pkg->h, RPMTAG_SUMMARY), 0));
  }

void
Pkg_description(pkg)
  URPM::Package pkg
    ALIAS:
     sourcerpm = 1
     packager  = 2
     buildhost = 3
     url       = 4
     license   = 5
     distribution = 6
     vendor    = 7
     os        = 8
     payload_format = 9
     disttag = 10
  PPCODE:
  if (pkg->h)
       switch (ix) {
       case 0:
       mXPUSHs(newSVpv_utf8(get_name(pkg->h, RPMTAG_DESCRIPTION), 0)); break;
       case 1:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_SOURCERPM), 0)); break;
       case 2:
       mXPUSHs(newSVpv_utf8(get_name(pkg->h, RPMTAG_PACKAGER), 0)); break;
       case 3:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_BUILDHOST), 0)); break;
       case 4:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_URL), 0)); break;
       case 5:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_LICENSE), 0)); break;
       case 6:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_DISTRIBUTION), 0)); break;
       case 7:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_VENDOR), 0)); break;
       case 8:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_OS), 0)); break;
       case 9:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_PAYLOADFORMAT), 0)); break;
       case 10:
       mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_DISTTAG), 0)); break;
       }

int
Pkg_buildtime(pkg)
  URPM::Package pkg
  ALIAS:
       installtid = 1
  CODE:
  if (pkg->h) {
       switch (ix) {
       case 0:
       RETVAL = get_int(pkg->h, RPMTAG_BUILDTIME); break;
       case 1:
       RETVAL = get_int(pkg->h, RPMTAG_INSTALLTID); break;
       }
  } else
    RETVAL = 0;
  OUTPUT:
  RETVAL


void
Pkg_fullname(pkg)
  URPM::Package pkg
  PREINIT:
  I32 gimme = GIMME_V;
  PPCODE:
  if (pkg->info) {
    if (gimme == G_SCALAR) {
      char *eos;
      if ((eos = strchr(pkg->info, '@')) != NULL) {
	mXPUSHs(newSVpv(pkg->info, eos-pkg->info));
      }
    } else if (gimme == G_ARRAY) {
      char *name, *version, *release, *arch, *eos;
      get_fullname_parts(pkg, &name, &version, &release, &arch, &eos);
      if (version - name < 1 || release - version < 1 || arch - release < 1)
	  croak("invalid fullname");
      EXTEND(SP, 4);
      PUSHs(sv_2mortal(newSVpv(name, version-name-1)));
      PUSHs(sv_2mortal(newSVpv(version, release-version-1)));
      PUSHs(sv_2mortal(newSVpv(release, arch-release-1)));
      PUSHs(sv_2mortal(newSVpv(arch, eos-arch)));
    }
  } else if (pkg->h) {
    char *name = get_name(pkg->h, RPMTAG_NAME);
    char *version = get_name(pkg->h, RPMTAG_VERSION);
    char *release = get_name(pkg->h, RPMTAG_RELEASE);
    char *arch = get_arch(pkg->h);

    if (gimme == G_SCALAR) {
      mXPUSHs(newSVpvf("%s-%s-%s.%s", name, version, release, arch));
    } else if (gimme == G_ARRAY) {
      EXTEND(SP, 4);
      PUSHs(sv_2mortal(newSVpv(name, 0)));
      PUSHs(sv_2mortal(newSVpv(version, 0)));
      PUSHs(sv_2mortal(newSVpv(release, 0)));
      PUSHs(sv_2mortal(newSVpv(arch, 0)));
    }
  }

int
Pkg_epoch(pkg)
  URPM::Package pkg
  CODE:
  if (pkg->info) {
    char *s, *eos;

    if ((s = strchr(pkg->info, '@')) != NULL) {
      if ((eos = strchr(s+1, '@')) != NULL) *eos = 0; /* mark end of string to enable searching backwards */
      RETVAL = atoi(s+1);
      if (eos != NULL) *eos = '@';
    } else
      RETVAL = 0;
  } else if (pkg->h) {
    RETVAL = get_int(pkg->h, RPMTAG_EPOCH);
  } else RETVAL = 0;
  OUTPUT:
  RETVAL

int
Pkg_compare_pkg(lpkg, rpkg)
  URPM::Package lpkg
  URPM::Package rpkg
  PREINIT:
  int compare = 0;
  int lepoch;
  char *lversion;
  char *lrelease;
  char *larch;
  char *leos;
  int repoch;
  char *rversion;
  char *rrelease;
  char *rarch;
  char *reos;
  CODE:
  if (lpkg == rpkg) RETVAL = 0;
  else {
    if (lpkg->info) {
      char *s;

      if ((s = strchr(lpkg->info, '@')) != NULL) {
	if ((leos = strchr(s+1, '@')) != NULL) *leos = 0; /* mark end of string to enable searching backwards */
	lepoch = atoi(s+1);
	if (leos != NULL) *leos = '@';
      } else
	lepoch = 0;
      get_fullname_parts(lpkg, NULL, &lversion, &lrelease, &larch, &leos);
      /* temporarily mark end of each substring */
      lrelease[-1] = 0;
      larch[-1] = 0;
    } else if (lpkg->h) {
      lepoch = get_int(lpkg->h, RPMTAG_EPOCH);
      lversion = get_name(lpkg->h, RPMTAG_VERSION);
      lrelease = get_name(lpkg->h, RPMTAG_RELEASE);
      larch = get_arch(lpkg->h);
    } else croak("undefined package");
    if (rpkg->info) {
      char *s;

      if ((s = strchr(rpkg->info, '@')) != NULL) {
	if ((reos = strchr(s+1, '@')) != NULL) *reos = 0; /* mark end of string to enable searching backwards */
	repoch = atoi(s+1);
	if (reos != NULL) *reos = '@';
      } else
	repoch = 0;
      get_fullname_parts(rpkg, NULL, &rversion, &rrelease, &rarch, &reos);
      /* temporarily mark end of each substring */
      rrelease[-1] = 0;
      rarch[-1] = 0;
    } else if (rpkg->h) {
      repoch = get_int(rpkg->h, RPMTAG_EPOCH);
      rversion = get_name(rpkg->h, RPMTAG_VERSION);
      rrelease = get_name(rpkg->h, RPMTAG_RELEASE);
      rarch = get_arch(rpkg->h);
    } else {
      /* restore info string modified */
      if (lpkg->info) {
	lrelease[-1] = '-';
	larch[-1] = '.';
      }
      croak("undefined package");
    }
    compare = lepoch - repoch;
    if (!compare) {
      compare = rpmvercmp(lversion, rversion);
      if (!compare) {
	compare = rpmvercmp(lrelease, rrelease);
	if (!compare) {
	  int lscore, rscore;
	  char *eolarch = strchr(larch, '@');
	  char *eorarch = strchr(rarch, '@');

	  read_config_files(0);
	  if (eolarch) *eolarch = 0; lscore = rpmMachineScore(RPM_MACHTABLE_INSTARCH, larch);
	  if (eorarch) *eorarch = 0; rscore = rpmMachineScore(RPM_MACHTABLE_INSTARCH, rarch);
	  if (lscore == 0) {
	    if (rscore == 0)
#if 0
              /* Nanar: TODO check this 
               * hu ?? what is the goal of strcmp, some of arch are equivalent */
              compare = 0
#endif
	      compare = strcmp(larch, rarch);
	    else
	      compare = -1;
	  } else {
	    if (rscore == 0)
	      compare = 1;
	    else
	      compare = rscore - lscore; /* score are lower for better */
	  }
	  if (eolarch) *eolarch = '@';
	  if (eorarch) *eorarch = '@';
	}
      }
    }
    /* restore info string modified */
    if (lpkg->info) {
      lrelease[-1] = '-';
      larch[-1] = '.';
    }
    if (rpkg->info) {
      rrelease[-1] = '-';
      rarch[-1] = '.';
    }
    RETVAL = compare;
  }
  OUTPUT:
  RETVAL

int
Pkg_compare(pkg, evr)
  URPM::Package pkg
  char *evr
  PREINIT:
  int compare = 0;
  int _epoch;
  char *_version;
  char *_release;
  char *_eos;
  CODE:
  if (pkg->info) {
    char *s;

    if ((s = strchr(pkg->info, '@')) != NULL) {
      if ((_eos = strchr(s+1, '@')) != NULL) *_eos = 0; /* mark end of string to enable searching backwards */
      _epoch = atoi(s+1);
      if (_eos != NULL) *_eos = '@';
    } else
      _epoch = 0;
    get_fullname_parts(pkg, NULL, &_version, &_release, &_eos, NULL);
    /* temporarily mark end of each substring */
    _release[-1] = 0;
    _eos[-1] = 0;
  } else if (pkg->h)
    _epoch = get_int(pkg->h, RPMTAG_EPOCH);
  else croak("undefined package");
  if (!compare) {
    char *epoch, *version, *release;

    /* extract epoch and version from evr */
    version = evr;
    while (*version && isdigit(*version)) version++;
    if (*version == ':') {
      epoch = evr;
      *version++ = 0;
      if (!*epoch) epoch = "0";
      compare = _epoch - (*epoch ? atoi(epoch) : 0);
      version[-1] = ':'; /* restore in memory modification */
    } else {
      /* there is no epoch defined, so assume epoch = 0 */
      version = evr;
      compare = _epoch;
    }
    if (!compare) {
      if (!pkg->info)
	_version = get_name(pkg->h, RPMTAG_VERSION);
      /* continue extracting release if any */
      if ((release = strrchr(version, '-')) != NULL) {
	*release++ = 0;
	compare = rpmvercmp(_version, version);
	if (!compare) {
	  /* need to compare with release here */
	  if (!pkg->info)
	    _release = get_name(pkg->h, RPMTAG_RELEASE);
	  compare = rpmvercmp(_release, release);
	}
	release[-1] = '-'; /* restore in memory modification */
      } else {
	compare = rpmvercmp(_version, version);
      }
    }
  }
  /* restore info string modified */
  if (pkg->info) {
    _release[-1] = '-';
    _eos[-1] = '.';
  }
  RETVAL = compare;
  OUTPUT:
  RETVAL

int
Pkg_size(pkg)
  URPM::Package pkg
  CODE:
  if (pkg->info) {
    char *s, *eos;

    if ((s = strchr(pkg->info, '@')) != NULL && (s = strchr(s+1, '@')) != NULL) {
      if ((eos = strchr(s+1, '@')) != NULL) *eos = 0; /* mark end of string to enable searching backwards */
      RETVAL = atoi(s+1);
      if (eos != NULL) *eos = '@';
    } else
      RETVAL = 0;
  } else if (pkg->h)
    RETVAL = get_int(pkg->h, RPMTAG_SIZE);
  else
    RETVAL = 0;
  OUTPUT:
  RETVAL

void
Pkg_set_filesize(pkg, filesize)
  URPM::Package pkg
  size_t filesize;
  PPCODE:
  pkg->filesize = filesize;

int
Pkg_filesize(pkg)
  URPM::Package pkg
  CODE:
  if (pkg->filesize)
    RETVAL = pkg->filesize;
  else if (pkg->h)
    RETVAL = get_filesize(pkg->h);
  else RETVAL = 0;
  OUTPUT:
  RETVAL

void
Pkg_group(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *s;

    if ((s = strchr(pkg->info, '@')) != NULL && (s = strchr(s+1, '@')) != NULL && (s = strchr(s+1, '@')) != NULL) {
      char *eos = strchr(s+1, '@');
      mXPUSHs(newSVpv_utf8(s+1, eos != NULL ? eos-s-1 : 0));
    }
  } else if (pkg->h)
    mXPUSHs(newSVpv_utf8(get_name(pkg->h, RPMTAG_GROUP), 0));

void
Pkg_filename(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *eon;

    if ((eon = strchr(pkg->info, '@')) != NULL) {
	char savbuf[4];
	memcpy(savbuf, eon, 4); /* there should be at least epoch and size described so (@0@0 minimum) */
	memcpy(eon, ".rpm", 4);
	mXPUSHs(newSVpv(pkg->info, eon-pkg->info+4));
	memcpy(eon, savbuf, 4);
    }
  } else if (pkg->h) {
    char *name = get_name(pkg->h, RPMTAG_NAME);
    char *version = get_name(pkg->h, RPMTAG_VERSION);
    char *release = get_name(pkg->h, RPMTAG_RELEASE);
    char *arch = get_arch(pkg->h);

    mXPUSHs(newSVpvf("%s-%s-%s.%s.rpm", name, version, release, arch));
  }

# deprecated
void
Pkg_header_filename(pkg)
  URPM::Package pkg
  PPCODE:
  if (pkg->info) {
    char *eon;

    if ((eon = strchr(pkg->info, '@')) != NULL) {
      mXPUSHs(newSVpv(pkg->info, eon-pkg->info));
    }
  } else if (pkg->h) {
    char buff[1024];
    char *p = buff;
    char *name = get_name(pkg->h, RPMTAG_NAME);
    char *version = get_name(pkg->h, RPMTAG_VERSION);
    char *release = get_name(pkg->h, RPMTAG_RELEASE);
    char *arch = get_arch(pkg->h);

    p += snprintf(buff, sizeof(buff), "%s-%s-%s.%s", name, version, release, arch);
    mXPUSHs(newSVpv(buff, p-buff));
  }

void
Pkg_id(pkg)
  URPM::Package pkg
  PPCODE:
  if ((pkg->flag & FLAG_ID) <= FLAG_ID_MAX) {
    mXPUSHs(newSViv(pkg->flag & FLAG_ID));
  }

void
Pkg_set_id(pkg, id=-1)
  URPM::Package pkg
  int id
  PPCODE:
  if ((pkg->flag & FLAG_ID) <= FLAG_ID_MAX)
    mXPUSHs(newSViv(pkg->flag & FLAG_ID));
  pkg->flag &= ~FLAG_ID;
  pkg->flag |= id >= 0 && id <= FLAG_ID_MAX ? id : FLAG_ID_INVALID;

void
Pkg_requires(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->requires, pkg->h, RPMTAG_REQUIRENAME, RPMTAG_REQUIREFLAGS, RPMTAG_REQUIREVERSION,
		  callback_list_str_xpush_requires, NULL);
  SPAGAIN;

void
Pkg_requires_nosense(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->requires, pkg->h, RPMTAG_REQUIRENAME, RPMTAG_REQUIREFLAGS, 0, 
		  callback_list_str_xpush_requires, NULL);
  SPAGAIN;

void
Pkg_suggests(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  int count = return_list_str(pkg->suggests, pkg->h, RPMTAG_SUGGESTSNAME, 0, 0, callback_list_str_xpush, NULL);
  if (count == 0)
    return_list_str(pkg->suggests, pkg->h, RPMTAG_REQUIRENAME, RPMTAG_REQUIREFLAGS, 0,
		    callback_list_str_xpush_old_suggests, NULL);
  SPAGAIN;

void
Pkg_obsoletes(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->obsoletes, pkg->h, RPMTAG_OBSOLETENAME, RPMTAG_OBSOLETEFLAGS, RPMTAG_OBSOLETEVERSION,
		  callback_list_str_xpush, NULL);
  SPAGAIN;

void
Pkg_obsoletes_nosense(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->obsoletes, pkg->h, RPMTAG_OBSOLETENAME, 0, 0, callback_list_str_xpush, NULL);
  SPAGAIN;

int
Pkg_obsoletes_overlap(pkg, s, b_nopromote=1, direction=-1)
  URPM::Package pkg
  char *s
  int b_nopromote
  int direction
  PREINIT:
  struct cb_overlap_s os;
  char *eon = NULL;
  char eonc = '\0';
  CODE:
  os.name = s;
  os.flags = 0;
  while (*s && *s != ' ' && *s != '[' && *s != '<' && *s != '>' && *s != '=') ++s;
  if (*s) {
    eon = s;
    while (*s) {
      if (*s == ' ' || *s == '[' || *s == '*' || *s == ']');
      else if (*s == '<') os.flags |= RPMSENSE_LESS;
      else if (*s == '>') os.flags |= RPMSENSE_GREATER;
      else if (*s == '=') os.flags |= RPMSENSE_EQUAL;
      else break;
      ++s;
    }
    os.evr = s;
  } else
    os.evr = "";
  os.direction = direction;
  os.b_nopromote = b_nopromote;
  /* mark end of name */
  if (eon) { eonc = *eon; *eon = 0; }
  /* return_list_str returns a negative value is the callback has returned non-zero */
  RETVAL = return_list_str(pkg->obsoletes, pkg->h, RPMTAG_OBSOLETENAME, RPMTAG_OBSOLETEFLAGS, RPMTAG_OBSOLETEVERSION,
			   callback_list_str_overlap, &os) < 0;
  /* restore end of name */
  if (eon) *eon = eonc;
  OUTPUT:
  RETVAL

void
Pkg_conflicts(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->conflicts, pkg->h, RPMTAG_CONFLICTNAME, RPMTAG_CONFLICTFLAGS, RPMTAG_CONFLICTVERSION,
		  callback_list_str_xpush, NULL);
  SPAGAIN;

void
Pkg_conflicts_nosense(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->conflicts, pkg->h, RPMTAG_CONFLICTNAME, 0, 0, callback_list_str_xpush, NULL);
  SPAGAIN;

void
Pkg_provides(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->provides, pkg->h, RPMTAG_PROVIDENAME, RPMTAG_PROVIDEFLAGS, RPMTAG_PROVIDEVERSION,
		  callback_list_str_xpush, NULL);
  SPAGAIN;

void
Pkg_provides_nosense(pkg)
  URPM::Package pkg
  PPCODE:
  PUTBACK;
  return_list_str(pkg->provides, pkg->h, RPMTAG_PROVIDENAME, 0, 0, callback_list_str_xpush, NULL);
  SPAGAIN;

int
Pkg_provides_overlap(pkg, s, b_nopromote=1, direction=1)
  URPM::Package pkg
  char *s
  int b_nopromote
  int direction
  PREINIT:
  struct cb_overlap_s os;
  char *eon = NULL;
  char eonc = '\0';
  CODE:
  os.name = s;
  os.flags = 0;
  while (*s && *s != ' ' && *s != '[' && *s != '<' && *s != '>' && *s != '=') ++s;
  if (*s) {
    eon = s;
    while (*s) {
      if (*s == ' ' || *s == '[' || *s == '*' || *s == ']');
      else if (*s == '<') os.flags |= RPMSENSE_LESS;
      else if (*s == '>') os.flags |= RPMSENSE_GREATER;
      else if (*s == '=') os.flags |= RPMSENSE_EQUAL;
      else break;
      ++s;
    }
    os.evr = s;
  } else
    os.evr = "";
  os.direction = direction;
  os.b_nopromote = b_nopromote;
  /* mark end of name */
  if (eon) { eonc = *eon; *eon = 0; }
  /* return_list_str returns a negative value is the callback has returned non-zero */
  RETVAL = return_list_str(pkg->provides, pkg->h, RPMTAG_PROVIDENAME, RPMTAG_PROVIDEFLAGS, RPMTAG_PROVIDEVERSION,
			   callback_list_str_overlap, &os) < 0;
  /* restore end of name */
  if (eon) *eon = eonc;
  OUTPUT:
  RETVAL

void
Pkg_buildarchs(pkg)
  URPM::Package pkg
  ALIAS:
    excludearchs   = 1
    exclusivearchs = 2
    dirnames       = 3
    filelinktos    = 4
    files          = 5
    files_md5sum   = 6
    files_owner    = 7
    files_group    = 8
    files_mtime    = 9
    files_size     = 10
    files_uid      = 11
    files_gid      = 12
    files_mode     = 13
    files_flags    = 14
    conf_files     = 15
    changelog_time = 16
    changelog_name = 17
    changelog_text = 18
  PPCODE:
  PUTBACK;
       switch (ix) {
       case 0:
            xpush_simple_list_str(pkg->h, RPMTAG_BUILDARCHS); break;
       case 1:
            xpush_simple_list_str(pkg->h, RPMTAG_EXCLUDEARCH); break;
       case 2:
            xpush_simple_list_str(pkg->h, RPMTAG_EXCLUSIVEARCH); break;
       case 3:
            xpush_simple_list_str(pkg->h, RPMTAG_DIRNAMES); break;
       case 4:
            xpush_simple_list_str(pkg->h, RPMTAG_FILELINKTOS); break;
       case 5:
            return_files(pkg->h, 0); break;
       case 6:
            xpush_simple_list_str(pkg->h, RPMTAG_FILEMD5S); break;
       case 7:
            xpush_simple_list_str(pkg->h, RPMTAG_FILEUSERNAME); break;
       case 8:
            xpush_simple_list_str(pkg->h, RPMTAG_FILEGROUPNAME); break;
       case 9:
            return_list_int32_t(pkg->h, RPMTAG_FILEMTIMES); break;
       case 10:
            return_list_int32_t(pkg->h, RPMTAG_FILESIZES); break;
       case 11:
            return_list_int32_t(pkg->h, RPMTAG_FILEUIDS); break;
       case 12:
            return_list_int32_t(pkg->h, RPMTAG_FILEGIDS); break;
       case 13:
            return_list_uint_16(pkg->h, RPMTAG_FILEMODES); break;
       case 14:
            return_list_int32_t(pkg->h, RPMTAG_FILEFLAGS); break;
       case 15:
            return_files(pkg->h, FILTER_MODE_CONF_FILES); break;
       case 16:
            return_list_int32_t(pkg->h, RPMTAG_CHANGELOGTIME); break;
       case 17:
            xpush_simple_list_str(pkg->h, RPMTAG_CHANGELOGNAME); break;
       case 18:
            xpush_simple_list_str(pkg->h, RPMTAG_CHANGELOGTEXT); break;
       }
  SPAGAIN;


void Pkg_distepoch(pkg)
  URPM::Package pkg
  PPCODE:
#ifdef RPMTAG_DISTEPOCH
  if (pkg->h) {
    mXPUSHs(newSVpv(get_name(pkg->h, RPMTAG_DISTEPOCH), 0));
  }
#else
  croak("distepoch isn't available with this rpm version");
#endif

void
Pkg_queryformat(pkg, fmt)
  URPM::Package pkg
  char *fmt
  PREINIT:
  char *s;
  PPCODE:
  if (pkg->h) {
    s = headerFormat(pkg->h, fmt, NULL);
      if (s)
        mXPUSHs(newSVpv_utf8(s,0));
  }
  
void
Pkg_get_tag(pkg, tagname)
  URPM::Package pkg
  int tagname;
  ALIAS:
    get_tag_modifiers = 1
  PPCODE:
  PUTBACK;
  switch (ix) {
  case 0:
       return_list_tag(pkg, tagname); break;
  case 1:
       return_list_tag_modifier(pkg->h, tagname); break;
  }
  SPAGAIN;

  
void
Pkg_pack_header(pkg)
  URPM::Package pkg
  CODE:
  pack_header(pkg);

int
Pkg_update_header(pkg, filename, ...)
  URPM::Package pkg
  char *filename
  PREINIT:
  int packing = 0;
  int keep_all_tags = 0;
  CODE:
  if (items > 3) {
    int i;
    for (i = 2; i < items-1; i+=2) {
      STRLEN len;
      char *s = SvPV(ST(i), len);

      if (len == 7 && !memcmp(s, "packing", 7))
	packing = SvTRUE(ST(i + 1));
      else if (len == 13 && !memcmp(s, "keep_all_tags", 13))
	keep_all_tags = SvTRUE(ST(i+1));
    }
  }
  RETVAL = update_header(filename, pkg, !packing && keep_all_tags, RPMVSF_DEFAULT);
  if (RETVAL && packing) pack_header(pkg);
  OUTPUT:
  RETVAL

void
Pkg_free_header(pkg)
  URPM::Package pkg
  CODE:
  if (pkg->h && !(pkg->flag & FLAG_NO_HEADER_FREE)) pkg->h = headerFree(pkg->h);
  pkg->h = NULL;

void
Pkg_build_info(pkg, fileno, provides_files=NULL)
  URPM::Package pkg
  int fileno
  char *provides_files
  CODE:
  if (pkg->info) {
    char buff[65536];
    size_t size;

    /* info line should be the last to be written */
    if (pkg->provides && *pkg->provides) {
      size = snprintf(buff, sizeof(buff), "@provides@%s\n", pkg->provides);
      if (size < sizeof(buff)) {
	if (provides_files && *provides_files) {
	  --size;
	  size += snprintf(buff+size, sizeof(buff)-size, "@%s\n", provides_files);
	}
	write_nocheck(fileno, buff, size);
      }
    }
    if (pkg->conflicts && *pkg->conflicts) {
      size = snprintf(buff, sizeof(buff), "@conflicts@%s\n", pkg->conflicts);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    if (pkg->obsoletes && *pkg->obsoletes) {
      size = snprintf(buff, sizeof(buff), "@obsoletes@%s\n", pkg->obsoletes);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    if (pkg->requires && *pkg->requires) {
      size = snprintf(buff, sizeof(buff), "@requires@%s\n", pkg->requires);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    if (pkg->suggests && *pkg->suggests) {
      size = snprintf(buff, sizeof(buff), "@suggests@%s\n", pkg->suggests);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    if (pkg->summary && *pkg->summary) {
      size = snprintf(buff, sizeof(buff), "@summary@%s\n", pkg->summary);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    if (pkg->filesize) {
      size = snprintf(buff, sizeof(buff), "@filesize@%d\n", pkg->filesize);
      if (size < sizeof(buff)) write_nocheck(fileno, buff, size);
    }
    size = snprintf(buff, sizeof(buff), "@info@%s\n", pkg->info);
    write_nocheck(fileno, buff, size);
  } else croak("no info available for package %s",
	  pkg->h ? get_name(pkg->h, RPMTAG_NAME) : "-");

void
Pkg_build_header(pkg, fileno)
  URPM::Package pkg
  int fileno
  CODE:
  if (pkg->h) {
    FD_t fd;

    if ((fd = fdDup(fileno)) != NULL) {
      headerWrite(fd, pkg->h, HEADER_MAGIC_YES);
      Fclose(fd);
    } else croak("unable to get rpmio handle on fileno %d", fileno);
  } else croak("no header available for package");

int
Pkg_flag(pkg, name)
  URPM::Package pkg
  char *name
  PREINIT:
  unsigned mask;
  CODE:
  if (!strcmp(name, "skip")) mask = FLAG_SKIP;
  else if (!strcmp(name, "disable_obsolete")) mask = FLAG_DISABLE_OBSOLETE;
  else if (!strcmp(name, "installed")) mask = FLAG_INSTALLED;
  else if (!strcmp(name, "requested")) mask = FLAG_REQUESTED;
  else if (!strcmp(name, "required")) mask = FLAG_REQUIRED;
  else if (!strcmp(name, "upgrade")) mask = FLAG_UPGRADE;
  else croak("unknown flag: %s", name);
  RETVAL = pkg->flag & mask;
  OUTPUT:
  RETVAL

int
Pkg_set_flag(pkg, name, value=1)
  URPM::Package pkg
  char *name
  int value
  PREINIT:
  unsigned mask;
  CODE:
  if (!strcmp(name, "skip")) mask = FLAG_SKIP;
  else if (!strcmp(name, "disable_obsolete")) mask = FLAG_DISABLE_OBSOLETE;
  else if (!strcmp(name, "installed")) mask = FLAG_INSTALLED;
  else if (!strcmp(name, "requested")) mask = FLAG_REQUESTED;
  else if (!strcmp(name, "required")) mask = FLAG_REQUIRED;
  else if (!strcmp(name, "upgrade")) mask = FLAG_UPGRADE;
  else croak("unknown flag: %s", name);
  RETVAL = pkg->flag & mask;
  if (value) pkg->flag |= mask;
  else       pkg->flag &= ~mask;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_skip(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_SKIP;
  if (value) pkg->flag |= FLAG_SKIP;
  else       pkg->flag &= ~FLAG_SKIP;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_base(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_BASE;
  if (value) pkg->flag |= FLAG_BASE;
  else       pkg->flag &= ~FLAG_BASE;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_disable_obsolete(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_DISABLE_OBSOLETE;
  if (value) pkg->flag |= FLAG_DISABLE_OBSOLETE;
  else       pkg->flag &= ~FLAG_DISABLE_OBSOLETE;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_installed(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_INSTALLED;
  if (value) pkg->flag |= FLAG_INSTALLED;
  else       pkg->flag &= ~FLAG_INSTALLED;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_requested(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_REQUESTED;
  if (value) pkg->flag |= FLAG_REQUESTED;
  else       pkg->flag &= ~FLAG_REQUESTED;
  OUTPUT:
  RETVAL

int
Pkg_flag_required(pkg)
  URPM::Package pkg
  ALIAS:
    flag_upgrade = 1
    flag_disable_obsolete = 2
    flag_requested = 3
    flag_installed = 4
    flag_base = 5
    flag_skip = 6
  CODE:
  unsigned flag;
  switch (ix) {
  case 0: flag = FLAG_REQUIRED; break;
  case 1: flag = FLAG_UPGRADE; break;
  case 2: flag = FLAG_DISABLE_OBSOLETE; break;
  case 3: flag = FLAG_REQUESTED; break;
  case 4: flag = FLAG_INSTALLED; break;
  case 5: flag = FLAG_BASE; break;
  case 6: flag = FLAG_SKIP; break;
  }
  RETVAL = pkg->flag & flag;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_required(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_REQUIRED;
  if (value) pkg->flag |= FLAG_REQUIRED;
  else       pkg->flag &= ~FLAG_REQUIRED;
  OUTPUT:
  RETVAL

int
Pkg_set_flag_upgrade(pkg, value=1)
  URPM::Package pkg
  int value
  CODE:
  RETVAL = pkg->flag & FLAG_UPGRADE;
  if (value) pkg->flag |= FLAG_UPGRADE;
  else       pkg->flag &= ~FLAG_UPGRADE;
  OUTPUT:
  RETVAL

int
Pkg_flag_selected(pkg)
  URPM::Package pkg
  CODE:
  RETVAL = pkg->flag & FLAG_UPGRADE ? pkg->flag & (FLAG_BASE | FLAG_REQUIRED) : 0;
  OUTPUT:
  RETVAL

int
Pkg_flag_available(pkg)
  URPM::Package pkg
  CODE:
  RETVAL = (pkg->flag & FLAG_INSTALLED && !(pkg->flag & FLAG_UPGRADE)) ||
           (pkg->flag & FLAG_UPGRADE ? pkg->flag & (FLAG_BASE | FLAG_REQUIRED) : 0);
  OUTPUT:
  RETVAL

int
Pkg_rate(pkg)
  URPM::Package pkg
  CODE:
  RETVAL = (pkg->flag & FLAG_RATE) >> FLAG_RATE_POS;
  OUTPUT:
  RETVAL

int
Pkg_set_rate(pkg, rate)
  URPM::Package pkg
  int rate
  CODE:
  RETVAL = (pkg->flag & FLAG_RATE) >> FLAG_RATE_POS;
  pkg->flag &= ~FLAG_RATE;
  pkg->flag |= (rate >= 0 && rate <= FLAG_RATE_MAX ? rate : FLAG_RATE_INVALID) << FLAG_RATE_POS;
  OUTPUT:
  RETVAL

void
Pkg_rflags(pkg)
  URPM::Package pkg
  PREINIT:
  I32 gimme = GIMME_V;
  PPCODE:
  if (gimme == G_ARRAY && pkg->rflags != NULL) {
    char *s = pkg->rflags;
    char *eos;
    while ((eos = strchr(s, '\t')) != NULL) {
      mXPUSHs(newSVpv(s, eos-s));
      s = eos + 1;
    }
    mXPUSHs(newSVpv(s, 0));
  }

void
Pkg_set_rflags(pkg, ...)
  URPM::Package pkg
  PREINIT:
  I32 gimme = GIMME_V;
  char *new_rflags;
  STRLEN total_len;
  int i;
  PPCODE:
  total_len = 0;
  for (i = 1; i < items; ++i)
    total_len += SvCUR(ST(i)) + 1;

  new_rflags = malloc(total_len);
  total_len = 0;
  for (i = 1; i < items; ++i) {
    STRLEN len;
    char *s = SvPV(ST(i), len);
    memcpy(new_rflags + total_len, s, len);
    new_rflags[total_len + len] = '\t';
    total_len += len + 1;
  }
  new_rflags[total_len - 1] = 0; /* but mark end-of-string correctly */

  if (gimme == G_ARRAY && pkg->rflags != NULL) {
    char *s = pkg->rflags;
    char *eos;
    while ((eos = strchr(s, '\t')) != NULL) {
      mXPUSHs(newSVpv(s, eos-s));
      s = eos + 1;
    }
    mXPUSHs(newSVpv(s, 0));
  }

  free(pkg->rflags);
  pkg->rflags = new_rflags;


MODULE = URPM            PACKAGE = URPM::DB            PREFIX = Db_

URPM::DB
Db_open(prefix=NULL, write_perm=0)
  char *prefix
  int write_perm
  PREINIT:
  URPM__DB db;
  CODE:
  read_config_files(0);
  db = malloc(sizeof(struct s_Transaction));
  db->count = 1;
  db->ts = rpmtsCreate();
  rpmtsSetRootDir(db->ts, prefix && prefix[0] ? prefix : NULL);
  if (rpmtsOpenDB(db->ts, write_perm ? O_RDWR | O_CREAT : O_RDONLY) == 0) {
    RETVAL = db;
  } else {
    RETVAL = NULL;
    (void)rpmtsFree(db->ts);
    free(db);
  }
  OUTPUT:
  RETVAL

int
Db_rebuild(prefix="")
  char *prefix
  PREINIT:
  rpmts ts;
  CODE:
  read_config_files(0);
  ts = rpmtsCreate();
  rpmtsSetRootDir(ts, prefix);
  RETVAL = rpmtsRebuildDB(ts) == 0;
  (void)rpmtsFree(ts);
  OUTPUT:
  RETVAL

int
Db_verify(prefix="")
  char *prefix
  PREINIT:
  rpmts ts;
  CODE:
  ts = rpmtsCreate();
  rpmtsSetRootDir(ts, prefix);
  RETVAL = rpmtsVerifyDB(ts) == 0;
  ts = rpmtsFree(ts);
  OUTPUT:
  RETVAL

void
Db_DESTROY(db)
  URPM::DB db
  CODE:
  (void)rpmtsFree(db->ts);
  if (!--db->count) free(db);

int
Db_traverse(db,callback)
  URPM::DB db
  SV *callback
  PREINIT:
  Header header;
  rpmdbMatchIterator mi;
  int count = 0;
  CODE:
  db->ts = rpmtsLink(db->ts);
  ts_nosignature(db->ts);
  mi = rpmtsInitIterator(db->ts, RPMDBI_PACKAGES, NULL, 0);
  while ((header = rpmdbNextIterator(mi))) {
    if (SvROK(callback)) {
      dSP;
      URPM__Package pkg = calloc(1, sizeof(struct s_Package));

      pkg->flag = FLAG_ID_INVALID | FLAG_NO_HEADER_FREE;
      pkg->h = header;

      PUSHMARK(SP);
      mXPUSHs(sv_setref_pv(newSVpv("", 0), "URPM::Package", pkg));
      PUTBACK;

      call_sv(callback, G_DISCARD | G_SCALAR);

      SPAGAIN;
      pkg->h = NULL; /* avoid using it anymore, in case it has been copied inside callback */
    }
    ++count;
  }
  rpmdbFreeIterator(mi);
  (void)rpmtsFree(db->ts);
  RETVAL = count;
  OUTPUT:
  RETVAL

int
Db_traverse_tag(db,tag,names,callback)
  URPM::DB db
  char *tag
  SV *names
  SV *callback
  PREINIT:
  Header header;
  rpmdbMatchIterator mi;
  int count = 0;
  CODE:
  if (SvROK(names) && SvTYPE(SvRV(names)) == SVt_PVAV) {
    AV* names_av = (AV*)SvRV(names);
    int len = av_len(names_av);
    int i, rpmtag;

    rpmtag = rpmtag_from_string(tag);

    for (i = 0; i <= len; ++i) {
      STRLEN str_len;
      SV **isv = av_fetch(names_av, i, 0);
      char *name = SvPV(*isv, str_len);
      db->ts = rpmtsLink(db->ts);
      ts_nosignature(db->ts);
      mi = rpmtsInitIterator(db->ts, rpmtag, name, str_len);
      while ((header = rpmdbNextIterator(mi))) {
	if (SvROK(callback)) {
	  dSP;
	  URPM__Package pkg = calloc(1, sizeof(struct s_Package));

	  pkg->flag = FLAG_ID_INVALID | FLAG_NO_HEADER_FREE;
	  pkg->h = header;

	  PUSHMARK(SP);
	  mXPUSHs(sv_setref_pv(newSVpv("", 0), "URPM::Package", pkg));
	  PUTBACK;

	  call_sv(callback, G_DISCARD | G_SCALAR);

	  SPAGAIN;
	  pkg->h = NULL; /* avoid using it anymore, in case it has been copied inside callback */
	}
	++count;
      }
      (void)rpmdbFreeIterator(mi);
      (void)rpmtsFree(db->ts);
    } 
  } else croak("bad arguments list");
  RETVAL = count;
  OUTPUT:
  RETVAL

int
Db_traverse_tag_find(db,tag,name,callback)
  URPM::DB db
  char *tag
  char *name
  SV *callback
  PREINIT:
  Header header;
  rpmdbMatchIterator mi;
  CODE:
  int rpmtag = rpmtag_from_string(tag);
  int found = 0;
  db->ts = rpmtsLink(db->ts);
  ts_nosignature(db->ts);
  mi = rpmtsInitIterator(db->ts, rpmtag, name, 0);
  while ((header = rpmdbNextIterator(mi))) {
      dSP;
      URPM__Package pkg = calloc(1, sizeof(struct s_Package));

      pkg->flag = FLAG_ID_INVALID | FLAG_NO_HEADER_FREE;
      pkg->h = header;

      PUSHMARK(SP);
      mXPUSHs(sv_setref_pv(newSVpv("", 0), "URPM::Package", pkg));
      PUTBACK;

      int count = call_sv(callback, G_SCALAR);

      SPAGAIN;
      pkg->h = NULL; /* avoid using it anymore, in case it has been copied inside callback */

      if (count == 1 && POPi) {
	found = 1;
	break;
      }
  }
  (void)rpmdbFreeIterator(mi);
  (void)rpmtsFree(db->ts);
  RETVAL = found;
  OUTPUT:
  RETVAL

URPM::Transaction
Db_create_transaction(db, prefix="/")
  URPM::DB db
  char *prefix
  CODE:
  /* this is *REALLY* dangerous to create a new transaction while another is open,
     so use the db transaction instead. */
  db->ts = rpmtsLink(db->ts);
  ++db->count;
  RETVAL = db;
  OUTPUT:
  RETVAL


MODULE = URPM            PACKAGE = URPM::Transaction   PREFIX = Trans_

void
Trans_DESTROY(trans)
  URPM::Transaction trans
  CODE:
  (void)rpmtsFree(trans->ts);
  if (!--trans->count) free(trans);

void
Trans_set_script_fd(trans, fdno)
  URPM::Transaction trans
  int fdno
  CODE:
  rpmtsSetScriptFd(trans->ts, fdDup(fdno));

int
Trans_add(trans, pkg, ...)
  URPM::Transaction trans
  URPM::Package pkg
  CODE:
  if ((pkg->flag & FLAG_ID) <= FLAG_ID_MAX && pkg->h != NULL) {
    int update = 0;
    rpmRelocation *relocations = NULL;
    if (items > 3) {
      int i;
      for (i = 2; i < items-1; i+=2) {
	STRLEN len;
	char *s = SvPV(ST(i), len);

	if (len == 6 && !memcmp(s, "update", 6))
	  update = SvIV(ST(i+1));
	else if (len == 11 && !memcmp(s, "excludepath", 11)) {
	  if (SvROK(ST(i+1)) && SvTYPE(SvRV(ST(i+1))) == SVt_PVAV) {
	    AV *excludepath = (AV*)SvRV(ST(i+1));
	    I32 j = 1 + av_len(excludepath);
	    relocations = calloc(j + 1, sizeof(rpmRelocation));
	    while (--j >= 0) {
	      SV **e = av_fetch(excludepath, j, 0);
	      if (e != NULL && *e != NULL)
		relocations[j].oldPath = SvPV_nolen(*e);
	    }
	  }
	}
      }
    }
    RETVAL = rpmtsAddInstallElement(trans->ts, pkg->h, (fnpyKey)(1+(long)(pkg->flag & FLAG_ID)), update, relocations) == 0;
    /* free allocated memory, check rpm is copying it just above, at least in 4.0.4 */
    free(relocations);
  } else RETVAL = 0;
  OUTPUT:
  RETVAL

int
Trans_remove(trans, name)
  URPM::Transaction trans
  char *name
  PREINIT:
  Header h;
  rpmdbMatchIterator mi;
  int count = 0;
  char *boa = NULL, *bor = NULL;
  CODE:
  /* hide arch in name if present */
  if ((boa = strrchr(name, '.'))) {
    *boa = 0;
    if ((bor = strrchr(name, '-'))) {
      *bor = 0;
      if (!strrchr(name, '-'))
	*boa = '.'; boa = NULL;
      *bor = '-'; bor = NULL;
    } else
      *boa = '.'; boa = NULL;
  }
  mi = rpmtsInitIterator(trans->ts, RPMDBI_LABEL, name, 0);
  while ((h = rpmdbNextIterator(mi))) {
    unsigned int recOffset = rpmdbGetIteratorOffset(mi);
    if (recOffset != 0) {
      rpmtsAddEraseElement(trans->ts, h, recOffset);
      ++count;
    }
  }
  rpmdbFreeIterator(mi);
  if (boa) *boa = '.';
  RETVAL=count;
  OUTPUT:
  RETVAL

int
Trans_traverse(trans, callback)
  URPM::Transaction trans
  SV *callback
  PREINIT:
  rpmdbMatchIterator mi;
  Header h;
  int c = 0;
  CODE:
  mi = rpmtsInitIterator(trans->ts, RPMDBI_PACKAGES, NULL, 0);
  while ((h = rpmdbNextIterator(mi))) {
    if (SvROK(callback)) {
      dSP;
      URPM__Package pkg = calloc(1, sizeof(struct s_Package));
      pkg->flag = FLAG_ID_INVALID | FLAG_NO_HEADER_FREE;
      pkg->h = h;
      PUSHMARK(SP);
      mXPUSHs(sv_setref_pv(newSVpv("", 0), "URPM::Package", pkg));
      PUTBACK;
      call_sv(callback, G_DISCARD | G_SCALAR);
      SPAGAIN;
      pkg->h = NULL; /* avoid using it anymore, in case it has been copied inside callback */
    }
    ++c;
  }
  rpmdbFreeIterator(mi);
  RETVAL = c;
  OUTPUT:
  RETVAL

void
Trans_check(trans, ...)
  URPM::Transaction trans
  PREINIT:
  I32 gimme = GIMME_V;
  int translate_message = 0;
  int i;
  PPCODE:
  for (i = 1; i < items-1; i+=2) {
    STRLEN len;
    char *s = SvPV(ST(i), len);

    if (len == 17 && !memcmp(s, "translate_message", 17))
      translate_message = SvIV(ST(i+1));
  }
  if (rpmtsCheck(trans->ts)) {
    if (gimme == G_SCALAR)
      mXPUSHs(newSViv(0));
    else if (gimme == G_ARRAY)
      mXPUSHs(newSVpv("error while checking dependencies", 0));
  } else {
    rpmps ps = rpmtsProblems(trans->ts);
    if (rpmpsNumProblems(ps) > 0) {
      if (gimme == G_SCALAR)
	mXPUSHs(newSViv(0));
      else if (gimme == G_ARRAY) {
	/* now translation is handled by rpmlib, but only for version 4.2 and above */
	PUTBACK;
	return_problems(ps, 1, 0);
	SPAGAIN;
      }
    } else if (gimme == G_SCALAR)
      mXPUSHs(newSViv(1));
    
    ps = rpmpsFree(ps);
  }

void
Trans_order(trans)
  URPM::Transaction trans
  PREINIT:
  I32 gimme = GIMME_V;
  PPCODE:
  if (rpmtsOrder(trans->ts) == 0) {
    if (gimme == G_SCALAR)
      mXPUSHs(newSViv(1));
  } else {
    if (gimme == G_SCALAR)
      mXPUSHs(newSViv(0));
    else if (gimme == G_ARRAY)
      mXPUSHs(newSVpv("error while ordering dependencies", 0));
  }

int
Trans_NElements(trans)
  URPM::Transaction trans
  CODE:
  RETVAL = rpmtsNElements(trans->ts);
  OUTPUT:
  RETVAL

char *
Trans_Element_name(trans, index)
  URPM::Transaction trans
  int index
  CODE:
  rpmte te = rpmtsElement(trans->ts, index);
  RETVAL = te ? (char *) rpmteN(te) : NULL;
  OUTPUT:
  RETVAL

char *
Trans_Element_version(trans, index)
  URPM::Transaction trans
  int index
  CODE:
  rpmte te = rpmtsElement(trans->ts, index);
  RETVAL = te ? (char *) rpmteV(te) : NULL;
  OUTPUT:
  RETVAL

char *
Trans_Element_release(trans, index)
  URPM::Transaction trans
  int index
  CODE:
  rpmte te = rpmtsElement(trans->ts, index);
  RETVAL = te ? (char *) rpmteR(te) : NULL;
  OUTPUT:
  RETVAL

char *
Trans_Element_fullname(trans, index)
  URPM::Transaction trans
  int index
  CODE:
  rpmte te = rpmtsElement(trans->ts, index);
  RETVAL = te ? (char *) rpmteNEVRA(te) : NULL;
  OUTPUT:
  RETVAL

void
Trans_run(trans, data, ...)
  URPM::Transaction trans
  SV *data
  PREINIT:
  struct s_TransactionData td = { NULL, NULL, NULL, NULL, NULL, 100000, data };
  rpmtransFlags transFlags = RPMTRANS_FLAG_NONE;
  int probFilter = 0;
  int translate_message = 0, raw_message = 0;
  int i;
  PPCODE:
  for (i = 2 ; i < items - 1 ; i += 2) {
    STRLEN len;
    char *s = SvPV(ST(i), len);

    if (len == 4 && !memcmp(s, "test", 4)) {
      if (SvIV(ST(i+1))) transFlags |= RPMTRANS_FLAG_TEST;
    } else if (len == 11 && !memcmp(s, "excludedocs", 11)) {
      if (SvIV(ST(i+1))) transFlags |= RPMTRANS_FLAG_NODOCS;
    } else if (len == 5) {
      if (!memcmp(s, "force", 5)) {
	if (SvIV(ST(i+1))) probFilter |= (RPMPROB_FILTER_REPLACEPKG |
					  RPMPROB_FILTER_REPLACEOLDFILES |
					  RPMPROB_FILTER_REPLACENEWFILES |
					  RPMPROB_FILTER_OLDPACKAGE);
      } else if (!memcmp(s, "delta", 5))
	td.min_delta = SvIV(ST(i+1));
    } else if (len == 6 && !memcmp(s, "nosize", 6)) {
      if (SvIV(ST(i+1))) probFilter |= (RPMPROB_FILTER_DISKSPACE|RPMPROB_FILTER_DISKNODES);
    } else if (len == 9 && !memcmp(s, "noscripts", 9)) {
      if (SvIV(ST(i+1))) transFlags |= (RPMTRANS_FLAG_NOSCRIPTS |
				        RPMTRANS_FLAG_NOPRE |
				        RPMTRANS_FLAG_NOPREUN |
				        RPMTRANS_FLAG_NOPOST |
				        RPMTRANS_FLAG_NOPOSTUN );
    } else if (len == 10 && !memcmp(s, "oldpackage", 10)) {
      if (SvIV(ST(i+1))) probFilter |= RPMPROB_FILTER_OLDPACKAGE;
    } else if (len == 11 && !memcmp(s, "replacepkgs", 11)) {
      if (SvIV(ST(i+1))) probFilter |= RPMPROB_FILTER_REPLACEPKG;
    } else if (len == 11 && !memcmp(s, "raw_message", 11)) {
      raw_message = 1;
    } else if (len == 12 && !memcmp(s, "replacefiles", 12)) {
      if (SvIV(ST(i+1))) probFilter |= RPMPROB_FILTER_REPLACEOLDFILES | RPMPROB_FILTER_REPLACENEWFILES;
    } else if (len == 9 && !memcmp(s, "repackage", 9)) {
      if (SvIV(ST(i+1))) transFlags |= RPMTRANS_FLAG_REPACKAGE;
    } else if (len == 6 && !memcmp(s, "justdb", 6)) {
      if (SvIV(ST(i+1))) transFlags |= RPMTRANS_FLAG_JUSTDB;
    } else if (len == 10 && !memcmp(s, "ignorearch", 10)) {
      if (SvIV(ST(i+1))) probFilter |= RPMPROB_FILTER_IGNOREARCH;
    } else if (len == 17 && !memcmp(s, "translate_message", 17))
      translate_message = 1;
    else if (len >= 9 && !memcmp(s, "callback_", 9)) {
      if (len == 9+4 && !memcmp(s+9, "open", 4)) {
	if (SvROK(ST(i+1))) td.callback_open = ST(i+1);
      } else if (len == 9+5 && !memcmp(s+9, "close", 5)) {
	if (SvROK(ST(i+1))) td.callback_close = ST(i+1);
      } else if (len == 9+5 && !memcmp(s+9, "trans", 5)) {
	if (SvROK(ST(i+1))) td.callback_trans = ST(i+1);
      } else if (len == 9+6 && !memcmp(s+9, "uninst", 6)) {
	if (SvROK(ST(i+1))) td.callback_uninst = ST(i+1);
      } else if (len == 9+4 && !memcmp(s+9, "inst", 4)) {
	if (SvROK(ST(i+1))) td.callback_inst = ST(i+1);
      }
    }
  }
  /* check macros */
  {
    char *repa = rpmExpand("%_repackage_all_erasures", NULL);
    if (repa && *repa && *repa != '0')
      transFlags |= RPMTRANS_FLAG_REPACKAGE;
    if (repa) free(repa);
  }
  rpmtsSetFlags(trans->ts, transFlags);
  trans->ts = rpmtsLink(trans->ts);
  rpmtsSetNotifyCallback(trans->ts, rpmRunTransactions_callback, &td);
  if (rpmtsRun(trans->ts, NULL, probFilter) > 0) {
    rpmps ps = rpmtsProblems(trans->ts);
    PUTBACK;
    return_problems(ps, translate_message, raw_message || !translate_message);
    SPAGAIN;
    ps = rpmpsFree(ps);
  }
  rpmtsEmpty(trans->ts);
  (void)rpmtsFree(trans->ts);

MODULE = URPM            PACKAGE = URPM                PREFIX = Urpm_

BOOT:
(void) read_config_files(0);

void
Urpm_bind_rpm_textdomain_codeset()
  CODE:
  rpm_codeset_is_utf8 = 1;
  bind_textdomain_codeset("rpm", "UTF-8");

int
Urpm_read_config_files()
  CODE:
  RETVAL = (read_config_files(1) == 0); /* force re-read of configuration files */
  OUTPUT:
  RETVAL

int
rpmvercmp(one, two)
    char *one
    char *two        
       
int
Urpm_ranges_overlap(a, b, b_nopromote=1)
  char *a
  char *b
  int b_nopromote
  PREINIT:
  char *sa = a, *sb = b;
  int aflags = 0, bflags = 0;
  CODE:
  while (*sa && *sa != ' ' && *sa != '[' && *sa != '<' && *sa != '>' && *sa != '=' && *sa == *sb) {
    ++sa;
    ++sb;
  }
  if ((*sa && *sa != ' ' && *sa != '[' && *sa != '<' && *sa != '>' && *sa != '=') ||
      (*sb && *sb != ' ' && *sb != '[' && *sb != '<' && *sb != '>' && *sb != '=')) {
    /* the strings are sure to be different */
    RETVAL = 0;
  } else {
    while (*sa) {
      if (*sa == ' ' || *sa == '[' || *sa == '*' || *sa == ']');
      else if (*sa == '<') aflags |= RPMSENSE_LESS;
      else if (*sa == '>') aflags |= RPMSENSE_GREATER;
      else if (*sa == '=') aflags |= RPMSENSE_EQUAL;
      else break;
      ++sa;
    }
    while (*sb) {
      if (*sb == ' ' || *sb == '[' || *sb == '*' || *sb == ']');
      else if (*sb == '<') bflags |= RPMSENSE_LESS;
      else if (*sb == '>') bflags |= RPMSENSE_GREATER;
      else if (*sb == '=') bflags |= RPMSENSE_EQUAL;
      else break;
      ++sb;
    }
    RETVAL = ranges_overlap(aflags, sa, bflags, sb, b_nopromote);
  }
  OUTPUT:
  RETVAL

void
Urpm_parse_synthesis__XS(urpm, filename, ...)
  SV *urpm
  char *filename
  PPCODE:
  if (SvROK(urpm) && SvTYPE(SvRV(urpm)) == SVt_PVHV) {
    SV **fdepslist = hv_fetch((HV*)SvRV(urpm), "depslist", 8, 0);
    AV *depslist = fdepslist && SvROK(*fdepslist) && SvTYPE(SvRV(*fdepslist)) == SVt_PVAV ? (AV*)SvRV(*fdepslist) : NULL;
    SV **fprovides = hv_fetch((HV*)SvRV(urpm), "provides", 8, 0);
    HV *provides = fprovides && SvROK(*fprovides) && SvTYPE(SvRV(*fprovides)) == SVt_PVHV ? (HV*)SvRV(*fprovides) : NULL;
    SV **fobsoletes = hv_fetch((HV*)SvRV(urpm), "obsoletes", 9, 0);
    HV *obsoletes = fobsoletes && SvROK(*fobsoletes) && SvTYPE(SvRV(*fobsoletes)) == SVt_PVHV ? (HV*)SvRV(*fobsoletes) : NULL;

    if (depslist != NULL) {
      char buff[65536];
      char *p, *eol;
      int buff_len;
      struct s_Package pkg;
      gzFile f;
      int start_id = 1 + av_len(depslist);
      SV *callback = NULL;

      if (items > 2) {
	int i;
	for (i = 2; i < items-1; i+=2) {
	  STRLEN len;
	  char *s = SvPV(ST(i), len);

	  if (len == 8 && !memcmp(s, "callback", 8) && SvROK(ST(i+1)))
	    callback = ST(i+1);
	}
      }

      PUTBACK;
      if ((f = gzopen(filename, "rb")) != NULL) {
	memset(&pkg, 0, sizeof(struct s_Package));
	buff[sizeof(buff)-1] = 0;
	p = buff;
	int ok = 1;
	while ((buff_len = gzread(f, p, sizeof(buff)-1-(p-buff))) >= 0 &&
	       (buff_len += p-buff)) {
	  buff[buff_len] = 0;
	  p = buff;
	  if ((eol = strchr(p, '\n')) != NULL) {
	    do {
	      *eol++ = 0;
	      if (!parse_line(depslist, provides, obsoletes, &pkg, p, urpm, callback)) { ok = 0; break; }
	      p = eol;
	    } while ((eol = strchr(p, '\n')) != NULL);
	  } else {
	    /* a line larger than sizeof(buff) has been encountered, bad file problably */
	    fprintf(stderr, "invalid line <%s>\n", p);
	    ok = 0;
	    break;
	  }
	  if (gzeof(f)) {
	    if (!parse_line(depslist, provides, obsoletes, &pkg, p, urpm, callback)) ok = 0;
	    break;
	  } else {
	    /* move the remaining non-complete-line at beginning */
	    memmove(buff, p, buff_len-(p-buff));
	    /* point to the end of the non-complete-line */
	    p = &buff[buff_len-(p-buff)];
	  }
	}
	if (gzclose(f) != 0) ok = 0;
	SPAGAIN;
	if (ok) {
	  mXPUSHs(newSViv(start_id));
	  mXPUSHs(newSViv(av_len(depslist)));
	}
      } else {
	  SV **nofatal = hv_fetch((HV*)SvRV(urpm), "nofatal", 7, 0);
	  if (!errno) errno = EINVAL; /* zlib error */
	  if (!nofatal || !SvIV(*nofatal))
	      croak(errno == ENOENT
		      ? "unable to read synthesis file %s"
		      : "unable to uncompress synthesis file %s", filename);
      }
    } else croak("first argument should contain a depslist ARRAY reference");
  } else croak("first argument should be a reference to a HASH");

void
Urpm_parse_hdlist__XS(urpm, filename, ...)
  SV *urpm
  char *filename
  PPCODE:
  if (SvROK(urpm) && SvTYPE(SvRV(urpm)) == SVt_PVHV) {
    SV **fdepslist = hv_fetch((HV*)SvRV(urpm), "depslist", 8, 0);
    AV *depslist = fdepslist && SvROK(*fdepslist) && SvTYPE(SvRV(*fdepslist)) == SVt_PVAV ? (AV*)SvRV(*fdepslist) : NULL;
    SV **fprovides = hv_fetch((HV*)SvRV(urpm), "provides", 8, 0);
    HV *provides = fprovides && SvROK(*fprovides) && SvTYPE(SvRV(*fprovides)) == SVt_PVHV ? (HV*)SvRV(*fprovides) : NULL;
    SV **fobsoletes = hv_fetch((HV*)SvRV(urpm), "obsoletes", 9, 0);
    HV *obsoletes = fobsoletes && SvROK(*fobsoletes) && SvTYPE(SvRV(*fobsoletes)) == SVt_PVHV ? (HV*)SvRV(*fobsoletes) : NULL;

    if (depslist != NULL) {
      int empty_archive = 0;
      FD_t fd;

      fd = open_archive(filename, &empty_archive);

      if (empty_archive) {
	  mXPUSHs(newSViv(1 + av_len(depslist)));
	  mXPUSHs(newSViv(av_len(depslist)));
      } else if (fd != NULL && !Ferror(fd)) {
	Header header;
	int start_id = 1 + av_len(depslist);
	int packing = 0;
	SV *callback = NULL;

	if (items > 3) {
	  int i;
	  for (i = 2; i < items-1; i+=2) {
	    STRLEN len;
	    char *s = SvPV(ST(i), len);

	    if (len == 7 && !memcmp(s, "packing", 7))
	      packing = SvTRUE(ST(i+1));
	    else if (len == 8 && !memcmp(s, "callback", 8) && SvROK(ST(i+1)))
	      callback = ST(i+1);
	  }
	}

	PUTBACK;
	do {
	  header = headerRead(fd, HEADER_MAGIC_YES);
	  if (header != NULL) {
	    struct s_Package pkg, *_pkg;
	    SV *sv_pkg;

	    memset(&pkg, 0, sizeof(struct s_Package));
	    pkg.flag = 1 + av_len(depslist);
	    pkg.h = header;
	    sv_pkg = sv_setref_pv(newSVpv("", 0), "URPM::Package",
				  _pkg = memcpy(malloc(sizeof(struct s_Package)), &pkg, sizeof(struct s_Package)));
	    if (call_package_callback(urpm, sv_pkg, callback)) {
	      if (provides) {
		update_provides(_pkg, provides);
		update_provides_files(_pkg, provides);
	      }
	      if (obsoletes) update_obsoletes(_pkg, obsoletes);
	      if (packing) pack_header(_pkg);
	      av_push(depslist, sv_pkg);
	    }
	  }
	} while (header != NULL);

	int ok = Fclose(fd) == 0;

	if (!empty_archive)
	  ok = av_len(depslist) >= start_id;
	SPAGAIN;
	if (ok) {
	  mXPUSHs(newSViv(start_id));
	  mXPUSHs(newSViv(av_len(depslist)));
	}
      } else {
	  SV **nofatal = hv_fetch((HV*)SvRV(urpm), "nofatal", 7, 0);
	  if (!nofatal || !SvIV(*nofatal))
	      croak("cannot open hdlist file %s", filename);
      }
    } else croak("first argument should contain a depslist ARRAY reference");
  } else croak("first argument should be a reference to a HASH");

void
Urpm_parse_rpm(urpm, filename, ...)
  SV *urpm
  char *filename
  PPCODE:
  if (SvROK(urpm) && SvTYPE(SvRV(urpm)) == SVt_PVHV) {
    SV **fdepslist = hv_fetch((HV*)SvRV(urpm), "depslist", 8, 0);
    AV *depslist = fdepslist && SvROK(*fdepslist) && SvTYPE(SvRV(*fdepslist)) == SVt_PVAV ? (AV*)SvRV(*fdepslist) : NULL;
    SV **fprovides = hv_fetch((HV*)SvRV(urpm), "provides", 8, 0);
    HV *provides = fprovides && SvROK(*fprovides) && SvTYPE(SvRV(*fprovides)) == SVt_PVHV ? (HV*)SvRV(*fprovides) : NULL;
    SV **fobsoletes = hv_fetch((HV*)SvRV(urpm), "obsoletes", 8, 0);
    HV *obsoletes = fobsoletes && SvROK(*fobsoletes) && SvTYPE(SvRV(*fobsoletes)) == SVt_PVHV ? (HV*)SvRV(*fobsoletes) : NULL;

    if (depslist != NULL) {
      struct s_Package pkg, *_pkg;
      SV *sv_pkg;
      int packing = 0;
      int keep_all_tags = 0;
      SV *callback = NULL;
      rpmVSFlags vsflags = RPMVSF_DEFAULT;

      if (items > 3) {
	int i;
	for (i = 2; i < items-1; i+=2) {
	  STRLEN len;
	  char *s = SvPV(ST(i), len);

	  if (len == 7 && !memcmp(s, "packing", 7))
	    packing = SvTRUE(ST(i + 1));
	  else if (len == 13 && !memcmp(s, "keep_all_tags", 13))
	    keep_all_tags = SvTRUE(ST(i+1));
	  else if (len == 8 && !memcmp(s, "callback", 8) && SvROK(ST(i+1)))
	    callback = ST(i+1);
	  else if (SvIV(ST(i+1))) {
             if (len == 5) {
                if (!memcmp(s, "nopgp", 5))
                  vsflags |= (RPMVSF_NOSHA1 | RPMVSF_NOSHA1HEADER);
                else if (!memcmp(s, "nogpg", 5))
                  vsflags |= (RPMVSF_NOSHA1 | RPMVSF_NOSHA1HEADER);
                else if (!memcmp(s, "nomd5", 5))
                  vsflags |= (RPMVSF_NOMD5 |  RPMVSF_NOMD5HEADER);
                else if (!memcmp(s, "norsa", 5))
                  vsflags |= (RPMVSF_NORSA | RPMVSF_NORSAHEADER);
                else if (!memcmp(s, "nodsa", 5))
                  vsflags |= (RPMVSF_NODSA | RPMVSF_NODSAHEADER);
             } else if (len == 9) {
                if (!memcmp(s, "nodigests", 9))
                  vsflags |= _RPMVSF_NODIGESTS;
                else if (!memcmp(s, "nopayload", 9))
                  vsflags |= _RPMVSF_NOPAYLOAD;
             }
          } 
	}
      }
      PUTBACK;
      memset(&pkg, 0, sizeof(struct s_Package));
      pkg.flag = 1 + av_len(depslist);
      _pkg = memcpy(malloc(sizeof(struct s_Package)), &pkg, sizeof(struct s_Package));

      if (update_header(filename, _pkg, keep_all_tags, vsflags)) {
	sv_pkg = sv_setref_pv(newSVpv("", 0), "URPM::Package", _pkg);
	if (call_package_callback(urpm, sv_pkg, callback)) {
	  if (provides) {
	    update_provides(_pkg, provides);
	    update_provides_files(_pkg, provides);
	  }
	  if (obsoletes) update_obsoletes(_pkg, obsoletes);
	  if (packing) pack_header(_pkg);
	  av_push(depslist, sv_pkg);
	}
	SPAGAIN;
	/* only one element read */
	mXPUSHs(newSViv(av_len(depslist)));
	mXPUSHs(newSViv(av_len(depslist)));
      } else free(_pkg);
    } else croak("first argument should contain a depslist ARRAY reference");
  } else croak("first argument should be a reference to a HASH");

int
Urpm_verify_rpm(filename, ...)
  char *filename
  PREINIT:
  FD_t fd;
  int i, oldlogmask;
  rpmts ts = NULL;
  struct rpmQVKArguments_s qva;
  CODE:
  /* Don't display error messages */
  oldlogmask = rpmlogSetMask(RPMLOG_UPTO(RPMLOG_PRI(4)));
  memset(&qva, 0, sizeof(struct rpmQVKArguments_s));
  qva.qva_source = RPMQV_RPM;
  qva.qva_flags = VERIFY_ALL;
  for (i = 1 ; i < items - 1 ; i += 2) {
    STRLEN len;
    char *s = SvPV(ST(i), len);
    if (SvIV(ST(i+1))) {
      if (len == 9 && !strncmp(s, "nodigests", 9))
        qva.qva_flags &= ~VERIFY_DIGEST;
      else if (len == 12 && !strncmp(s, "nosignatures", 12))
        qva.qva_flags &= ~VERIFY_SIGNATURE;
    }
  }
  fd = Fopen(filename, "r");
  if (fd == NULL)
    RETVAL = 0;
  else {
    read_config_files(0);
    ts = rpmtsCreate();
    rpmtsSetRootDir(ts, "/");
    rpmtsOpenDB(ts, O_RDONLY);
    if (rpmVerifySignatures(&qva, ts, fd, filename))
      RETVAL = 0;
    else
      RETVAL = 1;
    Fclose(fd);
    (void)rpmtsFree(ts);
  }
  rpmlogSetMask(oldlogmask);

  OUTPUT:
  RETVAL


char *
Urpm_get_gpg_fingerprint(filename)
    char * filename
    PREINIT:
    uint8_t fingerprint[sizeof(pgpKeyID_t)];
    char fingerprint_str[sizeof(pgpKeyID_t) * 2 + 1];
    const uint8_t *pkt = NULL;
    size_t pktlen = 0;
    int rc;

    CODE:
    memset (fingerprint, 0, sizeof (fingerprint));
    if ((rc = pgpReadPkts(filename, (uint8_t ** ) &pkt, &pktlen)) <= 0)
	pktlen = 0;
    else if (rc != PGPARMOR_PUBKEY)
	pktlen = 0;
    else {
	unsigned int i;
        pgpPubkeyFingerprint (pkt, pktlen, fingerprint);
   	for (i = 0; i < sizeof (pgpKeyID_t); i++)
	    sprintf(&fingerprint_str[i*2], "%02x", fingerprint[i]);
    }
    _free(pkt);
    RETVAL = fingerprint_str;
    OUTPUT:
    RETVAL


char *
Urpm_verify_signature(filename, prefix="/")
  char *filename
  char *prefix
  PREINIT:
  rpmts ts = NULL;
  char result[1024];
  rpmRC rc;
  FD_t fd;
  Header h;
  CODE:
  fd = Fopen(filename, "r");
  if (fd == NULL)
    RETVAL = "NOT OK (could not read file)";
  else {
    read_config_files(0);
    ts = rpmtsCreate();
    rpmtsSetRootDir(ts, prefix);
    rpmtsOpenDB(ts, O_RDONLY);
    rpmtsSetVSFlags(ts, RPMVSF_DEFAULT);
    rc = rpmReadPackageFile(ts, fd, filename, &h);
    Fclose(fd);
    *result = '\0';
    switch(rc) {
      case RPMRC_OK:
	if (h) {
	  char *fmtsig = headerFormat(
	      h,
	      "%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:"
	      "{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|",
	      NULL);
	  snprintf(result, sizeof(result), "OK (%s)", fmtsig);
	  free(fmtsig);
	} else snprintf(result, sizeof(result), "NOT OK (bad rpm): %s", rpmlogMessage());
	break;
      case RPMRC_NOTFOUND:
	snprintf(result, sizeof(result), "NOT OK (signature not found): %s", rpmlogMessage());
	break;
      case RPMRC_FAIL:
	snprintf(result, sizeof(result), "NOT OK (fail): %s", rpmlogMessage());
	break;
      case RPMRC_NOTTRUSTED:
	snprintf(result, sizeof(result), "NOT OK (key not trusted): %s", rpmlogMessage());
	break;
      case RPMRC_NOKEY:
	snprintf(result, sizeof(result), "NOT OK (no key): %s", rpmlogMessage());
	break;
    }
    RETVAL = result;
    if (h) h = headerFree(h);
    (void)rpmtsFree(ts);
  }

  OUTPUT:
  RETVAL

    
int
Urpm_import_pubkey_file(db, filename)
    URPM::DB db
    char * filename
    PREINIT:
    const uint8_t *pkt = NULL;
    size_t pktlen = 0;
    int rc;
    CODE:
    rpmts ts = rpmtsLink(db->ts);
    rpmtsClean(ts);
    
    if ((rc = pgpReadPkts(filename, (uint8_t ** ) &pkt, &pktlen)) <= 0)
        RETVAL = 0;
    else if (rc != PGPARMOR_PUBKEY)
        RETVAL = 0;
    else if (rpmtsImportPubkey(ts, pkt, pktlen) != RPMRC_OK)
        RETVAL = 0;
    else
        RETVAL = 1;
    pkt = _free(pkt);
    (void)rpmtsFree(ts);
    OUTPUT:
    RETVAL

int
Urpm_import_pubkey(...)
  CODE:
  unused_variable(&items);
  croak("import_pubkey() is dead. use import_pubkey_file() instead");
  RETVAL = 1;
  OUTPUT:
  RETVAL

int
Urpm_archscore(arch)
  const char * arch
  PREINIT:
  CODE:
  read_config_files(0);
  RETVAL=rpmMachineScore(RPM_MACHTABLE_INSTARCH, arch);
  OUTPUT:
  RETVAL

int
Urpm_osscore(os)
  const char * os
  PREINIT:
  CODE:
  read_config_files(0);
  RETVAL=rpmMachineScore(RPM_MACHTABLE_INSTOS, os);
  OUTPUT:
  RETVAL

void
Urpm_stream2header(fp)
    FILE *fp
  PREINIT:
    FD_t fd;
    URPM__Package pkg;
  PPCODE:
    if ((fd = fdDup(fileno(fp)))) {
        pkg = (URPM__Package)calloc(1, sizeof(struct s_Package));
        pkg->h = headerRead(fd, HEADER_MAGIC_YES);
        if (pkg->h) {
            SV *sv_pkg;
            EXTEND(SP, 1);
            sv_pkg = sv_newmortal();
            sv_setref_pv(sv_pkg, "URPM::Package", (void*)pkg);
            PUSHs(sv_pkg);
        }
        Fclose(fd);
    }

void
Urpm_spec2srcheader(specfile)
  char *specfile
  PREINIT:
    rpmts ts = rpmtsCreate();
    URPM__Package pkg;
    Spec spec = NULL;
    Header header = NULL;
  PPCODE:
/* ensure the config is in memory with all macro */
  read_config_files(0);
/* Do not verify architecture */
#define SPEC_ANYARCH 1
/* Do not verify whether sources exist */
#define SPEC_FORCE 1
  spec = rpmSpecParse(specfile, RPMSPEC_ANYARCH|RPMSPEC_FORCE, NULL);
  if (spec) {
    header = rpmSpecSourceHeader(spec);
    SV *sv_pkg;
#ifndef RPM490
    // FIXME: has disappeared in rpm-4.9.0rpmSpecParse
    // (See http://www.rpm.org/wiki/Releases/4.9.0)
    spec = rpmtsSetSpec(ts, NULL);
    header = spec->sourceHeader;
    if (! header)
      initSourceHeader(spec);
#endif
    pkg = (URPM__Package)calloc(1, sizeof(struct s_Package));
    headerPutString(header, RPMTAG_SOURCERPM, "");

    {
      struct rpmtd_s td = {
	.tag = RPMTAG_ARCH,
	.type = RPM_STRING_TYPE,
	.data = (void *) "src",
	.count = 1,
      };
      /* parseSpec() sets RPMTAG_ARCH to %{_target_cpu} whereas we really a header similar to .src.rpm header */
      headerMod(header, &td);
    }
    pkg->h = headerLink(header);
    sv_pkg = sv_newmortal();
    sv_setref_pv(sv_pkg, "URPM::Package", (void*)pkg);
    XPUSHs(sv_pkg);
    spec = rpmSpecFree(spec);
  } else {
    XPUSHs(&PL_sv_undef);
    /* apparently rpmlib sets errno this when given a bad spec. */
    if (errno == EBADF)
      errno = 0;
  }
  ts = rpmtsFree(ts);

void
expand(name)
    char * name
    PPCODE:
    const char * value = rpmExpand(name, NULL);
    XPUSHs(sv_2mortal(newSVpv(value, 0)));

void
add_macro_noexpand(macro)
    char * macro
    CODE:
    rpmDefineMacro(NULL, macro, RMIL_DEFAULT);

void
del_macro(name)
    char * name
    CODE:
    delMacro(NULL, name);

void
loadmacrosfile(filename)
    char * filename
    PPCODE:
    rpmInitMacros(NULL, filename);

void
resetmacros()
    PPCODE:
    rpmFreeMacros(NULL);

void
setVerbosity(level)
    int level
    PPCODE:
    rpmSetVerbosity(level);

const char *
rpmErrorString()
  CODE:
  RETVAL = rpmlogMessage();
  OUTPUT:
  RETVAL 

void
rpmErrorWriteTo(fd)
  int fd
  CODE:
  rpmError_callback_data = fd;
  rpmlogSetCallback(rpmError_callback, NULL);

  /* vim:set ts=8 sts=2 sw=2: */