File: dpkg-sig

package info (click to toggle)
dpkg-sig 0.13.1%2Bnmu4
  • links: PTS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 180 kB
  • ctags: 38
  • sloc: perl: 1,311; makefile: 51
file content (2020 lines) | stat: -rwxr-xr-x 56,660 bytes parent folder | download
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
#!/usr/bin/perl -w
#
# dpkg-sig signs deb-files in a standard way
#
# (c) Andreas Barth <aba@not.so.argh.org> 2003
# (c) Marc Brockschmidt <marc@dch-faq.de> 2004
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    Upstream web site used to be <http://dpkg-sig.turmzimmer.net/>.

=pod

=head1 NAME

B<dpkg-sig> - Debian package archive (.deb) signature generation and verification tool

=head1 DESCRIPTION

This is the description of the source code, trying to help people to understand
how B<dpkg-sig> works.

=head1 SYNOPSIS

=cut

use strict;
use Getopt::Long;
use Data::Dumper;
use IPC::Open2;
use IPC::Open3;
use File::Temp qw(tempdir);
use File::Copy qw(move);
use File::Basename qw(dirname basename);
$| = 1;

#Global variables (used for configuration and/or command line stuff) 
my ($sign, $list, $verify, $verify_role, $verify_exact, $client, $cache_pass,
    $pass_file, $key, $maintainer, $maintainer_pr, $verbose, %config, $tempdir,
    %part_cache, $check_v2_sig, $check_v3_sig, $batch, $gpgoptions, 
    $passphrase, $remote_dpkg_sig, %ssh_connections, $sign_changes, 
    $get_hashes, $sign_hashes, $write_signature, $help, $DEBUG, 
	$verify_pattern, $remote_ssh_port);

my @configfiles = qw(/etc/devscripts.conf ~/.devscripts);

my $DPKG_SIG_VERSION = 0.13;

&process_cli_options();

#If wanted, print only help and exit:
if ($help) { &help; exit; }

#In client mode, we wait for commands and STDIN, we don't need the rest:
if ($client) {
	print "Welcome. This is dpkg-sig in client mode. Protocol version 6\n";
	&read_cmds();
	exit;
}

#Only load Config::File if we're not in the client mode:
eval { require Config::File; import Config::File qw(read_config_file); };
_die($@) if $@;

$tempdir = tempdir("debsigs-ng.XXXXXX", CLEANUP => 1, TMPDIR => 1);


&load_config(@configfiles);

$remote_dpkg_sig ||= "dpkg-sig";

my @files = @ARGV;

if ($sign_hashes || $write_signature) {
	for (@files) {
		unless (/\.dpkg-sig-hashes$/) {
			die _die("$_: Make sure all files were generated by dpkg-sig --get-hashes file\n");
		}
	}
	
	for my $file (@files) {
		if ($sign_hashes) {
			print "Processing $file...\n";
			sign_hashes($file);
			print "Signed hashes in $file...\n";
		} else {
			print "Processing $file...\n";		
			my @done = write_signature($file);
			print "Added signature to $_\n" for (@done);
		}
	}
	exit;
}

if (grep { ! /(?:deb|changes)$/ } @files) {
	die _die("We can only work on debs and changes files.");
}

if ($sign) {
	if (length($sign) > 9) {
		die _die("The signing name '$sign' is too long.");
	} elsif ($sign !~ /^[a-z]+$/) {
		die _die("The signing name '$sign' is not valid. Please use only letters.");
	}
}

if ($verify_role) {
	$verify_pattern = "^_gpg".$verify_role."[0-9A-Z]?\$";
} elsif ($verify_exact) {
	$verify_pattern = "^_gpg$verify_exact";
} else {
	$verify_pattern = "^_gpg.+";
}


#The main loop:
for my $exp (@files) {
	my @globbed_files = glob_exp($exp);
	die _die("Cannot find $exp: no such file") if (! @globbed_files);
	for my $file (@globbed_files) {
		if ($file =~ /\.deb$/) { #Yay! That's easy!
			print "Processing $file...\n";
			if ($sign) {
				sign_deb($sign, $file);
				print "Signed deb $file\n" if ! $batch;
			} elsif ($verify || $verify_role || $verify_exact) {
				my @verify_output = verify_deb($file, $verify_pattern);
				print @verify_output;
				exit 2 if grep { /^BADSIG/ } @verify_output;
				exit 3 if grep { /^UNKNOWNSIG/ } @verify_output;
				exit 4 if grep { /^NOSIG/ } @verify_output;
			} elsif ($list) {
				for (get_deb_parts($file)) {
					print "$1\n" if ($_->[0] =~ /_gpg(.+)/);
				}
			} elsif ($get_hashes) {
				write_deb_info($get_hashes, $file);
				unlink "$file.dpkg-sig-hashes";
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", "deb\n$get_hashes\n$file ".get_file_md5sum($file)."\n" , "control");
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", _read_file("$tempdir/digests"), "deb0");
			}
			
		} else {
			print "--- Processing changes file $file:\n";
			my $changes_signed = 0;
			my (%new_debs, $sums_control_data, @deb_md5sums, $maintainer_from_changes);


			#Get default from *changes:
			unless ($maintainer || $key) {
				$maintainer_from_changes = 1;
				chomp($maintainer = `grep ^Changed-By: $file | cut -d " " -f 2-`);
				$maintainer = quotemeta($maintainer);
			}

			if ($get_hashes) {
				unlink "$file.dpkg-sig-hashes";
				$sums_control_data = "changes $file\n$get_hashes\n";
			}

			for my $deb (get_debs_from_changes($file, \$changes_signed)) {
				print "Processing $deb...\n";
				
				if ($sign) {
					my $r = sign_deb($sign, $deb);
					$new_debs{$r->[2]} = $r;
					print "Signed deb $deb\n" if ! $batch;
				} elsif ($verify || $verify_role || $verify_exact) {
					my @verify_output = verify_deb($deb, $verify_pattern);
					print @verify_output;
					exit 2 if grep { /^BADSIG/ } @verify_output;
					exit 3 if grep { /^UNKNOWNSIG/ } @verify_output;
					exit 4 if grep { /^NOSIG/ } @verify_output;
				} elsif ($list) {
					for (get_deb_parts($deb)) {
						print "$1\n" if ($_->[0] =~ /_gpg(.+)/);
					}
				} elsif ($get_hashes) {
					$sums_control_data .= $deb." ".get_file_md5sum($deb)."\n";
					write_deb_info($get_hashes, $deb);
					push @deb_md5sums, _read_file("$tempdir/digests");
				}
			}

			if ($sign) {
				correct_changes_file($file, \%new_debs);
				sign_control_files($file) if ($sign_changes ne "no" && ! ($sign_changes eq "auto" && ! $changes_signed));
			} elsif ($get_hashes) {
				add_part_to_ar_archive ("$file.dpkg-sig-hashes", $sums_control_data , "control");
				for (my $i=0; $i<@deb_md5sums; $i++) {
					add_part_to_ar_archive ("$file.dpkg-sig-hashes", $deb_md5sums[$i], "deb$i");
				}				
			}

			undef $maintainer if ($maintainer_from_changes);
		}
	}
}

#Clean our ssh connections:
for (values %ssh_connections) {
	my ($pid, $readerfh, $writerfh) = @$_;
	print $writerfh "quit\n";

	sleep 1;
	kill $pid;
}

exit;

=pod

