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