git-send-email.perlon commit send-email: ask confirmation if given encoding name is very short (852a15d)
   1#!/usr/bin/perl
   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 5.008;
  20use strict;
  21use warnings;
  22use Term::ReadLine;
  23use Getopt::Long;
  24use Text::ParseWords;
  25use Data::Dumper;
  26use Term::ANSIColor;
  27use File::Temp qw/ tempdir tempfile /;
  28use File::Spec::Functions qw(catfile);
  29use Error qw(:try);
  30use Git;
  31
  32Getopt::Long::Configure qw/ pass_through /;
  33
  34package FakeTerm;
  35sub new {
  36        my ($class, $reason) = @_;
  37        return bless \$reason, shift;
  38}
  39sub readline {
  40        my $self = shift;
  41        die "Cannot use readline on FakeTerm: $$self";
  42}
  43package main;
  44
  45
  46sub usage {
  47        print <<EOT;
  48git send-email [options] <file | directory | rev-list options >
  49
  50  Composing:
  51    --from                  <str>  * Email From:
  52    --[no-]to               <str>  * Email To:
  53    --[no-]cc               <str>  * Email Cc:
  54    --[no-]bcc              <str>  * Email Bcc:
  55    --subject               <str>  * Email "Subject:"
  56    --in-reply-to           <str>  * Email "In-Reply-To:"
  57    --[no-]annotate                * Review each patch that will be sent in an editor.
  58    --compose                      * Open an editor for introduction.
  59    --compose-encoding      <str>  * Encoding to assume for introduction.
  60    --8bit-encoding         <str>  * Encoding to assume 8bit mails if undeclared
  61
  62  Sending:
  63    --envelope-sender       <str>  * Email envelope sender.
  64    --smtp-server       <str:int>  * Outgoing SMTP server to use. The port
  65                                     is optional. Default 'localhost'.
  66    --smtp-server-option    <str>  * Outgoing SMTP server option to use.
  67    --smtp-server-port      <int>  * Outgoing SMTP server port.
  68    --smtp-user             <str>  * Username for SMTP-AUTH.
  69    --smtp-pass             <str>  * Password for SMTP-AUTH; not necessary.
  70    --smtp-encryption       <str>  * tls or ssl; anything else disables.
  71    --smtp-ssl                     * Deprecated. Use '--smtp-encryption ssl'.
  72    --smtp-ssl-cert-path    <str>  * Path to ca-certificates (either directory or file).
  73                                     Pass an empty string to disable certificate
  74                                     verification.
  75    --smtp-domain           <str>  * The domain name sent to HELO/EHLO handshake
  76    --smtp-debug            <0|1>  * Disable, enable Net::SMTP debug.
  77
  78  Automating:
  79    --identity              <str>  * Use the sendemail.<id> options.
  80    --to-cmd                <str>  * Email To: via `<str> \$patch_path`
  81    --cc-cmd                <str>  * Email Cc: via `<str> \$patch_path`
  82    --suppress-cc           <str>  * author, self, sob, cc, cccmd, body, bodycc, all.
  83    --[no-]signed-off-by-cc        * Send to Signed-off-by: addresses. Default on.
  84    --[no-]suppress-from           * Send to self. Default off.
  85    --[no-]chain-reply-to          * Chain In-Reply-To: fields. Default off.
  86    --[no-]thread                  * Use In-Reply-To: field. Default on.
  87
  88  Administering:
  89    --confirm               <str>  * Confirm recipients before sending;
  90                                     auto, cc, compose, always, or never.
  91    --quiet                        * Output one line of info per email.
  92    --dry-run                      * Don't actually send the emails.
  93    --[no-]validate                * Perform patch sanity checks. Default on.
  94    --[no-]format-patch            * understand any non optional arguments as
  95                                     `git format-patch` ones.
  96    --force                        * Send even if safety checks would prevent it.
  97
  98EOT
  99        exit(1);
 100}
 101
 102# most mail servers generate the Date: header, but not all...
 103sub format_2822_time {
 104        my ($time) = @_;
 105        my @localtm = localtime($time);
 106        my @gmttm = gmtime($time);
 107        my $localmin = $localtm[1] + $localtm[2] * 60;
 108        my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
 109        if ($localtm[0] != $gmttm[0]) {
 110                die "local zone differs from GMT by a non-minute interval\n";
 111        }
 112        if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
 113                $localmin += 1440;
 114        } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
 115                $localmin -= 1440;
 116        } elsif ($gmttm[6] != $localtm[6]) {
 117                die "local time offset greater than or equal to 24 hours\n";
 118        }
 119        my $offset = $localmin - $gmtmin;
 120        my $offhour = $offset / 60;
 121        my $offmin = abs($offset % 60);
 122        if (abs($offhour) >= 24) {
 123                die ("local time offset greater than or equal to 24 hours\n");
 124        }
 125
 126        return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
 127                       qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
 128                       $localtm[3],
 129                       qw(Jan Feb Mar Apr May Jun
 130                          Jul Aug Sep Oct Nov Dec)[$localtm[4]],
 131                       $localtm[5]+1900,
 132                       $localtm[2],
 133                       $localtm[1],
 134                       $localtm[0],
 135                       ($offset >= 0) ? '+' : '-',
 136                       abs($offhour),
 137                       $offmin,
 138                       );
 139}
 140
 141my $have_email_valid = eval { require Email::Valid; 1 };
 142my $have_mail_address = eval { require Mail::Address; 1 };
 143my $smtp;
 144my $auth;
 145
 146# Variables we fill in automatically, or via prompting:
 147my (@to,$no_to,@initial_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
 148        $initial_reply_to,$initial_subject,@files,
 149        $author,$sender,$smtp_authpass,$annotate,$compose,$time);
 150
 151my $envelope_sender;
 152
 153# Example reply to:
 154#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
 155
 156my $repo = eval { Git->repository() };
 157my @repo = $repo ? ($repo) : ();
 158my $term = eval {
 159        $ENV{"GIT_SEND_EMAIL_NOTTY"}
 160                ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
 161                : new Term::ReadLine 'git-send-email';
 162};
 163if ($@) {
 164        $term = new FakeTerm "$@: going non-interactive";
 165}
 166
 167# Behavior modification variables
 168my ($quiet, $dry_run) = (0, 0);
 169my $format_patch;
 170my $compose_filename;
 171my $force = 0;
 172
 173# Handle interactive edition of files.
 174my $multiedit;
 175my $editor;
 176
 177sub do_edit {
 178        if (!defined($editor)) {
 179                $editor = Git::command_oneline('var', 'GIT_EDITOR');
 180        }
 181        if (defined($multiedit) && !$multiedit) {
 182                map {
 183                        system('sh', '-c', $editor.' "$@"', $editor, $_);
 184                        if (($? & 127) || ($? >> 8)) {
 185                                die("the editor exited uncleanly, aborting everything");
 186                        }
 187                } @_;
 188        } else {
 189                system('sh', '-c', $editor.' "$@"', $editor, @_);
 190                if (($? & 127) || ($? >> 8)) {
 191                        die("the editor exited uncleanly, aborting everything");
 192                }
 193        }
 194}
 195
 196# Variables with corresponding config settings
 197my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
 198my ($to_cmd, $cc_cmd);
 199my ($smtp_server, $smtp_server_port, @smtp_server_options);
 200my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
 201my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
 202my ($validate, $confirm);
 203my (@suppress_cc);
 204my ($auto_8bit_encoding);
 205my ($compose_encoding);
 206
 207my ($debug_net_smtp) = 0;               # Net::SMTP, see send_message()
 208
 209my %config_bool_settings = (
 210    "thread" => [\$thread, 1],
 211    "chainreplyto" => [\$chain_reply_to, 0],
 212    "suppressfrom" => [\$suppress_from, undef],
 213    "signedoffbycc" => [\$signed_off_by_cc, undef],
 214    "signedoffcc" => [\$signed_off_by_cc, undef],      # Deprecated
 215    "validate" => [\$validate, 1],
 216    "multiedit" => [\$multiedit, undef],
 217    "annotate" => [\$annotate, undef]
 218);
 219
 220my %config_settings = (
 221    "smtpserver" => \$smtp_server,
 222    "smtpserverport" => \$smtp_server_port,
 223    "smtpserveroption" => \@smtp_server_options,
 224    "smtpuser" => \$smtp_authuser,
 225    "smtppass" => \$smtp_authpass,
 226    "smtpsslcertpath" => \$smtp_ssl_cert_path,
 227    "smtpdomain" => \$smtp_domain,
 228    "to" => \@initial_to,
 229    "tocmd" => \$to_cmd,
 230    "cc" => \@initial_cc,
 231    "cccmd" => \$cc_cmd,
 232    "aliasfiletype" => \$aliasfiletype,
 233    "bcc" => \@bcclist,
 234    "suppresscc" => \@suppress_cc,
 235    "envelopesender" => \$envelope_sender,
 236    "confirm"   => \$confirm,
 237    "from" => \$sender,
 238    "assume8bitencoding" => \$auto_8bit_encoding,
 239    "composeencoding" => \$compose_encoding,
 240);
 241
 242my %config_path_settings = (
 243    "aliasesfile" => \@alias_files,
 244);
 245
 246# Handle Uncouth Termination
 247sub signal_handler {
 248
 249        # Make text normal
 250        print color("reset"), "\n";
 251
 252        # SMTP password masked
 253        system "stty echo";
 254
 255        # tmp files from --compose
 256        if (defined $compose_filename) {
 257                if (-e $compose_filename) {
 258                        print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
 259                }
 260                if (-e ($compose_filename . ".final")) {
 261                        print "'$compose_filename.final' contains the composed email.\n"
 262                }
 263        }
 264
 265        exit;
 266};
 267
 268$SIG{TERM} = \&signal_handler;
 269$SIG{INT}  = \&signal_handler;
 270
 271# Begin by accumulating all the variables (defined above), that we will end up
 272# needing, first, from the command line:
 273
 274my $help;
 275my $rc = GetOptions("h" => \$help,
 276                    "sender|from=s" => \$sender,
 277                    "in-reply-to=s" => \$initial_reply_to,
 278                    "subject=s" => \$initial_subject,
 279                    "to=s" => \@initial_to,
 280                    "to-cmd=s" => \$to_cmd,
 281                    "no-to" => \$no_to,
 282                    "cc=s" => \@initial_cc,
 283                    "no-cc" => \$no_cc,
 284                    "bcc=s" => \@bcclist,
 285                    "no-bcc" => \$no_bcc,
 286                    "chain-reply-to!" => \$chain_reply_to,
 287                    "smtp-server=s" => \$smtp_server,
 288                    "smtp-server-option=s" => \@smtp_server_options,
 289                    "smtp-server-port=s" => \$smtp_server_port,
 290                    "smtp-user=s" => \$smtp_authuser,
 291                    "smtp-pass:s" => \$smtp_authpass,
 292                    "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
 293                    "smtp-encryption=s" => \$smtp_encryption,
 294                    "smtp-ssl-cert-path=s" => \$smtp_ssl_cert_path,
 295                    "smtp-debug:i" => \$debug_net_smtp,
 296                    "smtp-domain:s" => \$smtp_domain,
 297                    "identity=s" => \$identity,
 298                    "annotate!" => \$annotate,
 299                    "compose" => \$compose,
 300                    "quiet" => \$quiet,
 301                    "cc-cmd=s" => \$cc_cmd,
 302                    "suppress-from!" => \$suppress_from,
 303                    "suppress-cc=s" => \@suppress_cc,
 304                    "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
 305                    "confirm=s" => \$confirm,
 306                    "dry-run" => \$dry_run,
 307                    "envelope-sender=s" => \$envelope_sender,
 308                    "thread!" => \$thread,
 309                    "validate!" => \$validate,
 310                    "format-patch!" => \$format_patch,
 311                    "8bit-encoding=s" => \$auto_8bit_encoding,
 312                    "compose-encoding=s" => \$compose_encoding,
 313                    "force" => \$force,
 314         );
 315
 316usage() if $help;
 317unless ($rc) {
 318    usage();
 319}
 320
 321die "Cannot run git format-patch from outside a repository\n"
 322        if $format_patch and not $repo;
 323
 324# Now, let's fill any that aren't set in with defaults:
 325
 326sub read_config {
 327        my ($prefix) = @_;
 328
 329        foreach my $setting (keys %config_bool_settings) {
 330                my $target = $config_bool_settings{$setting}->[0];
 331                $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
 332        }
 333
 334        foreach my $setting (keys %config_path_settings) {
 335                my $target = $config_path_settings{$setting};
 336                if (ref($target) eq "ARRAY") {
 337                        unless (@$target) {
 338                                my @values = Git::config_path(@repo, "$prefix.$setting");
 339                                @$target = @values if (@values && defined $values[0]);
 340                        }
 341                }
 342                else {
 343                        $$target = Git::config_path(@repo, "$prefix.$setting") unless (defined $$target);
 344                }
 345        }
 346
 347        foreach my $setting (keys %config_settings) {
 348                my $target = $config_settings{$setting};
 349                next if $setting eq "to" and defined $no_to;
 350                next if $setting eq "cc" and defined $no_cc;
 351                next if $setting eq "bcc" and defined $no_bcc;
 352                if (ref($target) eq "ARRAY") {
 353                        unless (@$target) {
 354                                my @values = Git::config(@repo, "$prefix.$setting");
 355                                @$target = @values if (@values && defined $values[0]);
 356                        }
 357                }
 358                else {
 359                        $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
 360                }
 361        }
 362
 363        if (!defined $smtp_encryption) {
 364                my $enc = Git::config(@repo, "$prefix.smtpencryption");
 365                if (defined $enc) {
 366                        $smtp_encryption = $enc;
 367                } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
 368                        $smtp_encryption = 'ssl';
 369                }
 370        }
 371}
 372
 373# read configuration from [sendemail "$identity"], fall back on [sendemail]
 374$identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
 375read_config("sendemail.$identity") if (defined $identity);
 376read_config("sendemail");
 377
 378# fall back on builtin bool defaults
 379foreach my $setting (values %config_bool_settings) {
 380        ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
 381}
 382
 383# 'default' encryption is none -- this only prevents a warning
 384$smtp_encryption = '' unless (defined $smtp_encryption);
 385
 386# Set CC suppressions
 387my(%suppress_cc);
 388if (@suppress_cc) {
 389        foreach my $entry (@suppress_cc) {
 390                die "Unknown --suppress-cc field: '$entry'\n"
 391                        unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
 392                $suppress_cc{$entry} = 1;
 393        }
 394}
 395
 396if ($suppress_cc{'all'}) {
 397        foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
 398                $suppress_cc{$entry} = 1;
 399        }
 400        delete $suppress_cc{'all'};
 401}
 402
 403# If explicit old-style ones are specified, they trump --suppress-cc.
 404$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
 405$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
 406
 407if ($suppress_cc{'body'}) {
 408        foreach my $entry (qw (sob bodycc)) {
 409                $suppress_cc{$entry} = 1;
 410        }
 411        delete $suppress_cc{'body'};
 412}
 413
 414# Set confirm's default value
 415my $confirm_unconfigured = !defined $confirm;
 416if ($confirm_unconfigured) {
 417        $confirm = scalar %suppress_cc ? 'compose' : 'auto';
 418};
 419die "Unknown --confirm setting: '$confirm'\n"
 420        unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
 421
 422# Debugging, print out the suppressions.
 423if (0) {
 424        print "suppressions:\n";
 425        foreach my $entry (keys %suppress_cc) {
 426                printf "  %-5s -> $suppress_cc{$entry}\n", $entry;
 427        }
 428}
 429
 430my ($repoauthor, $repocommitter);
 431($repoauthor) = Git::ident_person(@repo, 'author');
 432($repocommitter) = Git::ident_person(@repo, 'committer');
 433
 434# Verify the user input
 435
 436foreach my $entry (@initial_to) {
 437        die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
 438}
 439
 440foreach my $entry (@initial_cc) {
 441        die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
 442}
 443
 444foreach my $entry (@bcclist) {
 445        die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
 446}
 447
 448sub parse_address_line {
 449        if ($have_mail_address) {
 450                return map { $_->format } Mail::Address->parse($_[0]);
 451        } else {
 452                return split_addrs($_[0]);
 453        }
 454}
 455
 456sub split_addrs {
 457        return quotewords('\s*,\s*', 1, @_);
 458}
 459
 460my %aliases;
 461my %parse_alias = (
 462        # multiline formats can be supported in the future
 463        mutt => sub { my $fh = shift; while (<$fh>) {
 464                if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
 465                        my ($alias, $addr) = ($1, $2);
 466                        $addr =~ s/#.*$//; # mutt allows # comments
 467                         # commas delimit multiple addresses
 468                        $aliases{$alias} = [ split_addrs($addr) ];
 469                }}},
 470        mailrc => sub { my $fh = shift; while (<$fh>) {
 471                if (/^alias\s+(\S+)\s+(.*)$/) {
 472                        # spaces delimit multiple addresses
 473                        $aliases{$1} = [ quotewords('\s+', 0, $2) ];
 474                }}},
 475        pine => sub { my $fh = shift; my $f='\t[^\t]*';
 476                for (my $x = ''; defined($x); $x = $_) {
 477                        chomp $x;
 478                        $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
 479                        $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
 480                        $aliases{$1} = [ split_addrs($2) ];
 481                }},
 482        elm => sub  { my $fh = shift;
 483                      while (<$fh>) {
 484                          if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
 485                              my ($alias, $addr) = ($1, $2);
 486                               $aliases{$alias} = [ split_addrs($addr) ];
 487                          }
 488                      } },
 489
 490        gnus => sub { my $fh = shift; while (<$fh>) {
 491                if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
 492                        $aliases{$1} = [ $2 ];
 493                }}}
 494);
 495
 496if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
 497        foreach my $file (@alias_files) {
 498                open my $fh, '<', $file or die "opening $file: $!\n";
 499                $parse_alias{$aliasfiletype}->($fh);
 500                close $fh;
 501        }
 502}
 503
 504($sender) = expand_aliases($sender) if defined $sender;
 505
 506# is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
 507# $f is a revision list specification to be passed to format-patch.
 508sub is_format_patch_arg {
 509        return unless $repo;
 510        my $f = shift;
 511        try {
 512                $repo->command('rev-parse', '--verify', '--quiet', $f);
 513                if (defined($format_patch)) {
 514                        return $format_patch;
 515                }
 516                die(<<EOF);
 517File '$f' exists but it could also be the range of commits
 518to produce patches for.  Please disambiguate by...
 519
 520    * Saying "./$f" if you mean a file; or
 521    * Giving --format-patch option if you mean a range.
 522EOF
 523        } catch Git::Error::Command with {
 524                # Not a valid revision.  Treat it as a filename.
 525                return 0;
 526        }
 527}
 528
 529# Now that all the defaults are set, process the rest of the command line
 530# arguments and collect up the files that need to be processed.
 531my @rev_list_opts;
 532while (defined(my $f = shift @ARGV)) {
 533        if ($f eq "--") {
 534                push @rev_list_opts, "--", @ARGV;
 535                @ARGV = ();
 536        } elsif (-d $f and !is_format_patch_arg($f)) {
 537                opendir my $dh, $f
 538                        or die "Failed to opendir $f: $!";
 539
 540                push @files, grep { -f $_ } map { catfile($f, $_) }
 541                                sort readdir $dh;
 542                closedir $dh;
 543        } elsif ((-f $f or -p $f) and !is_format_patch_arg($f)) {
 544                push @files, $f;
 545        } else {
 546                push @rev_list_opts, $f;
 547        }
 548}
 549
 550if (@rev_list_opts) {
 551        die "Cannot run git format-patch from outside a repository\n"
 552                unless $repo;
 553        push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
 554}
 555
 556if ($validate) {
 557        foreach my $f (@files) {
 558                unless (-p $f) {
 559                        my $error = validate_patch($f);
 560                        $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
 561                }
 562        }
 563}
 564
 565if (@files) {
 566        unless ($quiet) {
 567                print $_,"\n" for (@files);
 568        }
 569} else {
 570        print STDERR "\nNo patch files specified!\n\n";
 571        usage();
 572}
 573
 574sub get_patch_subject {
 575        my $fn = shift;
 576        open (my $fh, '<', $fn);
 577        while (my $line = <$fh>) {
 578                next unless ($line =~ /^Subject: (.*)$/);
 579                close $fh;
 580                return "GIT: $1\n";
 581        }
 582        close $fh;
 583        die "No subject line in $fn ?";
 584}
 585
 586if ($compose) {
 587        # Note that this does not need to be secure, but we will make a small
 588        # effort to have it be unique
 589        $compose_filename = ($repo ?
 590                tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
 591                tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
 592        open my $c, ">", $compose_filename
 593                or die "Failed to open for writing $compose_filename: $!";
 594
 595
 596        my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
 597        my $tpl_subject = $initial_subject || '';
 598        my $tpl_reply_to = $initial_reply_to || '';
 599
 600        print $c <<EOT;
 601From $tpl_sender # This line is ignored.
 602GIT: Lines beginning in "GIT:" will be removed.
 603GIT: Consider including an overall diffstat or table of contents
 604GIT: for the patch you are writing.
 605GIT:
 606GIT: Clear the body content if you don't wish to send a summary.
 607From: $tpl_sender
 608Subject: $tpl_subject
 609In-Reply-To: $tpl_reply_to
 610
 611EOT
 612        for my $f (@files) {
 613                print $c get_patch_subject($f);
 614        }
 615        close $c;
 616
 617        if ($annotate) {
 618                do_edit($compose_filename, @files);
 619        } else {
 620                do_edit($compose_filename);
 621        }
 622
 623        open my $c2, ">", $compose_filename . ".final"
 624                or die "Failed to open $compose_filename.final : " . $!;
 625
 626        open $c, "<", $compose_filename
 627                or die "Failed to open $compose_filename : " . $!;
 628
 629        my $need_8bit_cte = file_has_nonascii($compose_filename);
 630        my $in_body = 0;
 631        my $summary_empty = 1;
 632        if (!defined $compose_encoding) {
 633                $compose_encoding = "UTF-8";
 634        }
 635        while(<$c>) {
 636                next if m/^GIT:/;
 637                if ($in_body) {
 638                        $summary_empty = 0 unless (/^\n$/);
 639                } elsif (/^\n$/) {
 640                        $in_body = 1;
 641                        if ($need_8bit_cte) {
 642                                print $c2 "MIME-Version: 1.0\n",
 643                                         "Content-Type: text/plain; ",
 644                                           "charset=$compose_encoding\n",
 645                                         "Content-Transfer-Encoding: 8bit\n";
 646                        }
 647                } elsif (/^MIME-Version:/i) {
 648                        $need_8bit_cte = 0;
 649                } elsif (/^Subject:\s*(.+)\s*$/i) {
 650                        $initial_subject = $1;
 651                        my $subject = $initial_subject;
 652                        $_ = "Subject: " .
 653                                quote_subject($subject, $compose_encoding) .
 654                                "\n";
 655                } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
 656                        $initial_reply_to = $1;
 657                        next;
 658                } elsif (/^From:\s*(.+)\s*$/i) {
 659                        $sender = $1;
 660                        next;
 661                } elsif (/^(?:To|Cc|Bcc):/i) {
 662                        print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
 663                        next;
 664                }
 665                print $c2 $_;
 666        }
 667        close $c;
 668        close $c2;
 669
 670        if ($summary_empty) {
 671                print "Summary email is empty, skipping it\n";
 672                $compose = -1;
 673        }
 674} elsif ($annotate) {
 675        do_edit(@files);
 676}
 677
 678sub ask {
 679        my ($prompt, %arg) = @_;
 680        my $valid_re = $arg{valid_re};
 681        my $default = $arg{default};
 682        my $confirm_only = $arg{confirm_only};
 683        my $resp;
 684        my $i = 0;
 685        return defined $default ? $default : undef
 686                unless defined $term->IN and defined fileno($term->IN) and
 687                       defined $term->OUT and defined fileno($term->OUT);
 688        while ($i++ < 10) {
 689                $resp = $term->readline($prompt);
 690                if (!defined $resp) { # EOF
 691                        print "\n";
 692                        return defined $default ? $default : undef;
 693                }
 694                if ($resp eq '' and defined $default) {
 695                        return $default;
 696                }
 697                if (!defined $valid_re or $resp =~ /$valid_re/) {
 698                        return $resp;
 699                }
 700                if ($confirm_only) {
 701                        my $yesno = $term->readline("Are you sure you want to use <$resp> [y/N]? ");
 702                        if (defined $yesno && $yesno =~ /y/i) {
 703                                return $resp;
 704                        }
 705                }
 706        }
 707        return;
 708}
 709
 710my %broken_encoding;
 711
 712sub file_declares_8bit_cte {
 713        my $fn = shift;
 714        open (my $fh, '<', $fn);
 715        while (my $line = <$fh>) {
 716                last if ($line =~ /^$/);
 717                return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
 718        }
 719        close $fh;
 720        return 0;
 721}
 722
 723foreach my $f (@files) {
 724        next unless (body_or_subject_has_nonascii($f)
 725                     && !file_declares_8bit_cte($f));
 726        $broken_encoding{$f} = 1;
 727}
 728
 729if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
 730        print "The following files are 8bit, but do not declare " .
 731                "a Content-Transfer-Encoding.\n";
 732        foreach my $f (sort keys %broken_encoding) {
 733                print "    $f\n";
 734        }
 735        $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
 736                                  valid_re => qr/.{4}/, confirm_only => 1,
 737                                  default => "UTF-8");
 738}
 739
 740if (!$force) {
 741        for my $f (@files) {
 742                if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
 743                        die "Refusing to send because the patch\n\t$f\n"
 744                                . "has the template subject '*** SUBJECT HERE ***'. "
 745                                . "Pass --force if you really want to send.\n";
 746                }
 747        }
 748}
 749
 750if (!defined $sender) {
 751        $sender = $repoauthor || $repocommitter || '';
 752}
 753
 754# $sender could be an already sanitized address
 755# (e.g. sendemail.from could be manually sanitized by user).
 756# But it's a no-op to run sanitize_address on an already sanitized address.
 757$sender = sanitize_address($sender);
 758
 759my $prompting = 0;
 760if (!@initial_to && !defined $to_cmd) {
 761        my $to = ask("Who should the emails be sent to (if any)? ",
 762                     default => "",
 763                     valid_re => qr/\@.*\./, confirm_only => 1);
 764        push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
 765        $prompting++;
 766}
 767
 768sub expand_aliases {
 769        return map { expand_one_alias($_) } @_;
 770}
 771
 772my %EXPANDED_ALIASES;
 773sub expand_one_alias {
 774        my $alias = shift;
 775        if ($EXPANDED_ALIASES{$alias}) {
 776                die "fatal: alias '$alias' expands to itself\n";
 777        }
 778        local $EXPANDED_ALIASES{$alias} = 1;
 779        return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
 780}
 781
 782@initial_to = expand_aliases(@initial_to);
 783@initial_to = validate_address_list(sanitize_address_list(@initial_to));
 784@initial_cc = expand_aliases(@initial_cc);
 785@initial_cc = validate_address_list(sanitize_address_list(@initial_cc));
 786@bcclist = expand_aliases(@bcclist);
 787@bcclist = validate_address_list(sanitize_address_list(@bcclist));
 788
 789if ($thread && !defined $initial_reply_to && $prompting) {
 790        $initial_reply_to = ask(
 791                "Message-ID to be used as In-Reply-To for the first email (if any)? ",
 792                default => "",
 793                valid_re => qr/\@.*\./, confirm_only => 1);
 794}
 795if (defined $initial_reply_to) {
 796        $initial_reply_to =~ s/^\s*<?//;
 797        $initial_reply_to =~ s/>?\s*$//;
 798        $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
 799}
 800
 801if (!defined $smtp_server) {
 802        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
 803                if (-x $_) {
 804                        $smtp_server = $_;
 805                        last;
 806                }
 807        }
 808        $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
 809}
 810
 811if ($compose && $compose > 0) {
 812        @files = ($compose_filename . ".final", @files);
 813}
 814
 815# Variables we set as part of the loop over files
 816our ($message_id, %mail, $subject, $reply_to, $references, $message,
 817        $needs_confirm, $message_num, $ask_default);
 818
 819sub extract_valid_address {
 820        my $address = shift;
 821        my $local_part_regexp = qr/[^<>"\s@]+/;
 822        my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
 823
 824        # check for a local address:
 825        return $address if ($address =~ /^($local_part_regexp)$/);
 826
 827        $address =~ s/^\s*<(.*)>\s*$/$1/;
 828        if ($have_email_valid) {
 829                return scalar Email::Valid->address($address);
 830        }
 831
 832        # less robust/correct than the monster regexp in Email::Valid,
 833        # but still does a 99% job, and one less dependency
 834        return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
 835        return;
 836}
 837
 838sub extract_valid_address_or_die {
 839        my $address = shift;
 840        $address = extract_valid_address($address);
 841        die "error: unable to extract a valid address from: $address\n"
 842                if !$address;
 843        return $address;
 844}
 845
 846sub validate_address {
 847        my $address = shift;
 848        while (!extract_valid_address($address)) {
 849                print STDERR "error: unable to extract a valid address from: $address\n";
 850                $_ = ask("What to do with this address? ([q]uit|[d]rop|[e]dit): ",
 851                        valid_re => qr/^(?:quit|q|drop|d|edit|e)/i,
 852                        default => 'q');
 853                if (/^d/i) {
 854                        return undef;
 855                } elsif (/^q/i) {
 856                        cleanup_compose_files();
 857                        exit(0);
 858                }
 859                $address = ask("Who should the email be sent to (if any)? ",
 860                        default => "",
 861                        valid_re => qr/\@.*\./, confirm_only => 1);
 862        }
 863        return $address;
 864}
 865
 866sub validate_address_list {
 867        return (grep { defined $_ }
 868                map { validate_address($_) } @_);
 869}
 870
 871# Usually don't need to change anything below here.
 872
 873# we make a "fake" message id by taking the current number
 874# of seconds since the beginning of Unix time and tacking on
 875# a random number to the end, in case we are called quicker than
 876# 1 second since the last time we were called.
 877
 878# We'll setup a template for the message id, using the "from" address:
 879
 880my ($message_id_stamp, $message_id_serial);
 881sub make_message_id {
 882        my $uniq;
 883        if (!defined $message_id_stamp) {
 884                $message_id_stamp = sprintf("%s-%s", time, $$);
 885                $message_id_serial = 0;
 886        }
 887        $message_id_serial++;
 888        $uniq = "$message_id_stamp-$message_id_serial";
 889
 890        my $du_part;
 891        for ($sender, $repocommitter, $repoauthor) {
 892                $du_part = extract_valid_address(sanitize_address($_));
 893                last if (defined $du_part and $du_part ne '');
 894        }
 895        if (not defined $du_part or $du_part eq '') {
 896                require Sys::Hostname;
 897                $du_part = 'user@' . Sys::Hostname::hostname();
 898        }
 899        my $message_id_template = "<%s-git-send-email-%s>";
 900        $message_id = sprintf($message_id_template, $uniq, $du_part);
 901        #print "new message id = $message_id\n"; # Was useful for debugging
 902}
 903
 904
 905
 906$time = time - scalar $#files;
 907
 908sub unquote_rfc2047 {
 909        local ($_) = @_;
 910        my $encoding;
 911        s{=\?([^?]+)\?q\?(.*?)\?=}{
 912                $encoding = $1;
 913                my $e = $2;
 914                $e =~ s/_/ /g;
 915                $e =~ s/=([0-9A-F]{2})/chr(hex($1))/eg;
 916                $e;
 917        }eg;
 918        return wantarray ? ($_, $encoding) : $_;
 919}
 920
 921sub quote_rfc2047 {
 922        local $_ = shift;
 923        my $encoding = shift || 'UTF-8';
 924        s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
 925        s/(.*)/=\?$encoding\?q\?$1\?=/;
 926        return $_;
 927}
 928
 929sub is_rfc2047_quoted {
 930        my $s = shift;
 931        my $token = qr/[^][()<>@,;:"\/?.= \000-\037\177-\377]+/;
 932        my $encoded_text = qr/[!->@-~]+/;
 933        length($s) <= 75 &&
 934        $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
 935}
 936
 937sub subject_needs_rfc2047_quoting {
 938        my $s = shift;
 939
 940        return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
 941}
 942
 943sub quote_subject {
 944        local $subject = shift;
 945        my $encoding = shift || 'UTF-8';
 946
 947        if (subject_needs_rfc2047_quoting($subject)) {
 948                return quote_rfc2047($subject, $encoding);
 949        }
 950        return $subject;
 951}
 952
 953# use the simplest quoting being able to handle the recipient
 954sub sanitize_address {
 955        my ($recipient) = @_;
 956
 957        # remove garbage after email address
 958        $recipient =~ s/(.*>).*$/$1/;
 959
 960        my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
 961
 962        if (not $recipient_name) {
 963                return $recipient;
 964        }
 965
 966        # if recipient_name is already quoted, do nothing
 967        if (is_rfc2047_quoted($recipient_name)) {
 968                return $recipient;
 969        }
 970
 971        # rfc2047 is needed if a non-ascii char is included
 972        if ($recipient_name =~ /[^[:ascii:]]/) {
 973                $recipient_name =~ s/^"(.*)"$/$1/;
 974                $recipient_name = quote_rfc2047($recipient_name);
 975        }
 976
 977        # double quotes are needed if specials or CTLs are included
 978        elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
 979                $recipient_name =~ s/(["\\\r])/\\$1/g;
 980                $recipient_name = qq["$recipient_name"];
 981        }
 982
 983        return "$recipient_name $recipient_addr";
 984
 985}
 986
 987sub sanitize_address_list {
 988        return (map { sanitize_address($_) } @_);
 989}
 990
 991# Returns the local Fully Qualified Domain Name (FQDN) if available.
 992#
 993# Tightly configured MTAa require that a caller sends a real DNS
 994# domain name that corresponds the IP address in the HELO/EHLO
 995# handshake. This is used to verify the connection and prevent
 996# spammers from trying to hide their identity. If the DNS and IP don't
 997# match, the receiveing MTA may deny the connection.
 998#
 999# Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1000#
1001# Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1002# Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1003#
1004# This maildomain*() code is based on ideas in Perl library Test::Reporter
1005# /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1006
1007sub valid_fqdn {
1008        my $domain = shift;
1009        return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
1010}
1011
1012sub maildomain_net {
1013        my $maildomain;
1014
1015        if (eval { require Net::Domain; 1 }) {
1016                my $domain = Net::Domain::domainname();
1017                $maildomain = $domain if valid_fqdn($domain);
1018        }
1019
1020        return $maildomain;
1021}
1022
1023sub maildomain_mta {
1024        my $maildomain;
1025
1026        if (eval { require Net::SMTP; 1 }) {
1027                for my $host (qw(mailhost localhost)) {
1028                        my $smtp = Net::SMTP->new($host);
1029                        if (defined $smtp) {
1030                                my $domain = $smtp->domain;
1031                                $smtp->quit;
1032
1033                                $maildomain = $domain if valid_fqdn($domain);
1034
1035                                last if $maildomain;
1036                        }
1037                }
1038        }
1039
1040        return $maildomain;
1041}
1042
1043sub maildomain {
1044        return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
1045}
1046
1047sub smtp_host_string {
1048        if (defined $smtp_server_port) {
1049                return "$smtp_server:$smtp_server_port";
1050        } else {
1051                return $smtp_server;
1052        }
1053}
1054
1055# Returns 1 if authentication succeeded or was not necessary
1056# (smtp_user was not specified), and 0 otherwise.
1057
1058sub smtp_auth_maybe {
1059        if (!defined $smtp_authuser || $auth) {
1060                return 1;
1061        }
1062
1063        # Workaround AUTH PLAIN/LOGIN interaction defect
1064        # with Authen::SASL::Cyrus
1065        eval {
1066                require Authen::SASL;
1067                Authen::SASL->import(qw(Perl));
1068        };
1069
1070        # TODO: Authentication may fail not because credentials were
1071        # invalid but due to other reasons, in which we should not
1072        # reject credentials.
1073        $auth = Git::credential({
1074                'protocol' => 'smtp',
1075                'host' => smtp_host_string(),
1076                'username' => $smtp_authuser,
1077                # if there's no password, "git credential fill" will
1078                # give us one, otherwise it'll just pass this one.
1079                'password' => $smtp_authpass
1080        }, sub {
1081                my $cred = shift;
1082                return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1083        });
1084
1085        return $auth;
1086}
1087
1088sub ssl_verify_params {
1089        eval {
1090                require IO::Socket::SSL;
1091                IO::Socket::SSL->import(qw/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1092        };
1093        if ($@) {
1094                print STDERR "Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1095                return;
1096        }
1097
1098        if (!defined $smtp_ssl_cert_path) {
1099                # use the OpenSSL defaults
1100                return (SSL_verify_mode => SSL_VERIFY_PEER());
1101        }
1102
1103        if ($smtp_ssl_cert_path eq "") {
1104                return (SSL_verify_mode => SSL_VERIFY_NONE());
1105        } elsif (-d $smtp_ssl_cert_path) {
1106                return (SSL_verify_mode => SSL_VERIFY_PEER(),
1107                        SSL_ca_path => $smtp_ssl_cert_path);
1108        } elsif (-f $smtp_ssl_cert_path) {
1109                return (SSL_verify_mode => SSL_VERIFY_PEER(),
1110                        SSL_ca_file => $smtp_ssl_cert_path);
1111        } else {
1112                print STDERR "Not using SSL_VERIFY_PEER because the CA path does not exist.\n";
1113                return (SSL_verify_mode => SSL_VERIFY_NONE());
1114        }
1115}
1116
1117# Returns 1 if the message was sent, and 0 otherwise.
1118# In actuality, the whole program dies when there
1119# is an error sending a message.
1120
1121sub send_message {
1122        my @recipients = unique_email_list(@to);
1123        @cc = (grep { my $cc = extract_valid_address_or_die($_);
1124                      not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
1125                    }
1126               @cc);
1127        my $to = join (",\n\t", @recipients);
1128        @recipients = unique_email_list(@recipients,@cc,@bcclist);
1129        @recipients = (map { extract_valid_address_or_die($_) } @recipients);
1130        my $date = format_2822_time($time++);
1131        my $gitversion = '@@GIT_VERSION@@';
1132        if ($gitversion =~ m/..GIT_VERSION../) {
1133            $gitversion = Git::version();
1134        }
1135
1136        my $cc = join(",\n\t", unique_email_list(@cc));
1137        my $ccline = "";
1138        if ($cc ne '') {
1139                $ccline = "\nCc: $cc";
1140        }
1141        make_message_id() unless defined($message_id);
1142
1143        my $header = "From: $sender
1144To: $to${ccline}
1145Subject: $subject
1146Date: $date
1147Message-Id: $message_id
1148X-Mailer: git-send-email $gitversion
1149";
1150        if ($reply_to) {
1151
1152                $header .= "In-Reply-To: $reply_to\n";
1153                $header .= "References: $references\n";
1154        }
1155        if (@xh) {
1156                $header .= join("\n", @xh) . "\n";
1157        }
1158
1159        my @sendmail_parameters = ('-i', @recipients);
1160        my $raw_from = $sender;
1161        if (defined $envelope_sender && $envelope_sender ne "auto") {
1162                $raw_from = $envelope_sender;
1163        }
1164        $raw_from = extract_valid_address($raw_from);
1165        unshift (@sendmail_parameters,
1166                        '-f', $raw_from) if(defined $envelope_sender);
1167
1168        if ($needs_confirm && !$dry_run) {
1169                print "\n$header\n";
1170                if ($needs_confirm eq "inform") {
1171                        $confirm_unconfigured = 0; # squelch this message for the rest of this run
1172                        $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1173                        print "    The Cc list above has been expanded by additional\n";
1174                        print "    addresses found in the patch commit message. By default\n";
1175                        print "    send-email prompts before sending whenever this occurs.\n";
1176                        print "    This behavior is controlled by the sendemail.confirm\n";
1177                        print "    configuration setting.\n";
1178                        print "\n";
1179                        print "    For additional information, run 'git send-email --help'.\n";
1180                        print "    To retain the current behavior, but squelch this message,\n";
1181                        print "    run 'git config --global sendemail.confirm auto'.\n\n";
1182                }
1183                $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1184                         valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1185                         default => $ask_default);
1186                die "Send this email reply required" unless defined $_;
1187                if (/^n/i) {
1188                        return 0;
1189                } elsif (/^q/i) {
1190                        cleanup_compose_files();
1191                        exit(0);
1192                } elsif (/^a/i) {
1193                        $confirm = 'never';
1194                }
1195        }
1196
1197        unshift (@sendmail_parameters, @smtp_server_options);
1198
1199        if ($dry_run) {
1200                # We don't want to send the email.
1201        } elsif ($smtp_server =~ m#^/#) {
1202                my $pid = open my $sm, '|-';
1203                defined $pid or die $!;
1204                if (!$pid) {
1205                        exec($smtp_server, @sendmail_parameters) or die $!;
1206                }
1207                print $sm "$header\n$message";
1208                close $sm or die $!;
1209        } else {
1210
1211                if (!defined $smtp_server) {
1212                        die "The required SMTP server is not properly defined."
1213                }
1214
1215                if ($smtp_encryption eq 'ssl') {
1216                        $smtp_server_port ||= 465; # ssmtp
1217                        require Net::SMTP::SSL;
1218                        $smtp_domain ||= maildomain();
1219                        require IO::Socket::SSL;
1220                        # Net::SMTP::SSL->new() does not forward any SSL options
1221                        IO::Socket::SSL::set_client_defaults(
1222                                ssl_verify_params());
1223                        $smtp ||= Net::SMTP::SSL->new($smtp_server,
1224                                                      Hello => $smtp_domain,
1225                                                      Port => $smtp_server_port,
1226                                                      Debug => $debug_net_smtp);
1227                }
1228                else {
1229                        require Net::SMTP;
1230                        $smtp_domain ||= maildomain();
1231                        $smtp_server_port ||= 25;
1232                        $smtp ||= Net::SMTP->new($smtp_server,
1233                                                 Hello => $smtp_domain,
1234                                                 Debug => $debug_net_smtp,
1235                                                 Port => $smtp_server_port);
1236                        if ($smtp_encryption eq 'tls' && $smtp) {
1237                                require Net::SMTP::SSL;
1238                                $smtp->command('STARTTLS');
1239                                $smtp->response();
1240                                if ($smtp->code == 220) {
1241                                        $smtp = Net::SMTP::SSL->start_SSL($smtp,
1242                                                                          ssl_verify_params())
1243                                                or die "STARTTLS failed! ".IO::Socket::SSL::errstr();
1244                                        $smtp_encryption = '';
1245                                        # Send EHLO again to receive fresh
1246                                        # supported commands
1247                                        $smtp->hello($smtp_domain);
1248                                } else {
1249                                        die "Server does not support STARTTLS! ".$smtp->message;
1250                                }
1251                        }
1252                }
1253
1254                if (!$smtp) {
1255                        die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1256                            "VALUES: server=$smtp_server ",
1257                            "encryption=$smtp_encryption ",
1258                            "hello=$smtp_domain",
1259                            defined $smtp_server_port ? " port=$smtp_server_port" : "";
1260                }
1261
1262                smtp_auth_maybe or die $smtp->message;
1263
1264                $smtp->mail( $raw_from ) or die $smtp->message;
1265                $smtp->to( @recipients ) or die $smtp->message;
1266                $smtp->data or die $smtp->message;
1267                $smtp->datasend("$header\n$message") or die $smtp->message;
1268                $smtp->dataend() or die $smtp->message;
1269                $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1270        }
1271        if ($quiet) {
1272                printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1273        } else {
1274                print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1275                if ($smtp_server !~ m#^/#) {
1276                        print "Server: $smtp_server\n";
1277                        print "MAIL FROM:<$raw_from>\n";
1278                        foreach my $entry (@recipients) {
1279                            print "RCPT TO:<$entry>\n";
1280                        }
1281                } else {
1282                        print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1283                }
1284                print $header, "\n";
1285                if ($smtp) {
1286                        print "Result: ", $smtp->code, ' ',
1287                                ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1288                } else {
1289                        print "Result: OK\n";
1290                }
1291        }
1292
1293        return 1;
1294}
1295
1296$reply_to = $initial_reply_to;
1297$references = $initial_reply_to || '';
1298$subject = $initial_subject;
1299$message_num = 0;
1300
1301foreach my $t (@files) {
1302        open my $fh, "<", $t or die "can't open file $t";
1303
1304        my $author = undef;
1305        my $sauthor = undef;
1306        my $author_encoding;
1307        my $has_content_type;
1308        my $body_encoding;
1309        @to = ();
1310        @cc = ();
1311        @xh = ();
1312        my $input_format = undef;
1313        my @header = ();
1314        $message = "";
1315        $message_num++;
1316        # First unfold multiline header fields
1317        while(<$fh>) {
1318                last if /^\s*$/;
1319                if (/^\s+\S/ and @header) {
1320                        chomp($header[$#header]);
1321                        s/^\s+/ /;
1322                        $header[$#header] .= $_;
1323            } else {
1324                        push(@header, $_);
1325                }
1326        }
1327        # Now parse the header
1328        foreach(@header) {
1329                if (/^From /) {
1330                        $input_format = 'mbox';
1331                        next;
1332                }
1333                chomp;
1334                if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1335                        $input_format = 'mbox';
1336                }
1337
1338                if (defined $input_format && $input_format eq 'mbox') {
1339                        if (/^Subject:\s+(.*)$/i) {
1340                                $subject = $1;
1341                        }
1342                        elsif (/^From:\s+(.*)$/i) {
1343                                ($author, $author_encoding) = unquote_rfc2047($1);
1344                                $sauthor = sanitize_address($author);
1345                                next if $suppress_cc{'author'};
1346                                next if $suppress_cc{'self'} and $sauthor eq $sender;
1347                                printf("(mbox) Adding cc: %s from line '%s'\n",
1348                                        $1, $_) unless $quiet;
1349                                push @cc, $1;
1350                        }
1351                        elsif (/^To:\s+(.*)$/i) {
1352                                foreach my $addr (parse_address_line($1)) {
1353                                        printf("(mbox) Adding to: %s from line '%s'\n",
1354                                                $addr, $_) unless $quiet;
1355                                        push @to, $addr;
1356                                }
1357                        }
1358                        elsif (/^Cc:\s+(.*)$/i) {
1359                                foreach my $addr (parse_address_line($1)) {
1360                                        my $qaddr = unquote_rfc2047($addr);
1361                                        my $saddr = sanitize_address($qaddr);
1362                                        if ($saddr eq $sender) {
1363                                                next if ($suppress_cc{'self'});
1364                                        } else {
1365                                                next if ($suppress_cc{'cc'});
1366                                        }
1367                                        printf("(mbox) Adding cc: %s from line '%s'\n",
1368                                                $addr, $_) unless $quiet;
1369                                        push @cc, $addr;
1370                                }
1371                        }
1372                        elsif (/^Content-type:/i) {
1373                                $has_content_type = 1;
1374                                if (/charset="?([^ "]+)/) {
1375                                        $body_encoding = $1;
1376                                }
1377                                push @xh, $_;
1378                        }
1379                        elsif (/^Message-Id: (.*)/i) {
1380                                $message_id = $1;
1381                        }
1382                        elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
1383                                push @xh, $_;
1384                        }
1385
1386                } else {
1387                        # In the traditional
1388                        # "send lots of email" format,
1389                        # line 1 = cc
1390                        # line 2 = subject
1391                        # So let's support that, too.
1392                        $input_format = 'lots';
1393                        if (@cc == 0 && !$suppress_cc{'cc'}) {
1394                                printf("(non-mbox) Adding cc: %s from line '%s'\n",
1395                                        $_, $_) unless $quiet;
1396                                push @cc, $_;
1397                        } elsif (!defined $subject) {
1398                                $subject = $_;
1399                        }
1400                }
1401        }
1402        # Now parse the message body
1403        while(<$fh>) {
1404                $message .=  $_;
1405                if (/^(Signed-off-by|Cc): (.*)$/i) {
1406                        chomp;
1407                        my ($what, $c) = ($1, $2);
1408                        chomp $c;
1409                        my $sc = sanitize_address($c);
1410                        if ($sc eq $sender) {
1411                                next if ($suppress_cc{'self'});
1412                        } else {
1413                                next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1414                                next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1415                        }
1416                        push @cc, $c;
1417                        printf("(body) Adding cc: %s from line '%s'\n",
1418                                $c, $_) unless $quiet;
1419                }
1420        }
1421        close $fh;
1422
1423        push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1424                if defined $to_cmd;
1425        push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1426                if defined $cc_cmd && !$suppress_cc{'cccmd'};
1427
1428        if ($broken_encoding{$t} && !$has_content_type) {
1429                $has_content_type = 1;
1430                push @xh, "MIME-Version: 1.0",
1431                        "Content-Type: text/plain; charset=$auto_8bit_encoding",
1432                        "Content-Transfer-Encoding: 8bit";
1433                $body_encoding = $auto_8bit_encoding;
1434        }
1435
1436        if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1437                $subject = quote_subject($subject, $auto_8bit_encoding);
1438        }
1439
1440        if (defined $sauthor and $sauthor ne $sender) {
1441                $message = "From: $author\n\n$message";
1442                if (defined $author_encoding) {
1443                        if ($has_content_type) {
1444                                if ($body_encoding eq $author_encoding) {
1445                                        # ok, we already have the right encoding
1446                                }
1447                                else {
1448                                        # uh oh, we should re-encode
1449                                }
1450                        }
1451                        else {
1452                                $has_content_type = 1;
1453                                push @xh,
1454                                  'MIME-Version: 1.0',
1455                                  "Content-Type: text/plain; charset=$author_encoding",
1456                                  'Content-Transfer-Encoding: 8bit';
1457                        }
1458                }
1459        }
1460
1461        $needs_confirm = (
1462                $confirm eq "always" or
1463                ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1464                ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1465        $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1466
1467        @to = validate_address_list(sanitize_address_list(@to));
1468        @cc = validate_address_list(sanitize_address_list(@cc));
1469
1470        @to = (@initial_to, @to);
1471        @cc = (@initial_cc, @cc);
1472
1473        my $message_was_sent = send_message();
1474
1475        # set up for the next message
1476        if ($thread && $message_was_sent &&
1477                ($chain_reply_to || !defined $reply_to || length($reply_to) == 0 ||
1478                $message_num == 1)) {
1479                $reply_to = $message_id;
1480                if (length $references > 0) {
1481                        $references .= "\n $message_id";
1482                } else {
1483                        $references = "$message_id";
1484                }
1485        }
1486        $message_id = undef;
1487}
1488
1489# Execute a command (e.g. $to_cmd) to get a list of email addresses
1490# and return a results array
1491sub recipients_cmd {
1492        my ($prefix, $what, $cmd, $file) = @_;
1493
1494        my @addresses = ();
1495        open my $fh, "-|", "$cmd \Q$file\E"
1496            or die "($prefix) Could not execute '$cmd'";
1497        while (my $address = <$fh>) {
1498                $address =~ s/^\s*//g;
1499                $address =~ s/\s*$//g;
1500                $address = sanitize_address($address);
1501                next if ($address eq $sender and $suppress_cc{'self'});
1502                push @addresses, $address;
1503                printf("($prefix) Adding %s: %s from: '%s'\n",
1504                       $what, $address, $cmd) unless $quiet;
1505                }
1506        close $fh
1507            or die "($prefix) failed to close pipe to '$cmd'";
1508        return @addresses;
1509}
1510
1511cleanup_compose_files();
1512
1513sub cleanup_compose_files {
1514        unlink($compose_filename, $compose_filename . ".final") if $compose;
1515}
1516
1517$smtp->quit if $smtp;
1518
1519sub unique_email_list {
1520        my %seen;
1521        my @emails;
1522
1523        foreach my $entry (@_) {
1524                my $clean = extract_valid_address_or_die($entry);
1525                $seen{$clean} ||= 0;
1526                next if $seen{$clean}++;
1527                push @emails, $entry;
1528        }
1529        return @emails;
1530}
1531
1532sub validate_patch {
1533        my $fn = shift;
1534        open(my $fh, '<', $fn)
1535                or die "unable to open $fn: $!\n";
1536        while (my $line = <$fh>) {
1537                if (length($line) > 998) {
1538                        return "$.: patch contains a line longer than 998 characters";
1539                }
1540        }
1541        return;
1542}
1543
1544sub file_has_nonascii {
1545        my $fn = shift;
1546        open(my $fh, '<', $fn)
1547                or die "unable to open $fn: $!\n";
1548        while (my $line = <$fh>) {
1549                return 1 if $line =~ /[^[:ascii:]]/;
1550        }
1551        return 0;
1552}
1553
1554sub body_or_subject_has_nonascii {
1555        my $fn = shift;
1556        open(my $fh, '<', $fn)
1557                or die "unable to open $fn: $!\n";
1558        while (my $line = <$fh>) {
1559                last if $line =~ /^$/;
1560                return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1561        }
1562        while (my $line = <$fh>) {
1563                return 1 if $line =~ /[^[:ascii:]]/;
1564        }
1565        return 0;
1566}