=head2 I<\@file_info> = sign_deb (I<$signing_role>, I<$file>)

Does everything needed to add a signature to I<$file>:

=over 4

=item * Verifies existing signatures

=item * Creates the meta-data that is actually signed

=item * Calls gpg to sign the meta-data.

=item * Adds the signature to I<$file>

=back

Returns a reference to an array containing the new md5sum, the new size
and the name of the signed deb.

=cut

sub sign_deb {
	my ($sig_name, $file) = @_;

	#Check the existing signatures:
	my @verify = verify_deb($file, "^_gpg.+");
	if (grep { /^BADSIG/ } @verify) {
		print STDERR "Can't sign $file, some signatures are invalid:\n".(join "", grep { /^BADSIG/ } @verify)."\n";
		exit 2;
	}

	#This also chooses the right sig name:
	$sig_name = write_deb_info($sig_name, $file);

	sign_file ("$tempdir/digests", "$tempdir/digests.asc", "no_detach");

	#Read sig:
	my $sig = _read_file ($tempdir."/digests.asc");

	return add_sig_to_deb($file, $sig, $sig_name);
}

=pod

=head2 I<$signature_name> = write_deb_info (I<$signing_role>, I<$file>)

Creates a digests.asc file with the meta-data of I<$file> in dpkg-sig's tempdir:

=over 4

=item * Gets the needed information from I<$file>

=item * Chooses the name of the signature

=item * Writes a file in a RFC822-like format containing the meta-data

=back

Returns the name that should be used to add the file to the deb.

=cut

sub write_deb_info {
	my ($sig_name, $deb) = @_;

	#Get digests:
	my $digests = get_deb_digests($deb);

	#Get name for our new signature part of the archive
	$sig_name = get_sig_name($sig_name, $digests, $deb);

	#Create digests file
	unlink ($tempdir."/digests.asc");

	my $signer_name = $key || $maintainer;
	if ($signer_name =~ /^(0x)?[0-9A-F]{8}$/i) {
		my $uidline = (grep /^uid:/, qx/gpg --list-keys --with-colons --fixed-list-mode $signer_name/)[0];
		$signer_name = (split /:/, $uidline)[9] if defined $uidline;
		chomp($signer_name);
	}

	my @data;
	push @data, "Version: 4\n";
	push @data, "Signer: $signer_name\n";
	push @data, "Date: " . localtime() . "\n";
	push @data, "Role: $1\n" if $sig_name =~ /^_gpg(\S+?)[A-Z0-9]?$/;
	
	push @data, "Files: \n";
	for my $part_info (@$digests) {
		push @data, "\t" . join (" ", reverse @$part_info) . "\n";
	}

	_write_file("$tempdir/digests", @data);

	return $sig_name
}


=pod

=head2 sign_hashes (I<$file>)

Signs a .dpkg-sig-hashes I<$file> containing the digests of a deb/changes file:

=over 4

=item * Checks the .dpkg-sig-hashes file to see if it really was created by us

=item * Creates a new archive, containing the old control file

=item * Signs the digests and adds the clearsigned data to the the new archive

=item * Substitutes the old file by the new, signed one.

=back

=cut

sub sign_hashes {
	my ($file) = @_;

	unlink ($tempdir."/digests");			
	unlink ($tempdir."/digests.asc");
	unlink ($tempdir."/hashes.signed");

	#We don't need the control data, we just want to check if this is real
	#dpkg-sig generated hashes archiv:
	my $control = get_archive_part($file, "control");
	if ($control !~ /^(deb|changes)/) {
		die _die("$file seems not to be a dpkg-sig hash archive");
	}

	add_part_to_ar_archive($tempdir."/hashes.signed", $control, "control");

	#Now sign all hashes:
	my $num = 0;
	for (get_deb_parts($file)) {
		my $part_name = $_->[0];
		if ($part_name !~ /^(deb\d+|control)$/) {
			print STDERR "W: $file contains $part_name, which shouldn't happen in dpkg-sig hash archive\n";
		} elsif ($part_name =~ /^deb\d+/) {
			my $data = get_archive_part($file, $part_name);
			
			if ($data =~ /-----BEGIN PGP SIGNATURE-----/) {
				die _die("$file seems to be already signed!\n");
			}

			_write_file($tempdir."/digests", $data);
			sign_file("$tempdir/digests", "$tempdir/digests.asc", "no_detach");
			my $s_data = _read_file($tempdir."/digests.asc");

			add_part_to_ar_archive($tempdir."/hashes.signed", $s_data, "deb".$num++);
		}
	}

	move($tempdir."/hashes.signed", $file);
}

=pod

=head2 I<@changed_files> = write_signature (I<$file>)

Adds the signatures from a signed .dpkg-sig-hashes I<$file> to the signed debs:

=over 4

=item * Checks the .dpkg-sig-hashes file to see if it really was created by us

=item * Tries to find out where we find the debs that have sigs in the .dpkg-sig-hashes

=item * Checks if the debs were changed since they were signed

=item * Adds signatures from the .dpkg-sig-hashes file to the debs

=item * If needed, it corrects the changes file to reflect the new sizes/md5sums of the debs

=back

Returns the pathes of the debs that were changed.

=cut

sub write_signature {
	my ($file) = @_;
	my @done;

	unlink ($tempdir."/digests");
	unlink ($tempdir."/digests.asc");
	unlink ($tempdir."/hashes.signed");

	#Get control data:
	my @control = split (/\n/, get_archive_part($file, "control"));
	if ($control[0] !~ /^(deb|changes)/) {
		die _die("$file seems not to be a dpkg-sig hash archive");
	}
	chomp(my $sig_name = $control[1]);

	my ($num, %new_debs) = (0);
	for (get_ar_parts($file)) {
		my $part_name = $_->[0];
		if ($part_name !~ /^(deb\d+|control)$/) {
			print STDERR "W: $file contains $part_name, which shouldn't happen in dpkg-sig hash archive\n";
		} elsif ($part_name =~ /^deb\d+/) {
			my $sig = get_archive_part($file, $part_name);

			if ($sig !~ /-----BEGIN PGP SIGNATURE-----/) {
				die _die("$file seems to be unsigned!\n");
			}

			#deb$num is the detached sig for the deb named in control line $num + 1
			#Get the name and the md5sum:
			my ($name, $md5sum) = split / /, $control[$num + 2];

			my $path;
			
			#Try to find the deb in this dir:
			if (file_readable(basename($name)) && get_file_md5sum(basename($name)) eq $md5sum) {
				$path = basename($name);
			#Now try the path in the hashes file:
			} elsif (file_readable($name) && get_file_md5sum($name) eq $md5sum) {
				$path = $name;
			#Wrong md5sum
			} elsif (! (get_file_md5sum(basename($name)) eq $md5sum || get_file_md5sum($name) eq $md5sum)) {
				die _die("The md5sum for $name is wrong. Please use an archive of signed hashes of the version of the file existing now.");
			#We don't find the damn file!
			} else {
				die _die("Can't find $name. Please start dpkg-sig either in the dir with the debs to sign or in the dir where you got the hashes.");
			}

			push @done, $path;

			$sig_name = get_sig_name($sig_name, [get_deb_parts($path)], $path);
			my $r = add_sig_to_deb($path, $sig, $sig_name);
			$new_debs{$r->[2]} = $r;

			$num++;
		}
	}

	if ($control[0] =~ /^changes (.+)$/) {
		if (file_readable(basename($1))) {
			correct_changes_file(basename($1), \%new_debs);
			print "Corrected changes file ".basename($1)."\n";
		} elsif (file_readable($1)) {
			correct_changes_file($1, \%new_debs);
			print "Corrected changes file $1\n";			
		} else {
			print STDERR "Can't find changes file $1, so won't correct it.\n";
		}
	}

	return @done;
}

