]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/CGI/Bugreport.pm
fix #747267 by causing the closing regex to require a space, or some other non-word...
[debbugs.git] / Debbugs / CGI / Bugreport.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later version. See the
3 # file README and COPYING for more information.
4 #
5 # [Other people have contributed to this file; their copyrights should
6 # be listed here too.]
7 # Copyright 2008 by Don Armstrong <don@donarmstrong.com>.
8
9
10 package Debbugs::CGI::Bugreport;
11
12 =head1 NAME
13
14 Debbugs::CGI::Bugreport -- specific routines for the bugreport cgi script
15
16 =head1 SYNOPSIS
17
18
19 =head1 DESCRIPTION
20
21
22 =head1 BUGS
23
24 None known.
25
26 =cut
27
28 use warnings;
29 use strict;
30 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
31 use base qw(Exporter);
32
33 use IO::Scalar;
34 use Params::Validate qw(validate_with :types);
35 use Digest::MD5 qw(md5_hex);
36 use Debbugs::Mail qw(get_addresses);
37 use Debbugs::MIME qw(decode_rfc1522 create_mime_message);
38 use Debbugs::CGI qw(:url :html :util);
39 use Debbugs::Common qw(globify_scalar english_join);
40 use Debbugs::UTF8;
41 use Debbugs::Config qw(:config);
42 use POSIX qw(strftime);
43 use Encode qw(decode_utf8 encode_utf8);
44 use URI::Escape qw(uri_escape);
45
46 BEGIN{
47      ($VERSION) = q$Revision: 494 $ =~ /^Revision:\s+([^\s+])/;
48      $DEBUG = 0 unless defined $DEBUG;
49
50      @EXPORT = ();
51      %EXPORT_TAGS = ();
52      @EXPORT_OK = (qw(display_entity handle_record handle_email_message));
53      Exporter::export_ok_tags(keys %EXPORT_TAGS);
54      $EXPORT_TAGS{all} = [@EXPORT_OK];
55 }
56
57
58
59 =head2 display_entity
60
61      display_entity(entity      => $entity,
62                     bug_num     => $ref,
63                     outer       => 1,
64                     msg_num     => $msg_num,
65                     attachments => \@attachments,
66                     output      => \$output);
67
68
69 =over
70
71 =item entity -- MIME::Parser entity
72
73 =item bug_num -- Bug number
74
75 =item outer -- Whether this is the outer entity; defaults to 1
76
77 =item msg_num -- message number in the log
78
79 =item attachments -- arrayref of attachments
80
81 =item output -- scalar reference for output
82
83 =back
84
85 =cut
86
87 sub display_entity {
88     my %param = validate_with(params => \@_,
89                               spec   => {entity      => {type => OBJECT,
90                                                         },
91                                          bug_num     => {type => SCALAR,
92                                                          regex => qr/^\d+$/,
93                                                         },
94                                          outer       => {type => BOOLEAN,
95                                                          default => 1,
96                                                         },
97                                          msg_num     => {type => SCALAR,
98                                                         },
99                                          attachments => {type => ARRAYREF,
100                                                          default => [],
101                                                         },
102                                          output      => {type => SCALARREF|HANDLE,
103                                                          default => \*STDOUT,
104                                                         },
105                                          terse       => {type => BOOLEAN,
106                                                          default => 0,
107                                                         },
108                                          msg         => {type => SCALAR,
109                                                          optional => 1,
110                                                         },
111                                          att         => {type => SCALAR,
112                                                          optional => 1,
113                                                         },
114                                          trim_headers => {type => BOOLEAN,
115                                                           default => 1,
116                                                          },
117                                          avatars => {type => BOOLEAN,
118                                                      default => 1,
119                                                     },
120                                         }
121                              );
122
123     my $output = globify_scalar($param{output});
124     my $entity = $param{entity};
125     my $ref = $param{bug_num};
126     my $top = $param{outer};
127     my $xmessage = $param{msg_num};
128     my $attachments = $param{attachments};
129
130     my $head = $entity->head;
131     my $disposition = $head->mime_attr('content-disposition');
132     $disposition = 'inline' if not defined $disposition or $disposition eq '';
133     my $type = $entity->effective_type;
134     my $filename = $entity->head->recommended_filename;
135     $filename = '' unless defined $filename;
136     $filename = decode_rfc1522($filename);
137
138     if ($param{outer} and
139         not $param{terse} and
140         not exists $param{att}) {
141          my $header = $entity->head;
142          print {$output} "<div class=\"headers\">\n";
143          if ($param{trim_headers}) {
144               my @headers;
145               foreach (qw(From To Cc Subject Date)) {
146                    my $head_field = $head->get($_);
147                    next unless defined $head_field and $head_field ne '';
148                    chomp $head_field;
149                    if ($_ eq 'From' and $param{avatars}) {
150                        my $libravatar_url = __libravatar_url(decode_rfc1522($head_field));
151                        if (defined $libravatar_url and length $libravatar_url) {
152                            push @headers,q(<img src=").html_escape($libravatar_url).qq(" alt="">\n);
153                        }
154                    }
155                    push @headers, qq(<div class="header"><span class="headerfield">$_:</span> ) . html_escape(decode_rfc1522($head_field))."</div>\n";
156               }
157               print {$output} join(qq(), @headers);
158          } else {
159               print {$output} "<pre>".html_escape(decode_rfc1522($entity->head->stringify))."</pre>\n";
160          }
161          print {$output} "</div>\n";
162     }
163
164     if (not (($param{outer} and $type =~ m{^text(?:/plain)?(?:;|$)})
165              or $type =~ m{^multipart/}
166             )) {
167         push @$attachments, $param{entity};
168         # output this attachment
169         if (exists $param{att} and
170             $param{att} == $#$attachments) {
171             my $head = $entity->head;
172             chomp(my $type = $entity->effective_type);
173             my $body = $entity->stringify_body;
174             # this attachment has its own content type, so we must not
175             # try to convert it to UTF-8 or do anything funky.
176             binmode($output,':raw');
177             print {$output} "Content-Type: $type";
178             my ($charset) = $head->get('Content-Type:') =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
179             print {$output} qq(; charset="$charset") if defined $charset;
180             print {$output} "\n";
181             if ($filename ne '') {
182                 my $qf = $filename;
183                 $qf =~ s/"/\\"/g;
184                 $qf =~ s[.*/][];
185                 print {$output} qq{Content-Disposition: inline; filename="$qf"\n};
186             }
187             print {$output} "\n";
188             my $decoder = MIME::Decoder->new($head->mime_encoding);
189             $decoder->decode(IO::Scalar->new(\$body), $output);
190             # we don't reset the layers here, because it makes no
191             # sense to add anything to the output handle after this
192             # point.
193             return(1);
194         }
195         elsif (not exists $param{att}) {
196              my @dlargs = (msg=>$xmessage, att=>$#$attachments);
197              push @dlargs, (filename=>$filename) if $filename ne '';
198              my $printname = $filename;
199              $printname = 'Message part ' . ($#$attachments + 1) if $filename eq '';
200              print {$output} '<pre class="mime">[<a href="' .
201                   html_escape(bug_links(bug => $ref,
202                                         links_only => 1,
203                                         options => {@dlargs})
204                              ) . qq{">$printname</a> } .
205                                   "($type, $disposition)]</pre>\n";
206         }
207     }
208
209     return 0 if not $param{outer} and $disposition eq 'attachment' and not exists $param{att};
210     return 0 unless (($type =~ m[^text/?] and
211                       $type !~ m[^text/(?:html|enriched)(?:;|$)]) or
212                      $type =~ m[^application/pgp(?:;|$)] or
213                      $entity->parts);
214
215     if ($entity->is_multipart) {
216         my @parts = $entity->parts;
217         foreach my $part (@parts) {
218             my $raw_output =
219                 display_entity(entity => $part,
220                                bug_num => $ref,
221                                outer => 0,
222                                msg_num => $xmessage,
223                                output => $output,
224                                attachments => $attachments,
225                                terse => $param{terse},
226                                exists $param{msg}?(msg=>$param{msg}):(),
227                                exists $param{att}?(att=>$param{att}):(),
228                                exists $param{avatars}?(avatars=>$param{avatars}):(),
229                               );
230             if ($raw_output) {
231                 return $raw_output;
232             }
233             # print {$output} "\n";
234         }
235     } elsif ($entity->parts) {
236         # We must be dealing with a nested message.
237          if (not exists $param{att}) {
238               print {$output} "<blockquote>\n";
239          }
240         my @parts = $entity->parts;
241         foreach my $part (@parts) {
242             display_entity(entity => $part,
243                            bug_num => $ref,
244                            outer => 1,
245                            msg_num => $xmessage,
246                            output => $output,
247                            attachments => $attachments,
248                            terse => $param{terse},
249                            exists $param{msg}?(msg=>$param{msg}):(),
250                            exists $param{att}?(att=>$param{att}):(),
251                            exists $param{avatars}?(avatars=>$param{avatars}):(),
252                           );
253             # print {$output} "\n";
254         }
255          if (not exists $param{att}) {
256               print {$output} "</blockquote>\n";
257          }
258     } elsif (not $param{terse}) {
259          my $content_type = $entity->head->get('Content-Type:') || "text/html";
260          my ($charset) = $content_type =~ m/charset\s*=\s*\"?([\w-]+)\"?/i;
261          my $body = $entity->bodyhandle->as_string;
262          $body = convert_to_utf8($body,$charset//'utf8');
263          $body = html_escape($body);
264          # Attempt to deal with format=flowed
265          if ($content_type =~ m/format\s*=\s*\"?flowed\"?/i) {
266               $body =~ s{^\ }{}mgo;
267               # we ignore the other things that you can do with
268               # flowed e-mails cause they don't really matter.
269          }
270          # Add links to URLs
271          # We don't html escape here because we escape above;
272          # wierd terminators are because of that
273          $body =~ s{((?:ftp|http|https|svn|ftps|rsync)://[\S~-]+?/?) # Url
274                     ((?:\&gt\;)?[)]?(?:'|\&\#39\;)?[:.\,]?(?:\s|$)) # terminators
275               }{<a href=\"$1\">$1</a>$2}gox;
276          # Add links to bug closures
277          $body =~ s[((?:closes|see):\s* # start of closed/referenced bugs
278                         (?:bug)?\#?\s?\d+\s? # first bug
279                         (?:,?\s*(?:bug)?\#?\s?\d+)* # additional bugs
280                     (?:\s|\n|\)|\]|\}|\.|\,|$)) # ends with a space, newline, end of string, or ); fixes #747267
281                   ]
282                    [my $temp = $1;
283                     $temp =~ s{(\d+)}
284                               {bug_links(bug=>$1)}ge;
285                     $temp;]gxie;
286          if (defined $config{cve_tracker} and
287              length $config{cve_tracker}
288             ) {
289              # Add links to CVE vulnerabilities (closes #568464)
290              $body =~ s{(^|\s|[\(\[])(CVE-\d{4}-\d{4,})(\s|[,.-\[\]\)]|$)}
291                        {$1<a href="http://$config{cve_tracker}$2">$2</a>$3}gxm;
292          }
293          if (not exists $param{att}) {
294               print {$output} qq(<pre class="message">$body</pre>\n);
295          }
296     }
297     return 0;
298 }
299
300
301 =head2 handle_email_message
302
303      handle_email_message($record->{text},
304                           ref        => $bug_number,
305                           msg_num => $msg_number,
306                          );
307
308 Returns a decoded e-mail message and displays entities/attachments as
309 appropriate.
310
311
312 =cut
313
314 sub handle_email_message{
315      my ($email,%param) = @_;
316
317      my $output;
318      my $output_fh = globify_scalar(\$output);
319      my $parser = MIME::Parser->new();
320      # Because we are using memory, not tempfiles, there's no need to
321      # clean up here like in Debbugs::MIME
322      $parser->tmp_to_core(1);
323      $parser->output_to_core(1);
324      my $entity = $parser->parse_data( $email);
325      my @attachments = ();
326      my $raw_output =
327          display_entity(entity  => $entity,
328                         bug_num => $param{ref},
329                         outer   => 1,
330                         msg_num => $param{msg_num},
331                         output => $output_fh,
332                         attachments => \@attachments,
333                         terse       => $param{terse},
334                         exists $param{msg}?(msg=>$param{msg}):(),
335                         exists $param{att}?(att=>$param{att}):(),
336                         exists $param{trim_headers}?(trim_headers=>$param{trim_headers}):(),
337                         exists $param{avatars}?(avatars=>$param{avatars}):(),
338                        );
339      return $raw_output?$output:decode_utf8($output);
340 }
341
342 =head2 handle_record
343
344      push @log, handle_record($record,$ref,$msg_num);
345
346 Deals with a record in a bug log as returned by
347 L<Debbugs::Log::read_log_records>; returns the log information that
348 should be output to the browser.
349
350 =cut
351
352 sub handle_record{
353      my ($record,$bug_number,$msg_number,$seen_msg_ids,%param) = @_;
354
355      # output needs to have the is_utf8 flag on to avoid double
356      # encoding
357      my $output = decode_utf8('');
358      local $_ = $record->{type};
359      if (/html/) {
360          # $record->{text} is not in perl's internal encoding; convert it
361          my $text = decode_rfc1522(decode_utf8($record->{text}));
362           my ($time) = $text =~ /<!--\s+time:(\d+)\s+-->/;
363           my $class = $text =~ /^<strong>(?:Acknowledgement|Reply|Information|Report|Notification)/m ? 'infmessage':'msgreceived';
364           $output .= $text;
365           # Link to forwarded http:// urls in the midst of the report
366           # (even though these links already exist at the top)
367           $output =~ s,((?:ftp|http|https)://[\S~-]+?/?)((?:[\)\'\:\.\,]|\&\#39;)?(?:\s|\.<|$)),<a href=\"$1\">$1</a>$2,go;
368           # Add links to the cloned bugs
369           $output =~ s{(Bug )(\d+)( cloned as bugs? )(\d+)(?:\-(\d+)|)}{$1.bug_links(bug=>$2).$3.bug_links(bug=>(defined $5)?[$4..$5]:$4)}eo;
370           # Add links to merged bugs
371           $output =~ s{(?<=Merged )([\d\s]+)(?=\.)}{join(' ',map {bug_links(bug=>$_)} (split /\s+/, $1))}eo;
372           # Add links to blocked bugs
373           $output =~ s{(?<=Blocking bugs)(?:( of )(\d+))?( (?:added|set to|removed):\s+)([\d\s\,]+)}
374                       {(defined $2?$1.bug_links(bug=>$2):'').$3.
375                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+/, $4)])}eo;
376           $output =~ s{((?:[Aa]dded|[Rr]emoved)\ blocking\ bug(?:\(s\))?)(?:(\ of\ )(\d+))?(:?\s+)
377                        (\d+(?:,\s+\d+)*(?:\,?\s+and\s+\d+)?)}
378                       {$1.(defined $3?$2.bug_links(bug=>$3):'').$4.
379                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+(?:and\s+)?/, $5)])}xeo;
380           $output =~ s{([Aa]dded|[Rr]emoved)( indication that bug )(\d+)( blocks )([\d\s\,]+)}
381                       {$1.$2.(bug_links(bug=>$3)).$4.
382                            english_join([map {bug_links(bug=>$_)} (split /\,?\s+(?:and\s+)?/, $5)])}eo;
383           # Add links to reassigned packages
384           $output =~ s{(Bug reassigned from package \`)([^']+?)((?:'|\&\#39;) to \`)([^']+?)((?:'|\&\#39;))}
385           {$1.q(<a href=").html_escape(package_links(package=>$2)).qq(">$2</a>).$3.q(<a href=").html_escape(package_links(package=>$4)).qq(">$4</a>).$5}eo;
386           if (defined $time) {
387                $output .= ' ('.strftime('%a, %d %b %Y %T GMT',gmtime($time)).') ';
388           }
389           $output .= '<a href="' .
390                html_escape(bug_links(bug => $bug_number,
391                                      options => {msg => ($msg_number+1)},
392                                      links_only => 1,
393                                     )
394                           ) . '">Full text</a> and <a href="' .
395                                html_escape(bug_links(bug => $bug_number,
396                                                      options => {msg => ($msg_number+1),
397                                                                  mbox => 'yes'},
398                                                      links_only => 1)
399                                           ) . '">rfc822 format</a> available.';
400
401           $output = qq(<div class="$class"><hr>\n<a name="$msg_number"></a>\n) . $output . "</div>\n";
402      }
403      elsif (/recips/) {
404           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
405           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
406                return ();
407           }
408           elsif (defined $msg_id) {
409                $$seen_msg_ids{$msg_id} = 1;
410           }
411           $output .= qq(<hr><p class="msgreceived"><a name="$msg_number"></a>\n);
412           $output .= 'View this message in <a href="' . html_escape(bug_links(bug=>$bug_number, links_only => 1, options=>{msg=>$msg_number, mbox=>'yes'})) . '">rfc822 format</a></p>';
413           $output .= handle_email_message($record->{text},
414                                           ref     => $bug_number,
415                                           msg_num => $msg_number,
416                                           %param,
417                                          );
418      }
419      elsif (/autocheck/) {
420           # Do nothing
421      }
422      elsif (/incoming-recv/) {
423           my ($msg_id) = $record->{text} =~ /^Message-Id:\s+<(.+)>/im;
424           if (defined $msg_id and exists $$seen_msg_ids{$msg_id}) {
425                return ();
426           }
427           elsif (defined $msg_id) {
428                $$seen_msg_ids{$msg_id} = 1;
429           }
430           # Incomming Mail Message
431           my ($received,$hostname) = $record->{text} =~ m/Received: \(at (\S+)\) by (\S+)\;/;
432           $output .= qq|<hr><p class="msgreceived"><a name="$msg_number"></a><a name="msg$msg_number"></a><a href="#$msg_number">Message #$msg_number</a> received at |.
433                html_escape("$received\@$hostname") .
434                     q| (<a href="| . html_escape(bug_links(bug => $bug_number, links_only => 1, options => {msg=>$msg_number})) . '">full text</a>'.
435                          q|, <a href="| . html_escape(bug_links(bug => $bug_number,
436                                                                 links_only => 1,
437                                                                 options => {msg=>$msg_number,
438                                                                             mbox=>'yes'}
439                                                                )
440                                                      ) .'">mbox</a>)'.":</p>\n";
441           $output .= handle_email_message($record->{text},
442                                           ref     => $bug_number,
443                                           msg_num => $msg_number,
444                                           %param,
445                                          );
446      }
447      else {
448           die "Unknown record type $_";
449      }
450      return $output;
451 }
452
453
454 sub __libravatar_url {
455     my ($email) = @_;
456     if (not defined $config{libravatar_uri} or not length $config{libravatar_uri}) {
457         return undef;
458     }
459     ($email) = get_addresses($email);
460     return $config{libravatar_uri}.uri_escape($email.($config{libravatar_uri_options}//''));
461 }
462
463
464 1;
465
466
467 __END__
468
469
470
471
472
473