Code

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