Code

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