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