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