=pod

=head2 I<@output> = verify_deb (I<$deb>, I<$verify_pattern>)

Verifies all signatures in I<$deb> with names matching I<$verify_pattern>:

=over 4

=item * Gets the digests of all parts of I<$deb>.

=item * Skips all signatures that don't match I<$verify_pattern>.

=item * Writes the signatures to $tempdir/digests.asc.

=item * Calls a function to check if $tempdir/digests.asc is valid in the v4 format, then tries v3 and v2.

=back

Returns its output. This is needed to achieve a "silent" verification when signing a deb.

=cut

sub verify_deb {
	my ($deb, $verify_pattern) = @_;
	my @return;

	#Get MD5 sums:
	my $digests = get_deb_digests($deb);
	my $found_sigs;

	for (my $n=0;$n<@$digests;$n++) {
		my ($part_name, $size, $sha1sum, $md5sum) = @{@$digests[$n]};
		next if $part_name !~ /$verify_pattern/;
		
		unlink ($tempdir."/digests.asc");
		unlink ($tempdir."/digests");

		my $sig = get_archive_part($deb, $part_name);
		_write_file($tempdir."/digests.asc", $sig);

		my ($status, @info);

		if ($sig =~ /BEGIN PGP SIGNED MESSAGE/) {
			$status = verify_deb_sig_v4($part_name, $n, $digests, \@info, \@return);
			$found_sigs = 1;
		}
		if ($check_v3_sig && (!$status || $status eq "BAD")) {
			$status = verify_deb_sig_v3($part_name, $n, $digests, \@info, \@return);
			$found_sigs = 1;
		}
		if ($check_v2_sig && (!$status || $status eq "BAD")) {
			$status = verify_deb_sig_v2($part_name, $n, $digests, \@info, \@return);
			$found_sigs = 1;
		}

		if      ($status && $status eq "GOOD") {
			push @return, "GOODSIG $part_name $info[0] $info[2]\n";
		} elsif ($status && $status eq "UNKNOWN" && (! $batch || $batch >= 2)) {
			push @return, "UNKNOWNSIG $part_name $info[0]\n";
		} else {
			push @return, "BADSIG $part_name\n"
		}
	}
	if (!$found_sigs) {
		push @return, "NOSIG\n"
	}

	return @return;
}

=pod

=head2 I<$verification_status> = verify_deb_sig_v4 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 4) signature for the deb described with I<\@digests>:

=over 4

=item * Calls gpg to verify the OpenPGP signature in $tempdir/digests.asc itself.

=item * Parses the signature to get the digests that were actually signed

=item * Compare the digests of the deb and those extracted from the signature to see if the deb was changed.

=item * Check that the name in the ar archive matches the "Role" field in the signature.

=item * DON'T check the Signer- and Date-Fiels.

=item * Check that at least the digests for control.tar.gz, data.tar.gz and debian-binary were signed.

=back

Returns if the the signature is good, by an unknown key, or bad.

=cut


sub verify_deb_sig_v4 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	#Check signature:
	my @cmdline = qw(gpg --openpgp --decrypt --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "--output", "$tempdir/digests", "$tempdir/digests.asc";
	my $res=qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;

	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}

	return "FORCE_BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;

	#Now find out if the deb contains the data that was signed:
	open (FH, "<", "$tempdir/digests") || die "Can't open $tempdir/digests: $!";
	my (%data, $field_name);
	while (<FH>) {
		if (/^(\S+):\s*(.*)$/) {
			$field_name = lc($1);
			$data{$field_name} = $2 || "";
		} elsif (/^\s+(.+)$/ && $field_name) {
			$data{$field_name} .= ($data{$field_name} ? "\n" : "") . $1;
		}
	}
	close FH;

	if ($data{version} > 4) {
		push @$return, "$part_name: v$data{version} signature, dpkg-sig is too old to check it.\n";
		return "FORCE_BAD";
	}
	
	my %seen_files;
	for my $file_info (split /\n/, $data{files}) {
		my ($md5sum, $sha1sum, $size, $name) = split /\s+/, $file_info;
		$seen_files{$name} = 1;

		my $checked_something=0;		
		for my $member_info (@$digests) {
			if ($member_info->[0] eq $name) {
				$checked_something = 1;
				if ($member_info->[1] ne $size) {
					push @$return, "$part_name: ${name}'s size differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				} elsif ($member_info->[2] ne $sha1sum) {
					push @$return, "$part_name: ${name}'s sha1sum differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				} elsif ($member_info->[3] ne $md5sum) {
					push @$return, "$part_name: ${name}'s md5sum differs from signed size.\n" if $verbose;
					return "FORCE_BAD";
				}
			}
		}
		
		unless ($checked_something) {
			push @$return, "$part_name: ${name} signed, but not in the deb.\n" if $verbose;
			return "FORCE_BAD";
		}
	}

	$part_name =~ /^_gpg(\S+?)[A-Z0-9]?$/;
	if ($data{role} ne $1) {
		push @$return, "$part_name: signature name and signed role differ.\n" if $verbose;
		return "FORCE_BAD";
	}

	return "FORCE_BAD" unless ($seen_files{'debian-binary'} &&
	    ($seen_files{'control.tar'} || $seen_files{'control.tar.gz'} || $seen_files{'control.tar.xz'}) &&
	    ($seen_files{'data.tar'} || $seen_files{'data.tar.gz'} || $seen_files{'data.tar.xz'} || $seen_files{'data.tar.bz2'} || $seen_files{'data.tar.lzma'}));

	return "GOOD";
}

=pod


=head2 I<$verification_status> = verify_deb_sig_v3 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 3) signature for the deb described with I<\@digests>:

=over 4

=item * Creates a file in $tempdir/digests that contains the signing role and the digests from the current deb.

=item * Calls gpg to verify that the detached OpenPGP signature in $tempdir/digests.asc is valid for $tempdir/digests.

=back

Returns if the the signature is good, by an unknown key, or bad.

=cut

sub verify_deb_sig_v3 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	my @cmdline = qw(gpg --openpgp --verify --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "$tempdir/digests.asc", "$tempdir/digests";

	push @$return, "$part_name: Invalid v4 sig ... Trying v3\n" if $verbose;

	$part_name =~ s/^_gpg(\S+?)[A-Z0-9]?$/$1/;

	open (FH, ">", $tempdir."/digests") || die _die("Couldn't open $tempdir/digests: $!");
	print FH $part_name, "\n";
	print FH join "\n", map { $_->[3] . "  " . $_->[0] } @$digests[0..$part_number-1];
	print FH "\n";
	close FH;

	my $res=qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;
	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}
	return "BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;
	return "GOOD";
}

=pod

=head2 I<$verification_status> = verify_deb_sig_v2 (I<$part_name>, I<$part_number>, I<\@digests>, I<\@info>, I<\@return>)

Verifies if $tempdir/digests is a valid (version 2) signature for the deb described with I<\@digests>:

=over 4

=item * Creates a file in $tempdir/digests that contains the digests from the current deb.

=item * Calls gpg to verify that the detached OpenPGP signature in $tempdir/digests.asc is valid for $tempdir/digests.

