]> git.ipfire.org Git - thirdparty/git.git/blame - git-send-email.perl
Git 2.32.7
[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;
f916ab0c 22use POSIX qw/strftime/;
83b24437 23use Term::ReadLine;
83b24437 24use Getopt::Long;
0e73b3ee 25use Text::ParseWords;
412876dc 26use Term::ANSIColor;
eed6ca7c 27use File::Temp qw/ tempdir tempfile /;
6489660b 28use File::Spec::Functions qw(catdir catfile);
28654678 29use Git::LoadCPAN::Error qw(:try);
6489660b 30use Cwd qw(abs_path cwd);
3cb8caf7 31use Git;
a4dde4c4 32use Git::I18N;
1046c118
ÆAB
33use Net::Domain ();
34use Net::SMTP ();
28654678 35use Git::LoadCPAN::Mail::Address;
83b24437 36
5df9fcf6
PH
37Getopt::Long::Configure qw/ pass_through /;
38
280242d1
JH
39package FakeTerm;
40sub new {
41 my ($class, $reason) = @_;
42 return bless \$reason, shift;
43}
44sub readline {
45 my $self = shift;
46 die "Cannot use readline on FakeTerm: $$self";
47}
48package main;
49
1b0baf14
MC
50
51sub usage {
52 print <<EOT;
5df9fcf6 53git send-email [options] <file | directory | rev-list options >
17b7a832 54git send-email --dump-aliases
4ed62b03
MW
55
56 Composing:
57 --from <str> * Email From:
f434c083
SB
58 --[no-]to <str> * Email To:
59 --[no-]cc <str> * Email Cc:
60 --[no-]bcc <str> * Email Bcc:
4ed62b03 61 --subject <str> * Email "Subject:"
d11c943c 62 --reply-to <str> * Email "Reply-To:"
4ed62b03 63 --in-reply-to <str> * Email "In-Reply-To:"
ac1596a6 64 --[no-]xmailer * Add "X-Mailer:" header (default).
402596aa 65 --[no-]annotate * Review each patch that will be sent in an editor.
4ed62b03 66 --compose * Open an editor for introduction.
62e00690 67 --compose-encoding <str> * Encoding to assume for introduction.
3cae7e5b 68 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
8d814084 69 --transfer-encoding <str> * Transfer encoding to use (quoted-printable, 8bit, base64)
4ed62b03
MW
70
71 Sending:
72 --envelope-sender <str> * Email envelope sender.
73 --smtp-server <str:int> * Outgoing SMTP server to use. The port
74 is optional. Default 'localhost'.
052fbea2 75 --smtp-server-option <str> * Outgoing SMTP server option to use.
4ed62b03
MW
76 --smtp-server-port <int> * Outgoing SMTP server port.
77 --smtp-user <str> * Username for SMTP-AUTH.
78 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
79 --smtp-encryption <str> * tls or ssl; anything else disables.
80 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
35035bbf
RR
81 --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
82 Pass an empty string to disable certificate
83 verification.
134550fe 84 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
8dd9b3f8
JW
85 --smtp-auth <str> * Space-separated list of allowed AUTH mechanisms, or
86 "none" to disable authentication.
0f2e68b5 87 This setting forces to use one of the listed mechanisms.
8dd9b3f8
JW
88 --no-smtp-auth Disable SMTP authentication. Shorthand for
89 `--smtp-auth=none`
f60812ef 90 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
4ed62b03 91
5453b83b 92 --batch-size <int> * send max <int> message per connection.
93 --relogin-delay <int> * delay <int> seconds between two successive login.
94 This option can only be used with --batch-size
95
4ed62b03
MW
96 Automating:
97 --identity <str> * Use the sendemail.<id> options.
6e74e075 98 --to-cmd <str> * Email To: via `<str> \$patch_path`
4ed62b03 99 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
ef0cc1df 100 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, misc-by, all.
f515c904
MT
101 --[no-]cc-cover * Email Cc: addresses in the cover letter.
102 --[no-]to-cover * Email To: addresses in the cover letter.
3531e270 103 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
4ed62b03 104 --[no-]suppress-from * Send to self. Default off.
41fe87fa 105 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
4ed62b03
MW
106 --[no-]thread * Use In-Reply-To: field. Default on.
107
108 Administering:
c1f2aa45
JS
109 --confirm <str> * Confirm recipients before sending;
110 auto, cc, compose, always, or never.
4ed62b03
MW
111 --quiet * Output one line of info per email.
112 --dry-run * Don't actually send the emails.
113 --[no-]validate * Perform patch sanity checks. Default on.
5df9fcf6
PH
114 --[no-]format-patch * understand any non optional arguments as
115 `git format-patch` ones.
a03bc5b6 116 --force * Send even if safety checks would prevent it.
c764a0c2 117
17b7a832
JK
118 Information:
119 --dump-aliases * Dump configured aliases and exit.
120
1b0baf14
MC
121EOT
122 exit(1);
123}
124
13374987
NTND
125sub completion_helper {
126 print Git::command('format-patch', '--git-completion-helper');
127 exit(0);
128}
129
4bc87a28 130# most mail servers generate the Date: header, but not all...
6bdca890
JN
131sub format_2822_time {
132 my ($time) = @_;
133 my @localtm = localtime($time);
134 my @gmttm = gmtime($time);
135 my $localmin = $localtm[1] + $localtm[2] * 60;
136 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
137 if ($localtm[0] != $gmttm[0]) {
46493105 138 die __("local zone differs from GMT by a non-minute interval\n");
6bdca890
JN
139 }
140 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
141 $localmin += 1440;
142 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
143 $localmin -= 1440;
144 } elsif ($gmttm[6] != $localtm[6]) {
46493105 145 die __("local time offset greater than or equal to 24 hours\n");
6bdca890
JN
146 }
147 my $offset = $localmin - $gmtmin;
148 my $offhour = $offset / 60;
149 my $offmin = abs($offset % 60);
150 if (abs($offhour) >= 24) {
46493105 151 die __("local time offset greater than or equal to 24 hours\n");
6bdca890
JN
152 }
153
154 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
155 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
156 $localtm[3],
157 qw(Jan Feb Mar Apr May Jun
158 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
159 $localtm[5]+1900,
160 $localtm[2],
161 $localtm[1],
162 $localtm[0],
163 ($offset >= 0) ? '+' : '-',
164 abs($offhour),
165 $offmin,
166 );
167}
4bc87a28 168
567ffeb7 169my $have_email_valid = eval { require Email::Valid; 1 };
4bc87a28 170my $smtp;
5f5b6118 171my $auth;
5453b83b 172my $num_sent = 0;
4bc87a28 173
11f70a7e
РД
174# Regexes for RFC 2047 productions.
175my $re_token = qr/[^][()<>@,;:\\"\/?.= \000-\037\177-\377]+/;
176my $re_encoded_text = qr/[^? \000-\037\177-\377]+/;
177my $re_encoded_word = qr/=\?($re_token)\?($re_token)\?($re_encoded_text)\?=/;
178
83b24437 179# Variables we fill in automatically, or via prompting:
3494dfd3 180my (@to,@cc,@xh,$envelope_sender,
d11c943c 181 $initial_in_reply_to,$reply_to,$initial_subject,@files,
3494dfd3
ÆAB
182 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
183# Things we either get from config, *or* are overridden on the
184# command-line.
3ff15040 185my ($no_cc, $no_to, $no_bcc, $no_identity);
3494dfd3
ÆAB
186my (@config_to, @getopt_to);
187my (@config_cc, @getopt_cc);
188my (@config_bcc, @getopt_bcc);
78488b2c 189
9133261f 190# Example reply to:
15dc3b91 191#$initial_in_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
83b24437 192
ad79c024
FL
193my $repo = eval { Git->repository() };
194my @repo = $repo ? ($repo) : ();
280242d1 195my $term = eval {
0fb7fc75
JS
196 $ENV{"GIT_SEND_EMAIL_NOTTY"}
197 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
198 : new Term::ReadLine 'git-send-email';
280242d1
JH
199};
200if ($@) {
201 $term = new FakeTerm "$@: going non-interactive";
202}
83b24437 203
5483c71d
AR
204# Behavior modification variables
205my ($quiet, $dry_run) = (0, 0);
5df9fcf6 206my $format_patch;
afe756c9 207my $compose_filename;
a03bc5b6 208my $force = 0;
17b7a832 209my $dump_aliases = 0;
5483c71d 210
8fd5bb7f
PH
211# Handle interactive edition of files.
212my $multiedit;
0ce142c9 213my $editor;
b4479f07 214
d21616c0
ÆAB
215sub system_or_msg {
216 my ($args, $msg) = @_;
217 system(@$args);
218 my $signalled = $? & 127;
219 my $exit_code = $? >> 8;
220 return unless $signalled or $exit_code;
221
5b719b75
ÆAB
222 my @sprintf_args = ($args->[0], $exit_code);
223 if (defined $msg) {
224 # Quiet the 'redundant' warning category, except we
225 # need to support down to Perl 5.8, so we can't do a
226 # "no warnings 'redundant'", since that category was
227 # introduced in perl 5.22, and asking for it will die
228 # on older perls.
229 no warnings;
230 return sprintf($msg, @sprintf_args);
231 }
ea7811b3 232 return sprintf(__("fatal: command '%s' died with exit code %d"),
5b719b75 233 @sprintf_args);
d21616c0
ÆAB
234}
235
236sub system_or_die {
237 my $msg = system_or_msg(@_);
238 die $msg if $msg;
239}
240
8fd5bb7f 241sub do_edit {
0ce142c9
MG
242 if (!defined($editor)) {
243 $editor = Git::command_oneline('var', 'GIT_EDITOR');
244 }
d21616c0 245 my $die_msg = __("the editor exited uncleanly, aborting everything");
8fd5bb7f 246 if (defined($multiedit) && !$multiedit) {
d21616c0 247 system_or_die(['sh', '-c', $editor.' "$@"', $editor, $_], $die_msg) for @_;
8fd5bb7f 248 } else {
d21616c0 249 system_or_die(['sh', '-c', $editor.' "$@"', $editor, @_], $die_msg);
8fd5bb7f
PH
250 }
251}
5483c71d
AR
252
253# Variables with corresponding config settings
3494dfd3 254my ($suppress_from, $signed_off_by_cc);
f515c904 255my ($cover_cc, $cover_to);
6e74e075 256my ($to_cmd, $cc_cmd);
052fbea2 257my ($smtp_server, $smtp_server_port, @smtp_server_options);
35035bbf 258my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
5453b83b 259my ($batch_size, $relogin_delay);
0f2e68b5 260my ($identity, $aliasfiletype, @alias_files, $smtp_domain, $smtp_auth);
3494dfd3 261my ($confirm);
65648283 262my (@suppress_cc);
3cae7e5b 263my ($auto_8bit_encoding);
62e00690 264my ($compose_encoding);
3494dfd3 265# Variables with corresponding config settings & hardcoded defaults
f60812ef 266my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
3494dfd3
ÆAB
267my $thread = 1;
268my $chain_reply_to = 0;
269my $use_xmailer = 1;
270my $validate = 1;
271my $target_xfer_encoding = 'auto';
dd84e528 272my $forbid_sendmail_variables = 1;
f60812ef 273
34cc60ce 274my %config_bool_settings = (
3494dfd3
ÆAB
275 "thread" => \$thread,
276 "chainreplyto" => \$chain_reply_to,
277 "suppressfrom" => \$suppress_from,
278 "signedoffbycc" => \$signed_off_by_cc,
279 "cccover" => \$cover_cc,
280 "tocover" => \$cover_to,
281 "signedoffcc" => \$signed_off_by_cc,
282 "validate" => \$validate,
283 "multiedit" => \$multiedit,
284 "annotate" => \$annotate,
285 "xmailer" => \$use_xmailer,
dd84e528 286 "forbidsendmailvariables" => \$forbid_sendmail_variables,
e46f7a0e
AR
287);
288
34cc60ce
DS
289my %config_settings = (
290 "smtpserver" => \$smtp_server,
44b2476a 291 "smtpserverport" => \$smtp_server_port,
052fbea2 292 "smtpserveroption" => \@smtp_server_options,
34cc60ce
DS
293 "smtpuser" => \$smtp_authuser,
294 "smtppass" => \$smtp_authpass,
e1e9115d 295 "smtpdomain" => \$smtp_domain,
0f2e68b5 296 "smtpauth" => \$smtp_auth,
5453b83b 297 "smtpbatchsize" => \$batch_size,
298 "smtprelogindelay" => \$relogin_delay,
3494dfd3 299 "to" => \@config_to,
6e74e075 300 "tocmd" => \$to_cmd,
3494dfd3 301 "cc" => \@config_cc,
34cc60ce
DS
302 "cccmd" => \$cc_cmd,
303 "aliasfiletype" => \$aliasfiletype,
3494dfd3 304 "bcc" => \@config_bcc,
65648283 305 "suppresscc" => \@suppress_cc,
9f7820ae 306 "envelopesender" => \$envelope_sender,
c1f2aa45 307 "confirm" => \$confirm,
09caa24f 308 "from" => \$sender,
3cae7e5b 309 "assume8bitencoding" => \$auto_8bit_encoding,
62e00690 310 "composeencoding" => \$compose_encoding,
8d814084 311 "transferencoding" => \$target_xfer_encoding,
34cc60ce 312);
4a62d3f5 313
cec5dae8
CS
314my %config_path_settings = (
315 "aliasesfile" => \@alias_files,
6e07a3b5 316 "smtpsslcertpath" => \$smtp_ssl_cert_path,
cec5dae8
CS
317);
318
87429976
MW
319# Handle Uncouth Termination
320sub signal_handler {
321
322 # Make text normal
323 print color("reset"), "\n";
324
325 # SMTP password masked
326 system "stty echo";
327
328 # tmp files from --compose
afe756c9
JS
329 if (defined $compose_filename) {
330 if (-e $compose_filename) {
3c5cd20c
VA
331 printf __("'%s' contains an intermediate version ".
332 "of the email you were composing.\n"),
333 $compose_filename;
afe756c9
JS
334 }
335 if (-e ($compose_filename . ".final")) {
3c5cd20c
VA
336 printf __("'%s.final' contains the composed email.\n"),
337 $compose_filename;
afe756c9 338 }
87429976
MW
339 }
340
341 exit;
342};
343
344$SIG{TERM} = \&signal_handler;
345$SIG{INT} = \&signal_handler;
346
c573572c
ÆAB
347# Read our sendemail.* config
348sub read_config {
3ff15040 349 my ($configured, $prefix) = @_;
c573572c
ÆAB
350
351 foreach my $setting (keys %config_bool_settings) {
3494dfd3
ÆAB
352 my $target = $config_bool_settings{$setting};
353 my $v = Git::config_bool(@repo, "$prefix.$setting");
3ff15040
ÆAB
354 next unless defined $v;
355 next if $configured->{$setting}++;
356 $$target = $v;
c573572c
ÆAB
357 }
358
359 foreach my $setting (keys %config_path_settings) {
360 my $target = $config_path_settings{$setting};
361 if (ref($target) eq "ARRAY") {
3ff15040
ÆAB
362 my @values = Git::config_path(@repo, "$prefix.$setting");
363 next unless @values;
364 next if $configured->{$setting}++;
365 @$target = @values;
c573572c
ÆAB
366 }
367 else {
3494dfd3 368 my $v = Git::config_path(@repo, "$prefix.$setting");
3ff15040
ÆAB
369 next unless defined $v;
370 next if $configured->{$setting}++;
371 $$target = $v;
c573572c
ÆAB
372 }
373 }
374
375 foreach my $setting (keys %config_settings) {
376 my $target = $config_settings{$setting};
c573572c 377 if (ref($target) eq "ARRAY") {
3ff15040
ÆAB
378 my @values = Git::config(@repo, "$prefix.$setting");
379 next unless @values;
380 next if $configured->{$setting}++;
381 @$target = @values;
c573572c
ÆAB
382 }
383 else {
3494dfd3 384 my $v = Git::config(@repo, "$prefix.$setting");
3ff15040
ÆAB
385 next unless defined $v;
386 next if $configured->{$setting}++;
387 $$target = $v;
c573572c
ÆAB
388 }
389 }
390
391 if (!defined $smtp_encryption) {
3ff15040
ÆAB
392 my $setting = "$prefix.smtpencryption";
393 my $enc = Git::config(@repo, $setting);
394 return unless defined $enc;
395 return if $configured->{$setting}++;
c573572c
ÆAB
396 if (defined $enc) {
397 $smtp_encryption = $enc;
398 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
399 $smtp_encryption = 'ssl';
400 }
401 }
402}
403
3ff15040
ÆAB
404# sendemail.identity yields to --identity. We must parse this
405# special-case first before the rest of the config is read.
3494dfd3 406$identity = Git::config(@repo, "sendemail.identity");
3ff15040
ÆAB
407my $rc = GetOptions(
408 "identity=s" => \$identity,
409 "no-identity" => \$no_identity,
410);
411usage() unless $rc;
412undef $identity if $no_identity;
413
414# Now we know enough to read the config
415{
416 my %configured;
417 read_config(\%configured, "sendemail.$identity") if defined $identity;
418 read_config(\%configured, "sendemail");
419}
3494dfd3 420
83b24437
RA
421# Begin by accumulating all the variables (defined above), that we will end up
422# needing, first, from the command line:
423
c5978246 424my $help;
13374987 425my $git_completion_helper;
3ff15040
ÆAB
426$rc = GetOptions("h" => \$help,
427 "dump-aliases" => \$dump_aliases);
17b7a832 428usage() unless $rc;
46493105 429die __("--dump-aliases incompatible with other options\n")
17b7a832
JK
430 if !$help and $dump_aliases and @ARGV;
431$rc = GetOptions(
c5978246 432 "sender|from=s" => \$sender,
15dc3b91 433 "in-reply-to=s" => \$initial_in_reply_to,
d11c943c 434 "reply-to=s" => \$reply_to,
83b24437 435 "subject=s" => \$initial_subject,
3494dfd3 436 "to=s" => \@getopt_to,
6e74e075 437 "to-cmd=s" => \$to_cmd,
f434c083 438 "no-to" => \$no_to,
3494dfd3 439 "cc=s" => \@getopt_cc,
f434c083 440 "no-cc" => \$no_cc,
3494dfd3 441 "bcc=s" => \@getopt_bcc,
f434c083 442 "no-bcc" => \$no_bcc,
78488b2c 443 "chain-reply-to!" => \$chain_reply_to,
f4714943 444 "no-chain-reply-to" => sub {$chain_reply_to = 0},
3342d850 445 "smtp-server=s" => \$smtp_server,
052fbea2 446 "smtp-server-option=s" => \@smtp_server_options,
44b2476a 447 "smtp-server-port=s" => \$smtp_server_port,
34cc60ce 448 "smtp-user=s" => \$smtp_authuser,
2363d746 449 "smtp-pass:s" => \$smtp_authpass,
f6bebd12
TR
450 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
451 "smtp-encryption=s" => \$smtp_encryption,
979e652a 452 "smtp-ssl-cert-path=s" => \$smtp_ssl_cert_path,
f60812ef 453 "smtp-debug:i" => \$debug_net_smtp,
69cf7bfd 454 "smtp-domain:s" => \$smtp_domain,
0f2e68b5 455 "smtp-auth=s" => \$smtp_auth,
8dd9b3f8 456 "no-smtp-auth" => sub {$smtp_auth = 'none'},
402596aa 457 "annotate!" => \$annotate,
f4714943 458 "no-annotate" => sub {$annotate = 0},
1f038a0c 459 "compose" => \$compose,
30d08b34 460 "quiet" => \$quiet,
324a8bd0 461 "cc-cmd=s" => \$cc_cmd,
5483c71d 462 "suppress-from!" => \$suppress_from,
f4714943 463 "no-suppress-from" => sub {$suppress_from = 0},
65648283 464 "suppress-cc=s" => \@suppress_cc,
ddc3d4fe 465 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
f4714943 466 "no-signed-off-cc|no-signed-off-by-cc" => sub {$signed_off_by_cc = 0},
f515c904 467 "cc-cover|cc-cover!" => \$cover_cc,
f4714943 468 "no-cc-cover" => sub {$cover_cc = 0},
f515c904 469 "to-cover|to-cover!" => \$cover_to,
f4714943 470 "no-to-cover" => sub {$cover_to = 0},
c1f2aa45 471 "confirm=s" => \$confirm,
6130259c 472 "dry-run" => \$dry_run,
f073a592 473 "envelope-sender=s" => \$envelope_sender,
5483c71d 474 "thread!" => \$thread,
f4714943 475 "no-thread" => sub {$thread = 0},
dbf5e1e9 476 "validate!" => \$validate,
f4714943 477 "no-validate" => sub {$validate = 0},
8d814084 478 "transfer-encoding=s" => \$target_xfer_encoding,
5df9fcf6 479 "format-patch!" => \$format_patch,
f4714943 480 "no-format-patch" => sub {$format_patch = 0},
3cae7e5b 481 "8bit-encoding=s" => \$auto_8bit_encoding,
62e00690 482 "compose-encoding=s" => \$compose_encoding,
a03bc5b6 483 "force" => \$force,
ac1596a6 484 "xmailer!" => \$use_xmailer,
f4714943 485 "no-xmailer" => sub {$use_xmailer = 0},
5453b83b 486 "batch-size=i" => \$batch_size,
487 "relogin-delay=i" => \$relogin_delay,
13374987 488 "git-completion-helper" => \$git_completion_helper,
83b24437
RA
489 );
490
3494dfd3
ÆAB
491# Munge any "either config or getopt, not both" variables
492my @initial_to = @getopt_to ? @getopt_to : ($no_to ? () : @config_to);
493my @initial_cc = @getopt_cc ? @getopt_cc : ($no_cc ? () : @config_cc);
494my @initial_bcc = @getopt_bcc ? @getopt_bcc : ($no_bcc ? () : @config_bcc);
495
c5978246 496usage() if $help;
13374987 497completion_helper() if $git_completion_helper;
1b0baf14
MC
498unless ($rc) {
499 usage();
500}
501
dd84e528
DD
502if ($forbid_sendmail_variables && (scalar Git::config_regexp("^sendmail[.]")) != 0) {
503 die __("fatal: found configuration options for 'sendmail'\n" .
504 "git-send-email is configured with the sendemail.* options - note the 'e'.\n" .
505 "Set sendemail.forbidSendmailVariables to false to disable this check.\n");
506}
507
46493105 508die __("Cannot run git format-patch from outside a repository\n")
eed6ca7c
JS
509 if $format_patch and not $repo;
510
9caa7069
SB
511die __("`batch-size` and `relogin` must be specified together " .
512 "(via command-line or configuration option)\n")
513 if defined $relogin_delay and not defined $batch_size;
514
fa835cd5
TR
515# 'default' encryption is none -- this only prevents a warning
516$smtp_encryption = '' unless (defined $smtp_encryption);
517
65648283
DB
518# Set CC suppressions
519my(%suppress_cc);
520if (@suppress_cc) {
521 foreach my $entry (@suppress_cc) {
5a59a230
NTND
522 # Please update $__git_send_email_suppresscc_options
523 # in git-completion.bash when you add new options.
3c5cd20c 524 die sprintf(__("Unknown --suppress-cc field: '%s'\n"), $entry)
ef0cc1df 525 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc|misc-by)$/;
65648283
DB
526 $suppress_cc{$entry} = 1;
527 }
528}
529
530if ($suppress_cc{'all'}) {
ef0cc1df 531 foreach my $entry (qw (cccmd cc author self sob body bodycc misc-by)) {
65648283
DB
532 $suppress_cc{$entry} = 1;
533 }
534 delete $suppress_cc{'all'};
535}
536
537# If explicit old-style ones are specified, they trump --suppress-cc.
538$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
ddc3d4fe 539$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
65648283 540
3531e270 541if ($suppress_cc{'body'}) {
ef0cc1df 542 foreach my $entry (qw (sob bodycc misc-by)) {
3531e270
JS
543 $suppress_cc{$entry} = 1;
544 }
545 delete $suppress_cc{'body'};
546}
547
c1f2aa45
JS
548# Set confirm's default value
549my $confirm_unconfigured = !defined $confirm;
550if ($confirm_unconfigured) {
551 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
552};
5a59a230
NTND
553# Please update $__git_send_email_confirm_options in
554# git-completion.bash when you add new options.
3c5cd20c 555die sprintf(__("Unknown --confirm setting: '%s'\n"), $confirm)
c1f2aa45
JS
556 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
557
65648283
DB
558# Debugging, print out the suppressions.
559if (0) {
560 print "suppressions:\n";
561 foreach my $entry (keys %suppress_cc) {
562 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
563 }
564}
565
ad79c024
FL
566my ($repoauthor, $repocommitter);
567($repoauthor) = Git::ident_person(@repo, 'author');
568($repocommitter) = Git::ident_person(@repo, 'committer');
34cc60ce 569
5012699d 570sub parse_address_line {
bd869f67 571 return map { $_->format } Mail::Address->parse($_[0]);
5012699d
JS
572}
573
0e73b3ee 574sub split_addrs {
2f0e7cbb 575 return quotewords('\s*,\s*', 1, @_);
0e73b3ee
WF
576}
577
994d6c66 578my %aliases;
09f1157b
ES
579
580sub parse_sendmail_alias {
581 local $_ = shift;
582 if (/"/) {
3c5cd20c 583 printf STDERR __("warning: sendmail alias with quotes is not supported: %s\n"), $_;
86b89848 584 } elsif (/:include:/) {
3c5cd20c 585 printf STDERR __("warning: `:include:` not supported: %s\n"), $_;
86b89848 586 } elsif (/[\/|]/) {
3c5cd20c 587 printf STDERR __("warning: `/file` or `|pipe` redirection not supported: %s\n"), $_;
09f1157b
ES
588 } elsif (/^(\S+?)\s*:\s*(.+)$/) {
589 my ($alias, $addr) = ($1, $2);
590 $aliases{$alias} = [ split_addrs($addr) ];
591 } else {
3c5cd20c 592 printf STDERR __("warning: sendmail line is not recognized: %s\n"), $_;
09f1157b
ES
593 }
594}
595
596sub parse_sendmail_aliases {
597 my $fh = shift;
2532dd06 598 my $s = '';
09f1157b 599 while (<$fh>) {
2532dd06 600 chomp;
020be85f 601 next if /^\s*$/ || /^\s*#/;
2532dd06
ES
602 $s .= $_, next if $s =~ s/\\$// || s/^\s+//;
603 parse_sendmail_alias($s) if $s;
604 $s = $_;
09f1157b 605 }
2532dd06
ES
606 $s =~ s/\\$//; # silently tolerate stray '\' on last line
607 parse_sendmail_alias($s) if $s;
09f1157b
ES
608}
609
994d6c66
EW
610my %parse_alias = (
611 # multiline formats can be supported in the future
612 mutt => sub { my $fh = shift; while (<$fh>) {
ffc01f9b 613 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
994d6c66
EW
614 my ($alias, $addr) = ($1, $2);
615 $addr =~ s/#.*$//; # mutt allows # comments
2c510f21
EW
616 # commas delimit multiple addresses
617 my @addr = split_addrs($addr);
618
619 # quotes may be escaped in the file,
620 # unescape them so we do not double-escape them later.
621 s/\\"/"/g foreach @addr;
622 $aliases{$alias} = \@addr
994d6c66
EW
623 }}},
624 mailrc => sub { my $fh = shift; while (<$fh>) {
a277d1ef 625 if (/^alias\s+(\S+)\s+(.*?)\s*$/) {
994d6c66 626 # spaces delimit multiple addresses
fe87c921 627 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
994d6c66 628 }}},
73c427eb
TP
629 pine => sub { my $fh = shift; my $f='\t[^\t]*';
630 for (my $x = ''; defined($x); $x = $_) {
631 chomp $x;
632 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
633 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
0e73b3ee 634 $aliases{$1} = [ split_addrs($2) ];
73c427eb 635 }},
7613ea35
BP
636 elm => sub { my $fh = shift;
637 while (<$fh>) {
638 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
639 my ($alias, $addr) = ($1, $2);
640 $aliases{$alias} = [ split_addrs($addr) ];
641 }
642 } },
09f1157b 643 sendmail => \&parse_sendmail_aliases,
994d6c66
EW
644 gnus => sub { my $fh = shift; while (<$fh>) {
645 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
646 $aliases{$1} = [ $2 ];
647 }}}
5a59a230
NTND
648 # Please update _git_config() in git-completion.bash when you
649 # add new MUAs.
994d6c66
EW
650);
651
3cb8caf7 652if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
994d6c66
EW
653 foreach my $file (@alias_files) {
654 open my $fh, '<', $file or die "opening $file: $!\n";
655 $parse_alias{$aliasfiletype}->($fh);
656 close $fh;
657 }
658}
659
17b7a832
JK
660if ($dump_aliases) {
661 print "$_\n" for (sort keys %aliases);
662 exit(0);
663}
664
9b397039
RR
665# is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
666# $f is a revision list specification to be passed to format-patch.
667sub is_format_patch_arg {
eed6ca7c 668 return unless $repo;
5df9fcf6
PH
669 my $f = shift;
670 try {
671 $repo->command('rev-parse', '--verify', '--quiet', $f);
672 if (defined($format_patch)) {
5df9fcf6
PH
673 return $format_patch;
674 }
3c5cd20c
VA
675 die sprintf(__ <<EOF, $f, $f);
676File '%s' exists but it could also be the range of commits
5df9fcf6
PH
677to produce patches for. Please disambiguate by...
678
3c5cd20c 679 * Saying "./%s" if you mean a file; or
5df9fcf6
PH
680 * Giving --format-patch option if you mean a range.
681EOF
682 } catch Git::Error::Command with {
9b397039 683 # Not a valid revision. Treat it as a filename.
5df9fcf6
PH
684 return 0;
685 }
686}
687
aa54892f
JK
688# Now that all the defaults are set, process the rest of the command line
689# arguments and collect up the files that need to be processed.
5df9fcf6 690my @rev_list_opts;
69f4ce55 691while (defined(my $f = shift @ARGV)) {
5df9fcf6
PH
692 if ($f eq "--") {
693 push @rev_list_opts, "--", @ARGV;
694 @ARGV = ();
9b397039 695 } elsif (-d $f and !is_format_patch_arg($f)) {
c6038169 696 opendir my $dh, $f
3c5cd20c 697 or die sprintf(__("Failed to opendir %s: %s"), $f, $!);
aa54892f 698
89bf1bac 699 push @files, grep { -f $_ } map { catfile($f, $_) }
c6038169
ÆAB
700 sort readdir $dh;
701 closedir $dh;
9b397039 702 } elsif ((-f $f or -p $f) and !is_format_patch_arg($f)) {
aa54892f 703 push @files, $f;
aa54892f 704 } else {
5df9fcf6 705 push @rev_list_opts, $f;
aa54892f
JK
706 }
707}
708
5df9fcf6 709if (@rev_list_opts) {
46493105 710 die __("Cannot run git format-patch from outside a repository\n")
eed6ca7c 711 unless $repo;
5df9fcf6
PH
712 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
713}
714
531220ba
JH
715@files = handle_backup_files(@files);
716
dbf5e1e9 717if ($validate) {
c764a0c2 718 foreach my $f (@files) {
300913bd 719 unless (-p $f) {
d21616c0 720 validate_patch($f, $target_xfer_encoding);
300913bd 721 }
c764a0c2 722 }
747bbff9
JK
723}
724
aa54892f
JK
725if (@files) {
726 unless ($quiet) {
727 print $_,"\n" for (@files);
728 }
729} else {
46493105 730 print STDERR __("\nNo patch files specified!\n\n");
aa54892f
JK
731 usage();
732}
733
acf071b0 734sub get_patch_subject {
beece9da
PH
735 my $fn = shift;
736 open (my $fh, '<', $fn);
737 while (my $line = <$fh>) {
738 next unless ($line =~ /^Subject: (.*)$/);
739 close $fh;
740 return "GIT: $1\n";
741 }
742 close $fh;
3c5cd20c 743 die sprintf(__("No subject line in %s?"), $fn);
beece9da
PH
744}
745
746if ($compose) {
747 # Note that this does not need to be secure, but we will make a small
748 # effort to have it be unique
afe756c9
JS
749 $compose_filename = ($repo ?
750 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
751 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
fe0f944f 752 open my $c, ">", $compose_filename
3c5cd20c 753 or die sprintf(__("Failed to open for writing %s: %s"), $compose_filename, $!);
beece9da
PH
754
755
756 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
757 my $tpl_subject = $initial_subject || '';
15dc3b91 758 my $tpl_in_reply_to = $initial_in_reply_to || '';
d11c943c 759 my $tpl_reply_to = $reply_to || '';
beece9da 760
70aedfb3 761 print $c <<EOT1, Git::prefix_lines("GIT: ", __ <<EOT2), <<EOT3;
beece9da 762From $tpl_sender # This line is ignored.
70aedfb3
VA
763EOT1
764Lines beginning in "GIT:" will be removed.
765Consider including an overall diffstat or table of contents
766for the patch you are writing.
767
768Clear the body content if you don't wish to send a summary.
769EOT2
beece9da 770From: $tpl_sender
d11c943c 771Reply-To: $tpl_reply_to
beece9da 772Subject: $tpl_subject
15dc3b91 773In-Reply-To: $tpl_in_reply_to
beece9da 774
70aedfb3 775EOT3
beece9da 776 for my $f (@files) {
fe0f944f 777 print $c get_patch_subject($f);
beece9da 778 }
fe0f944f 779 close $c;
beece9da 780
beece9da
PH
781 if ($annotate) {
782 do_edit($compose_filename, @files);
783 } else {
784 do_edit($compose_filename);
785 }
786
fe0f944f 787 open $c, "<", $compose_filename
3c5cd20c 788 or die sprintf(__("Failed to open %s: %s"), $compose_filename, $!);
beece9da 789
4a47a4dd
KM
790 if (!defined $compose_encoding) {
791 $compose_encoding = "UTF-8";
792 }
b6049542
NP
793
794 my %parsed_email;
795 while (my $line = <$c>) {
796 next if $line =~ m/^GIT:/;
797 parse_header_line($line, \%parsed_email);
798 if ($line =~ /^$/) {
799 $parsed_email{'body'} = filter_body($c);
beece9da 800 }
beece9da 801 }
fe0f944f 802 close $c;
beece9da 803
b6049542
NP
804 open my $c2, ">", $compose_filename . ".final"
805 or die sprintf(__("Failed to open %s.final: %s"), $compose_filename, $!);
806
807
808 if ($parsed_email{'From'}) {
809 $sender = delete($parsed_email{'From'});
810 }
811 if ($parsed_email{'In-Reply-To'}) {
15dc3b91 812 $initial_in_reply_to = delete($parsed_email{'In-Reply-To'});
b6049542 813 }
d11c943c
CL
814 if ($parsed_email{'Reply-To'}) {
815 $reply_to = delete($parsed_email{'Reply-To'});
b6049542
NP
816 }
817 if ($parsed_email{'Subject'}) {
818 $initial_subject = delete($parsed_email{'Subject'});
819 print $c2 "Subject: " .
820 quote_subject($initial_subject, $compose_encoding) .
821 "\n";
822 }
823
824 if ($parsed_email{'MIME-Version'}) {
825 print $c2 "MIME-Version: $parsed_email{'MIME-Version'}\n",
826 "Content-Type: $parsed_email{'Content-Type'};\n",
827 "Content-Transfer-Encoding: $parsed_email{'Content-Transfer-Encoding'}\n";
828 delete($parsed_email{'MIME-Version'});
829 delete($parsed_email{'Content-Type'});
830 delete($parsed_email{'Content-Transfer-Encoding'});
831 } elsif (file_has_nonascii($compose_filename)) {
832 my $content_type = (delete($parsed_email{'Content-Type'}) or
833 "text/plain; charset=$compose_encoding");
834 print $c2 "MIME-Version: 1.0\n",
835 "Content-Type: $content_type\n",
836 "Content-Transfer-Encoding: 8bit\n";
837 }
838 # Preserve unknown headers
839 foreach my $key (keys %parsed_email) {
840 next if $key eq 'body';
841 print $c2 "$key: $parsed_email{$key}";
842 }
843
844 if ($parsed_email{'body'}) {
845 print $c2 "\n$parsed_email{'body'}\n";
846 delete($parsed_email{'body'});
847 } else {
46493105 848 print __("Summary email is empty, skipping it\n");
beece9da
PH
849 $compose = -1;
850 }
b6049542
NP
851
852 close $c2;
853
beece9da
PH
854} elsif ($annotate) {
855 do_edit(@files);
856}
857
6e182518
JS
858sub ask {
859 my ($prompt, %arg) = @_;
0da43a68 860 my $valid_re = $arg{valid_re};
6e182518 861 my $default = $arg{default};
51bbccfd 862 my $confirm_only = $arg{confirm_only};
6e182518
JS
863 my $resp;
864 my $i = 0;
5906f54e
JS
865 return defined $default ? $default : undef
866 unless defined $term->IN and defined fileno($term->IN) and
867 defined $term->OUT and defined fileno($term->OUT);
6e182518
JS
868 while ($i++ < 10) {
869 $resp = $term->readline($prompt);
870 if (!defined $resp) { # EOF
871 print "\n";
872 return defined $default ? $default : undef;
873 }
874 if ($resp eq '' and defined $default) {
875 return $default;
876 }
0da43a68 877 if (!defined $valid_re or $resp =~ /$valid_re/) {
6e182518
JS
878 return $resp;
879 }
51bbccfd 880 if ($confirm_only) {
3c5cd20c
VA
881 my $yesno = $term->readline(
882 # TRANSLATORS: please keep [y/N] as is.
883 sprintf(__("Are you sure you want to use <%s> [y/N]? "), $resp));
51bbccfd
JH
884 if (defined $yesno && $yesno =~ /y/i) {
885 return $resp;
886 }
887 }
6e182518 888 }
622bc930 889 return;
6e182518
JS
890}
891
b6049542
NP
892sub parse_header_line {
893 my $lines = shift;
894 my $parsed_line = shift;
895 my $addr_pat = join "|", qw(To Cc Bcc);
896
897 foreach (split(/\n/, $lines)) {
898 if (/^($addr_pat):\s*(.+)$/i) {
899 $parsed_line->{$1} = [ parse_address_line($2) ];
900 } elsif (/^([^:]*):\s*(.+)\s*$/i) {
901 $parsed_line->{$1} = $2;
902 }
903 }
904}
905
906sub filter_body {
907 my $c = shift;
908 my $body = "";
909 while (my $body_line = <$c>) {
910 if ($body_line !~ m/^GIT:/) {
911 $body .= $body_line;
912 }
913 }
914 return $body;
915}
916
917
3cae7e5b
TR
918my %broken_encoding;
919
1d50bfd9 920sub file_declares_8bit_cte {
3cae7e5b
TR
921 my $fn = shift;
922 open (my $fh, '<', $fn);
923 while (my $line = <$fh>) {
924 last if ($line =~ /^$/);
925 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
926 }
927 close $fh;
928 return 0;
929}
930
931foreach my $f (@files) {
932 next unless (body_or_subject_has_nonascii($f)
933 && !file_declares_8bit_cte($f));
934 $broken_encoding{$f} = 1;
935}
936
937if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
a4dde4c4
VA
938 print __("The following files are 8bit, but do not declare " .
939 "a Content-Transfer-Encoding.\n");
3cae7e5b
TR
940 foreach my $f (sort keys %broken_encoding) {
941 print " $f\n";
942 }
a4dde4c4 943 $auto_8bit_encoding = ask(__("Which 8bit encoding should I declare [UTF-8]? "),
852a15d7 944 valid_re => qr/.{4}/, confirm_only => 1,
3cae7e5b
TR
945 default => "UTF-8");
946}
947
a03bc5b6
TR
948if (!$force) {
949 for my $f (@files) {
0d290a46 950 if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
3c5cd20c 951 die sprintf(__("Refusing to send because the patch\n\t%s\n"
a03bc5b6 952 . "has the template subject '*** SUBJECT HERE ***'. "
3c5cd20c 953 . "Pass --force if you really want to send.\n"), $f);
a03bc5b6
TR
954 }
955 }
956}
957
c46e27aa 958if (defined $sender) {
fa5b1aa9 959 $sender =~ s/^\s+|\s+$//g;
c46e27aa
RL
960 ($sender) = expand_aliases($sender);
961} else {
ad79c024 962 $sender = $repoauthor || $repocommitter || '';
83b24437
RA
963}
964
da18759e
MT
965# $sender could be an already sanitized address
966# (e.g. sendemail.from could be manually sanitized by user).
967# But it's a no-op to run sanitize_address on an already sanitized address.
968$sender = sanitize_address($sender);
969
a4dde4c4 970my $to_whom = __("To whom should the emails be sent (if anyone)?");
8cac13dc 971my $prompting = 0;
8796ff7f 972if (!@initial_to && !defined $to_cmd) {
0d6b21e7 973 my $to = ask("$to_whom ",
61837493 974 default => "",
51bbccfd 975 valid_re => qr/\@.*\./, confirm_only => 1);
3c3bb51c 976 push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
1f038a0c 977 $prompting++;
83b24437
RA
978}
979
994d6c66 980sub expand_aliases {
302e04ea
JK
981 return map { expand_one_alias($_) } @_;
982}
983
984my %EXPANDED_ALIASES;
985sub expand_one_alias {
986 my $alias = shift;
987 if ($EXPANDED_ALIASES{$alias}) {
3c5cd20c 988 die sprintf(__("fatal: alias '%s' expands to itself\n"), $alias);
302e04ea
JK
989 }
990 local $EXPANDED_ALIASES{$alias} = 1;
991 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
994d6c66
EW
992}
993
b5e112d8
RL
994@initial_to = process_address_list(@initial_to);
995@initial_cc = process_address_list(@initial_cc);
e60f6d13 996@initial_bcc = process_address_list(@initial_bcc);
994d6c66 997
15dc3b91
CL
998if ($thread && !defined $initial_in_reply_to && $prompting) {
999 $initial_in_reply_to = ask(
a4dde4c4 1000 __("Message-ID to be used as In-Reply-To for the first email (if any)? "),
61837493 1001 default => "",
51bbccfd 1002 valid_re => qr/\@.*\./, confirm_only => 1);
83b24437 1003}
15dc3b91
CL
1004if (defined $initial_in_reply_to) {
1005 $initial_in_reply_to =~ s/^\s*<?//;
1006 $initial_in_reply_to =~ s/>?\s*$//;
1007 $initial_in_reply_to = "<$initial_in_reply_to>" if $initial_in_reply_to ne '';
ace9c2a9 1008}
ace72086 1009
d11c943c
CL
1010if (defined $reply_to) {
1011 $reply_to =~ s/^\s+|\s+$//g;
1012 ($reply_to) = expand_aliases($reply_to);
1013 $reply_to = sanitize_address($reply_to);
ace9c2a9 1014}
ace72086 1015
34cc60ce 1016if (!defined $smtp_server) {
1ab2fd4f
FK
1017 my @sendmail_paths = qw( /usr/sbin/sendmail /usr/lib/sendmail );
1018 push @sendmail_paths, map {"$_/sendmail"} split /:/, $ENV{PATH};
1019 foreach (@sendmail_paths) {
aca7ad76
EW
1020 if (-x $_) {
1021 $smtp_server = $_;
1022 last;
1023 }
1024 }
1025 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
3342d850
RA
1026}
1027
c1f2aa45
JS
1028if ($compose && $compose > 0) {
1029 @files = ($compose_filename . ".final", @files);
1f038a0c
RA
1030}
1031
83b24437 1032# Variables we set as part of the loop over files
15dc3b91 1033our ($message_id, %mail, $subject, $in_reply_to, $references, $message,
dc1460aa 1034 $needs_confirm, $message_num, $ask_default);
83b24437 1035
567ffeb7
EW
1036sub extract_valid_address {
1037 my $address = shift;
35b6ab95
ÆAB
1038 my $local_part_regexp = qr/[^<>"\s@]+/;
1039 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
db3106b2
EW
1040
1041 # check for a local address:
ad9c18f5 1042 return $address if ($address =~ /^($local_part_regexp)$/);
db3106b2 1043
155197e6 1044 $address =~ s/^\s*<(.*)>\s*$/$1/;
567ffeb7 1045 if ($have_email_valid) {
ad9c18f5 1046 return scalar Email::Valid->address($address);
567ffeb7 1047 }
95c0d4b6
KM
1048
1049 # less robust/correct than the monster regexp in Email::Valid,
1050 # but still does a 99% job, and one less dependency
1051 return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
622bc930 1052 return;
567ffeb7 1053}
83b24437 1054
e4312255
KM
1055sub extract_valid_address_or_die {
1056 my $address = shift;
1057 $address = extract_valid_address($address);
3c5cd20c 1058 die sprintf(__("error: unable to extract a valid address from: %s\n"), $address)
e4312255
KM
1059 if !$address;
1060 return $address;
1061}
1062
1063sub validate_address {
1064 my $address = shift;
d0e98107 1065 while (!extract_valid_address($address)) {
3c5cd20c 1066 printf STDERR __("error: unable to extract a valid address from: %s\n"), $address;
a4dde4c4
VA
1067 # TRANSLATORS: Make sure to include [q] [d] [e] in your
1068 # translation. The program will only accept English input
1069 # at this point.
1070 $_ = ask(__("What to do with this address? ([q]uit|[d]rop|[e]dit): "),
d0e98107 1071 valid_re => qr/^(?:quit|q|drop|d|edit|e)/i,
5c80afed
KM
1072 default => 'q');
1073 if (/^d/i) {
1074 return undef;
1075 } elsif (/^q/i) {
1076 cleanup_compose_files();
1077 exit(0);
1078 }
0d6b21e7 1079 $address = ask("$to_whom ",
d0e98107
KM
1080 default => "",
1081 valid_re => qr/\@.*\./, confirm_only => 1);
e4312255
KM
1082 }
1083 return $address;
1084}
1085
1086sub validate_address_list {
1087 return (grep { defined $_ }
1088 map { validate_address($_) } @_);
567ffeb7 1089}
83b24437
RA
1090
1091# Usually don't need to change anything below here.
1092
1093# we make a "fake" message id by taking the current number
1094# of seconds since the beginning of Unix time and tacking on
1095# a random number to the end, in case we are called quicker than
1096# 1 second since the last time we were called.
8037d1a3
RA
1097
1098# We'll setup a template for the message id, using the "from" address:
8037d1a3 1099
be510cfe 1100my ($message_id_stamp, $message_id_serial);
68ce9330 1101sub make_message_id {
be510cfe
JH
1102 my $uniq;
1103 if (!defined $message_id_stamp) {
f916ab0c 1104 $message_id_stamp = strftime("%Y%m%d%H%M%S.$$", gmtime(time));
be510cfe
JH
1105 $message_id_serial = 0;
1106 }
1107 $message_id_serial++;
1108 $uniq = "$message_id_stamp-$message_id_serial";
1109
aeb59328 1110 my $du_part;
94638f89
UKK
1111 for ($sender, $repocommitter, $repoauthor) {
1112 $du_part = extract_valid_address(sanitize_address($_));
1113 last if (defined $du_part and $du_part ne '');
aeb59328 1114 }
94638f89 1115 if (not defined $du_part or $du_part eq '') {
529dd386 1116 require Sys::Hostname;
aeb59328
JH
1117 $du_part = 'user@' . Sys::Hostname::hostname();
1118 }
f916ab0c 1119 my $message_id_template = "<%s-%s>";
be510cfe 1120 $message_id = sprintf($message_id_template, $uniq, $du_part);
8037d1a3 1121 #print "new message id = $message_id\n"; # Was useful for debugging
83b24437
RA
1122}
1123
1124
1125
a5370b16 1126$time = time - scalar $#files;
83b24437 1127
374c5905
JR
1128sub unquote_rfc2047 {
1129 local ($_) = @_;
11f70a7e 1130 my $charset;
ab47e2a5
РД
1131 my $sep = qr/[ \t]+/;
1132 s{$re_encoded_word(?:$sep$re_encoded_word)*}{
1133 my @words = split $sep, $&;
1134 foreach (@words) {
1135 m/$re_encoded_word/;
1136 $charset = $1;
1137 my $encoding = $2;
1138 my $text = $3;
1139 if ($encoding eq 'q' || $encoding eq 'Q') {
1140 $_ = $text;
1141 s/_/ /g;
1142 s/=([0-9A-F]{2})/chr(hex($1))/egi;
1143 } else {
1144 # other encodings not supported yet
1145 }
11f70a7e 1146 }
ab47e2a5 1147 join '', @words;
b622d4d1 1148 }eg;
11f70a7e 1149 return wantarray ? ($_, $charset) : $_;
374c5905
JR
1150}
1151
d54eaaa2
JK
1152sub quote_rfc2047 {
1153 local $_ = shift;
d1fff6fc 1154 my $encoding = shift || 'UTF-8';
d54eaaa2
JK
1155 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
1156 s/(.*)/=\?$encoding\?q\?$1\?=/;
1157 return $_;
1158}
1159
a3a8262b
BC
1160sub is_rfc2047_quoted {
1161 my $s = shift;
a3a8262b 1162 length($s) <= 75 &&
11f70a7e 1163 $s =~ m/^(?:"[[:ascii:]]*"|$re_encoded_word)$/o;
a3a8262b
BC
1164}
1165
ce547800
KM
1166sub subject_needs_rfc2047_quoting {
1167 my $s = shift;
1168
ce1459f7 1169 return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
ce547800
KM
1170}
1171
1172sub quote_subject {
1173 local $subject = shift;
1174 my $encoding = shift || 'UTF-8';
1175
1176 if (subject_needs_rfc2047_quoting($subject)) {
1177 return quote_rfc2047($subject, $encoding);
1178 }
1179 return $subject;
1180}
1181
5b56aaa2 1182# use the simplest quoting being able to handle the recipient
68ce9330 1183sub sanitize_address {
732263d4 1184 my ($recipient) = @_;
831a488b
KM
1185
1186 # remove garbage after email address
1187 $recipient =~ s/(.*>).*$/$1/;
1188
5b56aaa2
UKK
1189 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
1190
1191 if (not $recipient_name) {
ff483897 1192 return $recipient;
5b56aaa2
UKK
1193 }
1194
1195 # if recipient_name is already quoted, do nothing
a3a8262b 1196 if (is_rfc2047_quoted($recipient_name)) {
5b56aaa2
UKK
1197 return $recipient;
1198 }
1199
1fe9703f
RL
1200 # remove non-escaped quotes
1201 $recipient_name =~ s/(^|[^\\])"/$1/g;
1202
5b56aaa2
UKK
1203 # rfc2047 is needed if a non-ascii char is included
1204 if ($recipient_name =~ /[^[:ascii:]]/) {
d54eaaa2 1205 $recipient_name = quote_rfc2047($recipient_name);
732263d4 1206 }
5b56aaa2
UKK
1207
1208 # double quotes are needed if specials or CTLs are included
1209 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
1fe9703f 1210 $recipient_name =~ s/([\\\r])/\\$1/g;
d5c7d69d 1211 $recipient_name = qq["$recipient_name"];
5b56aaa2
UKK
1212 }
1213
1214 return "$recipient_name $recipient_addr";
1215
732263d4
RJ
1216}
1217
cb2922fe
MM
1218sub strip_garbage_one_address {
1219 my ($addr) = @_;
1220 chomp $addr;
1221 if ($addr =~ /^(("[^"]*"|[^"<]*)? *<[^>]*>).*/) {
1222 # "Foo Bar" <foobar@example.com> [possibly garbage here]
1223 # Foo Bar <foobar@example.com> [possibly garbage here]
1224 return $1;
1225 }
1226 if ($addr =~ /^(<[^>]*>).*/) {
1227 # <foo@example.com> [possibly garbage here]
1228 # if garbage contains other addresses, they are ignored.
1229 return $1;
1230 }
1231 if ($addr =~ /^([^"#,\s]*)/) {
1232 # address without quoting: remove anything after the address
1233 return $1;
1234 }
1235 return $addr;
1236}
1237
e4312255
KM
1238sub sanitize_address_list {
1239 return (map { sanitize_address($_) } @_);
1240}
1241
b5e112d8 1242sub process_address_list {
b1c8a11c
RL
1243 my @addr_list = map { parse_address_line($_) } @_;
1244 @addr_list = expand_aliases(@addr_list);
b5e112d8
RL
1245 @addr_list = sanitize_address_list(@addr_list);
1246 @addr_list = validate_address_list(@addr_list);
1247 return @addr_list;
1248}
1249
134550fe
JA
1250# Returns the local Fully Qualified Domain Name (FQDN) if available.
1251#
1252# Tightly configured MTAa require that a caller sends a real DNS
1253# domain name that corresponds the IP address in the HELO/EHLO
1254# handshake. This is used to verify the connection and prevent
1255# spammers from trying to hide their identity. If the DNS and IP don't
15beaaa3 1256# match, the receiving MTA may deny the connection.
134550fe
JA
1257#
1258# Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1259#
1260# Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1261# Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1262#
1263# This maildomain*() code is based on ideas in Perl library Test::Reporter
1264# /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1265
59a86303
BG
1266sub valid_fqdn {
1267 my $domain = shift;
61ef5e9b 1268 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
59a86303
BG
1269}
1270
68ce9330 1271sub maildomain_net {
134550fe
JA
1272 my $maildomain;
1273
1046c118
ÆAB
1274 my $domain = Net::Domain::domainname();
1275 $maildomain = $domain if valid_fqdn($domain);
134550fe
JA
1276
1277 return $maildomain;
1278}
1279
68ce9330 1280sub maildomain_mta {
134550fe
JA
1281 my $maildomain;
1282
1046c118
ÆAB
1283 for my $host (qw(mailhost localhost)) {
1284 my $smtp = Net::SMTP->new($host);
1285 if (defined $smtp) {
1286 my $domain = $smtp->domain;
1287 $smtp->quit;
134550fe 1288
1046c118 1289 $maildomain = $domain if valid_fqdn($domain);
134550fe 1290
1046c118 1291 last if $maildomain;
134550fe
JA
1292 }
1293 }
1294
1295 return $maildomain;
1296}
1297
68ce9330 1298sub maildomain {
69cf7bfd 1299 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
134550fe
JA
1300}
1301
4d31a44a
MN
1302sub smtp_host_string {
1303 if (defined $smtp_server_port) {
1304 return "$smtp_server:$smtp_server_port";
1305 } else {
1306 return $smtp_server;
1307 }
1308}
1309
1310# Returns 1 if authentication succeeded or was not necessary
1311# (smtp_user was not specified), and 0 otherwise.
1312
1313sub smtp_auth_maybe {
8dd9b3f8 1314 if (!defined $smtp_authuser || $auth || (defined $smtp_auth && $smtp_auth eq "none")) {
4d31a44a
MN
1315 return 1;
1316 }
1317
1318 # Workaround AUTH PLAIN/LOGIN interaction defect
1319 # with Authen::SASL::Cyrus
1320 eval {
1321 require Authen::SASL;
1322 Authen::SASL->import(qw(Perl));
1323 };
1324
0f2e68b5
JV
1325 # Check mechanism naming as defined in:
1326 # https://tools.ietf.org/html/rfc4422#page-8
904f6e7c 1327 if ($smtp_auth && $smtp_auth !~ /^(\b[A-Z0-9-_]{1,20}\s*)*$/) {
0f2e68b5
JV
1328 die "invalid smtp auth: '${smtp_auth}'";
1329 }
1330
4d31a44a
MN
1331 # TODO: Authentication may fail not because credentials were
1332 # invalid but due to other reasons, in which we should not
1333 # reject credentials.
1334 $auth = Git::credential({
1335 'protocol' => 'smtp',
1336 'host' => smtp_host_string(),
1337 'username' => $smtp_authuser,
1338 # if there's no password, "git credential fill" will
1339 # give us one, otherwise it'll just pass this one.
1340 'password' => $smtp_authpass
1341 }, sub {
1342 my $cred = shift;
0f2e68b5
JV
1343
1344 if ($smtp_auth) {
1345 my $sasl = Authen::SASL->new(
1346 mechanism => $smtp_auth,
1347 callback => {
1348 user => $cred->{'username'},
1349 pass => $cred->{'password'},
1350 authname => $cred->{'username'},
1351 }
1352 );
1353
1354 return !!$smtp->auth($sasl);
1355 }
1356
4d31a44a
MN
1357 return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1358 });
1359
1360 return $auth;
1361}
1362
35035bbf
RR
1363sub ssl_verify_params {
1364 eval {
1365 require IO::Socket::SSL;
1366 IO::Socket::SSL->import(qw/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1367 };
1368 if ($@) {
1369 print STDERR "Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1370 return;
1371 }
1372
1373 if (!defined $smtp_ssl_cert_path) {
01645b74
RK
1374 # use the OpenSSL defaults
1375 return (SSL_verify_mode => SSL_VERIFY_PEER());
35035bbf
RR
1376 }
1377
1378 if ($smtp_ssl_cert_path eq "") {
1379 return (SSL_verify_mode => SSL_VERIFY_NONE());
1380 } elsif (-d $smtp_ssl_cert_path) {
1381 return (SSL_verify_mode => SSL_VERIFY_PEER(),
1382 SSL_ca_path => $smtp_ssl_cert_path);
1383 } elsif (-f $smtp_ssl_cert_path) {
1384 return (SSL_verify_mode => SSL_VERIFY_PEER(),
1385 SSL_ca_file => $smtp_ssl_cert_path);
1386 } else {
3c5cd20c 1387 die sprintf(__("CA path \"%s\" does not exist"), $smtp_ssl_cert_path);
35035bbf
RR
1388 }
1389}
1390
cb005c1f
EFL
1391sub file_name_is_absolute {
1392 my ($path) = @_;
1393
1394 # msys does not grok DOS drive-prefixes
1395 if ($^O eq 'msys') {
f24ecf59 1396 return ($path =~ m#^/# || $path =~ m#^[a-zA-Z]\:#)
cb005c1f
EFL
1397 }
1398
1399 require File::Spec::Functions;
1400 return File::Spec::Functions::file_name_is_absolute($path);
1401}
1402
04c4a4e8
DD
1403# Prepares the email, then asks the user what to do.
1404#
1405# If the user chooses to send the email, it's sent and 1 is returned.
1406# If the user chooses not to send the email, 0 is returned.
1407# If the user decides they want to make further edits, -1 is returned and the
1408# caller is expected to call send_message again after the edits are performed.
1409#
1410# If an error occurs sending the email, this just dies.
15da1084 1411
68ce9330 1412sub send_message {
4bc87a28 1413 my @recipients = unique_email_list(@to);
e4312255 1414 @cc = (grep { my $cc = extract_valid_address_or_die($_);
83acaaec 1415 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
7ac17529 1416 }
7ac17529 1417 @cc);
4bc87a28 1418 my $to = join (",\n\t", @recipients);
e60f6d13 1419 @recipients = unique_email_list(@recipients,@cc,@initial_bcc);
e4312255 1420 @recipients = (map { extract_valid_address_or_die($_) } @recipients);
6bdca890 1421 my $date = format_2822_time($time++);
e923effb
ML
1422 my $gitversion = '@@GIT_VERSION@@';
1423 if ($gitversion =~ m/..GIT_VERSION../) {
3cb8caf7 1424 $gitversion = Git::version();
e923effb 1425 }
4bc87a28 1426
02461e0e 1427 my $cc = join(",\n\t", unique_email_list(@cc));
f06a6a49
JH
1428 my $ccline = "";
1429 if ($cc ne '') {
1430 $ccline = "\nCc: $cc";
1431 }
4f3d3703 1432 make_message_id() unless defined($message_id);
aeb59328 1433
da18759e 1434 my $header = "From: $sender
f06a6a49 1435To: $to${ccline}
4bc87a28 1436Subject: $subject
4bc87a28
EW
1437Date: $date
1438Message-Id: $message_id
4bc87a28 1439";
ac1596a6
LH
1440 if ($use_xmailer) {
1441 $header .= "X-Mailer: git-send-email $gitversion\n";
1442 }
15dc3b91 1443 if ($in_reply_to) {
7ccf7927 1444
15dc3b91 1445 $header .= "In-Reply-To: $in_reply_to\n";
7ccf7927
RA
1446 $header .= "References: $references\n";
1447 }
d11c943c
CL
1448 if ($reply_to) {
1449 $header .= "Reply-To: $reply_to\n";
1450 }
ce91c2f6
JH
1451 if (@xh) {
1452 $header .= join("\n", @xh) . "\n";
1453 }
4bc87a28 1454
c38f0247 1455 my @sendmail_parameters = ('-i', @recipients);
da18759e 1456 my $raw_from = $sender;
c89e3241
FC
1457 if (defined $envelope_sender && $envelope_sender ne "auto") {
1458 $raw_from = $envelope_sender;
1459 }
f073a592
RJ
1460 $raw_from = extract_valid_address($raw_from);
1461 unshift (@sendmail_parameters,
1462 '-f', $raw_from) if(defined $envelope_sender);
8e3d436b 1463
c1f2aa45
JS
1464 if ($needs_confirm && !$dry_run) {
1465 print "\n$header\n";
1466 if ($needs_confirm eq "inform") {
1467 $confirm_unconfigured = 0; # squelch this message for the rest of this run
6e182518 1468 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
a4dde4c4
VA
1469 print __ <<EOF ;
1470 The Cc list above has been expanded by additional
1471 addresses found in the patch commit message. By default
1472 send-email prompts before sending whenever this occurs.
1473 This behavior is controlled by the sendemail.confirm
1474 configuration setting.
1475
1476 For additional information, run 'git send-email --help'.
1477 To retain the current behavior, but squelch this message,
1478 run 'git config --global sendemail.confirm auto'.
1479
1480EOF
c1f2aa45 1481 }
04c4a4e8 1482 # TRANSLATORS: Make sure to include [y] [n] [e] [q] [a] in your
a4dde4c4
VA
1483 # translation. The program will only accept English input
1484 # at this point.
04c4a4e8
DD
1485 $_ = ask(__("Send this email? ([y]es|[n]o|[e]dit|[q]uit|[a]ll): "),
1486 valid_re => qr/^(?:yes|y|no|n|edit|e|quit|q|all|a)/i,
6e182518 1487 default => $ask_default);
46493105 1488 die __("Send this email reply required") unless defined $_;
c1f2aa45 1489 if (/^n/i) {
15da1084 1490 return 0;
04c4a4e8
DD
1491 } elsif (/^e/i) {
1492 return -1;
c1f2aa45
JS
1493 } elsif (/^q/i) {
1494 cleanup_compose_files();
1495 exit(0);
1496 } elsif (/^a/i) {
1497 $confirm = 'never';
1498 }
1499 }
1500
052fbea2
PO
1501 unshift (@sendmail_parameters, @smtp_server_options);
1502
6130259c
MW
1503 if ($dry_run) {
1504 # We don't want to send the email.
cb005c1f 1505 } elsif (file_name_is_absolute($smtp_server)) {
aca7ad76
EW
1506 my $pid = open my $sm, '|-';
1507 defined $pid or die $!;
1508 if (!$pid) {
8e3d436b 1509 exec($smtp_server, @sendmail_parameters) or die $!;
aca7ad76
EW
1510 }
1511 print $sm "$header\n$message";
5e2c2ab1 1512 close $sm or die $!;
aca7ad76 1513 } else {
44b2476a
JH
1514
1515 if (!defined $smtp_server) {
46493105 1516 die __("The required SMTP server is not properly defined.")
44b2476a
JH
1517 }
1518
0ead000c 1519 require Net::SMTP;
bfbfc9a9 1520 my $use_net_smtp_ssl = version->parse($Net::SMTP::VERSION) < version->parse("2.34");
0ead000c
DK
1521 $smtp_domain ||= maildomain();
1522
f6bebd12 1523 if ($smtp_encryption eq 'ssl') {
44b2476a 1524 $smtp_server_port ||= 465; # ssmtp
5508f3ed 1525 require IO::Socket::SSL;
9d605249
JK
1526
1527 # Suppress "variable accessed once" warning.
1528 {
1529 no warnings 'once';
1530 $IO::Socket::SSL::DEBUG = 1;
1531 }
1532
5508f3ed
TR
1533 # Net::SMTP::SSL->new() does not forward any SSL options
1534 IO::Socket::SSL::set_client_defaults(
1535 ssl_verify_params());
0ead000c
DK
1536
1537 if ($use_net_smtp_ssl) {
1538 require Net::SMTP::SSL;
1539 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1540 Hello => $smtp_domain,
1541 Port => $smtp_server_port,
1542 Debug => $debug_net_smtp);
1543 }
1544 else {
1545 $smtp ||= Net::SMTP->new($smtp_server,
1546 Hello => $smtp_domain,
1547 Port => $smtp_server_port,
1548 Debug => $debug_net_smtp,
1549 SSL => 1);
1550 }
34cc60ce 1551 }
636f3d7a 1552 elsif (!$smtp) {
1a741bf7 1553 $smtp_server_port ||= 25;
1554 $smtp ||= Net::SMTP->new($smtp_server,
69cf7bfd 1555 Hello => $smtp_domain,
1a741bf7 1556 Debug => $debug_net_smtp,
1557 Port => $smtp_server_port);
fb3650ed 1558 if ($smtp_encryption eq 'tls' && $smtp) {
0ead000c
DK
1559 if ($use_net_smtp_ssl) {
1560 $smtp->command('STARTTLS');
1561 $smtp->response();
1562 if ($smtp->code != 220) {
1563 die sprintf(__("Server does not support STARTTLS! %s"), $smtp->message);
1564 }
1565 require Net::SMTP::SSL;
35035bbf
RR
1566 $smtp = Net::SMTP::SSL->start_SSL($smtp,
1567 ssl_verify_params())
0ead000c
DK
1568 or die sprintf(__("STARTTLS failed! %s"), IO::Socket::SSL::errstr());
1569 }
1570 else {
1571 $smtp->starttls(ssl_verify_params())
1572 or die sprintf(__("STARTTLS failed! %s"), IO::Socket::SSL::errstr());
f6bebd12 1573 }
0ead000c
DK
1574 # Send EHLO again to receive fresh
1575 # supported commands
1576 $smtp->hello($smtp_domain);
f6bebd12 1577 }
44b2476a
JH
1578 }
1579
1580 if (!$smtp) {
3c5cd20c
VA
1581 die __("Unable to initialize SMTP properly. Check config and use --smtp-debug."),
1582 " VALUES: server=$smtp_server ",
e5afb3a6 1583 "encryption=$smtp_encryption ",
69cf7bfd 1584 "hello=$smtp_domain",
a1dd7e16 1585 defined $smtp_server_port ? " port=$smtp_server_port" : "";
44b2476a
JH
1586 }
1587
4d31a44a 1588 smtp_auth_maybe or die $smtp->message;
2363d746 1589
2b69bfc2 1590 $smtp->mail( $raw_from ) or die $smtp->message;
aca7ad76
EW
1591 $smtp->to( @recipients ) or die $smtp->message;
1592 $smtp->data or die $smtp->message;
f60c483d
SA
1593 $smtp->datasend("$header\n") or die $smtp->message;
1594 my @lines = split /^/, $message;
1595 foreach my $line (@lines) {
1596 $smtp->datasend("$line") or die $smtp->message;
1597 }
aca7ad76 1598 $smtp->dataend() or die $smtp->message;
3c5cd20c 1599 $smtp->code =~ /250|200/ or die sprintf(__("Failed to send %s\n"), $subject).$smtp->message;
aca7ad76 1600 }
2718435b 1601 if ($quiet) {
3c5cd20c 1602 printf($dry_run ? __("Dry-Sent %s\n") : __("Sent %s\n"), $subject);
2718435b 1603 } else {
a4dde4c4 1604 print($dry_run ? __("Dry-OK. Log says:\n") : __("OK. Log says:\n"));
cb005c1f 1605 if (!file_name_is_absolute($smtp_server)) {
aca7ad76 1606 print "Server: $smtp_server\n";
2b69bfc2 1607 print "MAIL FROM:<$raw_from>\n";
02461e0e
JP
1608 foreach my $entry (@recipients) {
1609 print "RCPT TO:<$entry>\n";
1610 }
aca7ad76 1611 } else {
8e3d436b 1612 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
aca7ad76 1613 }
b7f30e0a 1614 print $header, "\n";
aca7ad76 1615 if ($smtp) {
46493105 1616 print __("Result: "), $smtp->code, ' ',
aca7ad76
EW
1617 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1618 } else {
46493105 1619 print __("Result: OK\n");
aca7ad76 1620 }
30d08b34 1621 }
15da1084
MW
1622
1623 return 1;
83b24437
RA
1624}
1625
15dc3b91
CL
1626$in_reply_to = $initial_in_reply_to;
1627$references = $initial_in_reply_to || '';
83b24437 1628$subject = $initial_subject;
c1f2aa45 1629$message_num = 0;
83b24437 1630
04c4a4e8
DD
1631# Prepares the email, prompts the user, sends it out
1632# Returns 0 if an edit was done and the function should be called again, or 1
1633# otherwise.
1634sub process_file {
1635 my ($t) = @_;
1636
3c5cd20c 1637 open my $fh, "<", $t or die sprintf(__("can't open file %s"), $t);
83b24437 1638
94638f89 1639 my $author = undef;
4cb46bdd 1640 my $sauthor = undef;
8291db6f
JK
1641 my $author_encoding;
1642 my $has_content_type;
1643 my $body_encoding;
bb29456c
PB
1644 my $xfer_encoding;
1645 my $has_mime_version;
3c3bb51c 1646 @to = ();
c1f2aa45 1647 @cc = ();
ce91c2f6 1648 @xh = ();
e6b0964a 1649 my $input_format = undef;
5012699d 1650 my @header = ();
83b24437 1651 $message = "";
c1f2aa45 1652 $message_num++;
5012699d 1653 # First unfold multiline header fields
f9237e61 1654 while(<$fh>) {
5012699d
JS
1655 last if /^\s*$/;
1656 if (/^\s+\S/ and @header) {
1657 chomp($header[$#header]);
1658 s/^\s+/ /;
1659 $header[$#header] .= $_;
1660 } else {
1661 push(@header, $_);
1662 }
1663 }
1664 # Now parse the header
1665 foreach(@header) {
1666 if (/^From /) {
1667 $input_format = 'mbox';
1668 next;
1669 }
1670 chomp;
1671 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1672 $input_format = 'mbox';
1673 }
1674
1675 if (defined $input_format && $input_format eq 'mbox') {
6310071a 1676 if (/^Subject:\s+(.*)$/i) {
5012699d 1677 $subject = $1;
e6b0964a 1678 }
6310071a 1679 elsif (/^From:\s+(.*)$/i) {
5012699d 1680 ($author, $author_encoding) = unquote_rfc2047($1);
4cb46bdd 1681 $sauthor = sanitize_address($author);
5012699d 1682 next if $suppress_cc{'author'};
da18759e 1683 next if $suppress_cc{'self'} and $sauthor eq $sender;
a4dde4c4 1684 printf(__("(mbox) Adding cc: %s from line '%s'\n"),
5012699d
JS
1685 $1, $_) unless $quiet;
1686 push @cc, $1;
e6b0964a 1687 }
6310071a 1688 elsif (/^To:\s+(.*)$/i) {
21802cd3 1689 foreach my $addr (parse_address_line($1)) {
a4dde4c4 1690 printf(__("(mbox) Adding to: %s from line '%s'\n"),
21802cd3 1691 $addr, $_) unless $quiet;
e4312255 1692 push @to, $addr;
21802cd3
SB
1693 }
1694 }
6310071a 1695 elsif (/^Cc:\s+(.*)$/i) {
5012699d 1696 foreach my $addr (parse_address_line($1)) {
da18759e
MT
1697 my $qaddr = unquote_rfc2047($addr);
1698 my $saddr = sanitize_address($qaddr);
1699 if ($saddr eq $sender) {
65648283 1700 next if ($suppress_cc{'self'});
65648283
DB
1701 } else {
1702 next if ($suppress_cc{'cc'});
8a8e6235 1703 }
a4dde4c4 1704 printf(__("(mbox) Adding cc: %s from line '%s'\n"),
5012699d
JS
1705 $addr, $_) unless $quiet;
1706 push @cc, $addr;
83b24437 1707 }
5012699d
JS
1708 }
1709 elsif (/^Content-type:/i) {
1710 $has_content_type = 1;
1711 if (/charset="?([^ "]+)/) {
1712 $body_encoding = $1;
83b24437 1713 }
5012699d 1714 push @xh, $_;
83b24437 1715 }
bb29456c
PB
1716 elsif (/^MIME-Version/i) {
1717 $has_mime_version = 1;
1718 push @xh, $_;
1719 }
5012699d
JS
1720 elsif (/^Message-Id: (.*)/i) {
1721 $message_id = $1;
83b24437 1722 }
bb29456c
PB
1723 elsif (/^Content-Transfer-Encoding: (.*)/i) {
1724 $xfer_encoding = $1 if not defined $xfer_encoding;
1725 }
256be1d3 1726 elsif (/^In-Reply-To: (.*)/i) {
f9f60d70
RA
1727 if (!$initial_in_reply_to || $thread) {
1728 $in_reply_to = $1;
1729 }
256be1d3
SA
1730 }
1731 elsif (/^References: (.*)/i) {
f9f60d70
RA
1732 if (!$initial_in_reply_to || $thread) {
1733 $references = $1;
1734 }
256be1d3 1735 }
6310071a 1736 elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
5012699d
JS
1737 push @xh, $_;
1738 }
83b24437 1739 } else {
5012699d
JS
1740 # In the traditional
1741 # "send lots of email" format,
1742 # line 1 = cc
1743 # line 2 = subject
1744 # So let's support that, too.
1745 $input_format = 'lots';
1746 if (@cc == 0 && !$suppress_cc{'cc'}) {
a4dde4c4 1747 printf(__("(non-mbox) Adding cc: %s from line '%s'\n"),
5012699d
JS
1748 $_, $_) unless $quiet;
1749 push @cc, $_;
1750 } elsif (!defined $subject) {
1751 $subject = $_;
83b24437
RA
1752 }
1753 }
1754 }
5012699d 1755 # Now parse the message body
f9237e61 1756 while(<$fh>) {
5012699d 1757 $message .= $_;
9c545816 1758 if (/^([a-z][a-z-]*-by|Cc): (.*)/i) {
5012699d 1759 chomp;
3531e270 1760 my ($what, $c) = ($1, $2);
cb2922fe
MM
1761 # strip garbage for the address we'll use:
1762 $c = strip_garbage_one_address($c);
1763 # sanitize a bit more to decide whether to suppress the address:
da18759e
MT
1764 my $sc = sanitize_address($c);
1765 if ($sc eq $sender) {
3531e270
JS
1766 next if ($suppress_cc{'self'});
1767 } else {
ef0cc1df
RV
1768 if ($what =~ /^Signed-off-by$/i) {
1769 next if $suppress_cc{'sob'};
1770 } elsif ($what =~ /-by$/i) {
1771 next if $suppress_cc{'misc-by'};
1772 } elsif ($what =~ /Cc/i) {
1773 next if $suppress_cc{'bodycc'};
1774 }
3531e270 1775 }
fb34fe6a
RV
1776 if ($c !~ /.+@.+|<.+>/) {
1777 printf("(body) Ignoring %s from line '%s'\n",
1778 $what, $_) unless $quiet;
1779 next;
1780 }
5012699d 1781 push @cc, $c;
a4dde4c4 1782 printf(__("(body) Adding cc: %s from line '%s'\n"),
5012699d
JS
1783 $c, $_) unless $quiet;
1784 }
1785 }
f9237e61 1786 close $fh;
324a8bd0 1787
6e74e075
JP
1788 push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1789 if defined $to_cmd;
1790 push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1791 if defined $cc_cmd && !$suppress_cc{'cccmd'};
324a8bd0 1792
3cae7e5b 1793 if ($broken_encoding{$t} && !$has_content_type) {
bb29456c 1794 $xfer_encoding = '8bit' if not defined $xfer_encoding;
3cae7e5b 1795 $has_content_type = 1;
bb29456c 1796 push @xh, "Content-Type: text/plain; charset=$auto_8bit_encoding";
3cae7e5b
TR
1797 $body_encoding = $auto_8bit_encoding;
1798 }
1799
ce547800
KM
1800 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1801 $subject = quote_subject($subject, $auto_8bit_encoding);
3cae7e5b
TR
1802 }
1803
4cb46bdd 1804 if (defined $sauthor and $sauthor ne $sender) {
94638f89 1805 $message = "From: $author\n\n$message";
8291db6f
JK
1806 if (defined $author_encoding) {
1807 if ($has_content_type) {
1808 if ($body_encoding eq $author_encoding) {
1809 # ok, we already have the right encoding
1810 }
1811 else {
1812 # uh oh, we should re-encode
1813 }
1814 }
1815 else {
bb29456c 1816 $xfer_encoding = '8bit' if not defined $xfer_encoding;
3cae7e5b 1817 $has_content_type = 1;
8291db6f 1818 push @xh,
bb29456c 1819 "Content-Type: text/plain; charset=$author_encoding";
8291db6f
JK
1820 }
1821 }
8a8e6235 1822 }
e67a228c 1823 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1824 ($message, $xfer_encoding) = apply_transfer_encoding(
1825 $message, $xfer_encoding, $target_xfer_encoding);
1826 push @xh, "Content-Transfer-Encoding: $xfer_encoding";
1827 unshift @xh, 'MIME-Version: 1.0' unless $has_mime_version;
83b24437 1828
c1f2aa45
JS
1829 $needs_confirm = (
1830 $confirm eq "always" or
1831 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1832 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1833 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1834
b5e112d8
RL
1835 @to = process_address_list(@to);
1836 @cc = process_address_list(@cc);
e4312255 1837
3c3bb51c 1838 @to = (@initial_to, @to);
c1f2aa45
JS
1839 @cc = (@initial_cc, @cc);
1840
f515c904
MT
1841 if ($message_num == 1) {
1842 if (defined $cover_cc and $cover_cc) {
1843 @initial_cc = @cc;
1844 }
1845 if (defined $cover_to and $cover_to) {
1846 @initial_to = @to;
1847 }
1848 }
1849
15da1084 1850 my $message_was_sent = send_message();
04c4a4e8
DD
1851 if ($message_was_sent == -1) {
1852 do_edit($t);
1853 return 0;
1854 }
83b24437
RA
1855
1856 # set up for the next message
95a877a3 1857 if ($thread && $message_was_sent &&
15dc3b91 1858 ($chain_reply_to || !defined $in_reply_to || length($in_reply_to) == 0 ||
db54c8e7 1859 $message_num == 1)) {
15dc3b91 1860 $in_reply_to = $message_id;
7ccf7927 1861 if (length $references > 0) {
a925b89c 1862 $references .= "\n $message_id";
7ccf7927
RA
1863 } else {
1864 $references = "$message_id";
1865 }
78488b2c 1866 }
4f3d3703 1867 $message_id = undef;
5453b83b 1868 $num_sent++;
1869 if (defined $batch_size && $num_sent == $batch_size) {
1870 $num_sent = 0;
1871 $smtp->quit if defined $smtp;
1872 undef $smtp;
1873 undef $auth;
1874 sleep($relogin_delay) if defined $relogin_delay;
1875 }
04c4a4e8
DD
1876
1877 return 1;
1878}
1879
1880foreach my $t (@files) {
1881 while (!process_file($t)) {
1882 # user edited the file
1883 }
83b24437 1884}
e205735d 1885
6e74e075
JP
1886# Execute a command (e.g. $to_cmd) to get a list of email addresses
1887# and return a results array
1888sub recipients_cmd {
1889 my ($prefix, $what, $cmd, $file) = @_;
1890
6e74e075 1891 my @addresses = ();
a47eab03 1892 open my $fh, "-|", "$cmd \Q$file\E"
3c5cd20c 1893 or die sprintf(__("(%s) Could not execute '%s'"), $prefix, $cmd);
7ebee441 1894 while (my $address = <$fh>) {
6e74e075
JP
1895 $address =~ s/^\s*//g;
1896 $address =~ s/\s*$//g;
1897 $address = sanitize_address($address);
da18759e 1898 next if ($address eq $sender and $suppress_cc{'self'});
6e74e075 1899 push @addresses, $address;
3c5cd20c
VA
1900 printf(__("(%s) Adding %s: %s from: '%s'\n"),
1901 $prefix, $what, $address, $cmd) unless $quiet;
6e74e075 1902 }
7ebee441 1903 close $fh
3c5cd20c 1904 or die sprintf(__("(%s) failed to close pipe to '%s'"), $prefix, $cmd);
6e74e075
JP
1905 return @addresses;
1906}
1907
c1f2aa45 1908cleanup_compose_files();
1f038a0c 1909
4bf597ee 1910sub cleanup_compose_files {
c1f2aa45 1911 unlink($compose_filename, $compose_filename . ".final") if $compose;
1f038a0c
RA
1912}
1913
4bc87a28 1914$smtp->quit if $smtp;
e205735d 1915
8d814084
PB
1916sub apply_transfer_encoding {
1917 my $message = shift;
1918 my $from = shift;
1919 my $to = shift;
1920
3c88e46f 1921 return ($message, $to) if ($from eq $to and $from ne '7bit');
8d814084
PB
1922
1923 require MIME::QuotedPrint;
1924 require MIME::Base64;
1925
1926 $message = MIME::QuotedPrint::decode($message)
1927 if ($from eq 'quoted-printable');
1928 $message = MIME::Base64::decode($message)
1929 if ($from eq 'base64');
1930
74d76a17 1931 $to = ($message =~ /(?:.{999,}|\r)/) ? 'quoted-printable' : '8bit'
7a36987f 1932 if $to eq 'auto';
1933
46493105 1934 die __("cannot send message as 7bit")
8d814084 1935 if ($to eq '7bit' and $message =~ /[^[:ascii:]]/);
7a36987f 1936 return ($message, $to)
8d814084 1937 if ($to eq '7bit' or $to eq '8bit');
7a36987f 1938 return (MIME::QuotedPrint::encode($message, "\n", 0), $to)
8d814084 1939 if ($to eq 'quoted-printable');
7a36987f 1940 return (MIME::Base64::encode($message, "\n"), $to)
8d814084 1941 if ($to eq 'base64');
46493105 1942 die __("invalid transfer encoding");
8d814084
PB
1943}
1944
c438ea2a 1945sub unique_email_list {
e205735d
RA
1946 my %seen;
1947 my @emails;
1948
1949 foreach my $entry (@_) {
e4312255
KM
1950 my $clean = extract_valid_address_or_die($entry);
1951 $seen{$clean} ||= 0;
1952 next if $seen{$clean}++;
1953 push @emails, $entry;
e205735d
RA
1954 }
1955 return @emails;
1956}
747bbff9
JK
1957
1958sub validate_patch {
f2d06fb1 1959 my ($fn, $xfer_encoding) = @_;
6489660b 1960
177409e5 1961 if ($repo) {
7cbc0455
ÆAB
1962 my $hooks_path = $repo->command_oneline('rev-parse', '--git-path', 'hooks');
1963 my $validate_hook = catfile($hooks_path,
177409e5
JT
1964 'sendemail-validate');
1965 my $hook_error;
1966 if (-x $validate_hook) {
1967 my $target = abs_path($fn);
1968 # The hook needs a correct cwd and GIT_DIR.
1969 my $cwd_save = cwd();
1970 chdir($repo->wc_path() or $repo->repo_path())
1971 or die("chdir: $!");
1972 local $ENV{"GIT_DIR"} = $repo->repo_path();
d21616c0 1973 $hook_error = system_or_msg([$validate_hook, $target]);
177409e5
JT
1974 chdir($cwd_save) or die("chdir: $!");
1975 }
d21616c0
ÆAB
1976 if ($hook_error) {
1977 die sprintf(__("fatal: %s: rejected by sendemail-validate hook\n" .
ea7811b3
ÆAB
1978 "%s\n" .
1979 "warning: no patches were sent\n"), $fn, $hook_error);
d21616c0 1980 }
177409e5 1981 }
6489660b 1982
f2d06fb1 1983 # Any long lines will be automatically fixed if we use a suitable transfer
1984 # encoding.
1985 unless ($xfer_encoding =~ /^(?:auto|quoted-printable|base64)$/) {
1986 open(my $fh, '<', $fn)
1987 or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
1988 while (my $line = <$fh>) {
1989 if (length($line) > 998) {
ea7811b3
ÆAB
1990 die sprintf(__("fatal: %s:%d is longer than 998 characters\n" .
1991 "warning: no patches were sent\n"), $fn, $.);
f2d06fb1 1992 }
747bbff9
JK
1993 }
1994 }
622bc930 1995 return;
747bbff9 1996}
0706bd19 1997
531220ba
JH
1998sub handle_backup {
1999 my ($last, $lastlen, $file, $known_suffix) = @_;
2000 my ($suffix, $skip);
2001
2002 $skip = 0;
2003 if (defined $last &&
2004 ($lastlen < length($file)) &&
2005 (substr($file, 0, $lastlen) eq $last) &&
2006 ($suffix = substr($file, $lastlen)) !~ /^[a-z0-9]/i) {
2007 if (defined $known_suffix && $suffix eq $known_suffix) {
3c5cd20c 2008 printf(__("Skipping %s with backup suffix '%s'.\n"), $file, $known_suffix);
531220ba
JH
2009 $skip = 1;
2010 } else {
3c5cd20c
VA
2011 # TRANSLATORS: please keep "[y|N]" as is.
2012 my $answer = ask(sprintf(__("Do you really want to send %s? [y|N]: "), $file),
531220ba
JH
2013 valid_re => qr/^(?:y|n)/i,
2014 default => 'n');
2015 $skip = ($answer ne 'y');
2016 if ($skip) {
2017 $known_suffix = $suffix;
2018 }
2019 }
2020 }
2021 return ($skip, $known_suffix);
2022}
2023
2024sub handle_backup_files {
2025 my @file = @_;
2026 my ($last, $lastlen, $known_suffix, $skip, @result);
2027 for my $file (@file) {
2028 ($skip, $known_suffix) = handle_backup($last, $lastlen,
2029 $file, $known_suffix);
2030 push @result, $file unless $skip;
2031 $last = $file;
2032 $lastlen = length($file);
2033 }
2034 return @result;
2035}
2036
0706bd19
JK
2037sub file_has_nonascii {
2038 my $fn = shift;
2039 open(my $fh, '<', $fn)
3c5cd20c 2040 or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
0706bd19
JK
2041 while (my $line = <$fh>) {
2042 return 1 if $line =~ /[^[:ascii:]]/;
2043 }
2044 return 0;
2045}
3cae7e5b
TR
2046
2047sub body_or_subject_has_nonascii {
2048 my $fn = shift;
2049 open(my $fh, '<', $fn)
3c5cd20c 2050 or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
3cae7e5b
TR
2051 while (my $line = <$fh>) {
2052 last if $line =~ /^$/;
2053 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
2054 }
2055 while (my $line = <$fh>) {
2056 return 1 if $line =~ /[^[:ascii:]]/;
2057 }
2058 return 0;
2059}