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