=back


Returns if the the signature is good, by an unknown key, or bad.

=cut

sub verify_deb_sig_v2 {
	my ($part_name, $part_number, $digests, $info, $return) = @_;

	my @cmdline = qw(gpg --openpgp --verify --no-auto-check-trustdb --batch
	                     --no-tty --status-fd 1 2>&1);
	push @cmdline, "$tempdir/digests.asc", "$tempdir/digests";

	push @$return, "$part_name: Invalid v3 sig ... Trying v2\n" if $verbose;
	
	open (FH, ">", $tempdir."/digests") || die _die("Couldn't open $tempdir/digests: $!");
	print FH join "\n", map { $_->[3] . "  " . $_->[0] } @$digests[0..$part_number-1];
	print FH "\n";
	close FH;
	
	my $res= qx/@cmdline/;
	@$info = split(/ /, $1 ) if $res =~ /^\[GNUPG:\] VALIDSIG (.*)$/m;
	if ($res =~ /^\[GNUPG:\] NO_PUBKEY \S{8}(\S{8})/m) {
		$info->[0] = $1;
		return "UNKNOWN";
	}
	return "BAD" unless $res =~ /^\[GNUPG:\] GOOD/m;
	return "GOOD";
}

=pod

=head2 I<$sig_name> = get_sig_name (I<$sig_name>, I<\@parts>, I<$deb>)

Tries to find a filename for the signature. Receives the role and constructs
a name not already present in I<$deb>.

Returns the final name or dies if it wasn't possible to construct a name.

=cut

sub get_sig_name {
	my ($sig_name, $parts, $deb) = @_;

	$sig_name = "_gpg".$sig_name;
	if (grep { $_->[0] eq $sig_name } @$parts) {
		my $changed = 0;
		for my $ext (0..9, "A" .. "Z") {
			if (! grep { $_->[0] eq $sig_name.$ext} @$parts) {
				$sig_name .= $ext;
				++$changed;
				last;
			}
		}
		die _die("$deb: Couldn't get a name for the signature part") if ! $changed;
	}

	return $sig_name;
}

=pod

=head2 correct_changes_file (I<$changes>, I<\%new_deb_info>)

Receives a path to a changes file I<$changes> and a hash reference 
I<\%new_deb_info> containing new sizes and md5sums of debs in that changes
file. It'll parse the changes file, replace the old values by the new ones.
If the file is signed, the signature will be stripped (as it would be 
invalid anyway).

=cut

sub correct_changes_file {
	my ($changes, $new_deb_info) = @_;

	if ($changes =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($changes);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "correct_changes_file $file\n";
		
		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^300 /) {
			for (keys %$new_deb_info) {
				print $writerfh join (" ", @{$new_deb_info->{$_}}), "\n";
			}
			print $writerfh ".\n";
			
			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response !~ /^200 /) {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}
	} else {
		my ($new_changes, $in_files) = ('', 0);
		open (CHANGES, "+<", $changes) || die _die("$changes: Can't open file: $!");
		while (<CHANGES>) {
			if (/^-----BEGIN PGP SIGNED MESSAGE-----$/) { while (<CHANGES>) { last if /^\s*$/ }; next }

			if ($in_files) {
				chomp;				
				last if ! s/^ //;
				my ($md5sum, $size, $section, $priority, $file_name) = split / /, $_;
				if ($new_deb_info->{$file_name}) {
					$md5sum = $new_deb_info->{$file_name}->[0];
					$size   = $new_deb_info->{$file_name}->[1];
					chomp($md5sum);
				}
				$new_changes .= " " . join (" ", ($md5sum, $size, $section, $priority, $file_name)). "\n";
			} else {
				$new_changes .= $_;
			}

			$in_files = "yes" if /^Files:/;
		}
		
		seek(CHANGES, 0, 0)   || die _die("$changes: Can't rewind file: $!");
		truncate(CHANGES, 0)  || die _die("$changes: Can't truncate file: $!");

		print CHANGES $new_changes;
		close CHANGES;
	}
}

=pod

=head2 I<\@new_file_info> = add_part_to_ar_archive (I<$file>, I<$new_data>, I<$new_name>)

=head2 I<\@new_file_info> = add_sig_to_deb (I<$file>, I<$new_data>, I<$new_name>)

Adds I<$new_data> to I<$file> as new ar archiv part, using $new_name as 
filename. If I<$file> doesn't exist, a new ar archive is created. Returns
the new md5sum and size of I<$file>.

=cut

sub add_part_to_ar_archive { return add_sig_to_deb(@_); }
sub add_sig_to_deb {
	my ($deb, $sig, $sig_name) = @_;
	my ($new_md5sum, $new_file_size);

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "add_sig_to_deb $sig_name $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^300 /) {
			for (split /\n/, $sig) {
				s/^\./../g;
				print $writerfh $_, "\n";
			}
			print $writerfh ".\n";
			
			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response !~ /^200 /) {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			} else {
				
				$response = '';
				do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
				chomp($response);
				($new_md5sum, $new_file_size) = split (/ /, $response);
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}

	} else {
		die _die("$deb: Arch member name $sig_name too long!") if (length($sig_name) > 14);

		my $new_part = sprintf("%-16s%-12s%-6s%-6s%-8s%-10s`\n%s",
		   $sig_name, time, 0, 0, 100644, length($sig), $sig . (length($sig)%2 ? "\n":""));

		if (!stat($deb)) {
			open (DEB, ">", (glob $deb)[0]) || die _die("Couldn't open ".(glob $deb)[0].": $!");
			print DEB "!<arch>\n";
		} else {
			open (DEB, ">>", (glob $deb)[0]) || die _die("Couldn't open ".(glob $deb)[0].": $!");
		}

		print DEB $new_part || die _die("Couldn write to $deb: $!");
		close DEB;

		$new_md5sum = get_file_md5sum($deb);

		$new_file_size = (stat($deb))[7];
	}

	return [$new_md5sum, $new_file_size, basename($deb)];
}

=pod

=head2 I<@parts> = get_ar_parts (I<$file>)

=head2 I<@parts> = get_deb_parts (I<$file>)

Parses I<$file> as ar archive and returns all filenames included in the archive.

=cut

sub get_ar_parts { get_deb_parts(@_) }
sub get_deb_parts {
	my ($deb) = shift;

	my @parts;

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_deb_parts $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				push @parts, [$_];
			}
		}
	} else {
        open(DEB, "<", (glob $deb)[0]) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		do {
			my $line = <DEB>;
			if ($line =~ /\S/) { #This should help with additional newlines
				#debian-binary   1075243548  0     0     100644  4         `
				my $name   = substr($line, 0, 16);
				$name =~ s{/?\s*$}{}g;
				my $length = substr($line, 48, 10);
				$length =~ s/\s*//g;
				next if (!$name && $length && $length =~ /^\d+\s*$/);
				
				seek (DEB, $length, 1) or die _die("Couldn't read $name in $deb: File too short!");
				if ($length % 2) {
					seek (DEB, 1, 1) or die _die("Couldn't read $name in $deb: File too short!");
				}

				push @parts, [$name];
			}
		} while (!eof(DEB));
		close DEB;
	}

	return @parts;
}

=pod

=head2 I<@debs> = get_debs_from_changes (I<$file>, I<\$changes_signed>)

