]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Log.pm
Add IO::InnerFile support to Debbugs::Log and use 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 base qw(Exporter);
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         } elsif ($this->{state} eq 'autocheck') {
293             $record->{text} .= "$_\n" unless $this->{inner_file};
294             next if !/^X-Debian-Bugs(-\w+)?: This is an autoforward from (\S+)/;
295             $this->{state} = 'autowait';
296         } elsif ($this->{state} eq 'autowait') {
297             $record->{text} .= "$_\n" unless $this->{inner_file};
298             next if !/^$/;
299             $this->{state} = 'go-nox';
300         } else {
301             die "state $this->{state} at line $this->{linenum} ('$_')";
302         }
303     }
304     die "state $this->{state} at end" unless $this->{state} eq 'kill-end';
305
306     if (keys %$record) {
307         return $record;
308     } else {
309         return undef;
310     }
311 }
312
313 =item read_log_records
314
315 Takes a .log filehandle as input, and returns an array of all records in
316 that file. Throws exceptions using die(), so you may want to wrap this in an
317 eval().
318
319 Uses exactly the same options as Debbugs::Log::new
320
321 =cut
322
323 sub read_log_records
324 {
325     my %param;
326     if (@_ == 1) {
327          ($param{logfh}) = @_;
328     }
329     else {
330          %param = validate_with(params => \@_,
331                                 spec   => {bug_num => {type => SCALAR,
332                                                        optional => 1,
333                                                       },
334                                            logfh   => {type => HANDLE,
335                                                        optional => 1,
336                                                       },
337                                            log_name => {type => SCALAR,
338                                                         optional => 1,
339                                                        },
340                            inner_file => {type => BOOLEAN,
341                                           default => 0,
342                                          },
343                                           }
344                                );
345     }
346     if (grep({exists $param{$_} and defined $param{$_}} qw(bug_num logfh log_name)) ne 1) {
347          croak "Exactly one of bug_num, logfh, or log_name must be passed and must be defined";
348     }
349
350     my @records;
351     my $reader = Debbugs::Log->new(%param);
352     while (defined(my $record = $reader->read_record())) {
353         push @records, $record;
354     }
355     return @records;
356 }
357
358 =item write_log_records
359
360 Takes a filehandle and a list of records as input, and prints the .log
361 format representation of those records to that filehandle.
362
363 =back
364
365 =cut
366
367 sub write_log_records
368 {
369     my %param = validate_with(params => \@_,
370                               spec   => {bug_num => {type => SCALAR,
371                                                      optional => 1,
372                                                     },
373                                          logfh   => {type => HANDLE,
374                                                      optional => 1,
375                                                     },
376                                          log_name => {type => SCALAR,
377                                                       optional => 1,
378                                                      },
379                                          records => {type => HASHREF|ARRAYREF,
380                                                     },
381                                         },
382                              );
383     if (grep({exists $param{$_} and defined $param{$_}} qw(bug_num logfh log_name)) ne 1) {
384          croak "Exactly one of bug_num, logfh, or log_name must be passed and must be defined";
385     }
386     my $logfh;
387     if (exists $param{logfh}) {
388          $logfh = $param{logfh}
389     }
390     elsif (exists $param{log_name}) {
391          $logfh = IO::File->new(">>$param{log_name}") or
392               die "Unable to open bug log $param{log_name} for writing: $!";
393     }
394     elsif (exists $param{bug_num}) {
395          my $location = getbuglocation($param{bug_num},'log');
396          my $bug_log = getbugcomponent($param{bug_num},'log',$location);
397          $logfh = IO::File->new($bug_log, 'r') or
398               die "Unable to open bug log $bug_log for reading: $!";
399     }
400     my @records = make_list($param{records});
401
402     for my $record (@records) {
403         my $type = $record->{type};
404         croak "record type '$type' with no text field" unless defined $record->{text};
405         # I am not sure if we really want to croak here; but this is
406         # almost certainly a bug if is_utf8 is on.
407         my $text = $record->{text};
408         if (is_utf8($text)) {
409             carp('Record text was in the wrong encoding (perl internal instead of utf8 octets)');
410             $text = encode_utf8($text)
411         }
412         ($text) = escape_log($text);
413         if ($type eq 'autocheck') {
414             print {$logfh} "\01\n$text\03\n" or
415                 die "Unable to write to logfile: $!";
416         } elsif ($type eq 'recips') {
417             print {$logfh} "\02\n";
418             my $recips = $record->{recips};
419             if (defined $recips) {
420                 croak "recips not undef or array"
421                     unless ref($recips) eq 'ARRAY';
422                 my $wrong_encoding = 0;
423                 my @recips =
424                     map { if (is_utf8($_)) {
425                         $wrong_encoding=1;
426                         encode_utf8($_);
427                     } else {
428                         $_;
429                     }} @$recips;
430                 carp('Recipients was in the wrong encoding (perl internal instead of utf8 octets') if $wrong_encoding;
431                 print {$logfh} join("\04", @$recips) . "\n" or
432                     die "Unable to write to logfile: $!";
433             } else {
434                 print {$logfh} "-t\n" or
435                     die "Unable to write to logfile: $!";
436             }
437             #$text =~ s/^([\01-\07\030])/\030$1/gm;
438             print {$logfh} "\05\n$text\03\n" or
439                 die "Unable to write to logfile: $!";
440         } elsif ($type eq 'html') {
441             print {$logfh} "\06\n$text\03\n" or
442                 die "Unable to write to logfile: $!";
443         } elsif ($type eq 'incoming-recv') {
444             #$text =~ s/^([\01-\07\030])/\030$1/gm;
445             print {$logfh} "\07\n$text\03\n" or
446                 die "Unable to write to logfile: $!";
447         } else {
448             croak "unknown record type type '$type'";
449         }
450     }
451
452     1;
453 }
454
455 =head2 escape_log
456
457      print {$log} escape_log(@log)
458
459 Applies the log escape regex to the passed logfile.
460
461 =cut
462
463 sub escape_log {
464         my @log = @_;
465         return map {s/^([\01-\07\030])/\030$1/gm; $_ } @log;
466 }
467
468
469 sub record_text {
470     my ($record) = @_;
471     if ($record->{inner_file}) {
472         local $/;
473         my $text;
474         my $t = $record->{fh};
475         $text = <$t>;
476         $record->{fh}->seek(0,0);
477         return $text;
478     } else {
479         return $record->{text};
480     }
481 }
482
483 sub record_regex {
484     my ($record,$regex) = @_;
485     if ($record->{inner_file}) {
486         my @result;
487         my $fh = $record->{fh};
488         while (<$fh>) {
489             if (@result = $_ =~ m/$regex/) {
490                 $record->{fh}->seek(0,0);
491                 return @result;
492             }
493         }
494         $record->{fh}->seek(0,0);
495         return ();
496     } else {
497         my @result = $record->{text} =~ m/$regex/;
498         return @result;
499         return $record->{text};
500     }
501 }
502
503
504 =head1 CAVEATS
505
506 This module does none of the formatting that bugreport.cgi et al do. It's
507 simply a means for extracting and rewriting raw records.
508
509 =cut
510
511 1;