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