Parses I<$file> as Debian .changes file and returns all listed debs. The dirname
of I<$file> is prepended to the debs, which means that the returned URIs should
exist.
If I<$file> is signed, I<$changes_signed> is set to "yes".

=cut

sub get_debs_from_changes {
	my ($changes, $changes_signed) = @_;
	my $changes_path = dirname($changes);
	my @debs;

	if ($changes =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($changes);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_debs_from_changes $file\n";
		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			$$changes_signed = "yes" if $response =~ /^200 ok debs in signed/;	
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				if (defined ($user)) {
					push @debs, "ssh://$user\@$host:$_";
				} else {
					push @debs, "ssh://$host:$_";
				}
			}
		}
	} else {
		open (CHANGES, "<", $changes) || die _die("$changes: Can't open file: $!");
		while (<CHANGES>) { 
			$$changes_signed = "yes" if /-----BEGIN PGP SIGNED MESSAGE-----/;
			last if /^Files:/
		}

		while (<CHANGES>) {
			chomp;
			if (/^ [^ ]+ \d+ [^ ]+ [^ ]+ (.+)$/) {
				push @debs, $changes_path."/".$1 if $1 =~ /^(.+\.deb)$/;
			} elsif (/^\s*$/) {
				last;
			} else {
				print STDERR "$changes corrupted\n";
			}
		}
		close CHANGES;
	}

	return @debs;
}

=pod

=head2 I<\@digests> = get_deb_digests (I<$deb>)

Parses I<$deb> and returns the meta-data of the included files. The read
data is piped to md5sums and sha1sums, which create the respective 
digests. The digests, the filename and the size are put in an anymous
array looking like this: [B<$name>, B<$size>, B<$sha1sum>, B<$md5sum>].
One of these arrays is pushed to I<@digests> for every file in I<$deb>.

=cut

sub get_deb_digests {
	my $deb = shift;
	my @digests;
	
	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_deb_digests $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				my ($name, $size, $sha1sum, $md5sum) = split / /, $_;
				push @digests, [$name, $size, $sha1sum, $md5sum];
			}
		}
	} else {
        open(DEB, "<", (glob $deb)[0]) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		do {
			my $line = <DEB>;
			if ($line =~ /\S/) { #This should help with additional newlines
				my ($name, $size, $md5sum, $sha1sum);
				
				#debian-binary   1075243548  0     0     100644  4         `
				   $name   = substr($line, 0, 16);
				   $name =~ s{/?\s*$}{}g;
				my $length = substr($line, 48, 10);
				   $length =~ s/\s*//g;
				next if (!$name && $length && $length =~ /^\d+\s*$/);
				$size = $length;
			
				my ($part, $read_length, $md5sum_input, $md5sum_output, $sha1sum_input, $sha1sum_output);
				open2($md5sum_output, $md5sum_input, qq{md5sum});
				if (-x "/usr/bin/sha1sum") {
					open2($sha1sum_output, $sha1sum_input, qq{sha1sum});
				} elsif (-x "/usr/bin/gpg") { #We need this for woody *sigh*:
					open2($sha1sum_output, $sha1sum_input, qq{gpg --print-md sha1 | tr 'A-Z' 'a-z' | sed 's/ //g'});
				} else {
					die _die("Can't compute sha1sum, please install sha1sum or gpg");
				}

				do {
					$read_length = ($length > 4096) ? 4096 : $length;
					$length -= $read_length;
					if (read (DEB, $part, $read_length) != $read_length) {
						die _die("Couldn't read $name in $deb: File too short!");
					}					
					if ($read_length % 2 && read (DEB, $_, 1) != 1) {
						die _die("Couldn't read $name in $deb: File too short!");			
					}
					print $md5sum_input $part;
					print $sha1sum_input $part;
				} while ($length > 0);

				close $md5sum_input; close $sha1sum_input;
				($md5sum = <$md5sum_output>) =~ s/[\s\n\r-]//g;
				($sha1sum = <$sha1sum_output>) =~ s/[\s\n\r-]//g;

				push @digests, [$name, $size, $sha1sum, $md5sum];
			}
		} while (!eof(DEB));

		close DEB;
	}

	return \@digests;
}

=pod

=head2 I<$md5sum> = get_file_md5sum (I<$file>)

Returns the md5sum for I<$file>.

=cut

sub get_file_md5sum {
	my $file = shift;
	my $md5sum;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 5) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed md5sum of a file.");
		}

		print $writerfh "get_file_md5sum $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^200 ok md5sum is (\S+)/) {
			$md5sum = $1;
		} else {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		}
	} else {
		chomp ($md5sum = `md5sum $file | cut -d " " -f 1`);
	}

	return $md5sum;
}

=pod

=head2 I<$part_data> = get_archive_part (I<$archive>, I<$part_name>)

Returns the content of I<$part_name> in the ar archive I<$archive>.

=cut

sub get_archive_part {
	my ($deb, $part_name) = @_;
	my $part = '';

	if ($deb =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($deb);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "get_archive_part $part_name $file\n";
		my $response = <$readerfh>;
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				$part .= "$_\n";
			}
		}
	} else {
		open(DEB, "<", $deb) || die _die("Couldn't open $deb: $!");
		
		if (read(DEB, $_, 8) != 8) {
			die _die("Couldn't open $deb: ar format b0rken [Couldn't read first 8 bytes]");
		} elsif ($_ ne "!<arch>\n") {
			die _die("Couldn't open $deb: ar format b0rken");
		}

		while (!eof(DEB)) {
			my $line = <DEB>;
			#debian-binary   1075243548  0     0     100644  4         `
			my $name   = substr($line, 0, 16);
			$name =~ s{/?\s*$}{}g;
			my $length = substr($line, 48, 10);
			next if (!$name && $length && $length =~ /^\d+\s*$/);
			
			my $tmp_part;
			if (read (DEB, $tmp_part, $length) != $length) {
				die _die("Couldn't read $name in $deb: File too short!");
			}
			if ($length % 2 && read (DEB, $_, 1) != 1) {
				die _die("Couldn't read $name in $deb: File too short!");			
			}

			if ($name eq $part_name) {
				$part = $tmp_part;
				last;
			}
		}

		close DEB;
	}

	return $part;
}

=pod

=head2 I<@file_data> = read_control_file (I<$file>)

Returns the content of I<$file> as array with one line per element. 

=cut

sub read_control_file {
	my $file = shift;
	my @file_data;

	die _die("This only returns debian control files (ending with .changes or dsc)") if $file !~ /\.(?:dsc|changes)$/;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 3) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed control file data.");
		}

		print $writerfh "read_control_file $file\n";

		my $response = <$readerfh>;
		chomp($response);
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				push @file_data, $_;
			}
		}
	
	} else {
		open (FH, $file) or die _die("Can't open $file: $!");
		@file_data = <FH>;
		close FH;
	}

	return @file_data;
}

=pod

=head2 I<@file_info> = write_control_file (I<$file>, I<\@data>)

Writes contents of I<\@data> to I<$file>. Returns new md5sum and size
of I<$file>.

=cut

