3 # yapfaq Version 0.6 by Thomas Hochstein
4 # (Original author: Marc Brockschmidt)
6 # This script posts any project described in its config-file. Most people
7 # will use it in combination with cron(8).
9 # Copyright (C) 2003 Marc Brockschmidt <marc@marcbrockschmidt.de>
10 # Copyright (c) 2010 Thomas Hochstein <thh@inter.net>
12 # It can be redistributed and/or modified under the same terms under
13 # which Perl itself is published.
15 my $Version = "0.6-unreleased";
17 my $NNTPServer = "localhost";
21 my $ConfigFile = "yapfaq.cfg";
24 ################################## PGP-Config #################################
26 my $pgp = '/usr/bin/pgp'; # path to pgp
27 my $PGPVersion = '2'; # Use 2 for 2.X, 5 for PGP > 2.X and GPG for GPG
29 my $PGPSigner = ''; # sign as who?
30 my $PGPPass = ''; # pgp2 only
31 my $PathtoPGPPass = ''; # pgp2, pgp5 and gpg
34 my $pgpbegin ='-----BEGIN PGP SIGNATURE-----';# Begin of PGP-Signature
35 my $pgpend ='-----END PGP SIGNATURE-----'; # End of PGP-Signature
36 my $pgptmpf ='pgptmp'; # temporary file for PGP.
37 my $pgpheader ='X-PGP-Sig';
39 my @PGPSignHeaders = ('From', 'Newsgroups', 'Subject', 'Control',
40 'Supersedes', 'Followup-To', 'Date', 'Sender', 'Approved',
41 'Message-ID', 'Reply-To', 'Cancel-Lock', 'Cancel-Key',
42 'Also-Control', 'Distribution');
44 my @PGPorderheaders = ('from', 'newsgroups', 'subject', 'control',
45 'supersedes', 'followup-To', 'date', 'organization', 'lines',
46 'sender', 'approved', 'distribution', 'message-id',
47 'references', 'reply-to', 'mime-version', 'content-type',
48 'content-transfer-encoding', 'summary', 'keywords', 'cancel-lock',
49 'cancel-key', 'also-control', 'x-pgp', 'user-agent');
51 ############################# End of Configuration #############################
55 use Date::Calc qw(Add_Delta_YM Add_Delta_Days Delta_Days Today);
56 use Fcntl ':flock'; # import LOCK_* constants
58 my ($TDY, $TDM, $TDD) = Today(); #TD: Today's date
61 getopts('hvpdt:f:', \%Options);
63 print "$0 v $Version\nUsage: $0 [-hvpd] [-t <newsgroups>] [-f <faq>]\n";
66 my ($Faq) = $Options{'f'} if ($Options{'f'});
69 readconfig (\$ConfigFile, \@Config, \$Faq);
72 my ($LPD,$LPM,$LPY) = (01, 01, 0001); #LP: Last posting-date
73 my ($NPY,$NPM,$NPD); #NP: Next posting-date
76 my ($ActName,$File,$PFreq,$Expire) =($$_{'name'},$$_{'file'},$$_{'posting-frequency'},$$_{'expires'});
77 my ($From,$Subject,$NG,$Fup2)=($$_{'from'},$$_{'subject'},$$_{'ngs'},$$_{'fup2'});
78 my ($MIDF,$ReplyTo,$ExtHea)=($$_{'mid-format'},$$_{'reply-to'},$$_{'extraheader'});
79 my ($Supersede) =($$_{'supersede'});
81 next if (defined($Faq) && $ActName ne $Faq);
83 if (open (FH, "<$File.cfg")) {
85 if (/##;; Lastpost:\s*(\d{1,2})\.(\d{1,2})\.(\d{2}(\d{2})?)/){
86 ($LPD, $LPM, $LPY) = ($1, $2, $3);
87 } elsif (/^##;;\s*LastMID:\s*(<\S+@\S+>)\s*$/) {
93 warn "$0: W: Couldn't open $File.cfg: $!\n";
96 $SupersedeMID = "" unless $Supersede;
98 ($NPY,$NPM,$NPD) = calcdelta ($LPY,$LPM,$LPD,$PFreq);
100 if (Delta_Days($NPY,$NPM,$NPD,$TDY,$TDM,$TDD) >= 0 or ($Options{'p'})) {
102 print "$ActName: Would be posted now (but running in simulation mode [$0 -d]).\n" if $Options{'v'};
104 postfaq(\$ActName,\$File,\$From,\$Subject,\$NG,\$Fup2,\$MIDF,\$ExtHea,\$Sender,\$TDY,\$TDM,\$TDD,\$ReplyTo,\$SupersedeMID,\$Expire);
106 } elsif($Options{'v'}) {
107 print "$ActName: Nothing to do.\n";
113 ################################## readconfig ##################################
114 # Takes a filename, a reference to an array, which will hold hashes with
115 # the data from $File, and - optionally - the name of the (single) FAQ to post
118 my ($File, $Config, $Faq) = @_;
119 my ($LastEntry, $Error, $i) = ('','',0);
122 print "Reading configuration.\n";
125 open FH, "<$$File" or die "$0: E: Can't open $$File: $!";
127 next if (defined($$Faq) && !/^\s*=====\s*$/ && defined($$Config[$i]{'name'}) && $$Config[$i]{'name'} ne $$Faq );
128 if (/^(\s*(\S+)\s*=\s*'?(.*?)'?\s*(#.*$|$)|^(.*?)'?\s*(#.*$|$))/ && not /^\s*$/) {
129 $LastEntry = lc($2) if $2;
130 $$Config[$i]{$LastEntry} .= $3 if $3;
131 $$Config[$i]{$LastEntry} .= "\n$5" if $5 && $5;
133 if (/^\s*=====\s*$/) {
141 next if (defined($$Faq) && defined($$Config[$i]{'name'}) && $$Config[$i]{'name'} ne $$Faq );
142 unless($$Config[$i]{'from'} =~ /\S+\@(\S+\.)?\S{2,}\.\S{2,}/) {
143 $Error .= "E: The From-header for your project \"$$Config[$i]{'name'}\" seems to be incorrect.\n"
145 unless($$Config[$i]{'ngs'} =~ /^\S+$/) {
146 $Error .= "E: The Newsgroups-header for your project \"$$Config[$i]{'name'}\" contains whitespaces.\n"
148 unless(!$$Config[$i]{'fup2'} || $$Config[$i]{'fup2'} =~ /^\S+$/) {
149 $Error .= "E: The Followup-To-header for your project \"$$Config[$i]{'name'}\" contains whitespaces.\n"
151 unless($$Config[$i]{'posting-frequency'} =~ /^\s*\d+\s*[dwmy]\s*$/) {
152 $Error .= "E: The Posting-frequency for your project \"$$Config[$i]{'name'}\" is invalid.\n"
154 unless($$Config[$i]{'expires'} =~ /^\s*\d+\s*[dwmy]\s*$/) {
155 $$Config[$i]{'expires'} = '3m'; # set default: 3 month
156 warn "$0: W: The Expires for your project \"$$Config[$i]{'name'}\" is invalid - set to 3 month.\n";
158 $Error .= "-" x 25 . "\n" if $Error;
160 die $Error if $Error;
163 ################################# calcdelta #################################
164 # Takes a date (year, month and day) and a time period (1d, 1w, 1m, 1y, ...)
165 # and adds the latter to the former
168 my ($Year, $Month, $Day, $Period) = @_;
169 my ($NYear, $NMonth, $NDay);
171 if ($Period =~ /(\d+)\s*([dw])/) { # Is counted in days or weeks: Use Add_Delta_Days.
172 ($NYear, $NMonth, $NDay) = Add_Delta_Days($Year, $Month, $Day, (($2 eq "w")?$1 * 7: $1 * 1));
173 } elsif ($Period =~ /(\d+)\s*([my])/) { #Is counted in months or years: Use Add_Delta_YM
174 ($NYear, $NMonth, $NDay) = Add_Delta_YM($Year, $Month, $Day, (($2 eq "m")?(0,$1):($1,0)));
176 return ($NYear, $NMonth, $NDay);
179 ################################## postfaq ##################################
180 # Takes a filename and many other vars.
182 # It reads the data-file $File and then posts the article.
185 my ($ActName,$File,$From,$Subject,$NG,$Fup2,$MIDF,$ExtraHeaders,$Sender,$TDY,$TDM,$TDD,$ReplyTo,$Supersedes,$Expire) = @_;
186 my (@Header,@Body,$MID,$InRealBody,$LastModified);
189 print "$$ActName: Preparing to post.\n";
193 $$TDM = ($$TDM < 10 && $$TDM !~ /^0/) ? "0" . $$TDM : $$TDM;
194 $$TDD = ($$TDD < 10 && $$TDD !~ /^0/) ? "0" . $$TDD : $$TDD;
197 $MID =~ s/\%n/$$ActName/g;
198 $MID =~ s/\%d/$$TDD/g;
199 $MID =~ s/\%m/$$TDM/g;
200 $MID =~ s/\%y/$$TDY/g;
204 open (FH, "<$$File");
207 push (@Body, $_), next if $InRealBody;
208 $InRealBody++ if /^$/;
209 $LastModified = $1 if /^Last-modified: (\S+)$/i;
213 push @Body, "\n" if ($Body[-1] ne "\n");
215 #Create Date- and Expires-Header:
216 my @time = localtime;
217 my $ss = ($time[0]<10) ? "0" . $time[0] : $time[0];
218 my $mm = ($time[1]<10) ? "0" . $time[1] : $time[1];
219 my $hh = ($time[2]<10) ? "0" . $time[2] : $time[2];
221 my $month = ($time[4]+1<10) ? "0" . ($time[4]+1) : $time[4]+1;
222 my $monthN = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$time[4]];
223 my $wday = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat")[$time[6]];
224 my $year = (1900 + $time[5]);
225 my $tz = $time[8] ? " +0200" : " +0100";
227 my ($expY,$expM,$expD) = calcdelta ($year,$month,$day,$$Expire);
228 my $expmonthN = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$expM-1];
230 my $date = "$day $monthN $year " . $hh . ":" . $mm . ":" . $ss . $tz;
231 my $expdate = "$expD $expmonthN $expY $hh:$mm:$ss$tz";
233 #Replace %LM by the content of the news.answer-pseudo-header Last-modified:
235 $$Subject =~ s/\%LM/$LastModified/;
239 if($Options{'t'} and $Options{'t'} !~ /console/i) {
240 $$NG = $Options{'t'};
243 #Now create the complete Header:
244 push @Header, "From: $$From\n";
245 push @Header, "Newsgroups: $$NG\n";
246 push @Header, "Followup-To: $$Fup2\n" if $$Fup2;
247 push @Header, "Subject: $$Subject\n";
248 push @Header, "Message-ID: $MID\n";
249 push @Header, "Supersedes: $$Supersedes\n" if $$Supersedes;
250 push @Header, "Date: $date\n";
251 push @Header, "Expires: $expdate\n";
252 push @Header, "Sender: $$Sender\n" if $$Sender;
253 push @Header, "Mime-Version: 1.0\n";
254 push @Header, "Reply-To: $$ReplyTo\n" if $$ReplyTo;
255 push @Header, "Content-Type: text/plain; charset=ISO-8859-15\n";
256 push @Header, "Content-Transfer-Encoding: 8bit\n";
257 push @Header, "User-Agent: yapfaq/$Version\n";
258 if ($$ExtraHeaders) {
259 push @Header, "$_\n" for (split /\n/, $$ExtraHeaders);
262 my @Article = ($UsePGP)?@{signpgp(\@Header, \@Body)}:(@Header, "\n", @Body);
265 print "$$ActName: Posting article ...\n";
270 print "$$ActName: Save status information.\n";
273 open (FH, ">$$File.cfg") or die "$0: E: Can't open $$File.cfg: $!";
274 print FH "##;; Lastpost: $day.$month.$year\n";
275 print FH "##;; LastMID: $MID\n";
279 ################################## post ##################################
280 # Takes a complete article (Header and Body).
282 # It opens a connection to $NNTPServer and posts the message.
288 if(defined($Options{'t'}) and $Options{'t'} =~ /console/i) {
289 print "\n-----BEGIN--------------------------------------------------\n";
291 print "\n------END---------------------------------------------------\n";
295 my $NewsConnection = Net::NNTP->new($NNTPServer, Reader => 1)
296 or die "$0: E: Can't connect to news server '$NNTPServer'!\n";
298 $NewsConnection->authinfo ($NNTPUser, $NNTPPass);
299 $NewsConnection->post();
300 $NewsConnection->datasend (@$ArticleR);
301 $NewsConnection->dataend();
303 if (!$NewsConnection->ok()) {
304 open FH, ">>ERROR.dat";
305 print FH "\nPosting failed! Saving to ERROR.dat. Response from news server:\n";
306 print FH $NewsConnection->code();
307 print FH $NewsConnection->message();
310 print FH "-" x 80, "\n";
314 $NewsConnection->quit();
317 #-------- sub getpgpcommand
318 # getpgpcommand generates the command to sign the message and returns it.
321 # - $PGPVersion: A scalar holding the PGPVersion
323 my ($PGPVersion) = @_;
326 if ($PGPVersion eq '2') {
327 if ($PathtoPGPPass && !$PGPPass) {
328 open (PGPPW, $PathtoPGPPass) or die "$0: E: Can't open $PathtoPGPPass: $!";
334 $PGPCommand = "PGPPASS=\"".$PGPPass."\" ".$pgp." -u \"".$PGPSigner."\" +verbose=0 language='en' -saft <".$pgptmpf.".txt >".$pgptmpf.".txt.asc";
336 die "$0: E: PGP-Passphrase is unknown!\n";
338 } elsif ($PGPVersion eq '5') {
339 if ($PathtoPGPPass) {
340 $PGPCommand = "PGPPASSFD=2 ".$pgp."s -u \"".$PGPSigner."\" -t --armor -o ".$pgptmpf.".txt.asc -z -f < ".$pgptmpf.".txt 2<".$PathtoPGPPass;
342 die "$0: E: PGP-Passphrase is unknown!\n";
344 } elsif ($PGPVersion =~ m/GPG/io) {
345 if ($PathtoPGPPass) {
346 $PGPCommand = $pgp." --digest-algo MD5 -a -u \"".$PGPSigner."\" -o ".$pgptmpf.".txt.asc --no-tty --batch --passphrase-fd 2 2<".$PathtoPGPPass." --clearsign ".$pgptmpf.".txt";
348 die "$0: E: Passphrase is unknown!\n";
351 die "$0: E: Unknown PGP-Version $PGPVersion!";
357 #-------- sub signarticle
358 # signarticle signs an articel and returns a reference to an array
359 # containing the whole signed Message.
362 # - $HeaderAR: A reference to a array containing the articles headers.
363 # - $BodyR: A reference to an array containing the body.
366 # - $MessageRef: A reference to an array containing the whole message.
368 my ($HeaderAR, $BodyR) = @_;
369 my (@pgphead, @pgpbody, $pgphead, $pgpbody, $header, $signheaders, @signheaders, $currentheader, $HeaderR, $line);
371 foreach my $line (@$HeaderAR) {
372 if ($line =~ /^(\S+):\s+(.*)$/s) {
374 $$HeaderR{lc($currentheader)} = "$1: $2";
376 $$HeaderR{lc($currentheader)} .= $line;
380 foreach (@PGPSignHeaders) {
381 if (defined($$HeaderR{lc($_)}) && $$HeaderR{lc($_)} =~ m/^[^\s:]+: .+/o) {
382 push @signheaders, $_;
386 $pgpbody = join ("", @$BodyR);
388 # Delete and create the temporary pgp-Files
389 unlink "$pgptmpf.txt";
390 unlink "$pgptmpf.txt.asc";
391 $signheaders = join(",", @signheaders);
393 $pgphead = "X-Signed-Headers: $signheaders\n";
394 foreach $header (@signheaders) {
395 if ($$HeaderR{lc($header)} =~ m/^[^\s:]+: (.+?)\n?$/so) {
396 $pgphead .= $header.": ".$1."\n";
400 open(FH, ">" . $pgptmpf . ".txt") or die "$0: E: can't open $pgptmpf: $!\n";
401 print FH $pgphead, "\n", $pgpbody;
402 print FH "\n" if ($PGPVersion =~ m/GPG/io); # workaround a pgp/gpg incompatibility - should IMHO be fixed in pgpverify
403 close(FH) or warn "$0: W: Couldn't close TMP: $!\n";
405 # Start PGP, then read the signature;
406 my $PGPCommand = getpgpcommand($PGPVersion);
409 open (FH, "<" . $pgptmpf . ".txt.asc") or die "$0: E: can't open ".$pgptmpf.".txt.asc: $!\n";
412 unless (m/\Q$pgpbegin\E$/o) {
413 # unlink $pgptmpf . ".txt";
414 # unlink $pgptmpf . ".txt.asc";
415 die "$0: E: $pgpbegin not found in ".$pgptmpf.".txt.asc\n"
417 unlink($pgptmpf . ".txt") or warn "$0: W: Couldn't unlink $pgptmpf.txt: $!\n";
421 unless (m/^Version: (\S+)(?:\s(\S+))?/o) {
422 unlink $pgptmpf . ".txt";
423 unlink $pgptmpf . ".txt.asc";
424 die "$0: E: didn't find PGP Version line where expected.\n";
428 $$HeaderR{$pgpheader} = $1."-".$2." ".$signheaders;
430 $$HeaderR{$pgpheader} = $1." ".$signheaders;
433 do { # skip other pgp headers like
434 $_ = <FH>; # "charset:"||"comment:" until empty line
439 last if /^\Q$pgpend\E$/;
440 $$HeaderR{$pgpheader} .= "\n\t$_";
443 $$HeaderR{$pgpheader} .= "\n" unless ($$HeaderR{$pgpheader} =~ /\n$/s);
447 unlink $pgptmpf . ".txt";
448 unlink $pgptmpf . ".txt.asc";
449 die "$0: E: unexpected data following $pgpend\n";
452 unlink "$pgptmpf.txt.asc";
454 my $tmppgpheader = $pgpheader . ": " . $$HeaderR{$pgpheader};
455 delete $$HeaderR{$pgpheader};
458 foreach $header (@PGPorderheaders) {
459 if ($$HeaderR{$header} && $$HeaderR{$header} ne "\n") {
460 push(@pgphead, "$$HeaderR{$header}");
461 delete $$HeaderR{$header};
465 foreach $header (keys %$HeaderR) {
466 if ($$HeaderR{$header} && $$HeaderR{$header} ne "\n") {
467 push(@pgphead, "$$HeaderR{$header}");
468 delete $$HeaderR{$header};
472 push @pgphead, ("X-PGP-Key: " . $PGPSigner . "\n"), $tmppgpheader;
475 @pgpbody = split /$/m, $pgpbody;
476 my @pgpmessage = (@pgphead, "\n", @pgpbody);