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