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