Code

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