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