sub write_control_file {
	my ($file, $data) = @_;
	my ($response, $t, $new_md5sum, $new_file_size);

	die _die("This only writes debian control files (ending with .changes or dsc)") if $file !~ /\.(?:dsc|changes)$/;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		if ($prot_version < 3) {
			die _die("remote dpkg-sig on $host is too old and can't return the needed control file data.");
		}

		print $writerfh "write_control_file $file\n";

		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);
		
		if ($response =~ /^300 /) {
			print $writerfh @$data;
			print $writerfh ".\n";

			$response = '';
			do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
			chomp($response);

			if ($response =~ /^200 .+New md5sum, size: ([^ ]+) (\d+)/) {
				$new_md5sum = $1;
				$new_file_size = $2;
			} else {
				die _die("remote dpkg-sig on $host returned \"$response\"");
			}
		} else {
			die _die("remote dpkg-sig on $host seems to be weird. Can't parse \"$response\"");
		}	
	} else {
		_write_file($file, @$data);

		chomp ($new_md5sum = `md5sum $file | cut -d " " -f 1`);
		$new_file_size = (stat($file))[7];
	}

	return ($new_md5sum, $new_file_size);
}

=pod

=head2 I<@files> = glob_exp (I<$exp>)

Returns the result of globbing I<$exp> as array.

=cut

sub glob_exp {
	my $exp = shift;
	my @files;
	
	if ($exp =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($exp);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);

		print $writerfh "glob_exp $file\n";
		my $response = <$readerfh>;
		if ($response !~ /^200 /) {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		} else {
			while (<$readerfh>) {
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				if (defined ($user)) {
					push @files, "ssh://$user\@$host:$_";
				} else {
					push @files, "ssh://$host:$_";
				}
			}
		}
	} else {
		push @files, glob($exp);
	}

	return @files;
}

=pod

=head2 I<$file_readable> = file_readable (I<$file>)

Returns a true value if I<$file> is readable.

=cut

sub file_readable {
	my $file = shift;

	if ($file =~ m!^ssh://!) {
		my ($user, $host, $file) = split_ssh_uri($file);
		my ($readerfh, $writerfh, $prot_version) = get_ssh_connection($user, $host);


		if ($prot_version < 4) {
			print "W: remote dpkg-sig on $host is too old and can't return the needed data. .dsc not signed";
			return 0;
		}

		print $writerfh "file_readable $file\n";

		my ($response, $t);
		$response = '';
		do { read($readerfh, $t, 1); $response .= $t } while ($t ne "\n");
		chomp($response);

		if ($response =~ /^200 /) {
			return 1;
		} elsif ($response =~ /^400 /) {
			return 0;
		} else {
			die _die("remote dpkg-sig on $host returned \"$response\"");
		}
	} else {
		return -r $file;
	}
}

=pod

=head2 I<@ssh_uri_parts> = split_ssh_uri (I<$uri>)

Splits an ssh URI $uri into a B<$user>, B<$host> and B<$path> part.

=cut

sub split_ssh_uri {
	my ($uri) = @_;

	my ($user, $host, $path);
	
	#ssh://$USER@$HOST:$PATH

	if ($uri =~ m!^ssh://(?:([^@\s]+)@)?(\S+):(.+)!) {
		($user, $host, $path) = ($1, $2, $3);
		$user ||= undef;
		
		die _die("$uri: Please specify at least a host to connect to.") if !$host;
		die _die("$uri: Please specify a path on the remote host.") if !$path;	
	} else {
		die _die("$uri is no ssh uri!");
	}

	return ($user, $host, $path);
}

=pod

=head2 I<@ssh_connection_info> = get_ssh_connection (I<$user>, I<$host>)

Opens a ssh connection to I<$host> as user I<$user>, directly calling 
B<dpkg-sig>. It checks if the remote B<dpkg-sig> is compatible to the
current version and returns the B<$pid>, the Read-Filehandle B<$readerfh>
and the Write-Filehandle B<$writerfh>.

=cut

sub get_ssh_connection {
	my ($user, $host) = @_;

	my $connection_id = (defined ($user))?"$user\@$host":$host;

	$remote_ssh_port ||= "";
	$remote_ssh_port =~ s/^\s*(\d+)\s*$/-p $&/;
	if (! $ssh_connections{$connection_id} ) {
		my ($readerfh, $writerfh);
		die _die("No ssh installed, we need it to connect to the remote host.") if (not `which ssh`);
		
		my $pid = open2($readerfh, $writerfh, qq{ssh $remote_ssh_port $connection_id '$remote_dpkg_sig --client $DEBUG 2>/dev/null || echo "No dpkg-sig available"' 2>&1});
		
		my $response = <$readerfh>;
		if ($response && $response !~ /protocol version/i) {
			if ($response && $response =~ /No dpkg-sig available/) {
				die _die("No $remote_dpkg_sig on remote host installed.");
			} else {
				if ($response) {
					die _die("ssh returned $response");
				} else {
					die _die("Some problem with the ssh connection $connection_id occured");
				}
			}
		}
		
		if ($response !~ /protocol version (\d+)$/i || $1 < 6) {
			die _die("dpkg-sig on $host is too old (we need protocol version 6)");
		}
		
		$ssh_connections{$connection_id} = [$pid, $readerfh, $writerfh, $1];
	}

	return (@{$ssh_connections{$connection_id}}[1,2,3]);
}

=pod

=head2 sign_control_files (I<$changes_file>)

This works like debsign:

=over 4

=item Checks if a .dsc exists.

=item If the .dsc should be signed, it tries to do so..

=item Writes the new .dsc with the new signature.

=item Reads I<$changes_file> and puts in the new size/md5sum of the .dsc.

=item Signs I<$changes_file> and write the signed copy back.

=back

=cut

sub sign_control_files {
	my $file = shift;
	my $sign_dsc = $sign_changes =~ /full$/ ? 1 : 0;
	my ($dsc, $new_dsc_md5sum, $new_dsc_size);
	    $dsc = "$1.dsc" if ($file =~ /^(.+)_[^ _]+.changes/ && file_readable("$1.dsc"));

	#Clean the tempdir:
	unlink ($tempdir."/dsc.unsigned");
	unlink ($tempdir."/dsc.signed");
	unlink ($tempdir."/changes.unsigned");
	unlink ($tempdir."/changes.signed");

	if ($sign_dsc && $dsc) {
		open (DSC, ">", $tempdir."/dsc.unsigned") || die _die("Can't open $tempdir/dsc.unsigned: $!");
		my @data = read_control_file($dsc);
		for (my $i=0;$i<@data;$i++) {
			if ($data[$i] =~ /^-----BEGIN PGP SIGNED MESSAGE-----$/) {
				if ($sign_changes eq "force_full") { 
					$sign_dsc = 1;
				} elsif (! $batch) {
					print "The .dsc file is already signed.\nWould you like to use the current signature? [Yn] ";
					chomp(my $answer = lc(<STDIN>));
					$sign_dsc = 0 unless ($answer eq "n" || $answer eq "no");
				} else {
					$sign_dsc = 0;
				}
				while(defined $data[$i]) { last if $data[$i++] =~ /^\s*$/ }
			} elsif ($data[$i] =~ /^\s*$/) {
				last;
			}
			print DSC $data[$i];
		}
		print DSC "\n";
		close DSC;

		if ($sign_dsc) {
			#Sign it:
			sign_file($tempdir."/dsc.unsigned",$tempdir."/dsc.signed", "no_detach") if $sign_dsc;

			#Read and write them to the fitting location:
			open (DSC, $tempdir."/dsc.signed") || die _die("Can't open $tempdir/dsc.signed: $!");
			@data = <DSC>;
			close DSC;
			($new_dsc_md5sum, $new_dsc_size) = write_control_file($dsc, \@data);
			print "Signed .dsc $dsc\n" unless $batch;
		}
	}
	
	#Now the changes file:
	open (CHANGES, ">", $tempdir."/changes.unsigned") || die _die("Can't open $tempdir/changes.unsigned: $!");
	my $basename_dsc = basename($dsc) if $dsc;
	for (read_control_file($file), "\n") {
		#If we've changed the .dsc file, we have to use the new values in the .changes:
		if ($basename_dsc && $new_dsc_md5sum && $new_dsc_size && $_ =~ /\Q$basename_dsc\E$/) {
			 s/^ [^ ]+ \d+ (.+)$/ $new_dsc_md5sum $new_dsc_size $1/;
		}
		print CHANGES $_;
	}
	close CHANGES;

	sign_file($tempdir."/changes.unsigned",$tempdir."/changes.signed", "no_detach");
	
	my @data;
	open (CHANGES, $tempdir."/changes.signed") || die _die("Can't open $tempdir/changes.signed: $!");
	@data = <CHANGES>;
	close CHANGES;
	write_control_file($file, \@data);
	print "Signed .changes $file\n" unless $batch;	
}


