git-send-email.perlon commit Makefile: introduce NO_PTHREADS (46059cc)
   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; my $f='\t[^\t]*';
 378                for (my $x = ''; defined($x); $x = $_) {
 379                        chomp $x;
 380                        $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
 381                        $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
 382                        $aliases{$1} = [ split(/\s*,\s*/, $2) ];
 383                }},
 384        gnus => sub { my $fh = shift; while (<$fh>) {
 385                if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
 386                        $aliases{$1} = [ $2 ];
 387                }}}
 388);
 389
 390if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
 391        foreach my $file (@alias_files) {
 392                open my $fh, '<', $file or die "opening $file: $!\n";
 393                $parse_alias{$aliasfiletype}->($fh);
 394                close $fh;
 395        }
 396}
 397
 398($sender) = expand_aliases($sender) if defined $sender;
 399
 400# returns 1 if the conflict must be solved using it as a format-patch argument
 401sub check_file_rev_conflict($) {
 402        my $f = shift;
 403        try {
 404                $repo->command('rev-parse', '--verify', '--quiet', $f);
 405                if (defined($format_patch)) {
 406                        print "foo\n";
 407                        return $format_patch;
 408                }
 409                die(<<EOF);
 410File '$f' exists but it could also be the range of commits
 411to produce patches for.  Please disambiguate by...
 412
 413    * Saying "./$f" if you mean a file; or
 414    * Giving --format-patch option if you mean a range.
 415EOF
 416        } catch Git::Error::Command with {
 417                return 0;
 418        }
 419}
 420
 421# Now that all the defaults are set, process the rest of the command line
 422# arguments and collect up the files that need to be processed.
 423my @rev_list_opts;
 424while (defined(my $f = shift @ARGV)) {
 425        if ($f eq "--") {
 426                push @rev_list_opts, "--", @ARGV;
 427                @ARGV = ();
 428        } elsif (-d $f and !check_file_rev_conflict($f)) {
 429                opendir(DH,$f)
 430                        or die "Failed to opendir $f: $!";
 431
 432                push @files, grep { -f $_ } map { +$f . "/" . $_ }
 433                                sort readdir(DH);
 434                closedir(DH);
 435        } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
 436                push @files, $f;
 437        } else {
 438                push @rev_list_opts, $f;
 439        }
 440}
 441
 442if (@rev_list_opts) {
 443        push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
 444}
 445
 446if ($validate) {
 447        foreach my $f (@files) {
 448                unless (-p $f) {
 449                        my $error = validate_patch($f);
 450                        $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
 451                }
 452        }
 453}
 454
 455if (@files) {
 456        unless ($quiet) {
 457                print $_,"\n" for (@files);
 458        }
 459} else {
 460        print STDERR "\nNo patch files specified!\n\n";
 461        usage();
 462}
 463
 464sub get_patch_subject($) {
 465        my $fn = shift;
 466        open (my $fh, '<', $fn);
 467        while (my $line = <$fh>) {
 468                next unless ($line =~ /^Subject: (.*)$/);
 469                close $fh;
 470                return "GIT: $1\n";
 471        }
 472        close $fh;
 473        die "No subject line in $fn ?";
 474}
 475
 476if ($compose) {
 477        # Note that this does not need to be secure, but we will make a small
 478        # effort to have it be unique
 479        open(C,">",$compose_filename)
 480                or die "Failed to open for writing $compose_filename: $!";
 481
 482
 483        my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
 484        my $tpl_subject = $initial_subject || '';
 485        my $tpl_reply_to = $initial_reply_to || '';
 486
 487        print C <<EOT;
 488From $tpl_sender # This line is ignored.
 489GIT: Lines beginning in "GIT: " will be removed.
 490GIT: Consider including an overall diffstat or table of contents
 491GIT: for the patch you are writing.
 492GIT:
 493GIT: Clear the body content if you don't wish to send a summary.
 494From: $tpl_sender
 495Subject: $tpl_subject
 496In-Reply-To: $tpl_reply_to
 497
 498EOT
 499        for my $f (@files) {
 500                print C get_patch_subject($f);
 501        }
 502        close(C);
 503
 504        my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
 505
 506        if ($annotate) {
 507                do_edit($compose_filename, @files);
 508        } else {
 509                do_edit($compose_filename);
 510        }
 511
 512        open(C2,">",$compose_filename . ".final")
 513                or die "Failed to open $compose_filename.final : " . $!;
 514
 515        open(C,"<",$compose_filename)
 516                or die "Failed to open $compose_filename : " . $!;
 517
 518        my $need_8bit_cte = file_has_nonascii($compose_filename);
 519        my $in_body = 0;
 520        my $summary_empty = 1;
 521        while(<C>) {
 522                next if m/^GIT: /;
 523                if ($in_body) {
 524                        $summary_empty = 0 unless (/^\n$/);
 525                } elsif (/^\n$/) {
 526                        $in_body = 1;
 527                        if ($need_8bit_cte) {
 528                                print C2 "MIME-Version: 1.0\n",
 529                                         "Content-Type: text/plain; ",
 530                                           "charset=utf-8\n",
 531                                         "Content-Transfer-Encoding: 8bit\n";
 532                        }
 533                } elsif (/^MIME-Version:/i) {
 534                        $need_8bit_cte = 0;
 535                } elsif (/^Subject:\s*(.+)\s*$/i) {
 536                        $initial_subject = $1;
 537                        my $subject = $initial_subject;
 538                        $_ = "Subject: " .
 539                                ($subject =~ /[^[:ascii:]]/ ?
 540                                 quote_rfc2047($subject) :
 541                                 $subject) .
 542                                "\n";
 543                } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
 544                        $initial_reply_to = $1;
 545                        next;
 546                } elsif (/^From:\s*(.+)\s*$/i) {
 547                        $sender = $1;
 548                        next;
 549                } elsif (/^(?:To|Cc|Bcc):/i) {
 550                        print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
 551                        next;
 552                }
 553                print C2 $_;
 554        }
 555        close(C);
 556        close(C2);
 557
 558        if ($summary_empty) {
 559                print "Summary email is empty, skipping it\n";
 560                $compose = -1;
 561        }
 562} elsif ($annotate) {
 563        do_edit(@files);
 564}
 565
 566my $prompting = 0;
 567if (!defined $sender) {
 568        $sender = $repoauthor || $repocommitter || '';
 569
 570        while (1) {
 571                $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
 572                last if defined $_;
 573                print "\n";
 574        }
 575
 576        $sender = $_ if ($_);
 577        print "Emails will be sent from: ", $sender, "\n";
 578        $prompting++;
 579}
 580
 581if (!@to) {
 582
 583
 584        while (1) {
 585                $_ = $term->readline("Who should the emails be sent to? ", "");
 586                last if defined $_;
 587                print "\n";
 588        }
 589
 590        my $to = $_;
 591        push @to, split /,\s*/, $to;
 592        $prompting++;
 593}
 594
 595sub expand_aliases {
 596        my @cur = @_;
 597        my @last;
 598        do {
 599                @last = @cur;
 600                @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
 601        } while (join(',',@cur) ne join(',',@last));
 602        return @cur;
 603}
 604
 605@to = expand_aliases(@to);
 606@to = (map { sanitize_address($_) } @to);
 607@initial_cc = expand_aliases(@initial_cc);
 608@bcclist = expand_aliases(@bcclist);
 609
 610if ($thread && !defined $initial_reply_to && $prompting) {
 611        while (1) {
 612                $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
 613                last if defined $_;
 614                print "\n";
 615        }
 616
 617        $initial_reply_to = $_;
 618}
 619if (defined $initial_reply_to) {
 620        $initial_reply_to =~ s/^\s*<?//;
 621        $initial_reply_to =~ s/>?\s*$//;
 622        $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
 623}
 624
 625if (!defined $smtp_server) {
 626        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
 627                if (-x $_) {
 628                        $smtp_server = $_;
 629                        last;
 630                }
 631        }
 632        $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
 633}
 634
 635if ($compose) {
 636        while (1) {
 637                $_ = $term->readline("Send this email? (y|n) ");
 638                last if defined $_;
 639                print "\n";
 640        }
 641
 642        if (uc substr($_,0,1) ne 'Y') {
 643                cleanup_compose_files();
 644                exit(0);
 645        }
 646
 647        if ($compose > 0) {
 648                @files = ($compose_filename . ".final", @files);
 649        }
 650}
 651
 652# Variables we set as part of the loop over files
 653our ($message_id, %mail, $subject, $reply_to, $references, $message);
 654
 655sub extract_valid_address {
 656        my $address = shift;
 657        my $local_part_regexp = '[^<>"\s@]+';
 658        my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
 659
 660        # check for a local address:
 661        return $address if ($address =~ /^($local_part_regexp)$/);
 662
 663        $address =~ s/^\s*<(.*)>\s*$/$1/;
 664        if ($have_email_valid) {
 665                return scalar Email::Valid->address($address);
 666        } else {
 667                # less robust/correct than the monster regexp in Email::Valid,
 668                # but still does a 99% job, and one less dependency
 669                $address =~ /($local_part_regexp\@$domain_regexp)/;
 670                return $1;
 671        }
 672}
 673
 674# Usually don't need to change anything below here.
 675
 676# we make a "fake" message id by taking the current number
 677# of seconds since the beginning of Unix time and tacking on
 678# a random number to the end, in case we are called quicker than
 679# 1 second since the last time we were called.
 680
 681# We'll setup a template for the message id, using the "from" address:
 682
 683my ($message_id_stamp, $message_id_serial);
 684sub make_message_id
 685{
 686        my $uniq;
 687        if (!defined $message_id_stamp) {
 688                $message_id_stamp = sprintf("%s-%s", time, $$);
 689                $message_id_serial = 0;
 690        }
 691        $message_id_serial++;
 692        $uniq = "$message_id_stamp-$message_id_serial";
 693
 694        my $du_part;
 695        for ($sender, $repocommitter, $repoauthor) {
 696                $du_part = extract_valid_address(sanitize_address($_));
 697                last if (defined $du_part and $du_part ne '');
 698        }
 699        if (not defined $du_part or $du_part eq '') {
 700                use Sys::Hostname qw();
 701                $du_part = 'user@' . Sys::Hostname::hostname();
 702        }
 703        my $message_id_template = "<%s-git-send-email-%s>";
 704        $message_id = sprintf($message_id_template, $uniq, $du_part);
 705        #print "new message id = $message_id\n"; # Was useful for debugging
 706}
 707
 708
 709
 710$time = time - scalar $#files;
 711
 712sub unquote_rfc2047 {
 713        local ($_) = @_;
 714        my $encoding;
 715        if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
 716                $encoding = $1;
 717                s/_/ /g;
 718                s/=([0-9A-F]{2})/chr(hex($1))/eg;
 719        }
 720        return wantarray ? ($_, $encoding) : $_;
 721}
 722
 723sub quote_rfc2047 {
 724        local $_ = shift;
 725        my $encoding = shift || 'utf-8';
 726        s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
 727        s/(.*)/=\?$encoding\?q\?$1\?=/;
 728        return $_;
 729}
 730
 731# use the simplest quoting being able to handle the recipient
 732sub sanitize_address
 733{
 734        my ($recipient) = @_;
 735        my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
 736
 737        if (not $recipient_name) {
 738                return "$recipient";
 739        }
 740
 741        # if recipient_name is already quoted, do nothing
 742        if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
 743                return $recipient;
 744        }
 745
 746        # rfc2047 is needed if a non-ascii char is included
 747        if ($recipient_name =~ /[^[:ascii:]]/) {
 748                $recipient_name = quote_rfc2047($recipient_name);
 749        }
 750
 751        # double quotes are needed if specials or CTLs are included
 752        elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
 753                $recipient_name =~ s/(["\\\r])/\\$1/g;
 754                $recipient_name = "\"$recipient_name\"";
 755        }
 756
 757        return "$recipient_name $recipient_addr";
 758
 759}
 760
 761sub send_message
 762{
 763        my @recipients = unique_email_list(@to);
 764        @cc = (grep { my $cc = extract_valid_address($_);
 765                      not grep { $cc eq $_ } @recipients
 766                    }
 767               map { sanitize_address($_) }
 768               @cc);
 769        my $to = join (",\n\t", @recipients);
 770        @recipients = unique_email_list(@recipients,@cc,@bcclist);
 771        @recipients = (map { extract_valid_address($_) } @recipients);
 772        my $date = format_2822_time($time++);
 773        my $gitversion = '@@GIT_VERSION@@';
 774        if ($gitversion =~ m/..GIT_VERSION../) {
 775            $gitversion = Git::version();
 776        }
 777
 778        my $cc = join(", ", unique_email_list(@cc));
 779        my $ccline = "";
 780        if ($cc ne '') {
 781                $ccline = "\nCc: $cc";
 782        }
 783        my $sanitized_sender = sanitize_address($sender);
 784        make_message_id() unless defined($message_id);
 785
 786        my $header = "From: $sanitized_sender
 787To: $to${ccline}
 788Subject: $subject
 789Date: $date
 790Message-Id: $message_id
 791X-Mailer: git-send-email $gitversion
 792";
 793        if ($thread && $reply_to) {
 794
 795                $header .= "In-Reply-To: $reply_to\n";
 796                $header .= "References: $references\n";
 797        }
 798        if (@xh) {
 799                $header .= join("\n", @xh) . "\n";
 800        }
 801
 802        my @sendmail_parameters = ('-i', @recipients);
 803        my $raw_from = $sanitized_sender;
 804        $raw_from = $envelope_sender if (defined $envelope_sender);
 805        $raw_from = extract_valid_address($raw_from);
 806        unshift (@sendmail_parameters,
 807                        '-f', $raw_from) if(defined $envelope_sender);
 808
 809        if ($dry_run) {
 810                # We don't want to send the email.
 811        } elsif ($smtp_server =~ m#^/#) {
 812                my $pid = open my $sm, '|-';
 813                defined $pid or die $!;
 814                if (!$pid) {
 815                        exec($smtp_server, @sendmail_parameters) or die $!;
 816                }
 817                print $sm "$header\n$message";
 818                close $sm or die $?;
 819        } else {
 820
 821                if (!defined $smtp_server) {
 822                        die "The required SMTP server is not properly defined."
 823                }
 824
 825                if ($smtp_encryption eq 'ssl') {
 826                        $smtp_server_port ||= 465; # ssmtp
 827                        require Net::SMTP::SSL;
 828                        $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
 829                }
 830                else {
 831                        require Net::SMTP;
 832                        $smtp ||= Net::SMTP->new((defined $smtp_server_port)
 833                                                 ? "$smtp_server:$smtp_server_port"
 834                                                 : $smtp_server);
 835                        if ($smtp_encryption eq 'tls') {
 836                                require Net::SMTP::SSL;
 837                                $smtp->command('STARTTLS');
 838                                $smtp->response();
 839                                if ($smtp->code == 220) {
 840                                        $smtp = Net::SMTP::SSL->start_SSL($smtp)
 841                                                or die "STARTTLS failed! ".$smtp->message;
 842                                        $smtp_encryption = '';
 843                                        # Send EHLO again to receive fresh
 844                                        # supported commands
 845                                        $smtp->hello();
 846                                } else {
 847                                        die "Server does not support STARTTLS! ".$smtp->message;
 848                                }
 849                        }
 850                }
 851
 852                if (!$smtp) {
 853                        die "Unable to initialize SMTP properly.  Is there something wrong with your config?";
 854                }
 855
 856                if (defined $smtp_authuser) {
 857
 858                        if (!defined $smtp_authpass) {
 859
 860                                system "stty -echo";
 861
 862                                do {
 863                                        print "Password: ";
 864                                        $_ = <STDIN>;
 865                                        print "\n";
 866                                } while (!defined $_);
 867
 868                                chomp($smtp_authpass = $_);
 869
 870                                system "stty echo";
 871                        }
 872
 873                        $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
 874                }
 875
 876                $smtp->mail( $raw_from ) or die $smtp->message;
 877                $smtp->to( @recipients ) or die $smtp->message;
 878                $smtp->data or die $smtp->message;
 879                $smtp->datasend("$header\n$message") or die $smtp->message;
 880                $smtp->dataend() or die $smtp->message;
 881                $smtp->ok or die "Failed to send $subject\n".$smtp->message;
 882        }
 883        if ($quiet) {
 884                printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
 885        } else {
 886                print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
 887                if ($smtp_server !~ m#^/#) {
 888                        print "Server: $smtp_server\n";
 889                        print "MAIL FROM:<$raw_from>\n";
 890                        print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
 891                } else {
 892                        print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
 893                }
 894                print $header, "\n";
 895                if ($smtp) {
 896                        print "Result: ", $smtp->code, ' ',
 897                                ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
 898                } else {
 899                        print "Result: OK\n";
 900                }
 901        }
 902}
 903
 904$reply_to = $initial_reply_to;
 905$references = $initial_reply_to || '';
 906$subject = $initial_subject;
 907
 908foreach my $t (@files) {
 909        open(F,"<",$t) or die "can't open file $t";
 910
 911        my $author = undef;
 912        my $author_encoding;
 913        my $has_content_type;
 914        my $body_encoding;
 915        @cc = @initial_cc;
 916        @xh = ();
 917        my $input_format = undef;
 918        my $header_done = 0;
 919        $message = "";
 920        while(<F>) {
 921                if (!$header_done) {
 922                        if (/^From /) {
 923                                $input_format = 'mbox';
 924                                next;
 925                        }
 926                        chomp;
 927                        if (!defined $input_format && /^[-A-Za-z]+:\s/) {
 928                                $input_format = 'mbox';
 929                        }
 930
 931                        if (defined $input_format && $input_format eq 'mbox') {
 932                                if (/^Subject:\s+(.*)$/) {
 933                                        $subject = $1;
 934
 935                                } elsif (/^(Cc|From):\s+(.*)$/) {
 936                                        if (unquote_rfc2047($2) eq $sender) {
 937                                                next if ($suppress_cc{'self'});
 938                                        }
 939                                        elsif ($1 eq 'From') {
 940                                                ($author, $author_encoding)
 941                                                  = unquote_rfc2047($2);
 942                                                next if ($suppress_cc{'author'});
 943                                        } else {
 944                                                next if ($suppress_cc{'cc'});
 945                                        }
 946                                        printf("(mbox) Adding cc: %s from line '%s'\n",
 947                                                $2, $_) unless $quiet;
 948                                        push @cc, $2;
 949                                }
 950                                elsif (/^Content-type:/i) {
 951                                        $has_content_type = 1;
 952                                        if (/charset="?([^ "]+)/) {
 953                                                $body_encoding = $1;
 954                                        }
 955                                        push @xh, $_;
 956                                }
 957                                elsif (/^Message-Id: (.*)/i) {
 958                                        $message_id = $1;
 959                                }
 960                                elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
 961                                        push @xh, $_;
 962                                }
 963
 964                        } else {
 965                                # In the traditional
 966                                # "send lots of email" format,
 967                                # line 1 = cc
 968                                # line 2 = subject
 969                                # So let's support that, too.
 970                                $input_format = 'lots';
 971                                if (@cc == 0 && !$suppress_cc{'cc'}) {
 972                                        printf("(non-mbox) Adding cc: %s from line '%s'\n",
 973                                                $_, $_) unless $quiet;
 974
 975                                        push @cc, $_;
 976
 977                                } elsif (!defined $subject) {
 978                                        $subject = $_;
 979                                }
 980                        }
 981
 982                        # A whitespace line will terminate the headers
 983                        if (m/^\s*$/) {
 984                                $header_done = 1;
 985                        }
 986                } else {
 987                        $message .=  $_;
 988                        if (/^(Signed-off-by|Cc): (.*)$/i) {
 989                                next if ($suppress_cc{'sob'});
 990                                chomp;
 991                                my $c = $2;
 992                                chomp $c;
 993                                next if ($c eq $sender and $suppress_cc{'self'});
 994                                push @cc, $c;
 995                                printf("(sob) Adding cc: %s from line '%s'\n",
 996                                        $c, $_) unless $quiet;
 997                        }
 998                }
 999        }
