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