permit multiline comments and strings in macros
[bpt/coccinelle.git] / tools / cocci-send-email.perl
1 #!/usr/bin/perl -w
2 #
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
5 #
6 # GPL v2 (See COPYING)
7 #
8 # Added the --auto-to option, to get To information from an mbox
9 # (Julia Lawall <julia@diku.dk>)
10 # Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
11 #
12 # Sends a collection of emails to the given email addresses, disturbingly fast.
13 #
14 # Supports two formats:
15 # 1. mbox format files (ignoring most headers and MIME formatting - this is designed for sending patches)
16 # 2. The original format support by Greg's script:
17 # first line of the message is who to CC,
18 # and second line is the subject of the message.
19 #
20
21 use strict;
22 use warnings;
23 use Term::ReadLine;
24 use Getopt::Long;
25 use Text::ParseWords;
26 use Data::Dumper;
27 use Term::ANSIColor;
28 use File::Temp qw/ tempdir tempfile /;
29 use Error qw(:try);
30 use Git;
31
32 Getopt::Long::Configure qw/ pass_through /;
33
34 package FakeTerm;
35 sub new {
36 my ($class, $reason) = @_;
37 return bless \$reason, shift;
38 }
39 sub readline {
40 my $self = shift;
41 die "Cannot use readline on FakeTerm: $$self";
42 }
43 package main;
44
45
46 sub usage {
47 print <<EOT;
48 git send-email [options] <file | directory | rev-list options >
49
50 Composing:
51 --from <str> * Email From:
52 --[no-]to <str> * Email To:
53 --[no-]cc <str> * Email Cc:
54 --[no-]bcc <str> * Email Bcc:
55 --subject <str> * Email "Subject:"
56 --in-reply-to <str> * Email "In-Reply-To:"
57 --annotate * Review each patch that will be sent in an editor.
58 --compose * Open an editor for introduction.
59 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
60
61 Sending:
62 --envelope-sender <str> * Email envelope sender.
63 --smtp-server <str:int> * Outgoing SMTP server to use. The port
64 is optional. Default 'localhost'.
65 --smtp-server-port <int> * Outgoing SMTP server port.
66 --smtp-user <str> * Username for SMTP-AUTH.
67 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
68 --smtp-encryption <str> * tls or ssl; anything else disables.
69 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
70 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
71 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
72
73 Automating:
74 --identity <str> * Use the sendemail.<id> options.
75 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
76 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
77 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
78 --[no-]suppress-from * Send to self. Default off.
79 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
80 --[no-]thread * Use In-Reply-To: field. Default on.
81
82 Administering:
83 --confirm <str> * Confirm recipients before sending;
84 auto, cc, compose, always, or never.
85 --quiet * Output one line of info per email.
86 --dry-run * Don't actually send the emails.
87 --[no-]validate * Perform patch sanity checks. Default on.
88 --[no-]format-patch * understand any non optional arguments as
89 `git format-patch` ones.
90
91 EOT
92 exit(1);
93 }
94
95 # most mail servers generate the Date: header, but not all...
96 sub format_2822_time {
97 my ($time) = @_;
98 my @localtm = localtime($time);
99 my @gmttm = gmtime($time);
100 my $localmin = $localtm[1] + $localtm[2] * 60;
101 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
102 if ($localtm[0] != $gmttm[0]) {
103 die "local zone differs from GMT by a non-minute interval\n";
104 }
105 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
106 $localmin += 1440;
107 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
108 $localmin -= 1440;
109 } elsif ($gmttm[6] != $localtm[6]) {
110 die "local time offset greater than or equal to 24 hours\n";
111 }
112 my $offset = $localmin - $gmtmin;
113 my $offhour = $offset / 60;
114 my $offmin = abs($offset % 60);
115 if (abs($offhour) >= 24) {
116 die ("local time offset greater than or equal to 24 hours\n");
117 }
118
119 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
120 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
121 $localtm[3],
122 qw(Jan Feb Mar Apr May Jun
123 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
124 $localtm[5]+1900,
125 $localtm[2],
126 $localtm[1],
127 $localtm[0],
128 ($offset >= 0) ? '+' : '-',
129 abs($offhour),
130 $offmin,
131 );
132 }
133
134 my $have_email_valid = eval { require Email::Valid; 1 };
135 my $have_mail_address = eval { require Mail::Address; 1 };
136 my $smtp;
137 my $auth;
138
139 sub unique_email_list(@);
140 sub cleanup_compose_files();
141
142 # Variables we fill in automatically, or via prompting:
143 my (@to,@msgto,$no_to,$auto_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
144 $initial_reply_to,$initial_subject,@files,
145 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
146
147 my $envelope_sender;
148
149 # Example reply to:
150 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
151
152 my $repo = eval { Git->repository() };
153 my @repo = $repo ? ($repo) : ();
154 my $term = eval {
155 $ENV{"GIT_SEND_EMAIL_NOTTY"}
156 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
157 : new Term::ReadLine 'git-send-email';
158 };
159 if ($@) {
160 $term = new FakeTerm "$@: going non-interactive";
161 }
162
163 # Behavior modification variables
164 my ($quiet, $dry_run) = (0, 0);
165 my $format_patch;
166 my $compose_filename;
167
168 # Handle interactive edition of files.
169 my $multiedit;
170 my $editor;
171
172 sub do_edit {
173 if (!defined($editor)) {
174 $editor = Git::command_oneline('var', 'GIT_EDITOR');
175 }
176 if (defined($multiedit) && !$multiedit) {
177 map {
178 system('sh', '-c', $editor.' "$@"', $editor, $_);
179 if (($? & 127) || ($? >> 8)) {
180 die("the editor exited uncleanly, aborting everything");
181 }
182 } @_;
183 } else {
184 system('sh', '-c', $editor.' "$@"', $editor, @_);
185 if (($? & 127) || ($? >> 8)) {
186 die("the editor exited uncleanly, aborting everything");
187 }
188 }
189 }
190
191 # Variables with corresponding config settings
192 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
193 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
194 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
195 my ($validate, $confirm);
196 my (@suppress_cc);
197 my ($auto_8bit_encoding);
198
199 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
200
201 my $not_set_by_user = "true but not set by the user";
202
203 my %config_bool_settings = (
204 "thread" => [\$thread, 1],
205 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
206 "suppressfrom" => [\$suppress_from, undef],
207 "signedoffbycc" => [\$signed_off_by_cc, undef],
208 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
209 "validate" => [\$validate, 1],
210 );
211
212 my %config_settings = (
213 "smtpserver" => \$smtp_server,
214 "smtpserverport" => \$smtp_server_port,
215 "smtpuser" => \$smtp_authuser,
216 "smtppass" => \$smtp_authpass,
217 "smtpdomain" => \$smtp_domain,
218 "to" => \@to,
219 "cc" => \@initial_cc,
220 "cccmd" => \$cc_cmd,
221 "aliasfiletype" => \$aliasfiletype,
222 "bcc" => \@bcclist,
223 "aliasesfile" => \@alias_files,
224 "suppresscc" => \@suppress_cc,
225 "envelopesender" => \$envelope_sender,
226 "multiedit" => \$multiedit,
227 "confirm" => \$confirm,
228 "from" => \$sender,
229 "assume8bitencoding" => \$auto_8bit_encoding,
230 );
231
232 # Help users prepare for 1.7.0
233 sub chain_reply_to {
234 if (defined $chain_reply_to &&
235 $chain_reply_to eq $not_set_by_user) {
236 print STDERR
237 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
238 "Set sendemail.chainreplyto configuration variable to true if\n" .
239 "you want to keep --chain-reply-to as your default.\n";
240 $chain_reply_to = 0;
241 }
242 return $chain_reply_to;
243 }
244
245 # Handle Uncouth Termination
246 sub signal_handler {
247
248 # Make text normal
249 print color("reset"), "\n";
250
251 # SMTP password masked
252 system "stty echo";
253
254 # tmp files from --compose
255 if (defined $compose_filename) {
256 if (-e $compose_filename) {
257 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
258 }
259 if (-e ($compose_filename . ".final")) {
260 print "'$compose_filename.final' contains the composed email.\n"
261 }
262 }
263
264 exit;
265 };
266
267 $SIG{TERM} = \&signal_handler;
268 $SIG{INT} = \&signal_handler;
269
270 # Begin by accumulating all the variables (defined above), that we will end up
271 # needing, first, from the command line:
272
273 my $rc = GetOptions("sender|from=s" => \$sender,
274 "in-reply-to=s" => \$initial_reply_to,
275 "subject=s" => \$initial_subject,
276 "to=s" => \@to,
277 "no-to" => \$no_to,
278 "auto-to" => \$auto_to,
279 "cc=s" => \@initial_cc,
280 "no-cc" => \$no_cc,
281 "bcc=s" => \@bcclist,
282 "no-bcc" => \$no_bcc,
283 "chain-reply-to!" => \$chain_reply_to,
284 "smtp-server=s" => \$smtp_server,
285 "smtp-server-port=s" => \$smtp_server_port,
286 "smtp-user=s" => \$smtp_authuser,
287 "smtp-pass:s" => \$smtp_authpass,
288 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
289 "smtp-encryption=s" => \$smtp_encryption,
290 "smtp-debug:i" => \$debug_net_smtp,
291 "smtp-domain:s" => \$smtp_domain,
292 "identity=s" => \$identity,
293 "annotate" => \$annotate,
294 "compose" => \$compose,
295 "quiet" => \$quiet,
296 "cc-cmd=s" => \$cc_cmd,
297 "suppress-from!" => \$suppress_from,
298 "suppress-cc=s" => \@suppress_cc,
299 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
300 "confirm=s" => \$confirm,
301 "dry-run" => \$dry_run,
302 "envelope-sender=s" => \$envelope_sender,
303 "thread!" => \$thread,
304 "validate!" => \$validate,
305 "format-patch!" => \$format_patch,
306 "8bit-encoding=s" => \$auto_8bit_encoding,
307 );
308
309 unless ($rc) {
310 usage();
311 }
312
313 die "Cannot run git format-patch from outside a repository\n"
314 if $format_patch and not $repo;
315
316 # Now, let's fill any that aren't set in with defaults:
317
318 sub read_config {
319 my ($prefix) = @_;
320
321 foreach my $setting (keys %config_bool_settings) {
322 my $target = $config_bool_settings{$setting}->[0];
323 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
324 }
325
326 foreach my $setting (keys %config_settings) {
327 my $target = $config_settings{$setting};
328 next if $setting eq "to" and defined $no_to;
329 next if $setting eq "cc" and defined $no_cc;
330 next if $setting eq "bcc" and defined $no_bcc;
331 if (ref($target) eq "ARRAY") {
332 unless (@$target) {
333 my @values = Git::config(@repo, "$prefix.$setting");
334 @$target = @values if (@values && defined $values[0]);
335 }
336 }
337 else {
338 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
339 }
340 }
341
342 if (!defined $smtp_encryption) {
343 my $enc = Git::config(@repo, "$prefix.smtpencryption");
344 if (defined $enc) {
345 $smtp_encryption = $enc;
346 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
347 $smtp_encryption = 'ssl';
348 }
349 }
350 }
351
352 # read configuration from [sendemail "$identity"], fall back on [sendemail]
353 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
354 read_config("sendemail.$identity") if (defined $identity);
355 read_config("sendemail");
356
357 # fall back on builtin bool defaults
358 foreach my $setting (values %config_bool_settings) {
359 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
360 }
361
362 # 'default' encryption is none -- this only prevents a warning
363 $smtp_encryption = '' unless (defined $smtp_encryption);
364
365 # Set CC suppressions
366 my(%suppress_cc);
367 if (@suppress_cc) {
368 foreach my $entry (@suppress_cc) {
369 die "Unknown --suppress-cc field: '$entry'\n"
370 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
371 $suppress_cc{$entry} = 1;
372 }
373 }
374
375 if ($suppress_cc{'all'}) {
376 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
377 $suppress_cc{$entry} = 1;
378 }
379 delete $suppress_cc{'all'};
380 }
381
382 # If explicit old-style ones are specified, they trump --suppress-cc.
383 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
384 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
385
386 if ($suppress_cc{'body'}) {
387 foreach my $entry (qw (sob bodycc)) {
388 $suppress_cc{$entry} = 1;
389 }
390 delete $suppress_cc{'body'};
391 }
392
393 # Set confirm's default value
394 my $confirm_unconfigured = !defined $confirm;
395 if ($confirm_unconfigured) {
396 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
397 };
398 die "Unknown --confirm setting: '$confirm'\n"
399 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
400
401 # Debugging, print out the suppressions.
402 if (0) {
403 print "suppressions:\n";
404 foreach my $entry (keys %suppress_cc) {
405 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
406 }
407 }
408
409 my ($repoauthor, $repocommitter);
410 ($repoauthor) = Git::ident_person(@repo, 'author');
411 ($repocommitter) = Git::ident_person(@repo, 'committer');
412
413 # Verify the user input
414
415 foreach my $entry (@to) {
416 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
417 }
418
419 foreach my $entry (@initial_cc) {
420 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
421 }
422
423 foreach my $entry (@bcclist) {
424 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
425 }
426
427 sub parse_address_line {
428 if ($have_mail_address) {
429 return map { $_->format } Mail::Address->parse($_[0]);
430 } else {
431 return split_addrs($_[0]);
432 }
433 }
434
435 sub split_addrs {
436 return quotewords('\s*,\s*', 1, @_);
437 }
438
439 my %aliases;
440 my %parse_alias = (
441 # multiline formats can be supported in the future
442 mutt => sub { my $fh = shift; while (<$fh>) {
443 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
444 my ($alias, $addr) = ($1, $2);
445 $addr =~ s/#.*$//; # mutt allows # comments
446 # commas delimit multiple addresses
447 $aliases{$alias} = [ split_addrs($addr) ];
448 }}},
449 mailrc => sub { my $fh = shift; while (<$fh>) {
450 if (/^alias\s+(\S+)\s+(.*)$/) {
451 # spaces delimit multiple addresses
452 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
453 }}},
454 pine => sub { my $fh = shift; my $f='\t[^\t]*';
455 for (my $x = ''; defined($x); $x = $_) {
456 chomp $x;
457 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
458 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
459 $aliases{$1} = [ split_addrs($2) ];
460 }},
461 elm => sub { my $fh = shift;
462 while (<$fh>) {
463 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
464 my ($alias, $addr) = ($1, $2);
465 $aliases{$alias} = [ split_addrs($addr) ];
466 }
467 } },
468
469 gnus => sub { my $fh = shift; while (<$fh>) {
470 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
471 $aliases{$1} = [ $2 ];
472 }}}
473 );
474
475 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
476 foreach my $file (@alias_files) {
477 open my $fh, '<', $file or die "opening $file: $!\n";
478 $parse_alias{$aliasfiletype}->($fh);
479 close $fh;
480 }
481 }
482
483 ($sender) = expand_aliases($sender) if defined $sender;
484
485 # returns 1 if the conflict must be solved using it as a format-patch argument
486 sub check_file_rev_conflict($) {
487 return unless $repo;
488 my $f = shift;
489 try {
490 $repo->command('rev-parse', '--verify', '--quiet', $f);
491 if (defined($format_patch)) {
492 return $format_patch;
493 }
494 die(<<EOF);
495 File '$f' exists but it could also be the range of commits
496 to produce patches for. Please disambiguate by...
497
498 * Saying "./$f" if you mean a file; or
499 * Giving --format-patch option if you mean a range.
500 EOF
501 } catch Git::Error::Command with {
502 return 0;
503 }
504 }
505
506 # Now that all the defaults are set, process the rest of the command line
507 # arguments and collect up the files that need to be processed.
508 my @rev_list_opts;
509 while (defined(my $f = shift @ARGV)) {
510 if ($f eq "--") {
511 push @rev_list_opts, "--", @ARGV;
512 @ARGV = ();
513 } elsif (-d $f and !check_file_rev_conflict($f)) {
514 opendir(DH,$f)
515 or die "Failed to opendir $f: $!";
516
517 push @files, grep { -f $_ } map { +$f . "/" . $_ }
518 sort readdir(DH);
519 closedir(DH);
520 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
521 push @files, $f;
522 } else {
523 push @rev_list_opts, $f;
524 }
525 }
526
527 if (@rev_list_opts) {
528 die "Cannot run git format-patch from outside a repository\n"
529 unless $repo;
530 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
531 }
532
533 if ($validate) {
534 foreach my $f (@files) {
535 unless (-p $f) {
536 my $error = validate_patch($f);
537 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
538 }
539 }
540 }
541
542 if (@files) {
543 unless ($quiet) {
544 print $_,"\n" for (@files);
545 }
546 } else {
547 print STDERR "\nNo patch files specified!\n\n";
548 usage();
549 }
550
551 sub get_patch_subject($) {
552 my $fn = shift;
553 open (my $fh, '<', $fn);
554 while (my $line = <$fh>) {
555 next unless ($line =~ /^Subject: (.*)$/);
556 close $fh;
557 return "GIT: $1\n";
558 }
559 close $fh;
560 die "No subject line in $fn ?";
561 }
562
563 if ($compose) {
564 # Note that this does not need to be secure, but we will make a small
565 # effort to have it be unique
566 $compose_filename = ($repo ?
567 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
568 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
569 open(C,">",$compose_filename)
570 or die "Failed to open for writing $compose_filename: $!";
571
572
573 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
574 my $tpl_subject = $initial_subject || '';
575 my $tpl_reply_to = $initial_reply_to || '';
576
577 print C <<EOT;
578 From $tpl_sender # This line is ignored.
579 GIT: Lines beginning in "GIT:" will be removed.
580 GIT: Consider including an overall diffstat or table of contents
581 GIT: for the patch you are writing.
582 GIT:
583 GIT: Clear the body content if you don't wish to send a summary.
584 From: $tpl_sender
585 Subject: $tpl_subject
586 In-Reply-To: $tpl_reply_to
587
588 EOT
589 for my $f (@files) {
590 print C get_patch_subject($f);
591 }
592 close(C);
593
594 if ($annotate) {
595 do_edit($compose_filename, @files);
596 } else {
597 do_edit($compose_filename);
598 }
599
600 open(C2,">",$compose_filename . ".final")
601 or die "Failed to open $compose_filename.final : " . $!;
602
603 open(C,"<",$compose_filename)
604 or die "Failed to open $compose_filename : " . $!;
605
606 my $need_8bit_cte = file_has_nonascii($compose_filename);
607 my $in_body = 0;
608 my $summary_empty = 1;
609 while(<C>) {
610 next if m/^GIT:/;
611 if ($in_body) {
612 $summary_empty = 0 unless (/^\n$/);
613 } elsif (/^\n$/) {
614 $in_body = 1;
615 if ($need_8bit_cte) {
616 print C2 "MIME-Version: 1.0\n",
617 "Content-Type: text/plain; ",
618 "charset=UTF-8\n",
619 "Content-Transfer-Encoding: 8bit\n";
620 }
621 } elsif (/^MIME-Version:/i) {
622 $need_8bit_cte = 0;
623 } elsif (/^Subject:\s*(.+)\s*$/i) {
624 $initial_subject = $1;
625 my $subject = $initial_subject;
626 $_ = "Subject: " .
627 ($subject =~ /[^[:ascii:]]/ ?
628 quote_rfc2047($subject) :
629 $subject) .
630 "\n";
631 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
632 $initial_reply_to = $1;
633 next;
634 } elsif (/^From:\s*(.+)\s*$/i) {
635 $sender = $1;
636 next;
637 } elsif (/^(?:To|Cc|Bcc):/i) {
638 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
639 next;
640 }
641 print C2 $_;
642 }
643 close(C);
644 close(C2);
645
646 if ($summary_empty) {
647 print "Summary email is empty, skipping it\n";
648 $compose = -1;
649 }
650 } elsif ($annotate) {
651 do_edit(@files);
652 }
653
654 sub ask {
655 my ($prompt, %arg) = @_;
656 my $valid_re = $arg{valid_re};
657 my $default = $arg{default};
658 my $resp;
659 my $i = 0;
660 return defined $default ? $default : undef
661 unless defined $term->IN and defined fileno($term->IN) and
662 defined $term->OUT and defined fileno($term->OUT);
663 while ($i++ < 10) {
664 $resp = $term->readline($prompt);
665 if (!defined $resp) { # EOF
666 print "\n";
667 return defined $default ? $default : undef;
668 }
669 if ($resp eq '' and defined $default) {
670 return $default;
671 }
672 if (!defined $valid_re or $resp =~ /$valid_re/) {
673 return $resp;
674 }
675 }
676 return undef;
677 }
678
679 my %broken_encoding;
680
681 sub file_declares_8bit_cte($) {
682 my $fn = shift;
683 open (my $fh, '<', $fn);
684 while (my $line = <$fh>) {
685 last if ($line =~ /^$/);
686 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
687 }
688 close $fh;
689 return 0;
690 }
691
692 foreach my $f (@files) {
693 next unless (body_or_subject_has_nonascii($f)
694 && !file_declares_8bit_cte($f));
695 $broken_encoding{$f} = 1;
696 }
697
698 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
699 print "The following files are 8bit, but do not declare " .
700 "a Content-Transfer-Encoding.\n";
701 foreach my $f (sort keys %broken_encoding) {
702 print " $f\n";
703 }
704 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
705 default => "UTF-8");
706 }
707
708 my $prompting = 0;
709 if (!defined $sender) {
710 $sender = $repoauthor || $repocommitter || '';
711 $sender = ask("Who should the emails appear to be from? [$sender] ",
712 default => $sender);
713 print "Emails will be sent from: ", $sender, "\n";
714 $prompting++;
715 }
716
717 if (!@to && !$auto_to) {
718 my $to = ask("Who should the emails be sent to? ");
719 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
720 $prompting++;
721 }
722
723 sub expand_aliases {
724 return map { expand_one_alias($_) } @_;
725 }
726
727 my %EXPANDED_ALIASES;
728 sub expand_one_alias {
729 my $alias = shift;
730 if ($EXPANDED_ALIASES{$alias}) {
731 die "fatal: alias '$alias' expands to itself\n";
732 }
733 local $EXPANDED_ALIASES{$alias} = 1;
734 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
735 }
736
737 @to = expand_aliases(@to);
738 @to = (map { sanitize_address($_) } @to);
739 @initial_cc = expand_aliases(@initial_cc);
740 @bcclist = expand_aliases(@bcclist);
741
742 if ($thread && !defined $initial_reply_to && $prompting) {
743 $initial_reply_to = ask(
744 "Message-ID to be used as In-Reply-To for the first email? ");
745 }
746 if (defined $initial_reply_to) {
747 $initial_reply_to =~ s/^\s*<?//;
748 $initial_reply_to =~ s/>?\s*$//;
749 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
750 }
751
752 if (!defined $smtp_server) {
753 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
754 if (-x $_) {
755 $smtp_server = $_;
756 last;
757 }
758 }
759 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
760 }
761
762 if ($compose && $compose > 0) {
763 @files = ($compose_filename . ".final", @files);
764 }
765
766 # Variables we set as part of the loop over files
767 our ($message_id, %mail, $subject, $reply_to, $references, $message,
768 $needs_confirm, $message_num, $ask_default);
769
770 sub extract_valid_address {
771 my $address = shift;
772 my $local_part_regexp = '[^<>"\s@]+';
773 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
774
775 # check for a local address:
776 return $address if ($address =~ /^($local_part_regexp)$/);
777
778 $address =~ s/^\s*<(.*)>\s*$/$1/;
779 if ($have_email_valid) {
780 return scalar Email::Valid->address($address);
781 } else {
782 # less robust/correct than the monster regexp in Email::Valid,
783 # but still does a 99% job, and one less dependency
784 $address =~ /($local_part_regexp\@$domain_regexp)/;
785 return $1;
786 }
787 }
788
789 # Usually don't need to change anything below here.
790
791 # we make a "fake" message id by taking the current number
792 # of seconds since the beginning of Unix time and tacking on
793 # a random number to the end, in case we are called quicker than
794 # 1 second since the last time we were called.
795
796 # We'll setup a template for the message id, using the "from" address:
797
798 my ($message_id_stamp, $message_id_serial);
799 sub make_message_id {
800 my $uniq;
801 if (!defined $message_id_stamp) {
802 $message_id_stamp = sprintf("%s-%s", time, $$);
803 $message_id_serial = 0;
804 }
805 $message_id_serial++;
806 $uniq = "$message_id_stamp-$message_id_serial";
807
808 my $du_part;
809 for ($sender, $repocommitter, $repoauthor) {
810 $du_part = extract_valid_address(sanitize_address($_));
811 last if (defined $du_part and $du_part ne '');
812 }
813 if (not defined $du_part or $du_part eq '') {
814 use Sys::Hostname qw();
815 $du_part = 'user@' . Sys::Hostname::hostname();
816 }
817 my $message_id_template = "<%s-git-send-email-%s>";
818 $message_id = sprintf($message_id_template, $uniq, $du_part);
819 #print "new message id = $message_id\n"; # Was useful for debugging
820 }
821
822
823
824 $time = time - scalar $#files;
825
826 sub unquote_rfc2047 {
827 local ($_) = @_;
828 my $encoding;
829 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
830 $encoding = $1;
831 s/_/ /g;
832 s/=([0-9A-F]{2})/chr(hex($1))/eg;
833 }
834 return wantarray ? ($_, $encoding) : $_;
835 }
836
837 sub quote_rfc2047 {
838 local $_ = shift;
839 my $encoding = shift || 'UTF-8';
840 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
841 s/(.*)/=\?$encoding\?q\?$1\?=/;
842 return $_;
843 }
844
845 sub is_rfc2047_quoted {
846 my $s = shift;
847 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
848 my $encoded_text = '[!->@-~]+';
849 length($s) <= 75 &&
850 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
851 }
852
853 # use the simplest quoting being able to handle the recipient
854 sub sanitize_address {
855 my ($recipient) = @_;
856 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
857
858 if (not $recipient_name) {
859 return "$recipient";
860 }
861
862 # if recipient_name is already quoted, do nothing
863 if (is_rfc2047_quoted($recipient_name)) {
864 return $recipient;
865 }
866
867 # rfc2047 is needed if a non-ascii char is included
868 if ($recipient_name =~ /[^[:ascii:]]/) {
869 $recipient_name =~ s/^"(.*)"$/$1/;
870 $recipient_name = quote_rfc2047($recipient_name);
871 }
872
873 # double quotes are needed if specials or CTLs are included
874 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
875 $recipient_name =~ s/(["\\\r])/\\$1/g;
876 $recipient_name = "\"$recipient_name\"";
877 }
878
879 return "$recipient_name $recipient_addr";
880
881 }
882
883 # Returns the local Fully Qualified Domain Name (FQDN) if available.
884 #
885 # Tightly configured MTAa require that a caller sends a real DNS
886 # domain name that corresponds the IP address in the HELO/EHLO
887 # handshake. This is used to verify the connection and prevent
888 # spammers from trying to hide their identity. If the DNS and IP don't
889 # match, the receiveing MTA may deny the connection.
890 #
891 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
892 #
893 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
894 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
895 #
896 # This maildomain*() code is based on ideas in Perl library Test::Reporter
897 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
898
899 sub valid_fqdn {
900 my $domain = shift;
901 return !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
902 }
903
904 sub maildomain_net {
905 my $maildomain;
906
907 if (eval { require Net::Domain; 1 }) {
908 my $domain = Net::Domain::domainname();
909 $maildomain = $domain if valid_fqdn($domain);
910 }
911
912 return $maildomain;
913 }
914
915 sub maildomain_mta {
916 my $maildomain;
917
918 if (eval { require Net::SMTP; 1 }) {
919 for my $host (qw(mailhost localhost)) {
920 my $smtp = Net::SMTP->new($host);
921 if (defined $smtp) {
922 my $domain = $smtp->domain;
923 $smtp->quit;
924
925 $maildomain = $domain if valid_fqdn($domain);
926
927 last if $maildomain;
928 }
929 }
930 }
931
932 return $maildomain;
933 }
934
935 sub maildomain {
936 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
937 }
938
939 # Returns 1 if the message was sent, and 0 otherwise.
940 # In actuality, the whole program dies when there
941 # is an error sending a message.
942
943 sub send_message {
944 my @recipients = unique_email_list(@to,@msgto);
945 @cc = (grep { my $cc = extract_valid_address($_);
946 not grep { $cc eq $_ } @recipients
947 }
948 map { sanitize_address($_) }
949 @cc);
950 my $to = join (",\n\t", @recipients);
951 @recipients = unique_email_list(@recipients,@cc,@bcclist);
952 @recipients = (map { extract_valid_address($_) } @recipients);
953 my $date = format_2822_time($time++);
954 my $gitversion = '@@GIT_VERSION@@';
955 if ($gitversion =~ m/..GIT_VERSION../) {
956 $gitversion = Git::version();
957 }
958
959 my $cc = join(",\n\t", unique_email_list(@cc));
960 my $ccline = "";
961 if ($cc ne '') {
962 $ccline = "\nCc: $cc";
963 }
964 my $sanitized_sender = sanitize_address($sender);
965 make_message_id() unless defined($message_id);
966
967 my $header = "From: $sanitized_sender
968 To: $to${ccline}
969 Subject: $subject
970 Date: $date
971 Message-Id: $message_id
972 X-Mailer: git-send-email $gitversion
973 ";
974 if ($reply_to) {
975
976 $header .= "In-Reply-To: $reply_to\n";
977 $header .= "References: $references\n";
978 }
979 if (@xh) {
980 $header .= join("\n", @xh) . "\n";
981 }
982
983 my @sendmail_parameters = ('-i', @recipients);
984 my $raw_from = $sanitized_sender;
985 if (defined $envelope_sender && $envelope_sender ne "auto") {
986 $raw_from = $envelope_sender;
987 }
988 $raw_from = extract_valid_address($raw_from);
989 unshift (@sendmail_parameters,
990 '-f', $raw_from) if(defined $envelope_sender);
991
992 if ($needs_confirm && !$dry_run) {
993 print "\n$header\n";
994 if ($needs_confirm eq "inform") {
995 $confirm_unconfigured = 0; # squelch this message for the rest of this run
996 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
997 print " The Cc list above has been expanded by additional\n";
998 print " addresses found in the patch commit message. By default\n";
999 print " send-email prompts before sending whenever this occurs.\n";
1000 print " This behavior is controlled by the sendemail.confirm\n";
1001 print " configuration setting.\n";
1002 print "\n";
1003 print " For additional information, run 'git send-email --help'.\n";
1004 print " To retain the current behavior, but squelch this message,\n";
1005 print " run 'git config --global sendemail.confirm auto'.\n\n";
1006 }
1007 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1008 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1009 default => $ask_default);
1010 die "Send this email reply required" unless defined $_;
1011 if (/^n/i) {
1012 return 0;
1013 } elsif (/^q/i) {
1014 cleanup_compose_files();
1015 exit(0);
1016 } elsif (/^a/i) {
1017 $confirm = 'never';
1018 }
1019 }
1020
1021 if ($dry_run) {
1022 # We don't want to send the email.
1023 } elsif ($smtp_server =~ m#^/#) {
1024 my $pid = open my $sm, '|-';
1025 defined $pid or die $!;
1026 if (!$pid) {
1027 exec($smtp_server, @sendmail_parameters) or die $!;
1028 }
1029 print $sm "$header\n$message";
1030 close $sm or die $?;
1031 } else {
1032
1033 if (!defined $smtp_server) {
1034 die "The required SMTP server is not properly defined."
1035 }
1036
1037 if ($smtp_encryption eq 'ssl') {
1038 $smtp_server_port ||= 465; # ssmtp
1039 require Net::SMTP::SSL;
1040 $smtp_domain ||= maildomain();
1041 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1042 Hello => $smtp_domain,
1043 Port => $smtp_server_port);
1044 }
1045 else {
1046 require Net::SMTP;
1047 $smtp_domain ||= maildomain();
1048 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1049 ? "$smtp_server:$smtp_server_port"
1050 : $smtp_server,
1051 Hello => $smtp_domain,
1052 Debug => $debug_net_smtp);
1053 if ($smtp_encryption eq 'tls' && $smtp) {
1054 require Net::SMTP::SSL;
1055 $smtp->command('STARTTLS');
1056 $smtp->response();
1057 if ($smtp->code == 220) {
1058 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1059 or die "STARTTLS failed! ".$smtp->message;
1060 $smtp_encryption = '';
1061 # Send EHLO again to receive fresh
1062 # supported commands
1063 $smtp->hello();
1064 } else {
1065 die "Server does not support STARTTLS! ".$smtp->message;
1066 }
1067 }
1068 }
1069
1070 if (!$smtp) {
1071 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1072 "VALUES: server=$smtp_server ",
1073 "encryption=$smtp_encryption ",
1074 "hello=$smtp_domain",
1075 defined $smtp_server_port ? "port=$smtp_server_port" : "";
1076 }
1077
1078 if (defined $smtp_authuser) {
1079
1080 if (!defined $smtp_authpass) {
1081
1082 system "stty -echo";
1083
1084 do {
1085 print "Password: ";
1086 $_ = <STDIN>;
1087 print "\n";
1088 } while (!defined $_);
1089
1090 chomp($smtp_authpass = $_);
1091
1092 system "stty echo";
1093 }
1094
1095 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1096 }
1097
1098 $smtp->mail( $raw_from ) or die $smtp->message;
1099 $smtp->to( @recipients ) or die $smtp->message;
1100 $smtp->data or die $smtp->message;
1101 $smtp->datasend("$header\n$message") or die $smtp->message;
1102 $smtp->dataend() or die $smtp->message;
1103 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1104 }
1105 if ($quiet) {
1106 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1107 } else {
1108 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1109 if ($smtp_server !~ m#^/#) {
1110 print "Server: $smtp_server\n";
1111 print "MAIL FROM:<$raw_from>\n";
1112 foreach my $entry (@recipients) {
1113 print "RCPT TO:<$entry>\n";
1114 }
1115 } else {
1116 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1117 }
1118 print $header, "\n";
1119 if ($smtp) {
1120 print "Result: ", $smtp->code, ' ',
1121 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1122 } else {
1123 print "Result: OK\n";
1124 }
1125 }
1126
1127 return 1;
1128 }
1129
1130 $reply_to = $initial_reply_to;
1131 $references = $initial_reply_to || '';
1132 $subject = $initial_subject;
1133 $message_num = 0;
1134
1135 foreach my $t (@files) {
1136 open(F,"<",$t) or die "can't open file $t";
1137
1138 my $author = undef;
1139 my $author_encoding;
1140 my $has_content_type;
1141 my $body_encoding;
1142 @cc = ();
1143 @msgto = ();
1144 @xh = ();
1145 my $input_format = undef;
1146 my @header = ();
1147 $message = "";
1148 $message_num++;
1149 # First unfold multiline header fields
1150 while(<F>) {
1151 last if /^\s*$/;
1152 if (/^\s+\S/ and @header) {
1153 chomp($header[$#header]);
1154 s/^\s+/ /;
1155 $header[$#header] .= $_;
1156 } else {
1157 push(@header, $_);
1158 }
1159 }
1160 # Now parse the header
1161 foreach(@header) {
1162 if (/^From /) {
1163 $input_format = 'mbox';
1164 next;
1165 }
1166 chomp;
1167 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1168 $input_format = 'mbox';
1169 }
1170
1171 if (defined $input_format && $input_format eq 'mbox') {
1172 if (/^Subject:\s+(.*)$/) {
1173 $subject = $1;
1174 }
1175 elsif (/^From:\s+(.*)$/) {
1176 ($author, $author_encoding) = unquote_rfc2047($1);
1177 next if $suppress_cc{'author'};
1178 next if $suppress_cc{'self'} and $author eq $sender;
1179 printf("(mbox) Adding cc: %s from line '%s'\n",
1180 $1, $_) unless $quiet;
1181 push @cc, $1;
1182 }
1183 elsif (/^Cc:\s+(.*)$/) {
1184 foreach my $addr (parse_address_line($1)) {
1185 if (unquote_rfc2047($addr) eq $sender) {
1186 next if ($suppress_cc{'self'});
1187 } else {
1188 next if ($suppress_cc{'cc'});
1189 }
1190 printf("(mbox) Adding cc: %s from line '%s'\n",
1191 $addr, $_) unless $quiet;
1192 push @cc, $addr;
1193 }
1194 }
1195 elsif ($auto_to && /^To:\s+(.*)$/) {
1196 foreach my $addr (parse_address_line($1)) {
1197 printf("(mbox) Adding to: %s from line '%s'\n",
1198 $addr, $_) unless $quiet;
1199 push @msgto, $addr;
1200 }
1201 }
1202 elsif (/^Content-type:/i) {
1203 $has_content_type = 1;
1204 if (/charset="?([^ "]+)/) {
1205 $body_encoding = $1;
1206 }
1207 push @xh, $_;
1208 }
1209 elsif (/^Message-Id: (.*)/i) {
1210 $message_id = $1;
1211 }
1212 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1213 push @xh, $_;
1214 }
1215
1216 } else {
1217 # In the traditional
1218 # "send lots of email" format,
1219 # line 1 = cc
1220 # line 2 = subject
1221 # So let's support that, too.
1222 $input_format = 'lots';
1223 if (@cc == 0 && !$suppress_cc{'cc'}) {
1224 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1225 $_, $_) unless $quiet;
1226 push @cc, $_;
1227 } elsif (!defined $subject) {
1228 $subject = $_;
1229 }
1230 }
1231 }
1232 # Now parse the message body
1233 while(<F>) {
1234 $message .= $_;
1235 if (/^(Signed-off-by|Cc): (.*)$/i) {
1236 chomp;
1237 my ($what, $c) = ($1, $2);
1238 chomp $c;
1239 if ($c eq $sender) {
1240 next if ($suppress_cc{'self'});
1241 } else {
1242 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1243 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1244 }
1245 push @cc, $c;
1246 printf("(body) Adding cc: %s from line '%s'\n",
1247 $c, $_) unless $quiet;
1248 }
1249 }
1250 close F;
1251
1252 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1253 open(F, "$cc_cmd \Q$t\E |")
1254 or die "(cc-cmd) Could not execute '$cc_cmd'";
1255 while(<F>) {
1256 my $c = $_;
1257 $c =~ s/^\s*//g;
1258 $c =~ s/\n$//g;
1259 next if ($c eq $sender and $suppress_from);
1260 push @cc, $c;
1261 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1262 $c, $cc_cmd) unless $quiet;
1263 }
1264 close F
1265 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1266 }
1267
1268 if ($broken_encoding{$t} && !$has_content_type) {
1269 $has_content_type = 1;
1270 push @xh, "MIME-Version: 1.0",
1271 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1272 "Content-Transfer-Encoding: 8bit";
1273 $body_encoding = $auto_8bit_encoding;
1274 }
1275
1276 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1277 $subject = quote_rfc2047($subject, $auto_8bit_encoding);
1278 }
1279
1280 if (defined $author and $author ne $sender) {
1281 $message = "From: $author\n\n$message";
1282 if (defined $author_encoding) {
1283 if ($has_content_type) {
1284 if ($body_encoding eq $author_encoding) {
1285 # ok, we already have the right encoding
1286 }
1287 else {
1288 # uh oh, we should re-encode
1289 }
1290 }
1291 else {
1292 $has_content_type = 1;
1293 push @xh,
1294 'MIME-Version: 1.0',
1295 "Content-Type: text/plain; charset=$author_encoding",
1296 'Content-Transfer-Encoding: 8bit';
1297 }
1298 }
1299 }
1300
1301 $needs_confirm = (
1302 $confirm eq "always" or
1303 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1304 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1305 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1306
1307 @cc = (@initial_cc, @cc);
1308
1309 my $message_was_sent = send_message();
1310
1311 # set up for the next message
1312 if ($thread && $message_was_sent &&
1313 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
1314 $reply_to = $message_id;
1315 if (length $references > 0) {
1316 $references .= "\n $message_id";
1317 } else {
1318 $references = "$message_id";
1319 }
1320 }
1321 $message_id = undef;
1322 }
1323
1324 cleanup_compose_files();
1325
1326 sub cleanup_compose_files() {
1327 unlink($compose_filename, $compose_filename . ".final") if $compose;
1328 }
1329
1330 $smtp->quit if $smtp;
1331
1332 sub unique_email_list(@) {
1333 my %seen;
1334 my @emails;
1335
1336 foreach my $entry (@_) {
1337 if (my $clean = extract_valid_address($entry)) {
1338 $seen{$clean} ||= 0;
1339 next if $seen{$clean}++;
1340 push @emails, $entry;
1341 } else {
1342 print STDERR "W: unable to extract a valid address",
1343 " from: $entry\n";
1344 }
1345 }
1346 return @emails;
1347 }
1348
1349 sub validate_patch {
1350 my $fn = shift;
1351 open(my $fh, '<', $fn)
1352 or die "unable to open $fn: $!\n";
1353 while (my $line = <$fh>) {
1354 if (length($line) > 998) {
1355 return "$.: patch contains a line longer than 998 characters";
1356 }
1357 }
1358 return undef;
1359 }
1360
1361 sub file_has_nonascii {
1362 my $fn = shift;
1363 open(my $fh, '<', $fn)
1364 or die "unable to open $fn: $!\n";
1365 while (my $line = <$fh>) {
1366 return 1 if $line =~ /[^[:ascii:]]/;
1367 }
1368 return 0;
1369 }
1370
1371 sub body_or_subject_has_nonascii {
1372 my $fn = shift;
1373 open(my $fh, '<', $fn)
1374 or die "unable to open $fn: $!\n";
1375 while (my $line = <$fh>) {
1376 last if $line =~ /^$/;
1377 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1378 }
1379 while (my $line = <$fh>) {
1380 return 1 if $line =~ /[^[:ascii:]]/;
1381 }
1382 return 0;
1383 }