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