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