=pod

=head2 sign_file (I<$in_file>, I<$out_file>, I<$no_detach>)

Signs I<$in_file> with gpg and puts the detached signature in I<$out_file>.

If I<$no_detach> is true, I<$out_file> is a clearsigned copy of I<$in_file>.

=cut

sub sign_file {
	my ($in_file, $out_file, $no_detach) = @_;

	my @cmdline = ("gpg", "--openpgp", "--armor", "--output", $out_file);
	if ($no_detach) {
		push @cmdline, "--clearsign";
	} else {
		push @cmdline, "--detach-sign";
	}

	if ($key) {
		push (@cmdline, "--default-key", "'$key'");
		print "Default key: $key\n" if $verbose;
	} elsif ($maintainer) {
		push (@cmdline, "--default-key", "'$maintainer'");
	}

	if ($pass_file) {
		push (@cmdline, "--no-tty", "--batch", "--passphrase-fd", "42", "42<$pass_file");
		print "Using passphrase from $pass_file\n" if $verbose;
	} elsif ($passphrase) {
		push (@cmdline, "--no-tty", "--batch", "--passphrase-fd", "0");
		print "Using cached passphrase\n" if $verbose;
	}

	push (@cmdline, $gpgoptions) if $gpgoptions;

	print "Signing $in_file with key ".($key || "of $maintainer")."\n" if $verbose;		
	push (@cmdline, $in_file, "2>&1");
	open (GPG, "| ".join " ", @cmdline) || die _die("Signing failed: $!");
	print GPG $passphrase, "\n" if $passphrase;
	close GPG;
	die _die("Signing failed. Error code: $?") if $?;
}

