git-send-email.perlon commit git send-email: interpret unknown files as revision lists (5df9fcf)
   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 Data::Dumper;
  24use Term::ANSIColor;
  25use File::Temp qw/ tempdir /;
  26use Error qw(:try);
  27use Git;
  28
  29Getopt::Long::Configure qw/ pass_through /;
  30
  31package FakeTerm;
  32sub new {
  33        my ($class, $reason) = @_;
  34        return bless \$reason, shift;
  35}
  36sub readline {
  37        my $self = shift;
  38        die "Cannot use readline on FakeTerm: $$self";
  39}
  40package main;
  41
  42
  43sub usage {
  44        print <<EOT;
  45git send-email [options] <file | directory | rev-list options >
  46
  47  Composing:
  48    --from                  <str>  * Email From:
  49    --to                    <str>  * Email To:
  50    --cc                    <str>  * Email Cc:
  51    --bcc                   <str>  * Email Bcc:
  52    --subject               <str>  * Email "Subject:"
  53    --in-reply-to           <str>  * Email "In-Reply-To:"
  54    --compose                      * Open an editor for introduction.
  55
  56  Sending:
  57    --envelope-sender       <str>  * Email envelope sender.
  58    --smtp-server       <str:int>  * Outgoing SMTP server to use. The port
  59                                     is optional. Default 'localhost'.
  60    --smtp-server-port      <int>  * Outgoing SMTP server port.
  61    --smtp-user             <str>  * Username for SMTP-AUTH.
  62    --smtp-pass             <str>  * Password for SMTP-AUTH; not necessary.
  63    --smtp-encryption       <str>  * tls or ssl; anything else disables.
  64    --smtp-ssl                     * Deprecated. Use '--smtp-encryption ssl'.
  65
  66  Automating:
  67    --identity              <str>  * Use the sendemail.<id> options.
  68    --cc-cmd                <str>  * Email Cc: via `<str> \$patch_path`
  69    --suppress-cc           <str>  * author, self, sob, cccmd, all.
  70    --[no-]signed-off-by-cc        * Send to Cc: and Signed-off-by:
  71                                     addresses. Default on.
  72    --[no-]suppress-from           * Send to self. Default off.
  73    --[no-]chain-reply-to          * Chain In-Reply-To: fields. Default on.
  74    --[no-]thread                  * Use In-Reply-To: field. Default on.
  75
  76  Administering:
  77    --quiet                        * Output one line of info per email.
  78    --dry-run                      * Don't actually send the emails.
  79    --[no-]validate                * Perform patch sanity checks. Default on.
  80    --[no-]format-patch            * understand any non optional arguments as
  81                                     `git format-patch` ones.
  82
  83EOT
  84        exit(1);
  85}
  86
  87# most mail servers generate the Date: header, but not all...
  88sub format_2822_time {
  89        my ($time) = @_;
  90        my @localtm = localtime($time);
  91        my @gmttm = gmtime($time);
  92        my $localmin = $localtm[1] + $localtm[2] * 60;
  93        my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
  94        if ($localtm[0] != $gmttm[0]) {
  95                die "local zone differs from GMT by a non-minute interval\n";
  96        }
  97        if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
  98                $localmin += 1440;
  99        } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
 100                $localmin -= 1440;
 101        } elsif ($gmttm[6] != $localtm[6]) {
 102                die "local time offset greater than or equal to 24 hours\n";
 103        }
 104        my $offset = $localmin - $gmtmin;
 105        my $offhour = $offset / 60;
 106        my $offmin = abs($offset % 60);
 107        if (abs($offhour) >= 24) {
 108                die ("local time offset greater than or equal to 24 hours\n");
 109        }
 110
 111        return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
 112                       qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
 113                       $localtm[3],
 114                       qw(Jan Feb Mar Apr May Jun
 115                          Jul Aug Sep Oct Nov Dec)[$localtm[4]],
 116                       $localtm[5]+1900,
 117                       $localtm[2],
 118                       $localtm[1],
 119                       $localtm[0],
 120                       ($offset >= 0) ? '+' : '-',
 121                       abs($offhour),
 122                       $offmin,
 123                       );
 124}
 125
 126my $have_email_valid = eval { require Email::Valid; 1 };
 127my $smtp;
 128my $auth;
 129
 130sub unique_email_list(@);
 131sub cleanup_compose_files();
 132
 133# Variables we fill in automatically, or via prompting:
 134my (@to,@cc,@initial_cc,@bcclist,@xh,
 135        $initial_reply_to,$initial_subject,@files,$author,$sender,$smtp_authpass,$compose,$time);
 136
 137my $envelope_sender;
 138
 139# Example reply to:
 140#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
 141
 142my $repo = eval { Git->repository() };
 143my @repo = $repo ? ($repo) : ();
 144my $term = eval {
 145        $ENV{"GIT_SEND_EMAIL_NOTTY"}
 146                ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
 147                : new Term::ReadLine 'git-send-email';
 148};
 149if ($@) {
 150        $term = new FakeTerm "$@: going non-interactive";
 151}
 152
 153# Behavior modification variables
 154my ($quiet, $dry_run) = (0, 0);
 155my $format_patch;
 156my $compose_filename = $repo->repo_path() . "/.gitsendemail.msg.$$";
 157
 158# Variables with corresponding config settings
 159my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd);
 160my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption);
 161my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts);
 162my ($validate);
 163my (@suppress_cc);
 164
 165my %config_bool_settings = (
 166    "thread" => [\$thread, 1],
 167    "chainreplyto" => [\$chain_reply_to, 1],
 168    "suppressfrom" => [\$suppress_from, undef],
 169    "signedoffbycc" => [\$signed_off_by_cc, undef],
 170    "signedoffcc" => [\$signed_off_by_cc, undef],      # Deprecated
 171    "validate" => [\$validate, 1],
 172);
 173
 174my %config_settings = (
 175    "smtpserver" => \$smtp_server,
 176    "smtpserverport" => \$smtp_server_port,
 177    "smtpuser" => \$smtp_authuser,
 178    "smtppass" => \$smtp_authpass,
 179    "to" => \@to,
 180    "cc" => \@initial_cc,
 181    "cccmd" => \$cc_cmd,
 182    "aliasfiletype" => \$aliasfiletype,
 183    "bcc" => \@bcclist,
 184    "aliasesfile" => \@alias_files,
 185    "suppresscc" => \@suppress_cc,
 186    "envelopesender" => \$envelope_sender,
 187);
 188
 189# Handle Uncouth Termination
 190sub signal_handler {
 191
 192        # Make text normal
 193        print color("reset"), "\n";
 194
 195        # SMTP password masked
 196        system "stty echo";
 197
 198        # tmp files from --compose
 199        if (-e $compose_filename) {
 200                print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
 201        }
 202        if (-e ($compose_filename . ".final")) {
 203                print "'$compose_filename.final' contains the composed email.\n"
 204        }
 205
 206        exit;
 207};
 208
 209$SIG{TERM} = \&signal_handler;
 210$SIG{INT}  = \&signal_handler;
 211
 212# Begin by accumulating all the variables (defined above), that we will end up
 213# needing, first, from the command line:
 214
 215my $rc = GetOptions("sender|from=s" => \$sender,
 216                    "in-reply-to=s" => \$initial_reply_to,
 217                    "subject=s" => \$initial_subject,
 218                    "to=s" => \@to,
 219                    "cc=s" => \@initial_cc,
 220                    "bcc=s" => \@bcclist,
 221                    "chain-reply-to!" => \$chain_reply_to,
 222                    "smtp-server=s" => \$smtp_server,
 223                    "smtp-server-port=s" => \$smtp_server_port,
 224                    "smtp-user=s" => \$smtp_authuser,
 225                    "smtp-pass:s" => \$smtp_authpass,
 226                    "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
 227                    "smtp-encryption=s" => \$smtp_encryption,
 228                    "identity=s" => \$identity,
 229                    "compose" => \$compose,
 230                    "quiet" => \$quiet,
 231                    "cc-cmd=s" => \$cc_cmd,
 232                    "suppress-from!" => \$suppress_from,
 233                    "suppress-cc=s" => \@suppress_cc,
 234                    "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
 235                    "dry-run" => \$dry_run,
 236                    "envelope-sender=s" => \$envelope_sender,
 237                    "thread!" => \$thread,
 238                    "validate!" => \$validate,
 239                    "format-patch!" => \$format_patch,
 240         );
 241
 242unless ($rc) {
 243    usage();
 244}
 245
 246# Now, let's fill any that aren't set in with defaults:
 247
 248sub read_config {
 249        my ($prefix) = @_;
 250
 251        foreach my $setting (keys %config_bool_settings) {
 252                my $target = $config_bool_settings{$setting}->[0];
 253                $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
 254        }
 255
 256        foreach my $setting (keys %config_settings) {
 257                my $target = $config_settings{$setting};
 258                if (ref($target) eq "ARRAY") {
 259                        unless (@$target) {
 260                                my @values = Git::config(@repo, "$prefix.$setting");
 261                                @$target = @values if (@values && defined $values[0]);
 262                        }
 263                }
 264                else {
 265                        $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
 266                }
 267        }
 268
 269        if (!defined $smtp_encryption) {
 270                my $enc = Git::config(@repo, "$prefix.smtpencryption");
 271                if (defined $enc) {
 272                        $smtp_encryption = $enc;
 273                } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
 274                        $smtp_encryption = 'ssl';
 275                }
 276        }
 277}
 278
 279# read configuration from [sendemail "$identity"], fall back on [sendemail]
 280$identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
 281read_config("sendemail.$identity") if (defined $identity);
 282read_config("sendemail");
 283
 284# fall back on builtin bool defaults
 285foreach my $setting (values %config_bool_settings) {
 286        ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
 287}
 288
 289# 'default' encryption is none -- this only prevents a warning
 290$smtp_encryption = '' unless (defined $smtp_encryption);
 291
 292# Set CC suppressions
 293my(%suppress_cc);
 294if (@suppress_cc) {
 295        foreach my $entry (@suppress_cc) {
 296                die "Unknown --suppress-cc field: '$entry'\n"
 297                        unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
 298                $suppress_cc{$entry} = 1;
 299        }
 300}
 301
 302if ($suppress_cc{'all'}) {
 303        foreach my $entry (qw (ccmd cc author self sob)) {
 304                $suppress_cc{$entry} = 1;
 305        }
 306        delete $suppress_cc{'all'};
 307}
 308
 309# If explicit old-style ones are specified, they trump --suppress-cc.
 310$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
 311$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
 312
 313# Debugging, print out the suppressions.
 314if (0) {
 315        print "suppressions:\n";
 316        foreach my $entry (keys %suppress_cc) {
 317                printf "  %-5s -> $suppress_cc{$entry}\n", $entry;
 318        }
 319}
 320
 321my ($repoauthor, $repocommitter);
 322($repoauthor) = Git::ident_person(@repo, 'author');
 323($repocommitter) = Git::ident_person(@repo, 'committer');
 324
 325# Verify the user input
 326
 327foreach my $entry (@to) {
 328        die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
 329}
 330
 331foreach my $entry (@initial_cc) {
 332        die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
 333}
 334
 335foreach my $entry (@bcclist) {
 336        die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
 337}
 338
 339my %aliases;
 340my %parse_alias = (
 341        # multiline formats can be supported in the future
 342        mutt => sub { my $fh = shift; while (<$fh>) {
 343                if (/^\s*alias\s+(\S+)\s+(.*)$/) {
 344                        my ($alias, $addr) = ($1, $2);
 345                        $addr =~ s/#.*$//; # mutt allows # comments
 346                         # commas delimit multiple addresses
 347                        $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
 348                }}},
 349        mailrc => sub { my $fh = shift; while (<$fh>) {
 350                if (/^alias\s+(\S+)\s+(.*)$/) {
 351                        # spaces delimit multiple addresses
 352                        $aliases{$1} = [ split(/\s+/, $2) ];
 353                }}},
 354        pine => sub { my $fh = shift; while (<$fh>) {
 355                if (/^(\S+)\t.*\t(.*)$/) {
 356                        $aliases{$1} = [ split(/\s*,\s*/, $2) ];
 357                }}},
 358        gnus => sub { my $fh = shift; while (<$fh>) {
 359                if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
 360                        $aliases{$1} = [ $2 ];
 361                }}}
 362);
 363
 364if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
 365        foreach my $file (@alias_files) {
 366                open my $fh, '<', $file or die "opening $file: $!\n";
 367                $parse_alias{$aliasfiletype}->($fh);
 368                close $fh;
 369        }
 370}
 371
 372($sender) = expand_aliases($sender) if defined $sender;
 373
 374# returns 1 if the conflict must be solved using it as a format-patch argument
 375sub check_file_rev_conflict($) {
 376        my $f = shift;
 377        try {
 378                $repo->command('rev-parse', '--verify', '--quiet', $f);
 379                if (defined($format_patch)) {
 380                        print "foo\n";
 381                        return $format_patch;
 382                }
 383                die(<<EOF);
 384File '$f' exists but it could also be the range of commits
 385to produce patches for.  Please disambiguate by...
 386
 387    * Saying "./$f" if you mean a file; or
 388    * Giving --format-patch option if you mean a range.
 389EOF
 390        } catch Git::Error::Command with {
 391                return 0;
 392        }
 393}
 394
 395# Now that all the defaults are set, process the rest of the command line
 396# arguments and collect up the files that need to be processed.
 397my @rev_list_opts;
 398while (my $f = pop @ARGV) {
 399        if ($f eq "--") {
 400                push @rev_list_opts, "--", @ARGV;
 401                @ARGV = ();
 402        } elsif (-d $f and !check_file_rev_conflict($f)) {
 403                opendir(DH,$f)
 404                        or die "Failed to opendir $f: $!";
 405
 406                push @files, grep { -f $_ } map { +$f . "/" . $_ }
 407                                sort readdir(DH);
 408                closedir(DH);
 409        } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
 410                push @files, $f;
 411        } else {
 412                push @rev_list_opts, $f;
 413        }
 414}
 415
 416if (@rev_list_opts) {
 417        push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
 418}
 419
 420if ($validate) {
 421        foreach my $f (@files) {
 422                unless (-p $f) {
 423                        my $error = validate_patch($f);
 424                        $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
 425                }
 426        }
 427}
 428
 429if (@files) {
 430        unless ($quiet) {
 431                print $_,"\n" for (@files);
 432        }
 433} else {
 434        print STDERR "\nNo patch files specified!\n\n";
 435        usage();
 436}
 437
 438my $prompting = 0;
 439if (!defined $sender) {
 440        $sender = $repoauthor || $repocommitter || '';
 441
 442        while (1) {
 443                $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
 444                last if defined $_;
 445                print "\n";
 446        }
 447
 448        $sender = $_ if ($_);
 449        print "Emails will be sent from: ", $sender, "\n";
 450        $prompting++;
 451}
 452
 453if (!@to) {
 454
 455
 456        while (1) {
 457                $_ = $term->readline("Who should the emails be sent to? ", "");
 458                last if defined $_;
 459                print "\n";
 460        }
 461
 462        my $to = $_;
 463        push @to, split /,\s*/, $to;
 464        $prompting++;
 465}
 466
 467sub expand_aliases {
 468        my @cur = @_;
 469        my @last;
 470        do {
 471                @last = @cur;
 472                @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
 473        } while (join(',',@cur) ne join(',',@last));
 474        return @cur;
 475}
 476
 477@to = expand_aliases(@to);
 478@to = (map { sanitize_address($_) } @to);
 479@initial_cc = expand_aliases(@initial_cc);
 480@bcclist = expand_aliases(@bcclist);
 481
 482if (!defined $initial_subject && $compose) {
 483        while (1) {
 484                $_ = $term->readline("What subject should the initial email start with? ", $initial_subject);
 485                last if defined $_;
 486                print "\n";
 487        }
 488
 489        $initial_subject = $_;
 490        $prompting++;
 491}
 492
 493if ($thread && !defined $initial_reply_to && $prompting) {
 494        while (1) {
 495                $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
 496                last if defined $_;
 497                print "\n";
 498        }
 499
 500        $initial_reply_to = $_;
 501}
 502if (defined $initial_reply_to) {
 503        $initial_reply_to =~ s/^\s*<?//;
 504        $initial_reply_to =~ s/>?\s*$//;
 505        $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
 506}
 507
 508if (!defined $smtp_server) {
 509        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
 510                if (-x $_) {
 511                        $smtp_server = $_;
 512                        last;
 513                }
 514        }
 515        $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
 516}
 517
 518if ($compose) {
 519        # Note that this does not need to be secure, but we will make a small
 520        # effort to have it be unique
 521        open(C,">",$compose_filename)
 522                or die "Failed to open for writing $compose_filename: $!";
 523        print C "From $sender # This line is ignored.\n";
 524        printf C "Subject: %s\n\n", $initial_subject;
 525        printf C <<EOT;
 526GIT: Please enter your email below.
 527GIT: Lines beginning in "GIT: " will be removed.
 528GIT: Consider including an overall diffstat or table of contents
 529GIT: for the patch you are writing.
 530
 531EOT
 532        close(C);
 533
 534        my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
 535        system('sh', '-c', $editor.' "$@"', $editor, $compose_filename);
 536
 537        open(C2,">",$compose_filename . ".final")
 538                or die "Failed to open $compose_filename.final : " . $!;
 539
 540        open(C,"<",$compose_filename)
 541                or die "Failed to open $compose_filename : " . $!;
 542
 543        my $need_8bit_cte = file_has_nonascii($compose_filename);
 544        my $in_body = 0;
 545        while(<C>) {
 546                next if m/^GIT: /;
 547                if (!$in_body && /^\n$/) {
 548                        $in_body = 1;
 549                        if ($need_8bit_cte) {
 550                                print C2 "MIME-Version: 1.0\n",
 551                                         "Content-Type: text/plain; ",
 552                                           "charset=utf-8\n",
 553                                         "Content-Transfer-Encoding: 8bit\n";
 554                        }
 555                }
 556                if (!$in_body && /^MIME-Version:/i) {
 557                        $need_8bit_cte = 0;
 558                }
 559                if (!$in_body && /^Subject: ?(.*)/i) {
 560                        my $subject = $1;
 561                        $_ = "Subject: " .
 562                                ($subject =~ /[^[:ascii:]]/ ?
 563                                 quote_rfc2047($subject) :
 564                                 $subject) .
 565                                "\n";
 566                }
 567                print C2 $_;
 568        }
 569        close(C);
 570        close(C2);
 571
 572        while (1) {
 573                $_ = $term->readline("Send this email? (y|n) ");
 574                last if defined $_;
 575                print "\n";
 576        }
 577
 578        if (uc substr($_,0,1) ne 'Y') {
 579                cleanup_compose_files();
 580                exit(0);
 581        }
 582
 583        @files = ($compose_filename . ".final", @files);
 584}
 585
 586# Variables we set as part of the loop over files
 587our ($message_id, %mail, $subject, $reply_to, $references, $message);
 588
 589sub extract_valid_address {
 590        my $address = shift;
 591        my $local_part_regexp = '[^<>"\s@]+';
 592        my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
 593
 594        # check for a local address:
 595        return $address if ($address =~ /^($local_part_regexp)$/);
 596
 597        $address =~ s/^\s*<(.*)>\s*$/$1/;
 598        if ($have_email_valid) {
 599                return scalar Email::Valid->address($address);
 600        } else {
 601                # less robust/correct than the monster regexp in Email::Valid,
 602                # but still does a 99% job, and one less dependency
 603                $address =~ /($local_part_regexp\@$domain_regexp)/;
 604                return $1;
 605        }
 606}
 607
 608# Usually don't need to change anything below here.
 609
 610# we make a "fake" message id by taking the current number
 611# of seconds since the beginning of Unix time and tacking on
 612# a random number to the end, in case we are called quicker than
 613# 1 second since the last time we were called.
 614
 615# We'll setup a template for the message id, using the "from" address:
 616
 617my ($message_id_stamp, $message_id_serial);
 618sub make_message_id
 619{
 620        my $uniq;
 621        if (!defined $message_id_stamp) {
 622                $message_id_stamp = sprintf("%s-%s", time, $$);
 623                $message_id_serial = 0;
 624        }
 625        $message_id_serial++;
 626        $uniq = "$message_id_stamp-$message_id_serial";
 627
 628        my $du_part;
 629        for ($sender, $repocommitter, $repoauthor) {
 630                $du_part = extract_valid_address(sanitize_address($_));
 631                last if (defined $du_part and $du_part ne '');
 632        }
 633        if (not defined $du_part or $du_part eq '') {
 634                use Sys::Hostname qw();
 635                $du_part = 'user@' . Sys::Hostname::hostname();
 636        }
 637        my $message_id_template = "<%s-git-send-email-%s>";
 638        $message_id = sprintf($message_id_template, $uniq, $du_part);
 639        #print "new message id = $message_id\n"; # Was useful for debugging
 640}
 641
 642
 643
 644$time = time - scalar $#files;
 645
 646sub unquote_rfc2047 {
 647        local ($_) = @_;
 648        my $encoding;
 649        if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
 650                $encoding = $1;
 651                s/_/ /g;
 652                s/=([0-9A-F]{2})/chr(hex($1))/eg;
 653        }
 654        return wantarray ? ($_, $encoding) : $_;
 655}
 656
 657sub quote_rfc2047 {
 658        local $_ = shift;
 659        my $encoding = shift || 'utf-8';
 660        s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
 661        s/(.*)/=\?$encoding\?q\?$1\?=/;
 662        return $_;
 663}
 664
 665# use the simplest quoting being able to handle the recipient
 666sub sanitize_address
 667{
 668        my ($recipient) = @_;
 669        my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
 670
 671        if (not $recipient_name) {
 672                return "$recipient";
 673        }
 674
 675        # if recipient_name is already quoted, do nothing
 676        if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
 677                return $recipient;
 678        }
 679
 680        # rfc2047 is needed if a non-ascii char is included
 681        if ($recipient_name =~ /[^[:ascii:]]/) {
 682                $recipient_name = quote_rfc2047($recipient_name);
 683        }
 684
 685        # double quotes are needed if specials or CTLs are included
 686        elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
 687                $recipient_name =~ s/(["\\\r])/\\$1/g;
 688                $recipient_name = "\"$recipient_name\"";
 689        }
 690
 691        return "$recipient_name $recipient_addr";
 692
 693}
 694
 695sub send_message
 696{
 697        my @recipients = unique_email_list(@to);
 698        @cc = (grep { my $cc = extract_valid_address($_);
 699                      not grep { $cc eq $_ } @recipients
 700                    }
 701               map { sanitize_address($_) }
 702               @cc);
 703        my $to = join (",\n\t", @recipients);
 704        @recipients = unique_email_list(@recipients,@cc,@bcclist);
 705        @recipients = (map { extract_valid_address($_) } @recipients);
 706        my $date = format_2822_time($time++);
 707        my $gitversion = '@@GIT_VERSION@@';
 708        if ($gitversion =~ m/..GIT_VERSION../) {
 709            $gitversion = Git::version();
 710        }
 711
 712        my $cc = join(", ", unique_email_list(@cc));
 713        my $ccline = "";
 714        if ($cc ne '') {
 715                $ccline = "\nCc: $cc";
 716        }
 717        my $sanitized_sender = sanitize_address($sender);
 718        make_message_id() unless defined($message_id);
 719
 720        my $header = "From: $sanitized_sender
 721To: $to${ccline}
 722Subject: $subject
 723Date: $date
 724Message-Id: $message_id
 725X-Mailer: git-send-email $gitversion
 726";
 727        if ($thread && $reply_to) {
 728
 729                $header .= "In-Reply-To: $reply_to\n";
 730                $header .= "References: $references\n";
 731        }
 732        if (@xh) {
 733                $header .= join("\n", @xh) . "\n";
 734        }
 735
 736        my @sendmail_parameters = ('-i', @recipients);
 737        my $raw_from = $sanitized_sender;
 738        $raw_from = $envelope_sender if (defined $envelope_sender);
 739        $raw_from = extract_valid_address($raw_from);
 740        unshift (@sendmail_parameters,
 741                        '-f', $raw_from) if(defined $envelope_sender);
 742
 743        if ($dry_run) {
 744                # We don't want to send the email.
 745        } elsif ($smtp_server =~ m#^/#) {
 746                my $pid = open my $sm, '|-';
 747                defined $pid or die $!;
 748                if (!$pid) {
 749                        exec($smtp_server, @sendmail_parameters) or die $!;
 750                }
 751                print $sm "$header\n$message";
 752                close $sm or die $?;
 753        } else {
 754
 755                if (!defined $smtp_server) {
 756                        die "The required SMTP server is not properly defined."
 757                }
 758
 759                if ($smtp_encryption eq 'ssl') {
 760                        $smtp_server_port ||= 465; # ssmtp
 761                        require Net::SMTP::SSL;
 762                        $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
 763                }
 764                else {
 765                        require Net::SMTP;
 766                        $smtp ||= Net::SMTP->new((defined $smtp_server_port)
 767                                                 ? "$smtp_server:$smtp_server_port"
 768                                                 : $smtp_server);
 769                        if ($smtp_encryption eq 'tls') {
 770                                require Net::SMTP::SSL;
 771                                $smtp->command('STARTTLS');
 772                                $smtp->response();
 773                                if ($smtp->code == 220) {
 774                                        $smtp = Net::SMTP::SSL->start_SSL($smtp)
 775                                                or die "STARTTLS failed! ".$smtp->message;
 776                                        $smtp_encryption = '';
 777                                        # Send EHLO again to receive fresh
 778                                        # supported commands
 779                                        $smtp->hello();
 780                                } else {
 781                                        die "Server does not support STARTTLS! ".$smtp->message;
 782                                }
 783                        }
 784                }
 785
 786                if (!$smtp) {
 787                        die "Unable to initialize SMTP properly.  Is there something wrong with your config?";
 788                }
 789
 790                if (defined $smtp_authuser) {
 791
 792                        if (!defined $smtp_authpass) {
 793
 794                                system "stty -echo";
 795
 796                                do {
 797                                        print "Password: ";
 798                                        $_ = <STDIN>;
 799                                        print "\n";
 800                                } while (!defined $_);
 801
 802                                chomp($smtp_authpass = $_);
 803
 804                                system "stty echo";
 805                        }
 806
 807                        $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
 808                }
 809
 810                $smtp->mail( $raw_from ) or die $smtp->message;
 811                $smtp->to( @recipients ) or die $smtp->message;
 812                $smtp->data or die $smtp->message;
 813                $smtp->datasend("$header\n$message") or die $smtp->message;
 814                $smtp->dataend() or die $smtp->message;
 815                $smtp->ok or die "Failed to send $subject\n".$smtp->message;
 816        }
 817        if ($quiet) {
 818                printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
 819        } else {
 820                print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
 821                if ($smtp_server !~ m#^/#) {
 822                        print "Server: $smtp_server\n";
 823                        print "MAIL FROM:<$raw_from>\n";
 824                        print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
 825                } else {
 826                        print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
 827                }
 828                print $header, "\n";
 829                if ($smtp) {
 830                        print "Result: ", $smtp->code, ' ',
 831                                ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
 832                } else {
 833                        print "Result: OK\n";
 834                }
 835        }
 836}
 837
 838$reply_to = $initial_reply_to;
 839$references = $initial_reply_to || '';
 840$subject = $initial_subject;
 841
 842foreach my $t (@files) {
 843        open(F,"<",$t) or die "can't open file $t";
 844
 845        my $author = undef;
 846        my $author_encoding;
 847        my $has_content_type;
 848        my $body_encoding;
 849        @cc = @initial_cc;
 850        @xh = ();
 851        my $input_format = undef;
 852        my $header_done = 0;
 853        $message = "";
 854        while(<F>) {
 855                if (!$header_done) {
 856                        if (/^From /) {
 857                                $input_format = 'mbox';
 858                                next;
 859                        }
 860                        chomp;
 861                        if (!defined $input_format && /^[-A-Za-z]+:\s/) {
 862                                $input_format = 'mbox';
 863                        }
 864
 865                        if (defined $input_format && $input_format eq 'mbox') {
 866                                if (/^Subject:\s+(.*)$/) {
 867                                        $subject = $1;
 868
 869                                } elsif (/^(Cc|From):\s+(.*)$/) {
 870                                        if (unquote_rfc2047($2) eq $sender) {
 871                                                next if ($suppress_cc{'self'});
 872                                        }
 873                                        elsif ($1 eq 'From') {
 874                                                ($author, $author_encoding)
 875                                                  = unquote_rfc2047($2);
 876                                                next if ($suppress_cc{'author'});
 877                                        } else {
 878                                                next if ($suppress_cc{'cc'});
 879                                        }
 880                                        printf("(mbox) Adding cc: %s from line '%s'\n",
 881                                                $2, $_) unless $quiet;
 882                                        push @cc, $2;
 883                                }
 884                                elsif (/^Content-type:/i) {
 885                                        $has_content_type = 1;
 886                                        if (/charset="?([^ "]+)/) {
 887                                                $body_encoding = $1;
 888                                        }
 889                                        push @xh, $_;
 890                                }
 891                                elsif (/^Message-Id: (.*)/i) {
 892                                        $message_id = $1;
 893                                }
 894                                elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
 895                                        push @xh, $_;
 896                                }
 897
 898                        } else {
 899                                # In the traditional
 900                                # "send lots of email" format,
 901                                # line 1 = cc
 902                                # line 2 = subject
 903                                # So let's support that, too.
 904                                $input_format = 'lots';
 905                                if (@cc == 0 && !$suppress_cc{'cc'}) {
 906                                        printf("(non-mbox) Adding cc: %s from line '%s'\n",
 907                                                $_, $_) unless $quiet;
 908
 909                                        push @cc, $_;
 910
 911                                } elsif (!defined $subject) {
 912                                        $subject = $_;
 913                                }
 914                        }
 915
 916                        # A whitespace line will terminate the headers
 917                        if (m/^\s*$/) {
 918                                $header_done = 1;
 919                        }
 920                } else {
 921                        $message .=  $_;
 922                        if (/^(Signed-off-by|Cc): (.*)$/i) {
 923                                next if ($suppress_cc{'sob'});
 924                                chomp;
 925                                my $c = $2;
 926                                chomp $c;
 927                                next if ($c eq $sender and $suppress_cc{'self'});
 928                                push @cc, $c;
 929                                printf("(sob) Adding cc: %s from line '%s'\n",
 930                                        $c, $_) unless $quiet;
 931                        }
 932                }
 933        }
 934        close F;
 935
 936        if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
 937                open(F, "$cc_cmd $t |")
 938                        or die "(cc-cmd) Could not execute '$cc_cmd'";
 939                while(<F>) {
 940                        my $c = $_;
 941                        $c =~ s/^\s*//g;
 942                        $c =~ s/\n$//g;
 943                        next if ($c eq $sender and $suppress_from);
 944                        push @cc, $c;
 945                        printf("(cc-cmd) Adding cc: %s from: '%s'\n",
 946                                $c, $cc_cmd) unless $quiet;
 947                }
 948                close F
 949                        or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
 950        }
 951
 952        if (defined $author) {
 953                $message = "From: $author\n\n$message";
 954                if (defined $author_encoding) {
 955                        if ($has_content_type) {
 956                                if ($body_encoding eq $author_encoding) {
 957                                        # ok, we already have the right encoding
 958                                }
 959                                else {
 960                                        # uh oh, we should re-encode
 961                                }
 962                        }
 963                        else {
 964                                push @xh,
 965                                  'MIME-Version: 1.0',
 966                                  "Content-Type: text/plain; charset=$author_encoding",
 967                                  'Content-Transfer-Encoding: 8bit';
 968                        }
 969                }
 970        }
 971
 972        send_message();
 973
 974        # set up for the next message
 975        if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
 976                $reply_to = $message_id;
 977                if (length $references > 0) {
 978                        $references .= "\n $message_id";
 979                } else {
 980                        $references = "$message_id";
 981                }
 982        }
 983        $message_id = undef;
 984}
 985
 986if ($compose) {
 987        cleanup_compose_files();
 988}
 989
 990sub cleanup_compose_files() {
 991        unlink($compose_filename, $compose_filename . ".final");
 992
 993}
 994
 995$smtp->quit if $smtp;
 996
 997sub unique_email_list(@) {
 998        my %seen;
 999        my @emails;
1000
1001        foreach my $entry (@_) {
1002                if (my $clean = extract_valid_address($entry)) {
1003                        $seen{$clean} ||= 0;
1004                        next if $seen{$clean}++;
1005                        push @emails, $entry;
1006                } else {
1007                        print STDERR "W: unable to extract a valid address",
1008                                        " from: $entry\n";
1009                }
1010        }
1011        return @emails;
1012}
1013
1014sub validate_patch {
1015        my $fn = shift;
1016        open(my $fh, '<', $fn)
1017                or die "unable to open $fn: $!\n";
1018        while (my $line = <$fh>) {
1019                if (length($line) > 998) {
1020                        return "$.: patch contains a line longer than 998 characters";
1021                }
1022        }
1023        return undef;
1024}
1025
1026sub file_has_nonascii {
1027        my $fn = shift;
1028        open(my $fh, '<', $fn)
1029                or die "unable to open $fn: $!\n";
1030        while (my $line = <$fh>) {
1031                return 1 if $line =~ /[^[:ascii:]]/;
1032        }
1033        return 0;
1034}