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