]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Log.pm
Prefer "use Exporter qw(import)" to inheriting from it
[debbugs.git] / Debbugs / Log.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later
3 # version at your option.
4 # See the file README and COPYING for more information.
5 #
6 # [Other people have contributed to this file; their copyrights should
7 # go here too.]
8 # Copyright 2004 by Collin Watson <cjwatson@debian.org>
9 # Copyright 2007 by Don Armstrong <don@donarmstrong.com>
10
11
12 package Debbugs::Log;
13
14
15 use warnings;
16 use strict;
17
18 use vars qw($VERSION $DEBUG @EXPORT @EXPORT_OK %EXPORT_TAGS);
19 use Exporter qw(import);
20
21 BEGIN {
22     $VERSION = 1.00;
23     $DEBUG = 0 unless defined $DEBUG;
24
25     @EXPORT = ();
26     %EXPORT_TAGS = (write => [qw(write_log_records),
27                              ],
28                     read  => [qw(read_log_records record_text record_regex),
29                              ],
30                     misc  => [qw(escape_log),
31                              ],
32                    );
33     @EXPORT_OK = ();
34     Exporter::export_ok_tags(qw(write read misc));
35     $EXPORT_TAGS{all} = [@EXPORT_OK];
36 }
37
38 use Carp;
39
40 use Debbugs::Common qw(getbuglocation getbugcomponent make_list);
41 use Params::Validate qw(:types validate_with);
42 use Encode qw(encode encode_utf8 is_utf8);
43 use IO::InnerFile;
44
45 =head1 NAME
46
47 Debbugs::Log - an interface to debbugs .log files
48
49 =head1 DESCRIPTION
50
51 The Debbugs::Log module provides a convenient way for scripts to read and
52 write the .log files used by debbugs to store the complete textual records
53 of all bug transactions.
54
55 Debbugs::Log does not decode utf8 into perl's internal encoding or
56 encode into utf8 from perl's internal encoding. For html records and
57 all recips, this should probably be done. For other records, this should
58 not be needed.
59
60 =head2 The .log File Format
61
62 .log files consist of a sequence of records, of one of the following four
63 types. ^A, ^B, etc. represent those control characters.
64
65 =over 4
66
67 =item incoming-recv
68
69   ^G
70   [mail]
71   ^C
72
73 C<[mail]> must start with /^Received: \(at \S+\) by \S+;/, and is copied to
74 the output.
75
76 =item autocheck
77
78 Auto-forwarded messages are recorded like this:
79
80   ^A
81   [mail]
82   ^C
83
84 C<[mail]> must contain /^X-Debian-Bugs(-\w+)?: This is an autoforward from
85 \S+/. The first line matching that is removed; all lines in the message body
86 that begin with 'X' will be copied to the output, minus the 'X'.
87
88 Nothing in debbugs actually generates this record type any more, but it may
89 still be in old .logs at some sites.
90
91 =item recips
92
93   ^B
94   [recip]^D[recip]^D[...] OR -t
95   ^E
96   [mail]
97   ^C
98
99 Each [recip] is output after "Message sent"; C<-t> represents the same
100 sendmail option, indicating that the recipients are taken from the headers
101 of the message itself.
102
103 =item html
104
105   ^F
106   [html]
107   ^C
108
109 [html] is copied unescaped to the output. The record immediately following
110 this one is considered "boring" and only shown in certain output modes.
111
112 (This is a design flaw in the log format, since it makes it difficult to
113 change the HTML presentation later, or to present the data in an entirely
114 different format.)
115
116 =back
117
118 No other types of records are permitted, and the file must end with a ^C
119 line.
120
121 =cut
122
123 my %states = (
124     1 => 'autocheck',
125     2 => 'recips',
126     3 => 'kill-end',
127     5 => 'go',
128     6 => 'html',
129     7 => 'incoming-recv',
130 );
131
132 =head2 Perl Record Representation
133
134 Each record is a hash. The C<type> field is C<incoming-recv>, C<autocheck>,
135 C<recips>, or C<html> as above; C<text> contains text from C<[mail]> or
136 C<[html]> as above; C<recips> is a reference to an array of recipients
137 (strings), or undef for C<-t>.
138
139 =head1 FUNCTIONS
140
141 =over 4
142
143 =item new
144
145 Creates a new log reader based on a .log filehandle.
146
147       my $log = Debbugs::Log->new($logfh);
148       my $log = Debbugs::Log->new(bug_num => $nnn);
149       my $log = Debbugs::Log->new(logfh => $logfh);
150
151 Parameters
152
153 =over
154
155 =item bug_num -- bug number
156
157 =item logfh -- log filehandle
158
159 =item log_name -- name of log
160
161 =back
162
163 One of the above options must be passed.
164
165 =cut
166
167 sub new
168 {
169     my $this = shift;
170     my %param;
171     if (@_ == 1) {
172          ($param{logfh}) = @_;
173          $param{inner_file} = 0;
174     }
175     else {
176          %param = validate_with(params => \@_,
177                                 spec   => {bug_num => {type => SCALAR,
178                                                        optional => 1,
179                                                       },
180                                            logfh   => {type => HANDLE,
181                                                        optional => 1,
182                                                       },
183                                            log_name => {type => SCALAR,
184                                                         optional => 1,
185                                    },
186                            inner_file => {type => BOOLEAN,
187                                           default => 0,
188                                          },
189                                           }
190                                );
191     }
192     if (grep({exists $param{$_} and defined $param{$_}} qw(bug_num logfh log_name)) ne 1) {
193          croak "Exactly one of bug_num, logfh, or log_name must be passed and must be defined";
194     }
195
196     my $class = ref($this) || $this;
197     my $self = {};
198     bless $self, $class;
199
200     if (exists $param{logfh}) {
201          $self->{logfh} = $param{logfh}
202     }
203     elsif (exists $param{log_name}) {
204          $self->{logfh} = IO::File->new($param{log_name},'r') or
205               die "Unable to open bug log $param{log_name} for reading: $!";
206     }
207     elsif (exists $param{bug_num}) {
208          my $location = getbuglocation($param{bug_num},'log');
209          my $bug_log = getbugcomponent($param{bug_num},'log',$location);
210          $self->{logfh} = IO::File->new($bug_log, 'r') or
211               die "Unable to open bug log $bug_log for reading: $!";
212     }
213
214     $self->{state} = 'kill-init';
215     $self->{linenum} = 0;
216     $self->{inner_file} = $param{inner_file};
217     return $self;
218 }
219
220 =item read_record
221
222 Reads and returns a single record from a log reader object. At end of file,
223 returns undef. Throws exceptions using die(), so you may want to wrap this
224 in an eval().
225
226 =cut
227
228 sub read_record
229 {
230     my $this = shift;
231     my $logfh = $this->{logfh};
232
233     # This comes from bugreport.cgi, but is much simpler since it doesn't
234     # worry about the details of output.
235
236     my $record = {};
237
238     while (defined (my $line = <$logfh>)) {
239         chomp $line;
240         ++$this->{linenum};
241         if (length($line) == 1 and exists $states{ord($line)}) {
242             # state transitions
243             my $newstate = $states{ord($line)};
244
245             # disallowed transitions
246             $_ = "$this->{state} $newstate";
247             unless (/^(go|go-nox|html) kill-end$/ or
248                     /^(kill-init|kill-end) (incoming-recv|autocheck|recips|html)$/ or
249                     /^kill-body go$/) {
250                 die "transition from $this->{state} to $newstate at $this->{linenum} disallowed";
251             }
252
253             $this->{state} = $newstate;
254             if ($this->{state} =~ /^(autocheck|recips|html|incoming-recv)$/) {
255             $record->{type} = $this->{state};
256             $record->{start} = $logfh->tell;
257             $record->{stop} = $logfh->tell;
258             $record->{inner_file} = $this->{inner_file};
259             } elsif ($this->{state} eq 'kill-end') {
260             if ($this->{inner_file}) {
261                 $record->{fh} = IO::InnerFile->new($logfh,$record->{start},$record->{stop} - $record->{start})
262             }
263                 return $record;
264             }
265
266             next;
267         }
268     $record->{stop} = $logfh->tell;
269         $_ = $line;
270         if ($this->{state} eq 'incoming-recv') {
271             my $pl = $_;
272             unless (/^Received: \(at \S+\) by \S+;/) {
273                 die "bad line '$pl' in state incoming-recv";
274             }
275             $this->{state} = 'go';
276             $record->{text} .= "$_\n" unless $this->{inner_file};
277         } elsif ($this->{state} eq 'html') {
278             $record->{text} .= "$_\n"  unless $this->{inner_file};
279         } elsif ($this->{state} eq 'go') {
280             s/^\030//;
281             $record->{text} .= "$_\n"  unless $this->{inner_file};
282         } elsif ($this->{state} eq 'go-nox') {
283             $record->{text} .= "$_\n"  unless $this->{inner_file};
284         } elsif ($this->{state} eq 'recips') {
285             if (/^-t$/) {
286                 undef $record->{recips};
287             } else {
288                 # preserve trailing null fields, e.g. #2298
289                 $record->{recips} = [split /\04/, $_, -1];
290             }
291             $this->{state} = 'kill-body';
292         $record->{start} = $logfh->tell+2;
293         $record->{stop} = $logfh->tell+2;
294         $record->{inner_file} = $this->{inner_file};
295         } elsif ($this->{state} eq 'autocheck') {
296             $record->{text} .= "$_\n" unless $this->{inner_file};
297             next if !/^X-Debian-Bugs(-\w+)?: This is an autoforward from (\S+)/;
298             $this->{state} = 'autowait';
299         } elsif ($this->{state} eq 'autowait') {
300             $record->{text} .= "$_\n" unless $this->{inner_file};
301             next if !/^$/;
302             $this->{state} = 'go-nox';
303         } else {
304             die "state $this->{state} at line $this->{linenum} ('$_')";
305         }
306     }
307     die "state $this->{state} at end" unless $this->{state} eq 'kill-end';
308
309     if (keys %$record) {
310         return $record;
311     } else {
312         return undef;
313     }
314 }
315
316 =item read_log_records
317
318 Takes a .log filehandle as input, and returns an array of all records in
319 that file. Throws exceptions using die(), so you may want to wrap this in an
320 eval().
321
322 Uses exactly the same options as Debbugs::Log::new
323
324 =cut
325
326 sub read_log_records
327 {
328     my %param;
329     if (@_ == 1) {
330          ($param{logfh}) = @_;
331     }
332     else {
333          %param = validate_with(params => \@_,
334                                 spec   => {bug_num => {type => SCALAR,
335                                                        optional => 1,
336                                                       },
337                                            logfh   => {type => HANDLE,
338                                                        optional => 1,
339                                                       },
340                                            log_name => {type => SCALAR,
341                                                         optional => 1,
342                                                        },
343                            inner_file => {type => BOOLEAN,
344                                           default => 0,
345                                          },
346                                           }
347                                );
348     }
349     if (grep({exists $param{$_} and defined $param{$_}} qw(bug_num logfh log_name)) ne 1) {
350          croak "Exactly one of bug_num, logfh, or log_name must be passed and must be defined";
351     }
352
353     my @records;
354     my $reader = Debbugs::Log->new(%param);
355     while (defined(my $record = $reader->read_record())) {
356         push @records, $record;
357     }
358     return @records;
359 }
360
361 =item write_log_records
362
363 Takes a filehandle and a list of records as input, and prints the .log
364 format representation of those records to that filehandle.
365
366 =back
367
368 =cut
369
370 sub write_log_records
371 {
372     my %param = validate_with(params => \@_,
373                               spec   => {bug_num => {type => SCALAR,
374                                                      optional => 1,
375                                                     },
376                                          logfh   => {type => HANDLE,
377                                                      optional => 1,
378                                                     },
379                                          log_name => {type => SCALAR,
380                                                       optional => 1,
381                                                      },
382                                          records => {type => HASHREF|ARRAYREF,
383                                                     },
384                                         },
385                              );
386     if (grep({exists $param{$_} and defined $param{$_}} qw(bug_num logfh log_name)) ne 1) {
387          croak "Exactly one of bug_num, logfh, or log_name must be passed and must be defined";
388     }
389     my $logfh;
390     if (exists $param{logfh}) {
391          $logfh = $param{logfh}
392     }
393     elsif (exists $param{log_name}) {
394          $logfh = IO::File->new(">>$param{log_name}") or
395               die "Unable to open bug log $param{log_name} for writing: $!";
396     }
397     elsif (exists $param{bug_num}) {
398          my $location = getbuglocation($param{bug_num},'log');
399          my $bug_log = getbugcomponent($param{bug_num},'log',$location);
400          $logfh = IO::File->new($bug_log, 'r') or
401               die "Unable to open bug log $bug_log for reading: $!";
402     }
403     my @records = make_list($param{records});
404
405     for my $record (@records) {
406         my $type = $record->{type};
407         croak "record type '$type' with no text field" unless defined $record->{text};
408         # I am not sure if we really want to croak here; but this is
409         # almost certainly a bug if is_utf8 is on.
410         my $text = $record->{text};
411         if (is_utf8($text)) {
412             carp('Record text was in the wrong encoding (perl internal instead of utf8 octets)');
413             $text = encode_utf8($text)
414         }
415         ($text) = escape_log($text);
416         if ($type eq 'autocheck') {
417             print {$logfh} "\01\n$text\03\n" or
418                 die "Unable to write to logfile: $!";
419         } elsif ($type eq 'recips') {
420             print {$logfh} "\02\n";
421             my $recips = $record->{recips};
422             if (defined $recips) {
423                 croak "recips not undef or array"
424                     unless ref($recips) eq 'ARRAY';
425                 my $wrong_encoding = 0;
426                 my @recips =
427                     map { if (is_utf8($_)) {
428                         $wrong_encoding=1;
429                         encode_utf8($_);
430                     } else {
431                         $_;
432                     }} @$recips;
433                 carp('Recipients was in the wrong encoding (perl internal instead of utf8 octets') if $wrong_encoding;
434                 print {$logfh} join("\04", @$recips) . "\n" or
435                     die "Unable to write to logfile: $!";
436             } else {
437                 print {$logfh} "-t\n" or
438                     die "Unable to write to logfile: $!";
439             }
440             #$text =~ s/^([\01-\07\030])/\030$1/gm;
441             print {$logfh} "\05\n$text\03\n" or
442                 die "Unable to write to logfile: $!";
443         } elsif ($type eq 'html') {
444             print {$logfh} "\06\n$text\03\n" or
445                 die "Unable to write to logfile: $!";
446         } elsif ($type eq 'incoming-recv') {
447             #$text =~ s/^([\01-\07\030])/\030$1/gm;
448             print {$logfh} "\07\n$text\03\n" or
449                 die "Unable to write to logfile: $!";
450         } else {
451             croak "unknown record type type '$type'";
452         }
453     }
454
455     1;
456 }
457
458 =head2 escape_log
459
460      print {$log} escape_log(@log)
461
462 Applies the log escape regex to the passed logfile.
463
464 =cut
465
466 sub escape_log {
467         my @log = @_;
468         return map {s/^([\01-\07\030])/\030$1/gm; $_ } @log;
469 }
470
471
472 sub record_text {
473     my ($record) = @_;
474     if ($record->{inner_file}) {
475         local $/;
476         my $text;
477         my $t = $record->{fh};
478         $text = <$t>;
479         $record->{fh}->seek(0,0);
480         return $text;
481     } else {
482         return $record->{text};
483     }
484 }
485
486 sub record_regex {
487     my ($record,$regex) = @_;
488     if ($record->{inner_file}) {
489         my @result;
490         my $fh = $record->{fh};
491         while (<$fh>) {
492             if (@result = $_ =~ m/$regex/) {
493                 $record->{fh}->seek(0,0);
494                 return @result;
495             }
496         }
497         $record->{fh}->seek(0,0);
498         return ();
499     } else {
500         my @result = $record->{text} =~ m/$regex/;
501         return @result;
502         return $record->{text};
503     }
504 }
505
506
507 =head1 CAVEATS
508
509 This module does none of the formatting that bugreport.cgi et al do. It's
510 simply a means for extracting and rewriting raw records.
511
512 =cut
513
514 1;