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