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