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