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