sub read_cmds {
	$DEBUG && (open (LOG, ">", "/tmp/dpkg-sig.log") || die _die("Couldn't open log: $!"));
	$DEBUG && select LOG; $|=1; 
	$DEBUG && select STDOUT;
	
	sub send { print STDOUT @_; $DEBUG && print LOG "Sent: ", @_; }
	sub read { $_ = <STDIN>; $DEBUG && print LOG "Received: ", $_; return $_ } ;

	while ($_ = &read()) {
		chomp;

		if (/^get_deb_digests (.+)$/) {
			my $r = eval { get_deb_digests ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send ("500 error: $@\n");
			} else {
				&send("200 ok digests for $1 follow\n");
				&send(join (" ", @$_), "\n") for @$r;
				&send(".\n");
			}

		} elsif (/^get_deb_parts (.+)$/) {
			my @r = eval { get_deb_parts ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send ("500 error: $@\n");
			} else {
				&send("200 ok parts of $1 follow\n");
				&send($_->[0] . "\n") for @r;
				&send(".\n");
			}

		} elsif (/^get_archive_part ([^ ]+) (.+)$/) {
			my $r = eval { get_archive_part ($2, $1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");
			} else {
				&send("200 ok part $1 of $2 follows\n");
				for (split (/\n/, $r)) {
					s/^\./../;
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^read_control_file (.+)$/) {
			my @r = eval { read_control_file ($1) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");
			} else {
				&send("200 ok file $1 follows\n");
				for (@r) {
					s/^\./../;
					&send("$_");
				}
				&send(".\n");
			}

		} elsif (/^get_debs_from_changes (.+)$/) {
			my $changes_signed = 0;
			my @r = eval { get_debs_from_changes ($1, \$changes_signed) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				if ($changes_signed) {
					&send("200 ok debs in signed $1 follow\n");	
				} else {
					&send("200 ok debs in $1 follow\n");
				}
				for (@r) {
					s/^\./../;			
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^glob_exp (.+)$/) {
			my @r = eval { glob_exp ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				&send("200 ok files matching \"$1\" follow\n");	
				for (@r) {
					s/^\./../;			
					&send("$_\n");
				}
				&send(".\n");
			}

		} elsif (/^file_readable (.+)$/) {
			my $r = eval { file_readable ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				if ($r) {
					&send("200 ok file readable\n");
				} else {
					&send("400 not ok file not readable\n");
				}
			}

		} elsif (/^get_file_md5sum (.+)$/) {
			my $r = eval { get_file_md5sum ($1) };		
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: $@\n");		
			} else {
				&send("200 ok md5sum is $r\n");
			}


		} elsif (/^add_sig_to_deb ([^ ]+) (.+)$/) {
			my ($sig_name, $deb, $sig) = ($1, $2, '');
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {		
				last if (/^\.$/);
				s/^\.\././;
				$sig .= $_;
			}
			my $r = eval { add_sig_to_deb ($deb, $sig, $sig_name) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok added sig to $deb. New data follows\n");
				&send(join (" ", @$r), "\n");
			}

		} elsif (/^correct_changes_file (.+)$/) {
			my ($changes, $new_changes_data) = ($1, {});
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {	
				last if (/^\.$/);
				s/^\.\././;
				chomp;
				my ($md5sum, $size, $name) = split (/ /, $_, 3);
				$new_changes_data->{$name} = [$md5sum, $size, $name];
			}
			my $r = eval { correct_changes_file ($changes, $new_changes_data) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok $changes corrected\n");
			}

		} elsif (/^write_control_file (.+)$/) {
			my ($file, @data) = ($1, ());
			
			&send("300 ok waiting for data\n");
			while ($_ = &read()) {	
				last if (/^\.$/);
				s/^\.\././;
				push @data, $_;
			}
			my @r = eval { write_control_file ($file, \@data) };
			if ($@) {
				chomp($@); $@ =~ s/\n/\t/g;
				&send("500 error: ");
				&send($@, "\n");
			} else {
				&send("200 ok $file written. New md5sum, size: $r[0] $r[1]\n");
			}

		} elsif (/^quit\s*$/) {
			&send("200 ok Bye!\n");
			exit;

		} else {
			&send("501 unknown command ".(split / /, $_)[0]."\n");
		}
	}
	$DEBUG && close LOG;
}

sub process_cli_options {
	exit 1 unless GetOptions("sign|s=s" => \$sign,
	                         "list|l|t" => \$list,
	                         "verify|check|c" => \$verify,
	                         "verify-role=s" => \$verify_role,
	                         "verify-exact=s" => \$verify_exact,
	                         "get-hashes=s" => \$get_hashes,
	                         "sign-hashes" => \$sign_hashes,
	                         "write-signature" => \$write_signature,
	                         "client" => \$client,
	                         "help"   => \$help,
	                         #Options:
	                         "default-key|k=s" => \$key,
	                         "cache-passphrase|p" => \$cache_pass,
	                         "passphrase-file|f=s" => \$pass_file,
	                         "m=s" => \$maintainer,
	                         "e=s" => \$maintainer_pr,
	                         "verbose|v+" => \$verbose,
	                         "also-v2-sig" => \$check_v2_sig,
	                         "also-v3-sig" => \$check_v2_sig,
	                         "sign-changes|a:s" => \$sign_changes,
	                         "batch:i" => \$batch,
	                         "gpg-options|g=s" => \$gpgoptions,
	                         "remote-dpkg-sig|r=s" => \$remote_dpkg_sig,
							 "remote-ssh-port|o=i" => \$remote_ssh_port,
	                        );
	$check_v2_sig = ($check_v2_sig && $check_v2_sig eq "false"?0:"yes");
	$check_v3_sig = ($check_v3_sig && $check_v3_sig eq "false"?0:"yes");
	
	die _die('Please use only one of --sign, --list, --verify[-role|-exact], --get-hashes, --write-signature, --help and --client!')
	  if (! !$sign + ! !$list + ! !$verify + ! !$verify_role + ! !$verify_exact + ! !$client + ! !$get_hashes + ! !$sign_hashes + ! !$write_signature + ! ! $help> 1);
	
	$maintainer_pr && ($maintainer = $maintainer_pr);
	if (!$sign && !$list && !$verify && !$verify_role && !$verify_exact &&
	  !$client && !$get_hashes && !$sign_hashes && !$write_signature && 
	  !$help) {
		if (@ARGV) {
			$verify = 1;
			print "I: No action requested, verifying files.\n";
		} else {
			$help = 1;
		}
	}
}

sub load_config {
	my @configfiles = @_;

	for my $configfile (@configfiles) {
		$configfile = (glob($configfile))[0];
		
		if ($configfile && -r $configfile) {
			%config = %{read_config_file($configfile) || {}};
		}
	}

	($maintainer = ($config{'DEBSIGN_MAINT'} || "")) =~ s/^"(.+)"$/$1/ if ! $maintainer;
	($key        = ($config{'DPKGSIG_KEYID'} || $config{'DEBSIGN_KEYID'} || "")) =~ s/^"(.+)"$/$1/ if ! $key;
	($cache_pass = ($config{'DPKGSIG_CACHE_PASS'} || "")) =~ s/^"(.+)"$/$1/ if ! $cache_pass;
	($sign_changes=($config{'DPKGSIG_SIGN_CHANGES'} ||""))=~ s/^"(.+)"$/$1/ if ! $sign_changes;

	if (! $sign_changes) {
		$sign_changes = "auto";
	} elsif (! grep {$sign_changes eq $_} qw(no auto yes full force_full)) {
		if ($sign_changes =~ /(?:deb|changes)$/) {
			push @files, $sign_changes;
			$sign_changes = "yes";		
		} else {
			print "W: Unrecognized argument to --sign-changes, using \"auto\": $sign_changes\n";
			$sign_changes = "auto";		
		}
	}

	if ($sign && $cache_pass && ! $pass_file) {
		eval { require Term::ReadKey; };
		if ($@) {
			print STDERR "Couldn't load Term::ReadKey. Please install. Passphrase caching disabled.\n";
		} else {
			my $passphrase_valid = 0;
			while (! $passphrase_valid) {
				print "The passphrase for ".($key || "your default key").": ";
				Term::ReadKey::ReadMode("noecho");
				chomp($passphrase = Term::ReadKey::ReadLine(0));
				Term::ReadKey::ReadMode("restore");
				print "\n";

				#Try to use the key:
				open (TMP, ">", $tempdir . '/tmp-file') or die "Can't open $tempdir/tmp-file: $!";
				print TMP "Foobar";
				close TMP;

				my $error;
				eval {
					my  @sign_cmd = ("gpg", "--clearsign");
					push @sign_cmd, ("--default-key", $key) if $key;
					push @sign_cmd, ("--no-tty", "--batch", "--passphrase-fd", "0");
					push @sign_cmd, $gpgoptions if $gpgoptions;
					push @sign_cmd, "$tempdir/tmp-file";
					my ($write_handle, $read_handle);
					open3 ($write_handle, $read_handle, undef, @sign_cmd) || die _die("Signing failed: $!");
					print $write_handle $passphrase, "\n";
					close $write_handle;
					$error = join "", <$read_handle>;
					close $read_handle;
				};

				if ($error && $error =~ /^gpg:.+bad passphrase\n/) {
					$passphrase_valid = 0;
					print STDERR "Wrong passphrase for " . (($key)?"key $key":"default key") . "!\n";
				} else {
					$passphrase_valid = 1;
				}
			}
		}
	}
}

sub help {
	print <<EOH;
Short usage:
 If not stated otherwise, all commands have one or more .deb or .changes
 files as argument. In the case of .changes files, dpkg-sig will work on
 all .deb files named in there. 

 -s,--sign <SIGNING_NAME>         Sign files 
 -c,--verify                      Verify signatures on files
 -l,--list                        List signatures on files
  
    --get-hashes                  Get hashes file for files
    --sign-hashes <HASHES_FILE>   Sign hashes file
    --write-hashes <HASHES_FILE>  Write sigs from signed hashes file

Options:
 -m,-e <MAINTAINER_NAME>          Specify maintainer name to use when signing
 -k <KEYID>                       Specify keyid to use when signing
 -v,--verbose                     Makes dpkg-sig more verbose
    --also-v2-sig                 Verify sigs from dpkg-sig 0.2 and earlier
    --also-v3-sig                 Verify sigs from dpkg-sig 0.3-0.10
 -a,--sign-changes <no|auto|yes|full|force_full>
       Tells whether also sign the changes and dsc-files. The default is auto.

 -g,--gpgoptions <GPG_OPTIONS>    DANGEROUS: Specify custom gpg options.
 -p,--cache-passphrase            INSECURE: Caches gpg passphrase in dpkg-sig
 -f,--passphrase-file <FILE>      INSECURE: Let gpg use passphrase from <FILE>
EOH
}

sub _die {
	chomp(my $msg = shift || "No error msg given! This is a bug, hurt the author!");
	my $i = 0;
	
	while ($_ = (caller($i++))[3]) {
		if ($_ && $_ eq "(eval)") {
			return $msg;
		}
	}
	
	my $code = shift || 1;
	my $line = (caller)[2];
	print STDERR "E: $msg\n";
	exit $code;
}

sub _read_file {
	my $file = shift;
	my $content;
	
	open (FH, $file) or die _die "Can't open $file: $!";
	$content = join "", <FH>;
	close FH;

	return $content;
}

sub _write_file {
	my $file = shift;
	my @content = @_;
	
	open (FH, ">", $file) or die _die "Can't open $file for writing: $!";
	print FH @content;
	close FH;
}

=pod

=head1 AUTHOR

B<dpkg-sig> and this manpage were written by Andreas Barth und Marc 
Brockschmidt. They are Copyright (C) 2003, 2004 by them and released 
under the GNU General Public Licence version 2 or later; there is NO
WARRANTY.  See F</usr/share/doc/dpkg-sig/copyright> and 
F</usr/share/common-licenses/GPL> for details.

=cut

# vim:set shiftwidth=4:
# vim:set tabstop=4:
# vim:set noet:
# vim:set shiftround: