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