make the sample pre-commit hook script reject names with newlines, too
[git/jnareb-git.git] / git-send-email.perl
blobc1d8edbdd324fc1eca7bc475cbf31bd913036682
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 Error qw(:try);
29 use Git;
31 Getopt::Long::Configure qw/ pass_through /;
33 package FakeTerm;
34 sub new {
35 my ($class, $reason) = @_;
36 return bless \$reason, shift;
38 sub readline {
39 my $self = shift;
40 die "Cannot use readline on FakeTerm: $$self";
42 package main;
45 sub usage {
46 print <<EOT;
47 git send-email [options] <file | directory | rev-list options >
49 Composing:
50 --from <str> * Email From:
51 --[no-]to <str> * Email To:
52 --[no-]cc <str> * Email Cc:
53 --[no-]bcc <str> * Email Bcc:
54 --subject <str> * Email "Subject:"
55 --in-reply-to <str> * Email "In-Reply-To:"
56 --annotate * Review each patch that will be sent in an editor.
57 --compose * Open an editor for introduction.
58 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
60 Sending:
61 --envelope-sender <str> * Email envelope sender.
62 --smtp-server <str:int> * Outgoing SMTP server to use. The port
63 is optional. Default 'localhost'.
64 --smtp-server-port <int> * Outgoing SMTP server port.
65 --smtp-user <str> * Username for SMTP-AUTH.
66 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
67 --smtp-encryption <str> * tls or ssl; anything else disables.
68 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
69 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
70 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
72 Automating:
73 --identity <str> * Use the sendemail.<id> options.
74 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
75 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
76 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
77 --[no-]suppress-from * Send to self. Default off.
78 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
79 --[no-]thread * Use In-Reply-To: field. Default on.
81 Administering:
82 --confirm <str> * Confirm recipients before sending;
83 auto, cc, compose, always, or never.
84 --quiet * Output one line of info per email.
85 --dry-run * Don't actually send the emails.
86 --[no-]validate * Perform patch sanity checks. Default on.
87 --[no-]format-patch * understand any non optional arguments as
88 `git format-patch` ones.
89 --force * Send even if safety checks would prevent it.
91 EOT
92 exit(1);
95 # most mail servers generate the Date: header, but not all...
96 sub format_2822_time {
97 my ($time) = @_;
98 my @localtm = localtime($time);
99 my @gmttm = gmtime($time);
100 my $localmin = $localtm[1] + $localtm[2] * 60;
101 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
102 if ($localtm[0] != $gmttm[0]) {
103 die "local zone differs from GMT by a non-minute interval\n";
105 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
106 $localmin += 1440;
107 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
108 $localmin -= 1440;
109 } elsif ($gmttm[6] != $localtm[6]) {
110 die "local time offset greater than or equal to 24 hours\n";
112 my $offset = $localmin - $gmtmin;
113 my $offhour = $offset / 60;
114 my $offmin = abs($offset % 60);
115 if (abs($offhour) >= 24) {
116 die ("local time offset greater than or equal to 24 hours\n");
119 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
120 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
121 $localtm[3],
122 qw(Jan Feb Mar Apr May Jun
123 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
124 $localtm[5]+1900,
125 $localtm[2],
126 $localtm[1],
127 $localtm[0],
128 ($offset >= 0) ? '+' : '-',
129 abs($offhour),
130 $offmin,
134 my $have_email_valid = eval { require Email::Valid; 1 };
135 my $have_mail_address = eval { require Mail::Address; 1 };
136 my $smtp;
137 my $auth;
139 sub unique_email_list(@);
140 sub cleanup_compose_files();
142 # Variables we fill in automatically, or via prompting:
143 my (@to,$no_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, $cc_cmd);
194 my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
195 my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts, $smtp_domain);
196 my ($validate, $confirm);
197 my (@suppress_cc);
198 my ($auto_8bit_encoding);
200 my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
202 my $not_set_by_user = "true but not set by the user";
204 my %config_bool_settings = (
205 "thread" => [\$thread, 1],
206 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
207 "suppressfrom" => [\$suppress_from, undef],
208 "signedoffbycc" => [\$signed_off_by_cc, undef],
209 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
210 "validate" => [\$validate, 1],
213 my %config_settings = (
214 "smtpserver" => \$smtp_server,
215 "smtpserverport" => \$smtp_server_port,
216 "smtpuser" => \$smtp_authuser,
217 "smtppass" => \$smtp_authpass,
218 "smtpdomain" => \$smtp_domain,
219 "to" => \@to,
220 "cc" => \@initial_cc,
221 "cccmd" => \$cc_cmd,
222 "aliasfiletype" => \$aliasfiletype,
223 "bcc" => \@bcclist,
224 "aliasesfile" => \@alias_files,
225 "suppresscc" => \@suppress_cc,
226 "envelopesender" => \$envelope_sender,
227 "multiedit" => \$multiedit,
228 "confirm" => \$confirm,
229 "from" => \$sender,
230 "assume8bitencoding" => \$auto_8bit_encoding,
233 # Help users prepare for 1.7.0
234 sub chain_reply_to {
235 if (defined $chain_reply_to &&
236 $chain_reply_to eq $not_set_by_user) {
237 print STDERR
238 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
239 "Set sendemail.chainreplyto configuration variable to true if\n" .
240 "you want to keep --chain-reply-to as your default.\n";
241 $chain_reply_to = 0;
243 return $chain_reply_to;
246 # Handle Uncouth Termination
247 sub signal_handler {
249 # Make text normal
250 print color("reset"), "\n";
252 # SMTP password masked
253 system "stty echo";
255 # tmp files from --compose
256 if (defined $compose_filename) {
257 if (-e $compose_filename) {
258 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
260 if (-e ($compose_filename . ".final")) {
261 print "'$compose_filename.final' contains the composed email.\n"
265 exit;
268 $SIG{TERM} = \&signal_handler;
269 $SIG{INT} = \&signal_handler;
271 # Begin by accumulating all the variables (defined above), that we will end up
272 # needing, first, from the command line:
274 my $rc = GetOptions("sender|from=s" => \$sender,
275 "in-reply-to=s" => \$initial_reply_to,
276 "subject=s" => \$initial_subject,
277 "to=s" => \@to,
278 "no-to" => \$no_to,
279 "cc=s" => \@initial_cc,
280 "no-cc" => \$no_cc,
281 "bcc=s" => \@bcclist,
282 "no-bcc" => \$no_bcc,
283 "chain-reply-to!" => \$chain_reply_to,
284 "smtp-server=s" => \$smtp_server,
285 "smtp-server-port=s" => \$smtp_server_port,
286 "smtp-user=s" => \$smtp_authuser,
287 "smtp-pass:s" => \$smtp_authpass,
288 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
289 "smtp-encryption=s" => \$smtp_encryption,
290 "smtp-debug:i" => \$debug_net_smtp,
291 "smtp-domain:s" => \$smtp_domain,
292 "identity=s" => \$identity,
293 "annotate" => \$annotate,
294 "compose" => \$compose,
295 "quiet" => \$quiet,
296 "cc-cmd=s" => \$cc_cmd,
297 "suppress-from!" => \$suppress_from,
298 "suppress-cc=s" => \@suppress_cc,
299 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
300 "confirm=s" => \$confirm,
301 "dry-run" => \$dry_run,
302 "envelope-sender=s" => \$envelope_sender,
303 "thread!" => \$thread,
304 "validate!" => \$validate,
305 "format-patch!" => \$format_patch,
306 "8bit-encoding=s" => \$auto_8bit_encoding,
307 "force" => \$force,
310 unless ($rc) {
311 usage();
314 die "Cannot run git format-patch from outside a repository\n"
315 if $format_patch and not $repo;
317 # Now, let's fill any that aren't set in with defaults:
319 sub read_config {
320 my ($prefix) = @_;
322 foreach my $setting (keys %config_bool_settings) {
323 my $target = $config_bool_settings{$setting}->[0];
324 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
327 foreach my $setting (keys %config_settings) {
328 my $target = $config_settings{$setting};
329 next if $setting eq "to" and defined $no_to;
330 next if $setting eq "cc" and defined $no_cc;
331 next if $setting eq "bcc" and defined $no_bcc;
332 if (ref($target) eq "ARRAY") {
333 unless (@$target) {
334 my @values = Git::config(@repo, "$prefix.$setting");
335 @$target = @values if (@values && defined $values[0]);
338 else {
339 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
343 if (!defined $smtp_encryption) {
344 my $enc = Git::config(@repo, "$prefix.smtpencryption");
345 if (defined $enc) {
346 $smtp_encryption = $enc;
347 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
348 $smtp_encryption = 'ssl';
353 # read configuration from [sendemail "$identity"], fall back on [sendemail]
354 $identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
355 read_config("sendemail.$identity") if (defined $identity);
356 read_config("sendemail");
358 # fall back on builtin bool defaults
359 foreach my $setting (values %config_bool_settings) {
360 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
363 # 'default' encryption is none -- this only prevents a warning
364 $smtp_encryption = '' unless (defined $smtp_encryption);
366 # Set CC suppressions
367 my(%suppress_cc);
368 if (@suppress_cc) {
369 foreach my $entry (@suppress_cc) {
370 die "Unknown --suppress-cc field: '$entry'\n"
371 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
372 $suppress_cc{$entry} = 1;
376 if ($suppress_cc{'all'}) {
377 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
378 $suppress_cc{$entry} = 1;
380 delete $suppress_cc{'all'};
383 # If explicit old-style ones are specified, they trump --suppress-cc.
384 $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
385 $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
387 if ($suppress_cc{'body'}) {
388 foreach my $entry (qw (sob bodycc)) {
389 $suppress_cc{$entry} = 1;
391 delete $suppress_cc{'body'};
394 # Set confirm's default value
395 my $confirm_unconfigured = !defined $confirm;
396 if ($confirm_unconfigured) {
397 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
399 die "Unknown --confirm setting: '$confirm'\n"
400 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
402 # Debugging, print out the suppressions.
403 if (0) {
404 print "suppressions:\n";
405 foreach my $entry (keys %suppress_cc) {
406 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
410 my ($repoauthor, $repocommitter);
411 ($repoauthor) = Git::ident_person(@repo, 'author');
412 ($repocommitter) = Git::ident_person(@repo, 'committer');
414 # Verify the user input
416 foreach my $entry (@to) {
417 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
420 foreach my $entry (@initial_cc) {
421 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
424 foreach my $entry (@bcclist) {
425 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
428 sub parse_address_line {
429 if ($have_mail_address) {
430 return map { $_->format } Mail::Address->parse($_[0]);
431 } else {
432 return split_addrs($_[0]);
436 sub split_addrs {
437 return quotewords('\s*,\s*', 1, @_);
440 my %aliases;
441 my %parse_alias = (
442 # multiline formats can be supported in the future
443 mutt => sub { my $fh = shift; while (<$fh>) {
444 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
445 my ($alias, $addr) = ($1, $2);
446 $addr =~ s/#.*$//; # mutt allows # comments
447 # commas delimit multiple addresses
448 $aliases{$alias} = [ split_addrs($addr) ];
449 }}},
450 mailrc => sub { my $fh = shift; while (<$fh>) {
451 if (/^alias\s+(\S+)\s+(.*)$/) {
452 # spaces delimit multiple addresses
453 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
454 }}},
455 pine => sub { my $fh = shift; my $f='\t[^\t]*';
456 for (my $x = ''; defined($x); $x = $_) {
457 chomp $x;
458 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
459 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
460 $aliases{$1} = [ split_addrs($2) ];
462 elm => sub { my $fh = shift;
463 while (<$fh>) {
464 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
465 my ($alias, $addr) = ($1, $2);
466 $aliases{$alias} = [ split_addrs($addr) ];
468 } },
470 gnus => sub { my $fh = shift; while (<$fh>) {
471 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
472 $aliases{$1} = [ $2 ];
476 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
477 foreach my $file (@alias_files) {
478 open my $fh, '<', $file or die "opening $file: $!\n";
479 $parse_alias{$aliasfiletype}->($fh);
480 close $fh;
484 ($sender) = expand_aliases($sender) if defined $sender;
486 # returns 1 if the conflict must be solved using it as a format-patch argument
487 sub check_file_rev_conflict($) {
488 return unless $repo;
489 my $f = shift;
490 try {
491 $repo->command('rev-parse', '--verify', '--quiet', $f);
492 if (defined($format_patch)) {
493 return $format_patch;
495 die(<<EOF);
496 File '$f' exists but it could also be the range of commits
497 to produce patches for. Please disambiguate by...
499 * Saying "./$f" if you mean a file; or
500 * Giving --format-patch option if you mean a range.
502 } catch Git::Error::Command with {
503 return 0;
507 # Now that all the defaults are set, process the rest of the command line
508 # arguments and collect up the files that need to be processed.
509 my @rev_list_opts;
510 while (defined(my $f = shift @ARGV)) {
511 if ($f eq "--") {
512 push @rev_list_opts, "--", @ARGV;
513 @ARGV = ();
514 } elsif (-d $f and !check_file_rev_conflict($f)) {
515 opendir(DH,$f)
516 or die "Failed to opendir $f: $!";
518 push @files, grep { -f $_ } map { +$f . "/" . $_ }
519 sort readdir(DH);
520 closedir(DH);
521 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
522 push @files, $f;
523 } else {
524 push @rev_list_opts, $f;
528 if (@rev_list_opts) {
529 die "Cannot run git format-patch from outside a repository\n"
530 unless $repo;
531 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
534 if ($validate) {
535 foreach my $f (@files) {
536 unless (-p $f) {
537 my $error = validate_patch($f);
538 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
543 if (@files) {
544 unless ($quiet) {
545 print $_,"\n" for (@files);
547 } else {
548 print STDERR "\nNo patch files specified!\n\n";
549 usage();
552 sub get_patch_subject($) {
553 my $fn = shift;
554 open (my $fh, '<', $fn);
555 while (my $line = <$fh>) {
556 next unless ($line =~ /^Subject: (.*)$/);
557 close $fh;
558 return "GIT: $1\n";
560 close $fh;
561 die "No subject line in $fn ?";
564 if ($compose) {
565 # Note that this does not need to be secure, but we will make a small
566 # effort to have it be unique
567 $compose_filename = ($repo ?
568 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
569 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
570 open(C,">",$compose_filename)
571 or die "Failed to open for writing $compose_filename: $!";
574 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
575 my $tpl_subject = $initial_subject || '';
576 my $tpl_reply_to = $initial_reply_to || '';
578 print C <<EOT;
579 From $tpl_sender # This line is ignored.
580 GIT: Lines beginning in "GIT:" will be removed.
581 GIT: Consider including an overall diffstat or table of contents
582 GIT: for the patch you are writing.
583 GIT:
584 GIT: Clear the body content if you don't wish to send a summary.
585 From: $tpl_sender
586 Subject: $tpl_subject
587 In-Reply-To: $tpl_reply_to
590 for my $f (@files) {
591 print C get_patch_subject($f);
593 close(C);
595 if ($annotate) {
596 do_edit($compose_filename, @files);
597 } else {
598 do_edit($compose_filename);
601 open(C2,">",$compose_filename . ".final")
602 or die "Failed to open $compose_filename.final : " . $!;
604 open(C,"<",$compose_filename)
605 or die "Failed to open $compose_filename : " . $!;
607 my $need_8bit_cte = file_has_nonascii($compose_filename);
608 my $in_body = 0;
609 my $summary_empty = 1;
610 while(<C>) {
611 next if m/^GIT:/;
612 if ($in_body) {
613 $summary_empty = 0 unless (/^\n$/);
614 } elsif (/^\n$/) {
615 $in_body = 1;
616 if ($need_8bit_cte) {
617 print C2 "MIME-Version: 1.0\n",
618 "Content-Type: text/plain; ",
619 "charset=UTF-8\n",
620 "Content-Transfer-Encoding: 8bit\n";
622 } elsif (/^MIME-Version:/i) {
623 $need_8bit_cte = 0;
624 } elsif (/^Subject:\s*(.+)\s*$/i) {
625 $initial_subject = $1;
626 my $subject = $initial_subject;
627 $_ = "Subject: " .
628 ($subject =~ /[^[:ascii:]]/ ?
629 quote_rfc2047($subject) :
630 $subject) .
631 "\n";
632 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
633 $initial_reply_to = $1;
634 next;
635 } elsif (/^From:\s*(.+)\s*$/i) {
636 $sender = $1;
637 next;
638 } elsif (/^(?:To|Cc|Bcc):/i) {
639 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
640 next;
642 print C2 $_;
644 close(C);
645 close(C2);
647 if ($summary_empty) {
648 print "Summary email is empty, skipping it\n";
649 $compose = -1;
651 } elsif ($annotate) {
652 do_edit(@files);
655 sub ask {
656 my ($prompt, %arg) = @_;
657 my $valid_re = $arg{valid_re};
658 my $default = $arg{default};
659 my $resp;
660 my $i = 0;
661 return defined $default ? $default : undef
662 unless defined $term->IN and defined fileno($term->IN) and
663 defined $term->OUT and defined fileno($term->OUT);
664 while ($i++ < 10) {
665 $resp = $term->readline($prompt);
666 if (!defined $resp) { # EOF
667 print "\n";
668 return defined $default ? $default : undef;
670 if ($resp eq '' and defined $default) {
671 return $default;
673 if (!defined $valid_re or $resp =~ /$valid_re/) {
674 return $resp;
677 return undef;
680 my %broken_encoding;
682 sub file_declares_8bit_cte($) {
683 my $fn = shift;
684 open (my $fh, '<', $fn);
685 while (my $line = <$fh>) {
686 last if ($line =~ /^$/);
687 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
689 close $fh;
690 return 0;
693 foreach my $f (@files) {
694 next unless (body_or_subject_has_nonascii($f)
695 && !file_declares_8bit_cte($f));
696 $broken_encoding{$f} = 1;
699 if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
700 print "The following files are 8bit, but do not declare " .
701 "a Content-Transfer-Encoding.\n";
702 foreach my $f (sort keys %broken_encoding) {
703 print " $f\n";
705 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
706 default => "UTF-8");
709 if (!$force) {
710 for my $f (@files) {
711 if (get_patch_subject($f) =~ /\*\*\* SUBJECT HERE \*\*\*/) {
712 die "Refusing to send because the patch\n\t$f\n"
713 . "has the template subject '*** SUBJECT HERE ***'. "
714 . "Pass --force if you really want to send.\n";
719 my $prompting = 0;
720 if (!defined $sender) {
721 $sender = $repoauthor || $repocommitter || '';
722 $sender = ask("Who should the emails appear to be from? [$sender] ",
723 default => $sender);
724 print "Emails will be sent from: ", $sender, "\n";
725 $prompting++;
728 if (!@to) {
729 my $to = ask("Who should the emails be sent to? ");
730 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
731 $prompting++;
734 sub expand_aliases {
735 return map { expand_one_alias($_) } @_;
738 my %EXPANDED_ALIASES;
739 sub expand_one_alias {
740 my $alias = shift;
741 if ($EXPANDED_ALIASES{$alias}) {
742 die "fatal: alias '$alias' expands to itself\n";
744 local $EXPANDED_ALIASES{$alias} = 1;
745 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
748 @to = expand_aliases(@to);
749 @to = (map { sanitize_address($_) } @to);
750 @initial_cc = expand_aliases(@initial_cc);
751 @bcclist = expand_aliases(@bcclist);
753 if ($thread && !defined $initial_reply_to && $prompting) {
754 $initial_reply_to = ask(
755 "Message-ID to be used as In-Reply-To for the first email? ");
757 if (defined $initial_reply_to) {
758 $initial_reply_to =~ s/^\s*<?//;
759 $initial_reply_to =~ s/>?\s*$//;
760 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
763 if (!defined $smtp_server) {
764 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
765 if (-x $_) {
766 $smtp_server = $_;
767 last;
770 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
773 if ($compose && $compose > 0) {
774 @files = ($compose_filename . ".final", @files);
777 # Variables we set as part of the loop over files
778 our ($message_id, %mail, $subject, $reply_to, $references, $message,
779 $needs_confirm, $message_num, $ask_default);
781 sub extract_valid_address {
782 my $address = shift;
783 my $local_part_regexp = '[^<>"\s@]+';
784 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
786 # check for a local address:
787 return $address if ($address =~ /^($local_part_regexp)$/);
789 $address =~ s/^\s*<(.*)>\s*$/$1/;
790 if ($have_email_valid) {
791 return scalar Email::Valid->address($address);
792 } else {
793 # less robust/correct than the monster regexp in Email::Valid,
794 # but still does a 99% job, and one less dependency
795 $address =~ /($local_part_regexp\@$domain_regexp)/;
796 return $1;
800 # Usually don't need to change anything below here.
802 # we make a "fake" message id by taking the current number
803 # of seconds since the beginning of Unix time and tacking on
804 # a random number to the end, in case we are called quicker than
805 # 1 second since the last time we were called.
807 # We'll setup a template for the message id, using the "from" address:
809 my ($message_id_stamp, $message_id_serial);
810 sub make_message_id {
811 my $uniq;
812 if (!defined $message_id_stamp) {
813 $message_id_stamp = sprintf("%s-%s", time, $$);
814 $message_id_serial = 0;
816 $message_id_serial++;
817 $uniq = "$message_id_stamp-$message_id_serial";
819 my $du_part;
820 for ($sender, $repocommitter, $repoauthor) {
821 $du_part = extract_valid_address(sanitize_address($_));
822 last if (defined $du_part and $du_part ne '');
824 if (not defined $du_part or $du_part eq '') {
825 use Sys::Hostname qw();
826 $du_part = 'user@' . Sys::Hostname::hostname();
828 my $message_id_template = "<%s-git-send-email-%s>";
829 $message_id = sprintf($message_id_template, $uniq, $du_part);
830 #print "new message id = $message_id\n"; # Was useful for debugging
835 $time = time - scalar $#files;
837 sub unquote_rfc2047 {
838 local ($_) = @_;
839 my $encoding;
840 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
841 $encoding = $1;
842 s/_/ /g;
843 s/=([0-9A-F]{2})/chr(hex($1))/eg;
845 return wantarray ? ($_, $encoding) : $_;
848 sub quote_rfc2047 {
849 local $_ = shift;
850 my $encoding = shift || 'UTF-8';
851 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
852 s/(.*)/=\?$encoding\?q\?$1\?=/;
853 return $_;
856 sub is_rfc2047_quoted {
857 my $s = shift;
858 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
859 my $encoded_text = '[!->@-~]+';
860 length($s) <= 75 &&
861 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
864 # use the simplest quoting being able to handle the recipient
865 sub sanitize_address {
866 my ($recipient) = @_;
867 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
869 if (not $recipient_name) {
870 return "$recipient";
873 # if recipient_name is already quoted, do nothing
874 if (is_rfc2047_quoted($recipient_name)) {
875 return $recipient;
878 # rfc2047 is needed if a non-ascii char is included
879 if ($recipient_name =~ /[^[:ascii:]]/) {
880 $recipient_name =~ s/^"(.*)"$/$1/;
881 $recipient_name = quote_rfc2047($recipient_name);
884 # double quotes are needed if specials or CTLs are included
885 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
886 $recipient_name =~ s/(["\\\r])/\\$1/g;
887 $recipient_name = "\"$recipient_name\"";
890 return "$recipient_name $recipient_addr";
894 # Returns the local Fully Qualified Domain Name (FQDN) if available.
896 # Tightly configured MTAa require that a caller sends a real DNS
897 # domain name that corresponds the IP address in the HELO/EHLO
898 # handshake. This is used to verify the connection and prevent
899 # spammers from trying to hide their identity. If the DNS and IP don't
900 # match, the receiveing MTA may deny the connection.
902 # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
904 # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
905 # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
907 # This maildomain*() code is based on ideas in Perl library Test::Reporter
908 # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
910 sub valid_fqdn {
911 my $domain = shift;
912 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
915 sub maildomain_net {
916 my $maildomain;
918 if (eval { require Net::Domain; 1 }) {
919 my $domain = Net::Domain::domainname();
920 $maildomain = $domain if valid_fqdn($domain);
923 return $maildomain;
926 sub maildomain_mta {
927 my $maildomain;
929 if (eval { require Net::SMTP; 1 }) {
930 for my $host (qw(mailhost localhost)) {
931 my $smtp = Net::SMTP->new($host);
932 if (defined $smtp) {
933 my $domain = $smtp->domain;
934 $smtp->quit;
936 $maildomain = $domain if valid_fqdn($domain);
938 last if $maildomain;
943 return $maildomain;
946 sub maildomain {
947 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
950 # Returns 1 if the message was sent, and 0 otherwise.
951 # In actuality, the whole program dies when there
952 # is an error sending a message.
954 sub send_message {
955 my @recipients = unique_email_list(@to);
956 @cc = (grep { my $cc = extract_valid_address($_);
957 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
959 map { sanitize_address($_) }
960 @cc);
961 my $to = join (",\n\t", @recipients);
962 @recipients = unique_email_list(@recipients,@cc,@bcclist);
963 @recipients = (map { extract_valid_address($_) } @recipients);
964 my $date = format_2822_time($time++);
965 my $gitversion = '@@GIT_VERSION@@';
966 if ($gitversion =~ m/..GIT_VERSION../) {
967 $gitversion = Git::version();
970 my $cc = join(",\n\t", unique_email_list(@cc));
971 my $ccline = "";
972 if ($cc ne '') {
973 $ccline = "\nCc: $cc";
975 my $sanitized_sender = sanitize_address($sender);
976 make_message_id() unless defined($message_id);
978 my $header = "From: $sanitized_sender
979 To: $to${ccline}
980 Subject: $subject
981 Date: $date
982 Message-Id: $message_id
983 X-Mailer: git-send-email $gitversion
985 if ($reply_to) {
987 $header .= "In-Reply-To: $reply_to\n";
988 $header .= "References: $references\n";
990 if (@xh) {
991 $header .= join("\n", @xh) . "\n";
994 my @sendmail_parameters = ('-i', @recipients);
995 my $raw_from = $sanitized_sender;
996 if (defined $envelope_sender && $envelope_sender ne "auto") {
997 $raw_from = $envelope_sender;
999 $raw_from = extract_valid_address($raw_from);
1000 unshift (@sendmail_parameters,
1001 '-f', $raw_from) if(defined $envelope_sender);
1003 if ($needs_confirm && !$dry_run) {
1004 print "\n$header\n";
1005 if ($needs_confirm eq "inform") {
1006 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1007 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1008 print " The Cc list above has been expanded by additional\n";
1009 print " addresses found in the patch commit message. By default\n";
1010 print " send-email prompts before sending whenever this occurs.\n";
1011 print " This behavior is controlled by the sendemail.confirm\n";
1012 print " configuration setting.\n";
1013 print "\n";
1014 print " For additional information, run 'git send-email --help'.\n";
1015 print " To retain the current behavior, but squelch this message,\n";
1016 print " run 'git config --global sendemail.confirm auto'.\n\n";
1018 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1019 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1020 default => $ask_default);
1021 die "Send this email reply required" unless defined $_;
1022 if (/^n/i) {
1023 return 0;
1024 } elsif (/^q/i) {
1025 cleanup_compose_files();
1026 exit(0);
1027 } elsif (/^a/i) {
1028 $confirm = 'never';
1032 if ($dry_run) {
1033 # We don't want to send the email.
1034 } elsif ($smtp_server =~ m#^/#) {
1035 my $pid = open my $sm, '|-';
1036 defined $pid or die $!;
1037 if (!$pid) {
1038 exec($smtp_server, @sendmail_parameters) or die $!;
1040 print $sm "$header\n$message";
1041 close $sm or die $?;
1042 } else {
1044 if (!defined $smtp_server) {
1045 die "The required SMTP server is not properly defined."
1048 if ($smtp_encryption eq 'ssl') {
1049 $smtp_server_port ||= 465; # ssmtp
1050 require Net::SMTP::SSL;
1051 $smtp_domain ||= maildomain();
1052 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1053 Hello => $smtp_domain,
1054 Port => $smtp_server_port);
1056 else {
1057 require Net::SMTP;
1058 $smtp_domain ||= maildomain();
1059 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1060 ? "$smtp_server:$smtp_server_port"
1061 : $smtp_server,
1062 Hello => $smtp_domain,
1063 Debug => $debug_net_smtp);
1064 if ($smtp_encryption eq 'tls' && $smtp) {
1065 require Net::SMTP::SSL;
1066 $smtp->command('STARTTLS');
1067 $smtp->response();
1068 if ($smtp->code == 220) {
1069 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1070 or die "STARTTLS failed! ".$smtp->message;
1071 $smtp_encryption = '';
1072 # Send EHLO again to receive fresh
1073 # supported commands
1074 $smtp->hello();
1075 } else {
1076 die "Server does not support STARTTLS! ".$smtp->message;
1081 if (!$smtp) {
1082 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1083 "VALUES: server=$smtp_server ",
1084 "encryption=$smtp_encryption ",
1085 "hello=$smtp_domain",
1086 defined $smtp_server_port ? "port=$smtp_server_port" : "";
1089 if (defined $smtp_authuser) {
1091 if (!defined $smtp_authpass) {
1093 system "stty -echo";
1095 do {
1096 print "Password: ";
1097 $_ = <STDIN>;
1098 print "\n";
1099 } while (!defined $_);
1101 chomp($smtp_authpass = $_);
1103 system "stty echo";
1106 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
1109 $smtp->mail( $raw_from ) or die $smtp->message;
1110 $smtp->to( @recipients ) or die $smtp->message;
1111 $smtp->data or die $smtp->message;
1112 $smtp->datasend("$header\n$message") or die $smtp->message;
1113 $smtp->dataend() or die $smtp->message;
1114 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1116 if ($quiet) {
1117 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1118 } else {
1119 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1120 if ($smtp_server !~ m#^/#) {
1121 print "Server: $smtp_server\n";
1122 print "MAIL FROM:<$raw_from>\n";
1123 foreach my $entry (@recipients) {
1124 print "RCPT TO:<$entry>\n";
1126 } else {
1127 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1129 print $header, "\n";
1130 if ($smtp) {
1131 print "Result: ", $smtp->code, ' ',
1132 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1133 } else {
1134 print "Result: OK\n";
1138 return 1;
1141 $reply_to = $initial_reply_to;
1142 $references = $initial_reply_to || '';
1143 $subject = $initial_subject;
1144 $message_num = 0;
1146 foreach my $t (@files) {
1147 open(F,"<",$t) or die "can't open file $t";
1149 my $author = undef;
1150 my $author_encoding;
1151 my $has_content_type;
1152 my $body_encoding;
1153 @cc = ();
1154 @xh = ();
1155 my $input_format = undef;
1156 my @header = ();
1157 $message = "";
1158 $message_num++;
1159 # First unfold multiline header fields
1160 while(<F>) {
1161 last if /^\s*$/;
1162 if (/^\s+\S/ and @header) {
1163 chomp($header[$#header]);
1164 s/^\s+/ /;
1165 $header[$#header] .= $_;
1166 } else {
1167 push(@header, $_);
1170 # Now parse the header
1171 foreach(@header) {
1172 if (/^From /) {
1173 $input_format = 'mbox';
1174 next;
1176 chomp;
1177 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1178 $input_format = 'mbox';
1181 if (defined $input_format && $input_format eq 'mbox') {
1182 if (/^Subject:\s+(.*)$/) {
1183 $subject = $1;
1185 elsif (/^From:\s+(.*)$/) {
1186 ($author, $author_encoding) = unquote_rfc2047($1);
1187 next if $suppress_cc{'author'};
1188 next if $suppress_cc{'self'} and $author eq $sender;
1189 printf("(mbox) Adding cc: %s from line '%s'\n",
1190 $1, $_) unless $quiet;
1191 push @cc, $1;
1193 elsif (/^Cc:\s+(.*)$/) {
1194 foreach my $addr (parse_address_line($1)) {
1195 if (unquote_rfc2047($addr) eq $sender) {
1196 next if ($suppress_cc{'self'});
1197 } else {
1198 next if ($suppress_cc{'cc'});
1200 printf("(mbox) Adding cc: %s from line '%s'\n",
1201 $addr, $_) unless $quiet;
1202 push @cc, $addr;
1205 elsif (/^Content-type:/i) {
1206 $has_content_type = 1;
1207 if (/charset="?([^ "]+)/) {
1208 $body_encoding = $1;
1210 push @xh, $_;
1212 elsif (/^Message-Id: (.*)/i) {
1213 $message_id = $1;
1215 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1216 push @xh, $_;
1219 } else {
1220 # In the traditional
1221 # "send lots of email" format,
1222 # line 1 = cc
1223 # line 2 = subject
1224 # So let's support that, too.
1225 $input_format = 'lots';
1226 if (@cc == 0 && !$suppress_cc{'cc'}) {
1227 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1228 $_, $_) unless $quiet;
1229 push @cc, $_;
1230 } elsif (!defined $subject) {
1231 $subject = $_;
1235 # Now parse the message body
1236 while(<F>) {
1237 $message .= $_;
1238 if (/^(Signed-off-by|Cc): (.*)$/i) {
1239 chomp;
1240 my ($what, $c) = ($1, $2);
1241 chomp $c;
1242 if ($c eq $sender) {
1243 next if ($suppress_cc{'self'});
1244 } else {
1245 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1246 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1248 push @cc, $c;
1249 printf("(body) Adding cc: %s from line '%s'\n",
1250 $c, $_) unless $quiet;
1253 close F;
1255 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1256 open(F, "$cc_cmd \Q$t\E |")
1257 or die "(cc-cmd) Could not execute '$cc_cmd'";
1258 while(<F>) {
1259 my $c = $_;
1260 $c =~ s/^\s*//g;
1261 $c =~ s/\n$//g;
1262 next if ($c eq $sender and $suppress_from);
1263 push @cc, $c;
1264 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1265 $c, $cc_cmd) unless $quiet;
1267 close F
1268 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1271 if ($broken_encoding{$t} && !$has_content_type) {
1272 $has_content_type = 1;
1273 push @xh, "MIME-Version: 1.0",
1274 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1275 "Content-Transfer-Encoding: 8bit";
1276 $body_encoding = $auto_8bit_encoding;
1279 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1280 $subject = quote_rfc2047($subject, $auto_8bit_encoding);
1283 if (defined $author and $author ne $sender) {
1284 $message = "From: $author\n\n$message";
1285 if (defined $author_encoding) {
1286 if ($has_content_type) {
1287 if ($body_encoding eq $author_encoding) {
1288 # ok, we already have the right encoding
1290 else {
1291 # uh oh, we should re-encode
1294 else {
1295 $has_content_type = 1;
1296 push @xh,
1297 'MIME-Version: 1.0',
1298 "Content-Type: text/plain; charset=$author_encoding",
1299 'Content-Transfer-Encoding: 8bit';
1304 $needs_confirm = (
1305 $confirm eq "always" or
1306 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1307 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1308 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1310 @cc = (@initial_cc, @cc);
1312 my $message_was_sent = send_message();
1314 # set up for the next message
1315 if ($thread && $message_was_sent &&
1316 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
1317 $reply_to = $message_id;
1318 if (length $references > 0) {
1319 $references .= "\n $message_id";
1320 } else {
1321 $references = "$message_id";
1324 $message_id = undef;
1327 cleanup_compose_files();
1329 sub cleanup_compose_files() {
1330 unlink($compose_filename, $compose_filename . ".final") if $compose;
1333 $smtp->quit if $smtp;
1335 sub unique_email_list(@) {
1336 my %seen;
1337 my @emails;
1339 foreach my $entry (@_) {
1340 if (my $clean = extract_valid_address($entry)) {
1341 $seen{$clean} ||= 0;
1342 next if $seen{$clean}++;
1343 push @emails, $entry;
1344 } else {
1345 print STDERR "W: unable to extract a valid address",
1346 " from: $entry\n";
1349 return @emails;
1352 sub validate_patch {
1353 my $fn = shift;
1354 open(my $fh, '<', $fn)
1355 or die "unable to open $fn: $!\n";
1356 while (my $line = <$fh>) {
1357 if (length($line) > 998) {
1358 return "$.: patch contains a line longer than 998 characters";
1361 return undef;
1364 sub file_has_nonascii {
1365 my $fn = shift;
1366 open(my $fh, '<', $fn)
1367 or die "unable to open $fn: $!\n";
1368 while (my $line = <$fh>) {
1369 return 1 if $line =~ /[^[:ascii:]]/;
1371 return 0;
1374 sub body_or_subject_has_nonascii {
1375 my $fn = shift;
1376 open(my $fh, '<', $fn)
1377 or die "unable to open $fn: $!\n";
1378 while (my $line = <$fh>) {
1379 last if $line =~ /^$/;
1380 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1382 while (my $line = <$fh>) {
1383 return 1 if $line =~ /[^[:ascii:]]/;
1385 return 0;