libperl-git: refactor Git::config_*
[git.git] / git-send-email.perl
blobf17f7b3995c833d0434a258e18f6aa2d5568637e
1 #!/usr/bin/perl
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
6 # GPL v2 (See COPYING)
8 # Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
10 # Sends a collection of emails to the given email addresses, disturbingly fast.
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.
19 use 5.008;
20 use strict;
21 use warnings;
22 use Term::ReadLine;
23 use Getopt::Long;
24 use Text::ParseWords;
25 use Data::Dumper;
26 use Term::ANSIColor;
27 use File::Temp qw/ tempdir tempfile /;
28 use File::Spec::Functions qw(catfile);
29 use Error qw(:try);
30 use Git;
32 Getopt::Long::Configure qw/ pass_through /;
34 package FakeTerm;
35 sub new {
36 my ($class, $reason) = @_;
37 return bless \$reason, shift;
39 sub readline {
40 my $self = shift;
41 die "Cannot use readline on FakeTerm: $$self";
43 package main;
46 sub usage {
47 print <<EOT;
48 git send-email [options] <file | directory | rev-list options >
50 Composing:
51 --from <str> * Email From:
52 --[no-]to <str> * Email To:
53 --[no-]cc <str> * Email Cc:
54 --[no-]bcc <str> * Email Bcc:
55 --subject <str> * Email "Subject:"
56 --in-reply-to <str> * Email "In-Reply-To:"
57 --annotate * Review each patch that will be sent in an editor.
58 --compose * Open an editor for introduction.
59 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
61 Sending:
62 --envelope-sender <str> * Email envelope sender.
63 --smtp-server <str:int> * Outgoing SMTP server to use. The port
64 is optional. Default 'localhost'.
65 --smtp-server-option <str> * Outgoing SMTP server option to use.
66 --smtp-server-port <int> * Outgoing SMTP server port.
67 --smtp-user <str> * Username for SMTP-AUTH.
68 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
69 --smtp-encryption <str> * tls or ssl; anything else disables.
70 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
71 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
72 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
74 Automating:
75 --identity <str> * Use the sendemail.<id> options.
76 --to-cmd <str> * Email To: via `<str> \$patch_path`
77 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
78 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
79 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
80 --[no-]suppress-from * Send to self. Default off.
81 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
82 --[no-]thread * Use In-Reply-To: field. Default on.
84 Administering:
85 --confirm <str> * Confirm recipients before sending;
86 auto, cc, compose, always, or never.
87 --quiet * Output one line of info per email.
88 --dry-run * Don't actually send the emails.
89 --[no-]validate * Perform patch sanity checks. Default on.
90 --[no-]format-patch * understand any non optional arguments as
91 `git format-patch` ones.
92 --force * Send even if safety checks would prevent it.
94 EOT
95 exit(1);
98 # most mail servers generate the Date: header, but not all...
99 sub format_2822_time {
100 my ($time) = @_;
101 my @localtm = localtime($time);
102 my @gmttm = gmtime($time);
103 my $localmin = $localtm[1] + $localtm[2] * 60;
104 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
105 if ($localtm[0] != $gmttm[0]) {
106 die "local zone differs from GMT by a non-minute interval\n";
108 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
109 $localmin += 1440;
110 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
111 $localmin -= 1440;
112 } elsif ($gmttm[6] != $localtm[6]) {
113 die "local time offset greater than or equal to 24 hours\n";
115 my $offset = $localmin - $gmtmin;
116 my $offhour = $offset / 60;
117 my $offmin = abs($offset % 60);
118 if (abs($offhour) >= 24) {
119 die ("local time offset greater than or equal to 24 hours\n");
122 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
123 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
124 $localtm[3],
125 qw(Jan Feb Mar Apr May Jun
126 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
127 $localtm[5]+1900,
128 $localtm[2],
129 $localtm[1],
130 $localtm[0],
131 ($offset >= 0) ? '+' : '-',
132 abs($offhour),
133 $offmin,
137 my $have_email_valid = eval { require Email::Valid; 1 };
138 my $have_mail_address = eval { require Mail::Address; 1 };
139 my $smtp;
140 my $auth;
142 # Variables we fill in automatically, or via prompting:
143 my (@to,$no_to,@initial_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
144 $initial_reply_to,$initial_subject,@files,
145 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
147 my $envelope_sender;
149 # Example reply to:
150 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
152 my $repo = eval { Git->repository() };
153 my @repo = $repo ? ($repo) : ();
154 my $term = eval {
155 $ENV{"GIT_SEND_EMAIL_NOTTY"}
156 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
157 : new Term::ReadLine 'git-send-email';
159 if ($@) {
160 $term = new FakeTerm "$@: going non-interactive";
163 # Behavior modification variables
164 my ($quiet, $dry_run) = (0, 0);
165 my $format_patch;
166 my $compose_filename;
167 my $force = 0;
169 # Handle interactive edition of files.
170 my $multiedit;
171 my $editor;
173 sub do_edit {
174 if (!defined($editor)) {
175 $editor = Git::command_oneline('var', 'GIT_EDITOR');
177 if (defined($multiedit) && !$multiedit) {
178 map {
179 system('sh', '-c', $editor.' "$@"', $editor, $_);
180 if (($? & 127) || ($? >> 8)) {
181 die("the editor exited uncleanly, aborting everything");
183 } @_;
184 } else {
185 system('sh', '-c', $editor.' "$@"', $editor, @_);
186 if (($? & 127) || ($? >> 8)) {
187 die("the editor exited uncleanly, aborting everything");
192 # Variables with corresponding config settings
193 my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
194 my ($to_cmd, $cc_cmd);
195 my ($smtp_server, $smtp_server_port, @smtp_server_options);
196 my ($smtp_authuser, $smtp_encryption);
197 my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
198 my ($validate, $confirm);
199 my (@suppress_cc);
200 my ($auto_8bit_encoding);
202 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
204 my $not_set_by_user = "true but not set by the user";
206 my %config_bool_settings = (
207 "thread" => [\$thread, 1],
208 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
209 "suppressfrom" => [\$suppress_from, undef],
210 "signedoffbycc" => [\$signed_off_by_cc, undef],
211 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
212 "validate" => [\$validate, 1],
215 my %config_settings = (
216 "smtpserver" => \$smtp_server,
217 "smtpserverport" => \$smtp_server_port,
218 "smtpserveroption" => \@smtp_server_options,
219 "smtpuser" => \$smtp_authuser,
220 "smtppass" => \$smtp_authpass,
221 "smtpdomain" => \$smtp_domain,
222 "to" => \@initial_to,
223 "tocmd" => \$to_cmd,
224 "cc" => \@initial_cc,
225 "cccmd" => \$cc_cmd,
226 "aliasfiletype" => \$aliasfiletype,
227 "bcc" => \@bcclist,
228 "suppresscc" => \@suppress_cc,
229 "envelopesender" => \$envelope_sender,
230 "multiedit" => \$multiedit,
231 "confirm" => \$confirm,
232 "from" => \$sender,
233 "assume8bitencoding" => \$auto_8bit_encoding,
236 my %config_path_settings = (
237 "aliasesfile" => \@alias_files,
240 # Help users prepare for 1.7.0
241 sub chain_reply_to {
242 if (defined $chain_reply_to &&
243 $chain_reply_to eq $not_set_by_user) {
244 print STDERR
245 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
246 "Set sendemail.chainreplyto configuration variable to true if\n" .
247 "you want to keep --chain-reply-to as your default.\n";
248 $chain_reply_to = 0;
250 return $chain_reply_to;
253 # Handle Uncouth Termination
254 sub signal_handler {
256 # Make text normal
257 print color("reset"), "\n";
259 # SMTP password masked
260 system "stty echo";
262 # tmp files from --compose
263 if (defined $compose_filename) {
264 if (-e $compose_filename) {
265 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
267 if (-e ($compose_filename . ".final")) {
268 print "'$compose_filename.final' contains the composed email.\n"
272 exit;
275 $SIG{TERM} = \&signal_handler;
276 $SIG{INT} = \&signal_handler;
278 # Begin by accumulating all the variables (defined above), that we will end up
279 # needing, first, from the command line:
281 my $rc = GetOptions("sender|from=s" => \$sender,
282 "in-reply-to=s" => \$initial_reply_to,
283 "subject=s" => \$initial_subject,
284 "to=s" => \@initial_to,
285 "to-cmd=s" => \$to_cmd,
286 "no-to" => \$no_to,
287 "cc=s" => \@initial_cc,
288 "no-cc" => \$no_cc,
289 "bcc=s" => \@bcclist,
290 "no-bcc" => \$no_bcc,
291 "chain-reply-to!" => \$chain_reply_to,
292 "smtp-server=s" => \$smtp_server,
293 "smtp-server-option=s" => \@smtp_server_options,
294 "smtp-server-port=s" => \$smtp_server_port,
295 "smtp-user=s" => \$smtp_authuser,
296 "smtp-pass:s" => \$smtp_authpass,
297 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
298 "smtp-encryption=s" => \$smtp_encryption,
299 "smtp-debug:i" => \$debug_net_smtp,
300 "smtp-domain:s" => \$smtp_domain,
301 "identity=s" => \$identity,
302 "annotate" => \$annotate,
303 "compose" => \$compose,
304 "quiet" => \$quiet,
305 "cc-cmd=s" => \$cc_cmd,
306 "suppress-from!" => \$suppress_from,
307 "suppress-cc=s" => \@suppress_cc,
308 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
309 "confirm=s" => \$confirm,
310 "dry-run" => \$dry_run,
311 "envelope-sender=s" => \$envelope_sender,
312 "thread!" => \$thread,
313 "validate!" => \$validate,
314 "format-patch!" => \$format_patch,
315 "8bit-encoding=s" => \$auto_8bit_encoding,
316 "force" => \$force,
319 unless ($rc) {
320 usage();
323 die "Cannot run git format-patch from outside a repository\n"
324 if $format_patch and not $repo;
326 # Now, let's fill any that aren't set in with defaults:
328 sub read_config {
329 my ($prefix) = @_;
331 foreach my $setting (keys %config_bool_settings) {
332 my $target = $config_bool_settings{$setting}->[0];
333 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
336 foreach my $setting (keys %config_path_settings) {
337 my $target = $config_path_settings{$setting}->[0];
338 $$target = Git::config_path(@repo, "$prefix.$setting") unless (defined $$target);
341 foreach my $setting (keys %config_settings) {
342 my $target = $config_settings{$setting};
343 next if $setting eq "to" and defined $no_to;
344 next if $setting eq "cc" and defined $no_cc;
345 next if $setting eq "bcc" and defined $no_bcc;
346 if (ref($target) eq "ARRAY") {
347 unless (@$target) {
348 my @values = Git::config(@repo, "$prefix.$setting");
349 @$target = @values if (@values && defined $values[0]);
352 else {
353 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
357 if (!defined $smtp_encryption) {
358 my $enc = Git::config(@repo, "$prefix.smtpencryption");
359 if (defined $enc) {
360 $smtp_encryption = $enc;
361 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
362 $smtp_encryption = 'ssl';
367 # read configuration from [sendemail "$identity"], fall back on [sendemail]
368 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
369 read_config("sendemail.$identity") if (defined $identity);
370 read_config("sendemail");
372 # fall back on builtin bool defaults
373 foreach my $setting (values %config_bool_settings) {
374 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
377 # 'default' encryption is none -- this only prevents a warning
378 $smtp_encryption = '' unless (defined $smtp_encryption);
380 # Set CC suppressions
381 my(%suppress_cc);
382 if (@suppress_cc) {
383 foreach my $entry (@suppress_cc) {
384 die "Unknown --suppress-cc field: '$entry'\n"
385 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
386 $suppress_cc{$entry} = 1;
390 if ($suppress_cc{'all'}) {
391 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
392 $suppress_cc{$entry} = 1;
394 delete $suppress_cc{'all'};
397 # If explicit old-style ones are specified, they trump --suppress-cc.
398 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
399 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
401 if ($suppress_cc{'body'}) {
402 foreach my $entry (qw (sob bodycc)) {
403 $suppress_cc{$entry} = 1;
405 delete $suppress_cc{'body'};
408 # Set confirm's default value
409 my $confirm_unconfigured = !defined $confirm;
410 if ($confirm_unconfigured) {
411 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
413 die "Unknown --confirm setting: '$confirm'\n"
414 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
416 # Debugging, print out the suppressions.
417 if (0) {
418 print "suppressions:\n";
419 foreach my $entry (keys %suppress_cc) {
420 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
424 my ($repoauthor, $repocommitter);
425 ($repoauthor) = Git::ident_person(@repo, 'author');
426 ($repocommitter) = Git::ident_person(@repo, 'committer');
428 # Verify the user input
430 foreach my $entry (@initial_to) {
431 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
434 foreach my $entry (@initial_cc) {
435 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
438 foreach my $entry (@bcclist) {
439 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
442 sub parse_address_line {
443 if ($have_mail_address) {
444 return map { $_->format } Mail::Address->parse($_[0]);
445 } else {
446 return split_addrs($_[0]);
450 sub split_addrs {
451 return quotewords('\s*,\s*', 1, @_);
454 my %aliases;
455 my %parse_alias = (
456 # multiline formats can be supported in the future
457 mutt => sub { my $fh = shift; while (<$fh>) {
458 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
459 my ($alias, $addr) = ($1, $2);
460 $addr =~ s/#.*$//; # mutt allows # comments
461 # commas delimit multiple addresses
462 $aliases{$alias} = [ split_addrs($addr) ];
463 }}},
464 mailrc => sub { my $fh = shift; while (<$fh>) {
465 if (/^alias\s+(\S+)\s+(.*)$/) {
466 # spaces delimit multiple addresses
467 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
468 }}},
469 pine => sub { my $fh = shift; my $f='\t[^\t]*';
470 for (my $x = ''; defined($x); $x = $_) {
471 chomp $x;
472 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
473 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
474 $aliases{$1} = [ split_addrs($2) ];
476 elm => sub { my $fh = shift;
477 while (<$fh>) {
478 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
479 my ($alias, $addr) = ($1, $2);
480 $aliases{$alias} = [ split_addrs($addr) ];
482 } },
484 gnus => sub { my $fh = shift; while (<$fh>) {
485 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
486 $aliases{$1} = [ $2 ];
490 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
491 foreach my $file (@alias_files) {
492 open my $fh, '<', $file or die "opening $file: $!\n";
493 $parse_alias{$aliasfiletype}->($fh);
494 close $fh;
498 ($sender) = expand_aliases($sender) if defined $sender;
500 # returns 1 if the conflict must be solved using it as a format-patch argument
501 sub check_file_rev_conflict($) {
502 return unless $repo;
503 my $f = shift;
504 try {
505 $repo->command('rev-parse', '--verify', '--quiet', $f);
506 if (defined($format_patch)) {
507 return $format_patch;
509 die(<<EOF);
510 File '$f' exists but it could also be the range of commits
511 to produce patches for. Please disambiguate by...
513 * Saying "./$f" if you mean a file; or
514 * Giving --format-patch option if you mean a range.
516 } catch Git::Error::Command with {
517 return 0;
521 # Now that all the defaults are set, process the rest of the command line
522 # arguments and collect up the files that need to be processed.
523 my @rev_list_opts;
524 while (defined(my $f = shift @ARGV)) {
525 if ($f eq "--") {
526 push @rev_list_opts, "--", @ARGV;
527 @ARGV = ();
528 } elsif (-d $f and !check_file_rev_conflict($f)) {
529 opendir my $dh, $f
530 or die "Failed to opendir $f: $!";
532 push @files, grep { -f $_ } map { catfile($f, $_) }
533 sort readdir $dh;
534 closedir $dh;
535 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
536 push @files, $f;
537 } else {
538 push @rev_list_opts, $f;
542 if (@rev_list_opts) {
543 die "Cannot run git format-patch from outside a repository\n"
544 unless $repo;
545 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
548 if ($validate) {
549 foreach my $f (@files) {
550 unless (-p $f) {
551 my $error = validate_patch($f);
552 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
557 if (@files) {
558 unless ($quiet) {
559 print $_,"\n" for (@files);
561 } else {
562 print STDERR "\nNo patch files specified!\n\n";
563 usage();
566 sub get_patch_subject {
567 my $fn = shift;
568 open (my $fh, '<', $fn);
569 while (my $line = <$fh>) {
570 next unless ($line =~ /^Subject: (.*)$/);
571 close $fh;
572 return "GIT: $1\n";
574 close $fh;
575 die "No subject line in $fn ?";
578 if ($compose) {
579 # Note that this does not need to be secure, but we will make a small
580 # effort to have it be unique
581 $compose_filename = ($repo ?
582 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
583 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
584 open my $c, ">", $compose_filename
585 or die "Failed to open for writing $compose_filename: $!";
588 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
589 my $tpl_subject = $initial_subject || '';
590 my $tpl_reply_to = $initial_reply_to || '';
592 print $c <<EOT;
593 From $tpl_sender # This line is ignored.
594 GIT: Lines beginning in "GIT:" will be removed.
595 GIT: Consider including an overall diffstat or table of contents
596 GIT: for the patch you are writing.
597 GIT:
598 GIT: Clear the body content if you don't wish to send a summary.
599 From: $tpl_sender
600 Subject: $tpl_subject
601 In-Reply-To: $tpl_reply_to
604 for my $f (@files) {
605 print $c get_patch_subject($f);
607 close $c;
609 if ($annotate) {
610 do_edit($compose_filename, @files);
611 } else {
612 do_edit($compose_filename);
615 open my $c2, ">", $compose_filename . ".final"
616 or die "Failed to open $compose_filename.final : " . $!;
618 open $c, "<", $compose_filename
619 or die "Failed to open $compose_filename : " . $!;
621 my $need_8bit_cte = file_has_nonascii($compose_filename);
622 my $in_body = 0;
623 my $summary_empty = 1;
624 while(<$c>) {
625 next if m/^GIT:/;
626 if ($in_body) {
627 $summary_empty = 0 unless (/^\n$/);
628 } elsif (/^\n$/) {
629 $in_body = 1;
630 if ($need_8bit_cte) {
631 print $c2 "MIME-Version: 1.0\n",
632 "Content-Type: text/plain; ",
633 "charset=UTF-8\n",
634 "Content-Transfer-Encoding: 8bit\n";
636 } elsif (/^MIME-Version:/i) {
637 $need_8bit_cte = 0;
638 } elsif (/^Subject:\s*(.+)\s*$/i) {
639 $initial_subject = $1;
640 my $subject = $initial_subject;
641 $_ = "Subject: " .
642 ($subject =~ /[^[:ascii:]]/ ?
643 quote_rfc2047($subject) :
644 $subject) .
645 "\n";
646 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
647 $initial_reply_to = $1;
648 next;
649 } elsif (/^From:\s*(.+)\s*$/i) {
650 $sender = $1;
651 next;
652 } elsif (/^(?:To|Cc|Bcc):/i) {
653 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
654 next;
656 print $c2 $_;
658 close $c;
659 close $c2;
661 if ($summary_empty) {
662 print "Summary email is empty, skipping it\n";
663 $compose = -1;
665 } elsif ($annotate) {
666 do_edit(@files);
669 sub ask {
670 my ($prompt, %arg) = @_;
671 my $valid_re = $arg{valid_re};
672 my $default = $arg{default};
673 my $resp;
674 my $i = 0;
675 return defined $default ? $default : undef
676 unless defined $term->IN and defined fileno($term->IN) and
677 defined $term->OUT and defined fileno($term->OUT);
678 while ($i++ < 10) {
679 $resp = $term->readline($prompt);
680 if (!defined $resp) { # EOF
681 print "\n";
682 return defined $default ? $default : undef;
684 if ($resp eq '' and defined $default) {
685 return $default;
687 if (!defined $valid_re or $resp =~ /$valid_re/) {
688 return $resp;
691 return undef;
694 my %broken_encoding;
696 sub file_declares_8bit_cte {
697 my $fn = shift;
698 open (my $fh, '<', $fn);
699 while (my $line = <$fh>) {
700 last if ($line =~ /^$/);
701 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
703 close $fh;
704 return 0;
707 foreach my $f (@files) {
708 next unless (body_or_subject_has_nonascii($f)
709 && !file_declares_8bit_cte($f));
710 $broken_encoding{$f} = 1;
713 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
714 print "The following files are 8bit, but do not declare " .
715 "a Content-Transfer-Encoding.\n";
716 foreach my $f (sort keys %broken_encoding) {
717 print " $f\n";
719 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
720 default => "UTF-8");
723 if (!$force) {
724 for my $f (@files) {
725 if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
726 die "Refusing to send because the patch\n\t$f\n"
727 . "has the template subject '*** SUBJECT HERE ***'. "
728 . "Pass --force if you really want to send.\n";
733 my $prompting = 0;
734 if (!defined $sender) {
735 $sender = $repoauthor || $repocommitter || '';
736 $sender = ask("Who should the emails appear to be from? [$sender] ",
737 default => $sender);
738 print "Emails will be sent from: ", $sender, "\n";
739 $prompting++;
742 if (!@initial_to && !defined $to_cmd) {
743 my $to = ask("Who should the emails be sent to? ");
744 push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
745 $prompting++;
748 sub expand_aliases {
749 return map { expand_one_alias($_) } @_;
752 my %EXPANDED_ALIASES;
753 sub expand_one_alias {
754 my $alias = shift;
755 if ($EXPANDED_ALIASES{$alias}) {
756 die "fatal: alias '$alias' expands to itself\n";
758 local $EXPANDED_ALIASES{$alias} = 1;
759 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
762 @initial_to = expand_aliases(@initial_to);
763 @initial_to = (map { sanitize_address($_) } @initial_to);
764 @initial_cc = expand_aliases(@initial_cc);
765 @bcclist = expand_aliases(@bcclist);
767 if ($thread && !defined $initial_reply_to && $prompting) {
768 $initial_reply_to = ask(
769 "Message-ID to be used as In-Reply-To for the first email? ");
771 if (defined $initial_reply_to) {
772 $initial_reply_to =~ s/^\s*<?//;
773 $initial_reply_to =~ s/>?\s*$//;
774 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
777 if (!defined $smtp_server) {
778 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
779 if (-x $_) {
780 $smtp_server = $_;
781 last;
784 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
787 if ($compose && $compose > 0) {
788 @files = ($compose_filename . ".final", @files);
791 # Variables we set as part of the loop over files
792 our ($message_id, %mail, $subject, $reply_to, $references, $message,
793 $needs_confirm, $message_num, $ask_default);
795 sub extract_valid_address {
796 my $address = shift;
797 my $local_part_regexp = qr/[^<>"\s@]+/;
798 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
800 # check for a local address:
801 return $address if ($address =~ /^($local_part_regexp)$/);
803 $address =~ s/^\s*<(.*)>\s*$/$1/;
804 if ($have_email_valid) {
805 return scalar Email::Valid->address($address);
806 } else {
807 # less robust/correct than the monster regexp in Email::Valid,
808 # but still does a 99% job, and one less dependency
809 $address =~ /($local_part_regexp\@$domain_regexp)/;
810 return $1;
814 # Usually don't need to change anything below here.
816 # we make a "fake" message id by taking the current number
817 # of seconds since the beginning of Unix time and tacking on
818 # a random number to the end, in case we are called quicker than
819 # 1 second since the last time we were called.
821 # We'll setup a template for the message id, using the "from" address:
823 my ($message_id_stamp, $message_id_serial);
824 sub make_message_id {
825 my $uniq;
826 if (!defined $message_id_stamp) {
827 $message_id_stamp = sprintf("%s-%s", time, $$);
828 $message_id_serial = 0;
830 $message_id_serial++;
831 $uniq = "$message_id_stamp-$message_id_serial";
833 my $du_part;
834 for ($sender, $repocommitter, $repoauthor) {
835 $du_part = extract_valid_address(sanitize_address($_));
836 last if (defined $du_part and $du_part ne '');
838 if (not defined $du_part or $du_part eq '') {
839 require Sys::Hostname;
840 $du_part = 'user@' . Sys::Hostname::hostname();
842 my $message_id_template = "<%s-git-send-email-%s>";
843 $message_id = sprintf($message_id_template, $uniq, $du_part);
844 #print "new message id = $message_id\n"; # Was useful for debugging
849 $time = time - scalar $#files;
851 sub unquote_rfc2047 {
852 local ($_) = @_;
853 my $encoding;
854 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
855 $encoding = $1;
856 s/_/ /g;
857 s/=([0-9A-F]{2})/chr(hex($1))/eg;
859 return wantarray ? ($_, $encoding) : $_;
862 sub quote_rfc2047 {
863 local $_ = shift;
864 my $encoding = shift || 'UTF-8';
865 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
866 s/(.*)/=\?$encoding\?q\?$1\?=/;
867 return $_;
870 sub is_rfc2047_quoted {
871 my $s = shift;
872 my $token = qr/[^][()<>@,;:"\/?.= \000-\037\177-\377]+/;
873 my $encoded_text = qr/[!->@-~]+/;
874 length($s) <= 75 &&
875 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
878 # use the simplest quoting being able to handle the recipient
879 sub sanitize_address {
880 my ($recipient) = @_;
881 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
883 if (not $recipient_name) {
884 return $recipient;
887 # if recipient_name is already quoted, do nothing
888 if (is_rfc2047_quoted($recipient_name)) {
889 return $recipient;
892 # rfc2047 is needed if a non-ascii char is included
893 if ($recipient_name =~ /[^[:ascii:]]/) {
894 $recipient_name =~ s/^"(.*)"$/$1/;
895 $recipient_name = quote_rfc2047($recipient_name);
898 # double quotes are needed if specials or CTLs are included
899 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
900 $recipient_name =~ s/(["\\\r])/\\$1/g;
901 $recipient_name = qq["$recipient_name"];
904 return "$recipient_name $recipient_addr";
908 # Returns the local Fully Qualified Domain Name (FQDN) if available.
910 # Tightly configured MTAa require that a caller sends a real DNS
911 # domain name that corresponds the IP address in the HELO/EHLO
912 # handshake. This is used to verify the connection and prevent
913 # spammers from trying to hide their identity. If the DNS and IP don't
914 # match, the receiveing MTA may deny the connection.
916 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
918 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
919 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
921 # This maildomain*() code is based on ideas in Perl library Test::Reporter
922 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
924 sub valid_fqdn {
925 my $domain = shift;
926 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
929 sub maildomain_net {
930 my $maildomain;
932 if (eval { require Net::Domain; 1 }) {
933 my $domain = Net::Domain::domainname();
934 $maildomain = $domain if valid_fqdn($domain);
937 return $maildomain;
940 sub maildomain_mta {
941 my $maildomain;
943 if (eval { require Net::SMTP; 1 }) {
944 for my $host (qw(mailhost localhost)) {
945 my $smtp = Net::SMTP->new($host);
946 if (defined $smtp) {
947 my $domain = $smtp->domain;
948 $smtp->quit;
950 $maildomain = $domain if valid_fqdn($domain);
952 last if $maildomain;
957 return $maildomain;
960 sub maildomain {
961 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
964 # Returns 1 if the message was sent, and 0 otherwise.
965 # In actuality, the whole program dies when there
966 # is an error sending a message.
968 sub send_message {
969 my @recipients = unique_email_list(@to);
970 @cc = (grep { my $cc = extract_valid_address($_);
971 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
973 map { sanitize_address($_) }
974 @cc);
975 my $to = join (",\n\t", @recipients);
976 @recipients = unique_email_list(@recipients,@cc,@bcclist);
977 @recipients = (map { extract_valid_address($_) } @recipients);
978 my $date = format_2822_time($time++);
979 my $gitversion = '@@GIT_VERSION@@';
980 if ($gitversion =~ m/..GIT_VERSION../) {
981 $gitversion = Git::version();
984 my $cc = join(",\n\t", unique_email_list(@cc));
985 my $ccline = "";
986 if ($cc ne '') {
987 $ccline = "\nCc: $cc";
989 my $sanitized_sender = sanitize_address($sender);
990 make_message_id() unless defined($message_id);
992 my $header = "From: $sanitized_sender
993 To: $to${ccline}
994 Subject: $subject
995 Date: $date
996 Message-Id: $message_id
997 X-Mailer: git-send-email $gitversion
999 if ($reply_to) {
1001 $header .= "In-Reply-To: $reply_to\n";
1002 $header .= "References: $references\n";
1004 if (@xh) {
1005 $header .= join("\n", @xh) . "\n";
1008 my @sendmail_parameters = ('-i', @recipients);
1009 my $raw_from = $sanitized_sender;
1010 if (defined $envelope_sender && $envelope_sender ne "auto") {
1011 $raw_from = $envelope_sender;
1013 $raw_from = extract_valid_address($raw_from);
1014 unshift (@sendmail_parameters,
1015 '-f', $raw_from) if(defined $envelope_sender);
1017 if ($needs_confirm && !$dry_run) {
1018 print "\n$header\n";
1019 if ($needs_confirm eq "inform") {
1020 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1021 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1022 print " The Cc list above has been expanded by additional\n";
1023 print " addresses found in the patch commit message. By default\n";
1024 print " send-email prompts before sending whenever this occurs.\n";
1025 print " This behavior is controlled by the sendemail.confirm\n";
1026 print " configuration setting.\n";
1027 print "\n";
1028 print " For additional information, run 'git send-email --help'.\n";
1029 print " To retain the current behavior, but squelch this message,\n";
1030 print " run 'git config --global sendemail.confirm auto'.\n\n";
1032 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1033 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1034 default => $ask_default);
1035 die "Send this email reply required" unless defined $_;
1036 if (/^n/i) {
1037 return 0;
1038 } elsif (/^q/i) {
1039 cleanup_compose_files();
1040 exit(0);
1041 } elsif (/^a/i) {
1042 $confirm = 'never';
1046 unshift (@sendmail_parameters, @smtp_server_options);
1048 if ($dry_run) {
1049 # We don't want to send the email.
1050 } elsif ($smtp_server =~ m#^/#) {
1051 my $pid = open my $sm, '|-';
1052 defined $pid or die $!;
1053 if (!$pid) {
1054 exec($smtp_server, @sendmail_parameters) or die $!;
1056 print $sm "$header\n$message";
1057 close $sm or die $!;
1058 } else {
1060 if (!defined $smtp_server) {
1061 die "The required SMTP server is not properly defined."
1064 if ($smtp_encryption eq 'ssl') {
1065 $smtp_server_port ||= 465; # ssmtp
1066 require Net::SMTP::SSL;
1067 $smtp_domain ||= maildomain();
1068 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1069 Hello => $smtp_domain,
1070 Port => $smtp_server_port);
1072 else {
1073 require Net::SMTP;
1074 $smtp_domain ||= maildomain();
1075 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1076 ? "$smtp_server:$smtp_server_port"
1077 : $smtp_server,
1078 Hello => $smtp_domain,
1079 Debug => $debug_net_smtp);
1080 if ($smtp_encryption eq 'tls' && $smtp) {
1081 require Net::SMTP::SSL;
1082 $smtp->command('STARTTLS');
1083 $smtp->response();
1084 if ($smtp->code == 220) {
1085 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1086 or die "STARTTLS failed! ".$smtp->message;
1087 $smtp_encryption = '';
1088 # Send EHLO again to receive fresh
1089 # supported commands
1090 $smtp->hello();
1091 } else {
1092 die "Server does not support STARTTLS! ".$smtp->message;
1097 if (!$smtp) {
1098 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1099 "VALUES: server=$smtp_server ",
1100 "encryption=$smtp_encryption ",
1101 "hello=$smtp_domain",
1102 defined $smtp_server_port ? " port=$smtp_server_port" : "";
1105 if (defined $smtp_authuser) {
1107 if (!defined $smtp_authpass) {
1109 system "stty -echo";
1111 do {
1112 print "Password: ";
1113 $_ = <STDIN>;
1114 print "\n";
1115 } while (!defined $_);
1117 chomp($smtp_authpass = $_);
1119 system "stty echo";
1122 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1125 $smtp->mail( $raw_from ) or die $smtp->message;
1126 $smtp->to( @recipients ) or die $smtp->message;
1127 $smtp->data or die $smtp->message;
1128 $smtp->datasend("$header\n$message") or die $smtp->message;
1129 $smtp->dataend() or die $smtp->message;
1130 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1132 if ($quiet) {
1133 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1134 } else {
1135 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1136 if ($smtp_server !~ m#^/#) {
1137 print "Server: $smtp_server\n";
1138 print "MAIL FROM:<$raw_from>\n";
1139 foreach my $entry (@recipients) {
1140 print "RCPT TO:<$entry>\n";
1142 } else {
1143 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1145 print $header, "\n";
1146 if ($smtp) {
1147 print "Result: ", $smtp->code, ' ',
1148 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1149 } else {
1150 print "Result: OK\n";
1154 return 1;
1157 $reply_to = $initial_reply_to;
1158 $references = $initial_reply_to || '';
1159 $subject = $initial_subject;
1160 $message_num = 0;
1162 foreach my $t (@files) {
1163 open my $fh, "<", $t or die "can't open file $t";
1165 my $author = undef;
1166 my $author_encoding;
1167 my $has_content_type;
1168 my $body_encoding;
1169 @to = ();
1170 @cc = ();
1171 @xh = ();
1172 my $input_format = undef;
1173 my @header = ();
1174 $message = "";
1175 $message_num++;
1176 # First unfold multiline header fields
1177 while(<$fh>) {
1178 last if /^\s*$/;
1179 if (/^\s+\S/ and @header) {
1180 chomp($header[$#header]);
1181 s/^\s+/ /;
1182 $header[$#header] .= $_;
1183 } else {
1184 push(@header, $_);
1187 # Now parse the header
1188 foreach(@header) {
1189 if (/^From /) {
1190 $input_format = 'mbox';
1191 next;
1193 chomp;
1194 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1195 $input_format = 'mbox';
1198 if (defined $input_format && $input_format eq 'mbox') {
1199 if (/^Subject:\s+(.*)$/) {
1200 $subject = $1;
1202 elsif (/^From:\s+(.*)$/) {
1203 ($author, $author_encoding) = unquote_rfc2047($1);
1204 next if $suppress_cc{'author'};
1205 next if $suppress_cc{'self'} and $author eq $sender;
1206 printf("(mbox) Adding cc: %s from line '%s'\n",
1207 $1, $_) unless $quiet;
1208 push @cc, $1;
1210 elsif (/^To:\s+(.*)$/) {
1211 foreach my $addr (parse_address_line($1)) {
1212 printf("(mbox) Adding to: %s from line '%s'\n",
1213 $addr, $_) unless $quiet;
1214 push @to, sanitize_address($addr);
1217 elsif (/^Cc:\s+(.*)$/) {
1218 foreach my $addr (parse_address_line($1)) {
1219 if (unquote_rfc2047($addr) eq $sender) {
1220 next if ($suppress_cc{'self'});
1221 } else {
1222 next if ($suppress_cc{'cc'});
1224 printf("(mbox) Adding cc: %s from line '%s'\n",
1225 $addr, $_) unless $quiet;
1226 push @cc, $addr;
1229 elsif (/^Content-type:/i) {
1230 $has_content_type = 1;
1231 if (/charset="?([^ "]+)/) {
1232 $body_encoding = $1;
1234 push @xh, $_;
1236 elsif (/^Message-Id: (.*)/i) {
1237 $message_id = $1;
1239 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1240 push @xh, $_;
1243 } else {
1244 # In the traditional
1245 # "send lots of email" format,
1246 # line 1 = cc
1247 # line 2 = subject
1248 # So let's support that, too.
1249 $input_format = 'lots';
1250 if (@cc == 0 && !$suppress_cc{'cc'}) {
1251 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1252 $_, $_) unless $quiet;
1253 push @cc, $_;
1254 } elsif (!defined $subject) {
1255 $subject = $_;
1259 # Now parse the message body
1260 while(<$fh>) {
1261 $message .= $_;
1262 if (/^(Signed-off-by|Cc): (.*)$/i) {
1263 chomp;
1264 my ($what, $c) = ($1, $2);
1265 chomp $c;
1266 if ($c eq $sender) {
1267 next if ($suppress_cc{'self'});
1268 } else {
1269 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1270 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1272 push @cc, $c;
1273 printf("(body) Adding cc: %s from line '%s'\n",
1274 $c, $_) unless $quiet;
1277 close $fh;
1279 push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1280 if defined $to_cmd;
1281 push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1282 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1284 if ($broken_encoding{$t} && !$has_content_type) {
1285 $has_content_type = 1;
1286 push @xh, "MIME-Version: 1.0",
1287 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1288 "Content-Transfer-Encoding: 8bit";
1289 $body_encoding = $auto_8bit_encoding;
1292 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1293 $subject = quote_rfc2047($subject, $auto_8bit_encoding);
1296 if (defined $author and $author ne $sender) {
1297 $message = "From: $author\n\n$message";
1298 if (defined $author_encoding) {
1299 if ($has_content_type) {
1300 if ($body_encoding eq $author_encoding) {
1301 # ok, we already have the right encoding
1303 else {
1304 # uh oh, we should re-encode
1307 else {
1308 $has_content_type = 1;
1309 push @xh,
1310 'MIME-Version: 1.0',
1311 "Content-Type: text/plain; charset=$author_encoding",
1312 'Content-Transfer-Encoding: 8bit';
1317 $needs_confirm = (
1318 $confirm eq "always" or
1319 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1320 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1321 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1323 @to = (@initial_to, @to);
1324 @cc = (@initial_cc, @cc);
1326 my $message_was_sent = send_message();
1328 # set up for the next message
1329 if ($thread && $message_was_sent &&
1330 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0 ||
1331 $message_num == 1)) {
1332 $reply_to = $message_id;
1333 if (length $references > 0) {
1334 $references .= "\n $message_id";
1335 } else {
1336 $references = "$message_id";
1339 $message_id = undef;
1342 # Execute a command (e.g. $to_cmd) to get a list of email addresses
1343 # and return a results array
1344 sub recipients_cmd {
1345 my ($prefix, $what, $cmd, $file) = @_;
1347 my $sanitized_sender = sanitize_address($sender);
1348 my @addresses = ();
1349 open my $fh, "$cmd \Q$file\E |"
1350 or die "($prefix) Could not execute '$cmd'";
1351 while (my $address = <$fh>) {
1352 $address =~ s/^\s*//g;
1353 $address =~ s/\s*$//g;
1354 $address = sanitize_address($address);
1355 next if ($address eq $sanitized_sender and $suppress_from);
1356 push @addresses, $address;
1357 printf("($prefix) Adding %s: %s from: '%s'\n",
1358 $what, $address, $cmd) unless $quiet;
1360 close $fh
1361 or die "($prefix) failed to close pipe to '$cmd'";
1362 return @addresses;
1365 cleanup_compose_files();
1367 sub cleanup_compose_files {
1368 unlink($compose_filename, $compose_filename . ".final") if $compose;
1371 $smtp->quit if $smtp;
1373 sub unique_email_list {
1374 my %seen;
1375 my @emails;
1377 foreach my $entry (@_) {
1378 if (my $clean = extract_valid_address($entry)) {
1379 $seen{$clean} ||= 0;
1380 next if $seen{$clean}++;
1381 push @emails, $entry;
1382 } else {
1383 print STDERR "W: unable to extract a valid address",
1384 " from: $entry\n";
1387 return @emails;
1390 sub validate_patch {
1391 my $fn = shift;
1392 open(my $fh, '<', $fn)
1393 or die "unable to open $fn: $!\n";
1394 while (my $line = <$fh>) {
1395 if (length($line) > 998) {
1396 return "$.: patch contains a line longer than 998 characters";
1399 return undef;
1402 sub file_has_nonascii {
1403 my $fn = shift;
1404 open(my $fh, '<', $fn)
1405 or die "unable to open $fn: $!\n";
1406 while (my $line = <$fh>) {
1407 return 1 if $line =~ /[^[:ascii:]]/;
1409 return 0;
1412 sub body_or_subject_has_nonascii {
1413 my $fn = shift;
1414 open(my $fh, '<', $fn)
1415 or die "unable to open $fn: $!\n";
1416 while (my $line = <$fh>) {
1417 last if $line =~ /^$/;
1418 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1420 while (my $line = <$fh>) {
1421 return 1 if $line =~ /[^[:ascii:]]/;
1423 return 0;