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