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