eb9993778a5c082d0fb259e3a551566ade3606f7
[usenet/yapfaq.git] / yapfaq.pl
1 #! /usr/bin/perl -W
2 #
3 # yapfaq Version 0.6 by Thomas Hochstein
4 # (Original author: Marc Brockschmidt)
5 #
6 # This script posts any project described in its config-file. Most people
7 # will use it in combination with cron(8).
8
9 # Copyright (C) 2003 Marc Brockschmidt <marc@marcbrockschmidt.de>
10 # Copyright (c) 2010 Thomas Hochstein <thh@inter.net>
11 #
12 # It can be redistributed and/or modified under the same terms under 
13 # which Perl itself is published.
14
15 my $Version = "0.6-unreleased";
16
17 my $NNTPServer = "localhost";
18 my $NNTPUser = "";
19 my $NNTPPass = "";
20 my $Sender = "";
21 my $ConfigFile = "yapfaq.cfg";
22 my $UsePGP = 0;
23
24 ################################## PGP-Config #################################
25
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
28
29 my $PGPSigner     = '';                        # sign as who?
30 my $PGPPass       = '';                        # pgp2 only
31 my $PathtoPGPPass = '';                        # pgp2, pgp5 and gpg
32
33
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';
38
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');
43
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');
50
51 ############################# End of Configuration #############################
52
53 use strict;
54 use Net::NNTP;
55 use Date::Calc qw(Add_Delta_YM Add_Delta_Days Delta_Days Today);
56 use Fcntl ':flock'; # import LOCK_* constants
57 use Getopt::Std;
58 my ($TDY, $TDM, $TDD) = Today(); #TD: Today's date
59
60 my %Options;
61 getopts('hvpdt:f:', \%Options);
62 if ($Options{'h'}) {
63   print "$0 v $Version\nUsage: $0 [-hvpd] [-t <newsgroups>] [-f <faq>]\n";
64   exit(0);
65 };
66 my ($Faq) = $Options{'f'} if ($Options{'f'});
67
68 my @Config;
69 readconfig (\$ConfigFile, \@Config, \$Faq);
70
71 foreach (@Config) { 
72   my ($LPD,$LPM,$LPY) = (01, 01, 0001);  #LP: Last posting-date
73   my ($NPY,$NPM,$NPD);                   #NP: Next posting-date
74   my $SupersedeMID;
75   
76   my ($ActName,$File,$PFreq) =($$_{'name'},$$_{'file'},$$_{'posting-frequency'});
77   my ($From,$Subject,$NG,$Fup2)=($$_{'from'},$$_{'subject'},$$_{'ngs'},$$_{'fup2'});
78   my ($MIDF,$ReplyTo,$ExtHea)=($$_{'mid-format'},$$_{'reply-to'},$$_{'extraheader'});
79   my ($Supersede)            =($$_{'supersede'});
80
81   next if (defined($Faq) && $ActName ne $Faq);
82         
83   if (open (FH, "<$File.cfg")) {
84     while(<FH>){
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*$/) {
88         $SupersedeMID = $1;
89       }
90     }
91     close FH;
92   } else { 
93     warn "$0: W: Couldn't open $File.cfg: $!\n";
94   }
95
96   $SupersedeMID = "" unless $Supersede;
97
98   if ($PFreq =~ /(\d+)\s*([dw])/) { # Is counted in days or weeks: Use Add_Delta_Days.
99     ($NPY,$NPM,$NPD) = Add_Delta_Days($LPY, $LPM, $LPD, (($2 eq "w")?$1 * 7: $1 * 1));
100   } elsif ($PFreq =~ /(\d+)\s*([my])/) { #Is counted in months or years: Use Add_Delta_YM
101     ($NPY,$NPM,$NPD) = Add_Delta_YM($LPY, $LPM, $LPD, (($2 eq "m")?(0,$1):($1,0)));
102   }
103     
104   if (Delta_Days($NPY,$NPM,$NPD,$TDY,$TDM,$TDD) >= 0 or ($Options{'p'})) {
105     if($Options{'d'}) {
106           print "$ActName: Would be posted now (but running in simulation mode [$0 -d]).\n" if $Options{'v'};
107         } else {
108       postfaq(\$ActName,\$File,\$From,\$Subject,\$NG,\$Fup2,\$MIDF,\$ExtHea,\$Sender,\$TDY,\$TDM,\$TDD,\$ReplyTo,\$SupersedeMID);
109         }
110   } elsif($Options{'v'}) {
111     print "$ActName: Nothing to do.\n";
112   }
113 }
114
115 exit;
116
117 ################################## readconfig ##################################
118 # Takes a filename, a reference to an array, which will hold hashes with
119 # the data from $File, and - optionally - the name of the (single) FAQ to post
120
121 sub readconfig{
122   my ($File, $Config, $Faq) = @_;
123   my ($LastEntry, $Error, $i) = ('','',0);
124
125   if($Options{'v'}) {
126     print "Reading configuration.\n";
127   }
128
129   open FH, "<$$File" or die "$0: E: Can't open $$File: $!";
130   while (<FH>) {
131     next if (defined($$Faq) && !/^\s*=====\s*$/ && defined($$Config[$i]{'name'}) && $$Config[$i]{'name'} ne $$Faq );
132     if (/^(\s*(\S+)\s*=\s*'?(.*?)'?\s*(#.*$|$)|^(.*?)'?\s*(#.*$|$))/ && not /^\s*$/) {
133       $LastEntry = lc($2) if $2;
134       $$Config[$i]{$LastEntry} .= $3 if $3;  
135       $$Config[$i]{$LastEntry} .= "\n$5" if $5 && $5;
136     } 
137     if (/^\s*=====\s*$/) {
138       $i++;
139     }
140   }
141   close FH;
142
143   #Check saved values:
144   for $i (0..$i){
145     next if (defined($$Faq) && defined($$Config[$i]{'name'}) && $$Config[$i]{'name'} ne $$Faq );
146     unless($$Config[$i]{'from'} =~ /\S+\@(\S+\.)?\S{2,}\.\S{2,}/) {
147       $Error .= "E: The From-header for your project \"$$Config[$i]{'name'}\" seems to be incorrect.\n"
148     }
149     unless($$Config[$i]{'ngs'} =~ /^\S+$/) {
150       $Error .= "E: The Newsgroups-header for your project \"$$Config[$i]{'name'}\" contains whitespaces.\n"
151     }
152     unless(!$$Config[$i]{'fup2'} || $$Config[$i]{'fup2'} =~ /^\S+$/) {
153       $Error .= "E: The Followup-To-header for your project \"$$Config[$i]{'name'}\" contains whitespaces.\n"
154     }
155     unless($$Config[$i]{'posting-frequency'} =~ /^\s*\d+\s*[dwmy]\s*$/) {
156       $Error .= "E: The Posting-frequency for your project \"$$Config[$i]{'name'}\" is invalid.\n"
157     }
158     $Error .= "-" x 25 . "\n" if $Error;
159   }
160   die $Error if $Error;
161 }
162
163 ################################## postfaq ##################################
164 # Takes a filename and many other vars.
165 #
166 # It reads the data-file $File and then posts the article.
167
168 sub postfaq {
169   my ($ActName,$File,$From,$Subject,$NG,$Fup2,$MIDF,$ExtraHeaders,$Sender,$TDY,$TDM,$TDD,$ReplyTo,$Supersedes) = @_;
170   my (@Header,@Body,$MID,$InRealBody,$LastModified);
171
172   if($Options{'v'}) {
173     print "$$ActName: Preparing to post.\n";
174   }
175   
176   #Prepare MID:
177   $$TDM = ($$TDM < 10 && $$TDM !~ /^0/) ? "0" . $$TDM : $$TDM;
178   $$TDD = ($$TDD < 10 && $$TDD !~ /^0/) ? "0" . $$TDD : $$TDD;
179
180   $MID = $$MIDF;
181   $MID =~ s/\%n/$$ActName/g;
182   $MID =~ s/\%d/$$TDD/g;
183   $MID =~ s/\%m/$$TDM/g;
184   $MID =~ s/\%y/$$TDY/g;
185
186
187   #Now get the body:
188   open (FH, "<$$File");
189   while (<FH>){  
190     s/\r//;
191     push (@Body, $_), next if $InRealBody;
192     $InRealBody++ if /^$/;
193     $LastModified = $1 if /^Last-modified: (\S+)$/i;
194     push @Body, $_;
195   }
196   close FH;
197   push @Body, "\n" if ($Body[-1] ne "\n");
198
199   #Create Date- and Expires-Header:
200   my @time = localtime;
201   my $ss =  ($time[0]<10) ? "0" . $time[0] : $time[0];
202   my $mm =  ($time[1]<10) ? "0" . $time[1] : $time[1];
203   my $hh =  ($time[2]<10) ? "0" . $time[2] : $time[2];
204   my $day = $time[3];
205   my $month = ($time[4]+1<10) ? "0" . ($time[4]+1) : $time[4]+1;
206   my $monthN = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$time[4]];
207   my $wday = ("Sun","Mon","Tue","Wed","Thu","Fri","Sat")[$time[6]];
208   my $year = (1900 + $time[5]);
209   my $tz = $time[8] ? " +0200" : " +0100";
210   
211   my ($expY,$expM,$expD) = Add_Delta_YM($year, $month, $day, 0, 3);
212   my $expmonthN = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$expM-1];
213
214   my $date = "$day $monthN $year " . $hh . ":" . $mm . ":" . $ss . $tz;
215   my $expdate = "$expD $expmonthN $expY $hh:$mm:$ss$tz";
216
217   #Replace %LM by the content of the news.answer-pseudo-header Last-modified:
218   if ($LastModified) {
219     $$Subject =~ s/\%LM/$LastModified/;
220   }
221
222   # Test mode?
223   if($Options{'t'} and $Options{'t'} !~ /console/i) {
224     $$NG = $Options{'t'};
225   }
226
227   #Now create the complete Header:
228   push @Header, "From: $$From\n";
229   push @Header, "Newsgroups: $$NG\n";
230   push @Header, "Followup-To: $$Fup2\n" if $$Fup2;
231   push @Header, "Subject: $$Subject\n";
232   push @Header, "Message-ID: $MID\n";
233   push @Header, "Supersedes: $$Supersedes\n" if $$Supersedes;
234   push @Header, "Date: $date\n";
235   push @Header, "Expires: $expdate\n";
236   push @Header, "Sender: $$Sender\n" if $$Sender;
237   push @Header, "Mime-Version: 1.0\n";
238   push @Header, "Reply-To: $$ReplyTo\n" if $$ReplyTo;
239   push @Header, "Content-Type: text/plain; charset=ISO-8859-15\n";
240   push @Header, "Content-Transfer-Encoding: 8bit\n";
241   push @Header, "User-Agent: yapfaq/$Version\n";
242   if ($$ExtraHeaders) {
243     push @Header, "$_\n" for (split /\n/, $$ExtraHeaders);
244   }
245
246   my @Article = ($UsePGP)?@{signpgp(\@Header, \@Body)}:(@Header, "\n", @Body);
247   
248   if($Options{'v'}) {
249     print "$$ActName: Posting article ...\n";
250   }
251   post(\@Article);
252
253   if($Options{'v'}) {
254     print "$$ActName: Save status information.\n";
255   }
256
257   open (FH, ">$$File.cfg") or die "$0: E: Can't open $$File.cfg: $!";
258   print FH "##;; Lastpost: $day.$month.$year\n";
259   print FH "##;; LastMID: $MID\n";
260   close FH;
261 }
262
263 ################################## post ##################################
264 # Takes a complete article (Header and Body).
265 #
266 # It opens a connection to $NNTPServer and posts the message.
267
268 sub post {
269   my ($ArticleR) = @_;
270
271   # Test mode?
272   if(defined($Options{'t'}) and $Options{'t'} =~ /console/i) {
273     print "\n-----BEGIN--------------------------------------------------\n";
274         print @$ArticleR;
275     print "\n------END---------------------------------------------------\n";
276         return;
277   }
278
279   my $NewsConnection = Net::NNTP->new($NNTPServer, Reader => 1)
280     or die "$0: E: Can't connect to news server '$NNTPServer'!\n";
281
282   $NewsConnection->authinfo ($NNTPUser, $NNTPPass);
283   $NewsConnection->post();
284   $NewsConnection->datasend (@$ArticleR);
285   $NewsConnection->dataend();
286
287   if (!$NewsConnection->ok()) {
288     open FH, ">>ERROR.dat";
289     print FH "\nPosting failed! Saving to ERROR.dat. Response from news server:\n";
290     print FH $NewsConnection->code();
291     print FH $NewsConnection->message();
292     print FH "\n";
293     print FH @$ArticleR;
294     print FH "-" x 80, "\n";
295     close FH;
296   }
297
298   $NewsConnection->quit();
299 }
300
301 #-------- sub getpgpcommand
302 # getpgpcommand generates the command to sign the message and returns it.
303 #
304 # Receives:
305 #       - $PGPVersion: A scalar holding the PGPVersion
306 sub getpgpcommand {
307   my ($PGPVersion) = @_;
308   my $PGPCommand;
309
310   if ($PGPVersion eq '2') {
311     if ($PathtoPGPPass && !$PGPPass) {
312       open (PGPPW, $PathtoPGPPass) or die "$0: E: Can't open $PathtoPGPPass: $!";
313       $PGPPass = <PGPPW>;
314       close PGPPW;
315     }
316   
317     if ($PGPPass) {
318       $PGPCommand = "PGPPASS=\"".$PGPPass."\" ".$pgp." -u \"".$PGPSigner."\" +verbose=0 language='en' -saft <".$pgptmpf.".txt >".$pgptmpf.".txt.asc";
319     } else {
320       die "$0: E: PGP-Passphrase is unknown!\n";
321     }
322   } elsif ($PGPVersion eq '5') {
323     if ($PathtoPGPPass) {
324       $PGPCommand = "PGPPASSFD=2 ".$pgp."s -u \"".$PGPSigner."\" -t --armor -o ".$pgptmpf.".txt.asc -z -f < ".$pgptmpf.".txt 2<".$PathtoPGPPass;
325     } else {
326       die "$0: E: PGP-Passphrase is unknown!\n";
327     }
328   } elsif ($PGPVersion =~ m/GPG/io) {
329     if ($PathtoPGPPass) {
330       $PGPCommand = $pgp." --digest-algo MD5 -a -u \"".$PGPSigner."\" -o ".$pgptmpf.".txt.asc --no-tty --batch --passphrase-fd 2 2<".$PathtoPGPPass." --clearsign ".$pgptmpf.".txt";
331     } else {
332       die "$0: E: Passphrase is unknown!\n";
333     }
334   } else {
335     die "$0: E: Unknown PGP-Version $PGPVersion!";
336   }
337   return $PGPCommand;
338 }
339
340
341 #-------- sub signarticle
342 # signarticle signs an articel and returns a reference to an array
343 #       containing the whole signed Message.
344 #
345 # Receives:
346 #       - $HeaderAR: A reference to a array containing the articles headers.
347 #       - $BodyR: A reference to an array containing the body.
348 #
349 # Returns:
350 #       - $MessageRef: A reference to an array containing the whole message.
351 sub signpgp {
352   my ($HeaderAR, $BodyR) = @_;
353   my (@pgphead, @pgpbody, $pgphead, $pgpbody, $header, $signheaders, @signheaders, $currentheader, $HeaderR, $line);
354
355   foreach my $line (@$HeaderAR) {
356     if ($line =~ /^(\S+):\s+(.*)$/s) {
357       $currentheader = $1;
358       $$HeaderR{lc($currentheader)} = "$1: $2";
359     } else {
360       $$HeaderR{lc($currentheader)} .= $line;
361     }
362   }
363
364   foreach (@PGPSignHeaders) {
365     if (defined($$HeaderR{lc($_)}) && $$HeaderR{lc($_)} =~ m/^[^\s:]+: .+/o) {
366       push @signheaders, $_;
367     }
368   }
369
370   $pgpbody = join ("", @$BodyR);
371
372   # Delete and create the temporary pgp-Files
373   unlink "$pgptmpf.txt";
374   unlink "$pgptmpf.txt.asc";
375   $signheaders = join(",", @signheaders);
376
377   $pgphead = "X-Signed-Headers: $signheaders\n";
378   foreach $header (@signheaders) {
379     if ($$HeaderR{lc($header)} =~ m/^[^\s:]+: (.+?)\n?$/so) {
380       $pgphead .= $header.": ".$1."\n";
381     }
382   }
383
384   open(FH, ">" . $pgptmpf . ".txt") or die "$0: E: can't open $pgptmpf: $!\n";
385   print FH $pgphead, "\n", $pgpbody;
386   print FH "\n" if ($PGPVersion =~ m/GPG/io);   # workaround a pgp/gpg incompatibility - should IMHO be fixed in pgpverify
387   close(FH) or warn "$0: W: Couldn't close TMP: $!\n";
388
389   # Start PGP, then read the signature;
390   my $PGPCommand = getpgpcommand($PGPVersion);
391   `$PGPCommand`;
392
393   open (FH, "<" . $pgptmpf . ".txt.asc") or die "$0: E: can't open ".$pgptmpf.".txt.asc: $!\n";
394   $/ = "$pgpbegin\n";
395   $_ = <FH>;
396   unless (m/\Q$pgpbegin\E$/o) {
397 #    unlink $pgptmpf . ".txt";
398 #    unlink $pgptmpf . ".txt.asc";
399     die "$0: E: $pgpbegin not found in ".$pgptmpf.".txt.asc\n"
400   }
401   unlink($pgptmpf . ".txt") or warn "$0: W: Couldn't unlink $pgptmpf.txt: $!\n";
402
403   $/ = "\n";
404   $_ = <FH>;
405   unless (m/^Version: (\S+)(?:\s(\S+))?/o) {
406     unlink $pgptmpf . ".txt";
407     unlink $pgptmpf . ".txt.asc";
408     die "$0: E: didn't find PGP Version line where expected.\n";
409   }
410   
411   if (defined($2)) {
412     $$HeaderR{$pgpheader} = $1."-".$2." ".$signheaders;
413   } else {
414     $$HeaderR{$pgpheader} = $1." ".$signheaders;
415   }
416   
417   do {          # skip other pgp headers like
418     $_ = <FH>;  # "charset:"||"comment:" until empty line
419   } while ! /^$/;
420
421   while (<FH>) {
422     chomp;
423     last if /^\Q$pgpend\E$/;
424     $$HeaderR{$pgpheader} .= "\n\t$_";
425   }
426   
427   $$HeaderR{$pgpheader} .= "\n" unless ($$HeaderR{$pgpheader} =~ /\n$/s);
428
429   $_ = <FH>;
430   unless (eof(FH)) {
431     unlink $pgptmpf . ".txt";
432     unlink $pgptmpf . ".txt.asc";
433     die "$0: E: unexpected data following $pgpend\n";
434   }
435   close(FH);
436   unlink "$pgptmpf.txt.asc";
437
438   my $tmppgpheader = $pgpheader . ": " . $$HeaderR{$pgpheader};
439   delete $$HeaderR{$pgpheader};
440
441   @pgphead = ();
442   foreach $header (@PGPorderheaders) {
443     if ($$HeaderR{$header} && $$HeaderR{$header} ne "\n") {
444       push(@pgphead, "$$HeaderR{$header}");
445       delete $$HeaderR{$header};
446     }
447   }
448
449   foreach $header (keys %$HeaderR) {
450     if ($$HeaderR{$header} && $$HeaderR{$header} ne "\n") {
451       push(@pgphead, "$$HeaderR{$header}");
452       delete $$HeaderR{$header};
453     }
454   }
455
456   push @pgphead, ("X-PGP-Key: " . $PGPSigner . "\n"), $tmppgpheader;
457   undef $tmppgpheader;
458
459   @pgpbody = split /$/m, $pgpbody;
460   my @pgpmessage = (@pgphead, "\n", @pgpbody);
461   return \@pgpmessage;
462 }
This page took 0.022584 seconds and 3 git commands to generate.