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