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