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