1000        close F;
1001
1002        if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
1003                open(F, "$cc_cmd $t |")
1004                        or die "(cc-cmd) Could not execute '$cc_cmd'";
1005                while(<F>) {
1006                        my $c = $_;
1007                        $c =~ s/^\s*//g;
1008                        $c =~ s/\n$//g;
1009                        next if ($c eq $sender and $suppress_from);
1010                        push @cc, $c;
1011                        printf("(cc-cmd) Adding cc: %s from: '%s'\n",
1012                                $c, $cc_cmd) unless $quiet;
1013                }
1014                close F
1015                        or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
1016        }
1017
1018        if (defined $author) {
1019                $message = "From: $author\n\n$message";
1020                if (defined $author_encoding) {
1021                        if ($has_content_type) {
1022                                if ($body_encoding eq $author_encoding) {
1023                                        # ok, we already have the right encoding
1024                                }
1025                                else {
1026                                        # uh oh, we should re-encode
1027                                }
1028                        }
1029                        else {
1030                                push @xh,
1031                                  'MIME-Version: 1.0',
1032                                  "Content-Type: text/plain; charset=$author_encoding",
1033                                  'Content-Transfer-Encoding: 8bit';
1034                        }
1035                }
1036        }
1037
1038        send_message();
1039
1040        # set up for the next message
1041        if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
1042                $reply_to = $message_id;
1043                if (length $references > 0) {
1044                        $references .= "\n $message_id";
1045                } else {
1046                        $references = "$message_id";
1047                }
1048        }
1049        $message_id = undef;
1050}
1051
1052if ($compose) {
1053        cleanup_compose_files();
1054}
1055
1056sub cleanup_compose_files() {
1057        unlink($compose_filename, $compose_filename . ".final");
1058
1059}
1060
1061$smtp->quit if $smtp;
1062
1063sub unique_email_list(@) {
1064        my %seen;
1065        my @emails;
1066
1067        foreach my $entry (@_) {
1068                if (my $clean = extract_valid_address($entry)) {
1069                        $seen{$clean} ||= 0;
1070                        next if $seen{$clean}++;
1071                        push @emails, $entry;
1072                } else {
1073                        print STDERR "W: unable to extract a valid address",
1074                                        " from: $entry\n";
1075                }
1076        }
1077        return @emails;
1078}
1079
1080sub validate_patch {
1081        my $fn = shift;
1082        open(my $fh, '<', $fn)
1083                or die "unable to open $fn: $!\n";
1084        while (my $line = <$fh>) {
1085                if (length($line) > 998) {
1086                        return "$.: patch contains a line longer than 998 characters";
1087                }
1088        }
1089        return undef;
1090}
1091
1092sub file_has_nonascii {
1093        my $fn = shift;
1094        open(my $fh, '<', $fn)
1095                or die "unable to open $fn: $!\n";
1096        while (my $line = <$fh>) {
1097                return 1 if $line =~ /[^[:ascii:]]/;
1098        }
1099        return 0;
1100}