]> git.ipfire.org Git - thirdparty/git.git/blame - git-send-email.perl
Merge branch 'ab/require-perl-5.8'
[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;
22use Term::ReadLine;
83b24437 23use Getopt::Long;
0e73b3ee 24use Text::ParseWords;
83b24437 25use Data::Dumper;
412876dc 26use Term::ANSIColor;
eed6ca7c 27use File::Temp qw/ tempdir tempfile /;
89bf1bac 28use File::Spec::Functions qw(catfile);
5df9fcf6 29use Error qw(:try);
3cb8caf7 30use Git;
83b24437 31
5df9fcf6
PH
32Getopt::Long::Configure qw/ pass_through /;
33
280242d1
JH
34package FakeTerm;
35sub new {
36 my ($class, $reason) = @_;
37 return bless \$reason, shift;
38}
39sub readline {
40 my $self = shift;
41 die "Cannot use readline on FakeTerm: $$self";
42}
43package main;
44
1b0baf14
MC
45
46sub usage {
47 print <<EOT;
5df9fcf6 48git send-email [options] <file | directory | rev-list options >
4ed62b03
MW
49
50 Composing:
51 --from <str> * Email From:
f434c083
SB
52 --[no-]to <str> * Email To:
53 --[no-]cc <str> * Email Cc:
54 --[no-]bcc <str> * Email Bcc:
4ed62b03
MW
55 --subject <str> * Email "Subject:"
56 --in-reply-to <str> * Email "In-Reply-To:"
8fd5bb7f 57 --annotate * Review each patch that will be sent in an editor.
4ed62b03 58 --compose * Open an editor for introduction.
3cae7e5b 59 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
4ed62b03
MW
60
61 Sending:
62 --envelope-sender <str> * Email envelope sender.
63 --smtp-server <str:int> * Outgoing SMTP server to use. The port
64 is optional. Default 'localhost'.
052fbea2 65 --smtp-server-option <str> * Outgoing SMTP server option to use.
4ed62b03
MW
66 --smtp-server-port <int> * Outgoing SMTP server port.
67 --smtp-user <str> * Username for SMTP-AUTH.
68 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
69 --smtp-encryption <str> * tls or ssl; anything else disables.
70 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
134550fe 71 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
f60812ef 72 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
4ed62b03
MW
73
74 Automating:
75 --identity <str> * Use the sendemail.<id> options.
6e74e075 76 --to-cmd <str> * Email To: via `<str> \$patch_path`
4ed62b03 77 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
3531e270
JS
78 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
79 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
4ed62b03 80 --[no-]suppress-from * Send to self. Default off.
41fe87fa 81 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
4ed62b03
MW
82 --[no-]thread * Use In-Reply-To: field. Default on.
83
84 Administering:
c1f2aa45
JS
85 --confirm <str> * Confirm recipients before sending;
86 auto, cc, compose, always, or never.
4ed62b03
MW
87 --quiet * Output one line of info per email.
88 --dry-run * Don't actually send the emails.
89 --[no-]validate * Perform patch sanity checks. Default on.
5df9fcf6
PH
90 --[no-]format-patch * understand any non optional arguments as
91 `git format-patch` ones.
a03bc5b6 92 --force * Send even if safety checks would prevent it.
c764a0c2 93
1b0baf14
MC
94EOT
95 exit(1);
96}
97
4bc87a28 98# most mail servers generate the Date: header, but not all...
6bdca890
JN
99sub format_2822_time {
100 my ($time) = @_;
101 my @localtm = localtime($time);
102 my @gmttm = gmtime($time);
103 my $localmin = $localtm[1] + $localtm[2] * 60;
104 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
105 if ($localtm[0] != $gmttm[0]) {
106 die "local zone differs from GMT by a non-minute interval\n";
107 }
108 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
109 $localmin += 1440;
110 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
111 $localmin -= 1440;
112 } elsif ($gmttm[6] != $localtm[6]) {
113 die "local time offset greater than or equal to 24 hours\n";
114 }
115 my $offset = $localmin - $gmtmin;
116 my $offhour = $offset / 60;
117 my $offmin = abs($offset % 60);
118 if (abs($offhour) >= 24) {
119 die ("local time offset greater than or equal to 24 hours\n");
120 }
121
122 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
123 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
124 $localtm[3],
125 qw(Jan Feb Mar Apr May Jun
126 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
127 $localtm[5]+1900,
128 $localtm[2],
129 $localtm[1],
130 $localtm[0],
131 ($offset >= 0) ? '+' : '-',
132 abs($offhour),
133 $offmin,
134 );
135}
4bc87a28 136
567ffeb7 137my $have_email_valid = eval { require Email::Valid; 1 };
5012699d 138my $have_mail_address = eval { require Mail::Address; 1 };
4bc87a28 139my $smtp;
5f5b6118 140my $auth;
4bc87a28 141
e205735d 142sub unique_email_list(@);
1f038a0c
RA
143sub cleanup_compose_files();
144
83b24437 145# Variables we fill in automatically, or via prompting:
f434c083 146my (@to,$no_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
8fd5bb7f
PH
147 $initial_reply_to,$initial_subject,@files,
148 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
83b24437 149
f073a592 150my $envelope_sender;
78488b2c 151
9133261f 152# Example reply to:
83b24437 153#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
83b24437 154
ad79c024
FL
155my $repo = eval { Git->repository() };
156my @repo = $repo ? ($repo) : ();
280242d1 157my $term = eval {
0fb7fc75
JS
158 $ENV{"GIT_SEND_EMAIL_NOTTY"}
159 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
160 : new Term::ReadLine 'git-send-email';
280242d1
JH
161};
162if ($@) {
163 $term = new FakeTerm "$@: going non-interactive";
164}
83b24437 165
5483c71d
AR
166# Behavior modification variables
167my ($quiet, $dry_run) = (0, 0);
5df9fcf6 168my $format_patch;
afe756c9 169my $compose_filename;
a03bc5b6 170my $force = 0;
5483c71d 171
8fd5bb7f
PH
172# Handle interactive edition of files.
173my $multiedit;
0ce142c9 174my $editor;
b4479f07 175
8fd5bb7f 176sub do_edit {
0ce142c9
MG
177 if (!defined($editor)) {
178 $editor = Git::command_oneline('var', 'GIT_EDITOR');
179 }
8fd5bb7f 180 if (defined($multiedit) && !$multiedit) {
beece9da
PH
181 map {
182 system('sh', '-c', $editor.' "$@"', $editor, $_);
183 if (($? & 127) || ($? >> 8)) {
184 die("the editor exited uncleanly, aborting everything");
185 }
186 } @_;
8fd5bb7f
PH
187 } else {
188 system('sh', '-c', $editor.' "$@"', $editor, @_);
beece9da
PH
189 if (($? & 127) || ($? >> 8)) {
190 die("the editor exited uncleanly, aborting everything");
191 }
8fd5bb7f
PH
192 }
193}
5483c71d
AR
194
195# Variables with corresponding config settings
6e74e075
JP
196my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
197my ($to_cmd, $cc_cmd);
052fbea2
PO
198my ($smtp_server, $smtp_server_port, @smtp_server_options);
199my ($smtp_authuser, $smtp_encryption);
1d02a005 200my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
c1f2aa45 201my ($validate, $confirm);
65648283 202my (@suppress_cc);
3cae7e5b 203my ($auto_8bit_encoding);
5483c71d 204
f60812ef
JA
205my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
206
528fb087
NS
207my $not_set_by_user = "true but not set by the user";
208
34cc60ce 209my %config_bool_settings = (
5483c71d 210 "thread" => [\$thread, 1],
528fb087 211 "chainreplyto" => [\$chain_reply_to, $not_set_by_user],
65648283 212 "suppressfrom" => [\$suppress_from, undef],
ddc3d4fe
MW
213 "signedoffbycc" => [\$signed_off_by_cc, undef],
214 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
dbf5e1e9 215 "validate" => [\$validate, 1],
e46f7a0e
AR
216);
217
34cc60ce
DS
218my %config_settings = (
219 "smtpserver" => \$smtp_server,
44b2476a 220 "smtpserverport" => \$smtp_server_port,
052fbea2 221 "smtpserveroption" => \@smtp_server_options,
34cc60ce
DS
222 "smtpuser" => \$smtp_authuser,
223 "smtppass" => \$smtp_authpass,
e1e9115d 224 "smtpdomain" => \$smtp_domain,
2db9b49c 225 "to" => \@to,
6e74e075 226 "tocmd" => \$to_cmd,
5f8b9fcd 227 "cc" => \@initial_cc,
34cc60ce
DS
228 "cccmd" => \$cc_cmd,
229 "aliasfiletype" => \$aliasfiletype,
230 "bcc" => \@bcclist,
231 "aliasesfile" => \@alias_files,
65648283 232 "suppresscc" => \@suppress_cc,
9f7820ae 233 "envelopesender" => \$envelope_sender,
8fd5bb7f 234 "multiedit" => \$multiedit,
c1f2aa45 235 "confirm" => \$confirm,
09caa24f 236 "from" => \$sender,
3cae7e5b 237 "assume8bitencoding" => \$auto_8bit_encoding,
34cc60ce 238);
4a62d3f5 239
528fb087
NS
240# Help users prepare for 1.7.0
241sub chain_reply_to {
242 if (defined $chain_reply_to &&
243 $chain_reply_to eq $not_set_by_user) {
244 print STDERR
a19f101e 245 "In git 1.7.0, the default has changed to --no-chain-reply-to\n" .
528fb087
NS
246 "Set sendemail.chainreplyto configuration variable to true if\n" .
247 "you want to keep --chain-reply-to as your default.\n";
a19f101e 248 $chain_reply_to = 0;
528fb087
NS
249 }
250 return $chain_reply_to;
251}
252
87429976
MW
253# Handle Uncouth Termination
254sub signal_handler {
255
256 # Make text normal
257 print color("reset"), "\n";
258
259 # SMTP password masked
260 system "stty echo";
261
262 # tmp files from --compose
afe756c9
JS
263 if (defined $compose_filename) {
264 if (-e $compose_filename) {
265 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
266 }
267 if (-e ($compose_filename . ".final")) {
268 print "'$compose_filename.final' contains the composed email.\n"
269 }
87429976
MW
270 }
271
272 exit;
273};
274
275$SIG{TERM} = \&signal_handler;
276$SIG{INT} = \&signal_handler;
277
83b24437
RA
278# Begin by accumulating all the variables (defined above), that we will end up
279# needing, first, from the command line:
280
94638f89 281my $rc = GetOptions("sender|from=s" => \$sender,
83b24437
RA
282 "in-reply-to=s" => \$initial_reply_to,
283 "subject=s" => \$initial_subject,
284 "to=s" => \@to,
6e74e075 285 "to-cmd=s" => \$to_cmd,
f434c083 286 "no-to" => \$no_to,
da140f8b 287 "cc=s" => \@initial_cc,
f434c083 288 "no-cc" => \$no_cc,
58063245 289 "bcc=s" => \@bcclist,
f434c083 290 "no-bcc" => \$no_bcc,
78488b2c 291 "chain-reply-to!" => \$chain_reply_to,
3342d850 292 "smtp-server=s" => \$smtp_server,
052fbea2 293 "smtp-server-option=s" => \@smtp_server_options,
44b2476a 294 "smtp-server-port=s" => \$smtp_server_port,
34cc60ce 295 "smtp-user=s" => \$smtp_authuser,
2363d746 296 "smtp-pass:s" => \$smtp_authpass,
f6bebd12
TR
297 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
298 "smtp-encryption=s" => \$smtp_encryption,
f60812ef 299 "smtp-debug:i" => \$debug_net_smtp,
69cf7bfd 300 "smtp-domain:s" => \$smtp_domain,
34cc60ce 301 "identity=s" => \$identity,
8fd5bb7f 302 "annotate" => \$annotate,
1f038a0c 303 "compose" => \$compose,
30d08b34 304 "quiet" => \$quiet,
324a8bd0 305 "cc-cmd=s" => \$cc_cmd,
5483c71d 306 "suppress-from!" => \$suppress_from,
65648283 307 "suppress-cc=s" => \@suppress_cc,
ddc3d4fe 308 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
c1f2aa45 309 "confirm=s" => \$confirm,
6130259c 310 "dry-run" => \$dry_run,
f073a592 311 "envelope-sender=s" => \$envelope_sender,
5483c71d 312 "thread!" => \$thread,
dbf5e1e9 313 "validate!" => \$validate,
5df9fcf6 314 "format-patch!" => \$format_patch,
3cae7e5b 315 "8bit-encoding=s" => \$auto_8bit_encoding,
a03bc5b6 316 "force" => \$force,
83b24437
RA
317 );
318
1b0baf14
MC
319unless ($rc) {
320 usage();
321}
322
eed6ca7c
JS
323die "Cannot run git format-patch from outside a repository\n"
324 if $format_patch and not $repo;
325
34cc60ce
DS
326# Now, let's fill any that aren't set in with defaults:
327
328sub read_config {
329 my ($prefix) = @_;
330
331 foreach my $setting (keys %config_bool_settings) {
332 my $target = $config_bool_settings{$setting}->[0];
ad79c024 333 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
34cc60ce
DS
334 }
335
336 foreach my $setting (keys %config_settings) {
337 my $target = $config_settings{$setting};
f434c083
SB
338 next if $setting eq "to" and defined $no_to;
339 next if $setting eq "cc" and defined $no_cc;
340 next if $setting eq "bcc" and defined $no_bcc;
34cc60ce
DS
341 if (ref($target) eq "ARRAY") {
342 unless (@$target) {
ad79c024 343 my @values = Git::config(@repo, "$prefix.$setting");
34cc60ce
DS
344 @$target = @values if (@values && defined $values[0]);
345 }
346 }
347 else {
ad79c024 348 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
34cc60ce
DS
349 }
350 }
f6bebd12
TR
351
352 if (!defined $smtp_encryption) {
353 my $enc = Git::config(@repo, "$prefix.smtpencryption");
354 if (defined $enc) {
355 $smtp_encryption = $enc;
356 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
357 $smtp_encryption = 'ssl';
358 }
359 }
34cc60ce
DS
360}
361
362# read configuration from [sendemail "$identity"], fall back on [sendemail]
ad79c024 363$identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
34cc60ce
DS
364read_config("sendemail.$identity") if (defined $identity);
365read_config("sendemail");
366
367# fall back on builtin bool defaults
368foreach my $setting (values %config_bool_settings) {
369 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
370}
371
fa835cd5
TR
372# 'default' encryption is none -- this only prevents a warning
373$smtp_encryption = '' unless (defined $smtp_encryption);
374
65648283
DB
375# Set CC suppressions
376my(%suppress_cc);
377if (@suppress_cc) {
378 foreach my $entry (@suppress_cc) {
379 die "Unknown --suppress-cc field: '$entry'\n"
3531e270 380 unless $entry =~ /^(all|cccmd|cc|author|self|sob|body|bodycc)$/;
65648283
DB
381 $suppress_cc{$entry} = 1;
382 }
383}
384
385if ($suppress_cc{'all'}) {
cb8a9bd5 386 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
65648283
DB
387 $suppress_cc{$entry} = 1;
388 }
389 delete $suppress_cc{'all'};
390}
391
392# If explicit old-style ones are specified, they trump --suppress-cc.
393$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
ddc3d4fe 394$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
65648283 395
3531e270
JS
396if ($suppress_cc{'body'}) {
397 foreach my $entry (qw (sob bodycc)) {
398 $suppress_cc{$entry} = 1;
399 }
400 delete $suppress_cc{'body'};
401}
402
c1f2aa45
JS
403# Set confirm's default value
404my $confirm_unconfigured = !defined $confirm;
405if ($confirm_unconfigured) {
406 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
407};
408die "Unknown --confirm setting: '$confirm'\n"
409 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
410
65648283
DB
411# Debugging, print out the suppressions.
412if (0) {
413 print "suppressions:\n";
414 foreach my $entry (keys %suppress_cc) {
415 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
416 }
417}
418
ad79c024
FL
419my ($repoauthor, $repocommitter);
420($repoauthor) = Git::ident_person(@repo, 'author');
421($repocommitter) = Git::ident_person(@repo, 'committer');
34cc60ce 422
79ee555b
EB
423# Verify the user input
424
425foreach my $entry (@to) {
426 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
427}
428
429foreach my $entry (@initial_cc) {
430 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
431}
432
433foreach my $entry (@bcclist) {
434 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
435}
436
5012699d
JS
437sub parse_address_line {
438 if ($have_mail_address) {
439 return map { $_->format } Mail::Address->parse($_[0]);
440 } else {
441 return split_addrs($_[0]);
442 }
443}
444
0e73b3ee 445sub split_addrs {
2f0e7cbb 446 return quotewords('\s*,\s*', 1, @_);
0e73b3ee
WF
447}
448
994d6c66 449my %aliases;
994d6c66
EW
450my %parse_alias = (
451 # multiline formats can be supported in the future
452 mutt => sub { my $fh = shift; while (<$fh>) {
ffc01f9b 453 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
994d6c66
EW
454 my ($alias, $addr) = ($1, $2);
455 $addr =~ s/#.*$//; # mutt allows # comments
456 # commas delimit multiple addresses
0e73b3ee 457 $aliases{$alias} = [ split_addrs($addr) ];
994d6c66
EW
458 }}},
459 mailrc => sub { my $fh = shift; while (<$fh>) {
460 if (/^alias\s+(\S+)\s+(.*)$/) {
461 # spaces delimit multiple addresses
fe87c921 462 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
994d6c66 463 }}},
73c427eb
TP
464 pine => sub { my $fh = shift; my $f='\t[^\t]*';
465 for (my $x = ''; defined($x); $x = $_) {
466 chomp $x;
467 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
468 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
0e73b3ee 469 $aliases{$1} = [ split_addrs($2) ];
73c427eb 470 }},
7613ea35
BP
471 elm => sub { my $fh = shift;
472 while (<$fh>) {
473 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
474 my ($alias, $addr) = ($1, $2);
475 $aliases{$alias} = [ split_addrs($addr) ];
476 }
477 } },
478
994d6c66
EW
479 gnus => sub { my $fh = shift; while (<$fh>) {
480 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
481 $aliases{$1} = [ $2 ];
482 }}}
483);
484
3cb8caf7 485if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
994d6c66
EW
486 foreach my $file (@alias_files) {
487 open my $fh, '<', $file or die "opening $file: $!\n";
488 $parse_alias{$aliasfiletype}->($fh);
489 close $fh;
490 }
491}
492
94638f89 493($sender) = expand_aliases($sender) if defined $sender;
ae740a58 494
5df9fcf6
PH
495# returns 1 if the conflict must be solved using it as a format-patch argument
496sub check_file_rev_conflict($) {
eed6ca7c 497 return unless $repo;
5df9fcf6
PH
498 my $f = shift;
499 try {
500 $repo->command('rev-parse', '--verify', '--quiet', $f);
501 if (defined($format_patch)) {
5df9fcf6
PH
502 return $format_patch;
503 }
504 die(<<EOF);
505File '$f' exists but it could also be the range of commits
506to produce patches for. Please disambiguate by...
507
508 * Saying "./$f" if you mean a file; or
509 * Giving --format-patch option if you mean a range.
510EOF
511 } catch Git::Error::Command with {
512 return 0;
513 }
514}
515
aa54892f
JK
516# Now that all the defaults are set, process the rest of the command line
517# arguments and collect up the files that need to be processed.
5df9fcf6 518my @rev_list_opts;
69f4ce55 519while (defined(my $f = shift @ARGV)) {
5df9fcf6
PH
520 if ($f eq "--") {
521 push @rev_list_opts, "--", @ARGV;
522 @ARGV = ();
523 } elsif (-d $f and !check_file_rev_conflict($f)) {
aa54892f
JK
524 opendir(DH,$f)
525 or die "Failed to opendir $f: $!";
526
89bf1bac 527 push @files, grep { -f $_ } map { catfile($f, $_) }
aa54892f 528 sort readdir(DH);
8c178687 529 closedir(DH);
5df9fcf6 530 } elsif ((-f $f or -p $f) and !check_file_rev_conflict($f)) {
aa54892f 531 push @files, $f;
aa54892f 532 } else {
5df9fcf6 533 push @rev_list_opts, $f;
aa54892f
JK
534 }
535}
536
5df9fcf6 537if (@rev_list_opts) {
eed6ca7c
JS
538 die "Cannot run git format-patch from outside a repository\n"
539 unless $repo;
5df9fcf6
PH
540 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
541}
542
dbf5e1e9 543if ($validate) {
c764a0c2 544 foreach my $f (@files) {
300913bd
KB
545 unless (-p $f) {
546 my $error = validate_patch($f);
547 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
548 }
c764a0c2 549 }
747bbff9
JK
550}
551
aa54892f
JK
552if (@files) {
553 unless ($quiet) {
554 print $_,"\n" for (@files);
555 }
556} else {
557 print STDERR "\nNo patch files specified!\n\n";
558 usage();
559}
560
beece9da
PH
561sub get_patch_subject($) {
562 my $fn = shift;
563 open (my $fh, '<', $fn);
564 while (my $line = <$fh>) {
565 next unless ($line =~ /^Subject: (.*)$/);
566 close $fh;
567 return "GIT: $1\n";
568 }
569 close $fh;
570 die "No subject line in $fn ?";
571}
572
573if ($compose) {
574 # Note that this does not need to be secure, but we will make a small
575 # effort to have it be unique
afe756c9
JS
576 $compose_filename = ($repo ?
577 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
578 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
beece9da
PH
579 open(C,">",$compose_filename)
580 or die "Failed to open for writing $compose_filename: $!";
581
582
583 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
584 my $tpl_subject = $initial_subject || '';
585 my $tpl_reply_to = $initial_reply_to || '';
586
587 print C <<EOT;
588From $tpl_sender # This line is ignored.
40e6e8a0 589GIT: Lines beginning in "GIT:" will be removed.
beece9da
PH
590GIT: Consider including an overall diffstat or table of contents
591GIT: for the patch you are writing.
592GIT:
593GIT: Clear the body content if you don't wish to send a summary.
594From: $tpl_sender
595Subject: $tpl_subject
596In-Reply-To: $tpl_reply_to
597
598EOT
599 for my $f (@files) {
600 print C get_patch_subject($f);
601 }
602 close(C);
603
beece9da
PH
604 if ($annotate) {
605 do_edit($compose_filename, @files);
606 } else {
607 do_edit($compose_filename);
608 }
609
610 open(C2,">",$compose_filename . ".final")
611 or die "Failed to open $compose_filename.final : " . $!;
612
613 open(C,"<",$compose_filename)
614 or die "Failed to open $compose_filename : " . $!;
615
616 my $need_8bit_cte = file_has_nonascii($compose_filename);
617 my $in_body = 0;
618 my $summary_empty = 1;
619 while(<C>) {
40e6e8a0 620 next if m/^GIT:/;
beece9da
PH
621 if ($in_body) {
622 $summary_empty = 0 unless (/^\n$/);
623 } elsif (/^\n$/) {
624 $in_body = 1;
625 if ($need_8bit_cte) {
626 print C2 "MIME-Version: 1.0\n",
627 "Content-Type: text/plain; ",
d1fff6fc 628 "charset=UTF-8\n",
beece9da
PH
629 "Content-Transfer-Encoding: 8bit\n";
630 }
631 } elsif (/^MIME-Version:/i) {
632 $need_8bit_cte = 0;
633 } elsif (/^Subject:\s*(.+)\s*$/i) {
634 $initial_subject = $1;
635 my $subject = $initial_subject;
636 $_ = "Subject: " .
637 ($subject =~ /[^[:ascii:]]/ ?
638 quote_rfc2047($subject) :
639 $subject) .
640 "\n";
641 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
642 $initial_reply_to = $1;
643 next;
644 } elsif (/^From:\s*(.+)\s*$/i) {
645 $sender = $1;
646 next;
647 } elsif (/^(?:To|Cc|Bcc):/i) {
648 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
649 next;
650 }
651 print C2 $_;
652 }
653 close(C);
654 close(C2);
655
656 if ($summary_empty) {
657 print "Summary email is empty, skipping it\n";
658 $compose = -1;
659 }
660} elsif ($annotate) {
661 do_edit(@files);
662}
663
6e182518
JS
664sub ask {
665 my ($prompt, %arg) = @_;
0da43a68 666 my $valid_re = $arg{valid_re};
6e182518
JS
667 my $default = $arg{default};
668 my $resp;
669 my $i = 0;
5906f54e
JS
670 return defined $default ? $default : undef
671 unless defined $term->IN and defined fileno($term->IN) and
672 defined $term->OUT and defined fileno($term->OUT);
6e182518
JS
673 while ($i++ < 10) {
674 $resp = $term->readline($prompt);
675 if (!defined $resp) { # EOF
676 print "\n";
677 return defined $default ? $default : undef;
678 }
679 if ($resp eq '' and defined $default) {
680 return $default;
681 }
0da43a68 682 if (!defined $valid_re or $resp =~ /$valid_re/) {
6e182518
JS
683 return $resp;
684 }
685 }
686 return undef;
687}
688
3cae7e5b
TR
689my %broken_encoding;
690
691sub file_declares_8bit_cte($) {
692 my $fn = shift;
693 open (my $fh, '<', $fn);
694 while (my $line = <$fh>) {
695 last if ($line =~ /^$/);
696 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
697 }
698 close $fh;
699 return 0;
700}
701
702foreach my $f (@files) {
703 next unless (body_or_subject_has_nonascii($f)
704 && !file_declares_8bit_cte($f));
705 $broken_encoding{$f} = 1;
706}
707
708if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
709 print "The following files are 8bit, but do not declare " .
710 "a Content-Transfer-Encoding.\n";
711 foreach my $f (sort keys %broken_encoding) {
712 print " $f\n";
713 }
714 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
715 default => "UTF-8");
716}
717
a03bc5b6
TR
718if (!$force) {
719 for my $f (@files) {
720 if (get_patch_subject($f) =~ /\*\*\* SUBJECT HERE \*\*\*/) {
721 die "Refusing to send because the patch\n\t$f\n"
722 . "has the template subject '*** SUBJECT HERE ***'. "
723 . "Pass --force if you really want to send.\n";
724 }
725 }
726}
727
1f038a0c 728my $prompting = 0;
94638f89 729if (!defined $sender) {
ad79c024 730 $sender = $repoauthor || $repocommitter || '';
6e182518
JS
731 $sender = ask("Who should the emails appear to be from? [$sender] ",
732 default => $sender);
94638f89 733 print "Emails will be sent from: ", $sender, "\n";
1f038a0c 734 $prompting++;
83b24437
RA
735}
736
6e74e075 737if (!@to && !defined $to_cmd) {
6e182518
JS
738 my $to = ask("Who should the emails be sent to? ");
739 push @to, parse_address_line($to) if defined $to; # sanitized/validated later
1f038a0c 740 $prompting++;
83b24437
RA
741}
742
994d6c66 743sub expand_aliases {
302e04ea
JK
744 return map { expand_one_alias($_) } @_;
745}
746
747my %EXPANDED_ALIASES;
748sub expand_one_alias {
749 my $alias = shift;
750 if ($EXPANDED_ALIASES{$alias}) {
751 die "fatal: alias '$alias' expands to itself\n";
752 }
753 local $EXPANDED_ALIASES{$alias} = 1;
754 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
994d6c66
EW
755}
756
757@to = expand_aliases(@to);
5b56aaa2 758@to = (map { sanitize_address($_) } @to);
994d6c66 759@initial_cc = expand_aliases(@initial_cc);
58063245 760@bcclist = expand_aliases(@bcclist);
994d6c66 761
5483c71d 762if ($thread && !defined $initial_reply_to && $prompting) {
6e182518
JS
763 $initial_reply_to = ask(
764 "Message-ID to be used as In-Reply-To for the first email? ");
83b24437 765}
1ca3d6ed 766if (defined $initial_reply_to) {
0fb7fc75
JS
767 $initial_reply_to =~ s/^\s*<?//;
768 $initial_reply_to =~ s/>?\s*$//;
769 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
ace9c2a9 770}
ace72086 771
34cc60ce 772if (!defined $smtp_server) {
aca7ad76
EW
773 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
774 if (-x $_) {
775 $smtp_server = $_;
776 last;
777 }
778 }
779 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
3342d850
RA
780}
781
c1f2aa45
JS
782if ($compose && $compose > 0) {
783 @files = ($compose_filename . ".final", @files);
1f038a0c
RA
784}
785
83b24437 786# Variables we set as part of the loop over files
c1f2aa45 787our ($message_id, %mail, $subject, $reply_to, $references, $message,
dc1460aa 788 $needs_confirm, $message_num, $ask_default);
83b24437 789
567ffeb7
EW
790sub extract_valid_address {
791 my $address = shift;
ad9c18f5 792 my $local_part_regexp = '[^<>"\s@]+';
09302e17 793 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
db3106b2
EW
794
795 # check for a local address:
ad9c18f5 796 return $address if ($address =~ /^($local_part_regexp)$/);
db3106b2 797
155197e6 798 $address =~ s/^\s*<(.*)>\s*$/$1/;
567ffeb7 799 if ($have_email_valid) {
ad9c18f5 800 return scalar Email::Valid->address($address);
567ffeb7
EW
801 } else {
802 # less robust/correct than the monster regexp in Email::Valid,
803 # but still does a 99% job, and one less dependency
ad9c18f5 804 $address =~ /($local_part_regexp\@$domain_regexp)/;
e96fd305 805 return $1;
567ffeb7
EW
806 }
807}
83b24437
RA
808
809# Usually don't need to change anything below here.
810
811# we make a "fake" message id by taking the current number
812# of seconds since the beginning of Unix time and tacking on
813# a random number to the end, in case we are called quicker than
814# 1 second since the last time we were called.
8037d1a3
RA
815
816# We'll setup a template for the message id, using the "from" address:
8037d1a3 817
be510cfe 818my ($message_id_stamp, $message_id_serial);
68ce9330 819sub make_message_id {
be510cfe
JH
820 my $uniq;
821 if (!defined $message_id_stamp) {
822 $message_id_stamp = sprintf("%s-%s", time, $$);
823 $message_id_serial = 0;
824 }
825 $message_id_serial++;
826 $uniq = "$message_id_stamp-$message_id_serial";
827
aeb59328 828 my $du_part;
94638f89
UKK
829 for ($sender, $repocommitter, $repoauthor) {
830 $du_part = extract_valid_address(sanitize_address($_));
831 last if (defined $du_part and $du_part ne '');
aeb59328 832 }
94638f89 833 if (not defined $du_part or $du_part eq '') {
aeb59328
JH
834 use Sys::Hostname qw();
835 $du_part = 'user@' . Sys::Hostname::hostname();
836 }
be510cfe
JH
837 my $message_id_template = "<%s-git-send-email-%s>";
838 $message_id = sprintf($message_id_template, $uniq, $du_part);
8037d1a3 839 #print "new message id = $message_id\n"; # Was useful for debugging
83b24437
RA
840}
841
842
843
a5370b16 844$time = time - scalar $#files;
83b24437 845
374c5905
JR
846sub unquote_rfc2047 {
847 local ($_) = @_;
8291db6f
JK
848 my $encoding;
849 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
850 $encoding = $1;
374c5905
JR
851 s/_/ /g;
852 s/=([0-9A-F]{2})/chr(hex($1))/eg;
853 }
8291db6f 854 return wantarray ? ($_, $encoding) : $_;
374c5905
JR
855}
856
d54eaaa2
JK
857sub quote_rfc2047 {
858 local $_ = shift;
d1fff6fc 859 my $encoding = shift || 'UTF-8';
d54eaaa2
JK
860 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
861 s/(.*)/=\?$encoding\?q\?$1\?=/;
862 return $_;
863}
864
a3a8262b
BC
865sub is_rfc2047_quoted {
866 my $s = shift;
867 my $token = '[^][()<>@,;:"\/?.= \000-\037\177-\377]+';
868 my $encoded_text = '[!->@-~]+';
869 length($s) <= 75 &&
870 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
871}
872
5b56aaa2 873# use the simplest quoting being able to handle the recipient
68ce9330 874sub sanitize_address {
732263d4 875 my ($recipient) = @_;
5b56aaa2
UKK
876 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
877
878 if (not $recipient_name) {
879 return "$recipient";
880 }
881
882 # if recipient_name is already quoted, do nothing
a3a8262b 883 if (is_rfc2047_quoted($recipient_name)) {
5b56aaa2
UKK
884 return $recipient;
885 }
886
887 # rfc2047 is needed if a non-ascii char is included
888 if ($recipient_name =~ /[^[:ascii:]]/) {
a61c0ffa 889 $recipient_name =~ s/^"(.*)"$/$1/;
d54eaaa2 890 $recipient_name = quote_rfc2047($recipient_name);
732263d4 891 }
5b56aaa2
UKK
892
893 # double quotes are needed if specials or CTLs are included
894 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
18023c20 895 $recipient_name =~ s/(["\\\r])/\\$1/g;
5b56aaa2
UKK
896 $recipient_name = "\"$recipient_name\"";
897 }
898
899 return "$recipient_name $recipient_addr";
900
732263d4
RJ
901}
902
134550fe
JA
903# Returns the local Fully Qualified Domain Name (FQDN) if available.
904#
905# Tightly configured MTAa require that a caller sends a real DNS
906# domain name that corresponds the IP address in the HELO/EHLO
907# handshake. This is used to verify the connection and prevent
908# spammers from trying to hide their identity. If the DNS and IP don't
909# match, the receiveing MTA may deny the connection.
910#
911# Here is a deny example of Net::SMTP with the default "localhost.localdomain"
912#
913# Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
914# Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
915#
916# This maildomain*() code is based on ideas in Perl library Test::Reporter
917# /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
918
59a86303
BG
919sub valid_fqdn {
920 my $domain = shift;
61ef5e9b 921 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
59a86303
BG
922}
923
68ce9330 924sub maildomain_net {
134550fe
JA
925 my $maildomain;
926
927 if (eval { require Net::Domain; 1 }) {
928 my $domain = Net::Domain::domainname();
59a86303 929 $maildomain = $domain if valid_fqdn($domain);
134550fe
JA
930 }
931
932 return $maildomain;
933}
934
68ce9330 935sub maildomain_mta {
134550fe
JA
936 my $maildomain;
937
938 if (eval { require Net::SMTP; 1 }) {
939 for my $host (qw(mailhost localhost)) {
940 my $smtp = Net::SMTP->new($host);
941 if (defined $smtp) {
942 my $domain = $smtp->domain;
943 $smtp->quit;
944
59a86303 945 $maildomain = $domain if valid_fqdn($domain);
134550fe
JA
946
947 last if $maildomain;
948 }
949 }
950 }
951
952 return $maildomain;
953}
954
68ce9330 955sub maildomain {
69cf7bfd 956 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
134550fe
JA
957}
958
15da1084 959# Returns 1 if the message was sent, and 0 otherwise.
a1b5b371 960# In actuality, the whole program dies when there
15da1084
MW
961# is an error sending a message.
962
68ce9330 963sub send_message {
4bc87a28 964 my @recipients = unique_email_list(@to);
7ac17529
ABH
965 @cc = (grep { my $cc = extract_valid_address($_);
966 not grep { $cc eq $_ } @recipients
967 }
968 map { sanitize_address($_) }
969 @cc);
4bc87a28 970 my $to = join (",\n\t", @recipients);
58063245 971 @recipients = unique_email_list(@recipients,@cc,@bcclist);
c38f0247 972 @recipients = (map { extract_valid_address($_) } @recipients);
6bdca890 973 my $date = format_2822_time($time++);
e923effb
ML
974 my $gitversion = '@@GIT_VERSION@@';
975 if ($gitversion =~ m/..GIT_VERSION../) {
3cb8caf7 976 $gitversion = Git::version();
e923effb 977 }
4bc87a28 978
02461e0e 979 my $cc = join(",\n\t", unique_email_list(@cc));
f06a6a49
JH
980 my $ccline = "";
981 if ($cc ne '') {
982 $ccline = "\nCc: $cc";
983 }
94638f89 984 my $sanitized_sender = sanitize_address($sender);
4f3d3703 985 make_message_id() unless defined($message_id);
aeb59328 986
94638f89 987 my $header = "From: $sanitized_sender
f06a6a49 988To: $to${ccline}
4bc87a28 989Subject: $subject
4bc87a28
EW
990Date: $date
991Message-Id: $message_id
e923effb 992X-Mailer: git-send-email $gitversion
4bc87a28 993";
3e0c4ffd 994 if ($reply_to) {
7ccf7927
RA
995
996 $header .= "In-Reply-To: $reply_to\n";
997 $header .= "References: $references\n";
998 }
ce91c2f6
JH
999 if (@xh) {
1000 $header .= join("\n", @xh) . "\n";
1001 }
4bc87a28 1002
c38f0247 1003 my @sendmail_parameters = ('-i', @recipients);
94638f89 1004 my $raw_from = $sanitized_sender;
c89e3241
FC
1005 if (defined $envelope_sender && $envelope_sender ne "auto") {
1006 $raw_from = $envelope_sender;
1007 }
f073a592
RJ
1008 $raw_from = extract_valid_address($raw_from);
1009 unshift (@sendmail_parameters,
1010 '-f', $raw_from) if(defined $envelope_sender);
8e3d436b 1011
c1f2aa45
JS
1012 if ($needs_confirm && !$dry_run) {
1013 print "\n$header\n";
1014 if ($needs_confirm eq "inform") {
1015 $confirm_unconfigured = 0; # squelch this message for the rest of this run
6e182518 1016 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
c1f2aa45
JS
1017 print " The Cc list above has been expanded by additional\n";
1018 print " addresses found in the patch commit message. By default\n";
1019 print " send-email prompts before sending whenever this occurs.\n";
1020 print " This behavior is controlled by the sendemail.confirm\n";
1021 print " configuration setting.\n";
1022 print "\n";
1023 print " For additional information, run 'git send-email --help'.\n";
1024 print " To retain the current behavior, but squelch this message,\n";
1025 print " run 'git config --global sendemail.confirm auto'.\n\n";
1026 }
6e182518
JS
1027 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1028 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1029 default => $ask_default);
1030 die "Send this email reply required" unless defined $_;
c1f2aa45 1031 if (/^n/i) {
15da1084 1032 return 0;
c1f2aa45
JS
1033 } elsif (/^q/i) {
1034 cleanup_compose_files();
1035 exit(0);
1036 } elsif (/^a/i) {
1037 $confirm = 'never';
1038 }
1039 }
1040
052fbea2
PO
1041 unshift (@sendmail_parameters, @smtp_server_options);
1042
6130259c
MW
1043 if ($dry_run) {
1044 # We don't want to send the email.
1045 } elsif ($smtp_server =~ m#^/#) {
aca7ad76
EW
1046 my $pid = open my $sm, '|-';
1047 defined $pid or die $!;
1048 if (!$pid) {
8e3d436b 1049 exec($smtp_server, @sendmail_parameters) or die $!;
aca7ad76
EW
1050 }
1051 print $sm "$header\n$message";
1052 close $sm or die $?;
1053 } else {
44b2476a
JH
1054
1055 if (!defined $smtp_server) {
1056 die "The required SMTP server is not properly defined."
1057 }
1058
f6bebd12 1059 if ($smtp_encryption eq 'ssl') {
44b2476a 1060 $smtp_server_port ||= 465; # ssmtp
34cc60ce 1061 require Net::SMTP::SSL;
69cf7bfd 1062 $smtp_domain ||= maildomain();
134550fe 1063 $smtp ||= Net::SMTP::SSL->new($smtp_server,
69cf7bfd 1064 Hello => $smtp_domain,
134550fe 1065 Port => $smtp_server_port);
34cc60ce
DS
1066 }
1067 else {
1068 require Net::SMTP;
69cf7bfd 1069 $smtp_domain ||= maildomain();
44b2476a
JH
1070 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
1071 ? "$smtp_server:$smtp_server_port"
f60812ef 1072 : $smtp_server,
69cf7bfd 1073 Hello => $smtp_domain,
f60812ef 1074 Debug => $debug_net_smtp);
fb3650ed 1075 if ($smtp_encryption eq 'tls' && $smtp) {
f6bebd12
TR
1076 require Net::SMTP::SSL;
1077 $smtp->command('STARTTLS');
1078 $smtp->response();
1079 if ($smtp->code == 220) {
1080 $smtp = Net::SMTP::SSL->start_SSL($smtp)
1081 or die "STARTTLS failed! ".$smtp->message;
6cbf8b00 1082 $smtp_encryption = '';
9d1ccf5e
RS
1083 # Send EHLO again to receive fresh
1084 # supported commands
1085 $smtp->hello();
f6bebd12
TR
1086 } else {
1087 die "Server does not support STARTTLS! ".$smtp->message;
1088 }
1089 }
44b2476a
JH
1090 }
1091
1092 if (!$smtp) {
f60812ef 1093 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
e5afb3a6
JA
1094 "VALUES: server=$smtp_server ",
1095 "encryption=$smtp_encryption ",
69cf7bfd 1096 "hello=$smtp_domain",
e5afb3a6 1097 defined $smtp_server_port ? "port=$smtp_server_port" : "";
44b2476a
JH
1098 }
1099
2363d746
MW
1100 if (defined $smtp_authuser) {
1101
1102 if (!defined $smtp_authpass) {
1103
1104 system "stty -echo";
1105
1106 do {
1107 print "Password: ";
1108 $_ = <STDIN>;
1109 print "\n";
1110 } while (!defined $_);
1111
1112 chomp($smtp_authpass = $_);
1113
1114 system "stty echo";
1115 }
1116
5f5b6118 1117 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
34cc60ce 1118 }
2363d746 1119
2b69bfc2 1120 $smtp->mail( $raw_from ) or die $smtp->message;
aca7ad76
EW
1121 $smtp->to( @recipients ) or die $smtp->message;
1122 $smtp->data or die $smtp->message;
1123 $smtp->datasend("$header\n$message") or die $smtp->message;
1124 $smtp->dataend() or die $smtp->message;
15da1084 1125 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
aca7ad76 1126 }
2718435b 1127 if ($quiet) {
71c7da94 1128 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
2718435b 1129 } else {
b7f30e0a 1130 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
2b69bfc2 1131 if ($smtp_server !~ m#^/#) {
aca7ad76 1132 print "Server: $smtp_server\n";
2b69bfc2 1133 print "MAIL FROM:<$raw_from>\n";
02461e0e
JP
1134 foreach my $entry (@recipients) {
1135 print "RCPT TO:<$entry>\n";
1136 }
aca7ad76 1137 } else {
8e3d436b 1138 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
aca7ad76 1139 }
b7f30e0a 1140 print $header, "\n";
aca7ad76
EW
1141 if ($smtp) {
1142 print "Result: ", $smtp->code, ' ',
1143 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1144 } else {
1145 print "Result: OK\n";
1146 }
30d08b34 1147 }
15da1084
MW
1148
1149 return 1;
83b24437
RA
1150}
1151
83b24437 1152$reply_to = $initial_reply_to;
2186d566 1153$references = $initial_reply_to || '';
83b24437 1154$subject = $initial_subject;
c1f2aa45 1155$message_num = 0;
83b24437
RA
1156
1157foreach my $t (@files) {
83b24437
RA
1158 open(F,"<",$t) or die "can't open file $t";
1159
94638f89 1160 my $author = undef;
8291db6f
JK
1161 my $author_encoding;
1162 my $has_content_type;
1163 my $body_encoding;
c1f2aa45 1164 @cc = ();
ce91c2f6 1165 @xh = ();
e6b0964a 1166 my $input_format = undef;
5012699d 1167 my @header = ();
83b24437 1168 $message = "";
c1f2aa45 1169 $message_num++;
5012699d 1170 # First unfold multiline header fields
83b24437 1171 while(<F>) {
5012699d
JS
1172 last if /^\s*$/;
1173 if (/^\s+\S/ and @header) {
1174 chomp($header[$#header]);
1175 s/^\s+/ /;
1176 $header[$#header] .= $_;
1177 } else {
1178 push(@header, $_);
1179 }
1180 }
1181 # Now parse the header
1182 foreach(@header) {
1183 if (/^From /) {
1184 $input_format = 'mbox';
1185 next;
1186 }
1187 chomp;
1188 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1189 $input_format = 'mbox';
1190 }
1191
1192 if (defined $input_format && $input_format eq 'mbox') {
1193 if (/^Subject:\s+(.*)$/) {
1194 $subject = $1;
e6b0964a 1195 }
5012699d
JS
1196 elsif (/^From:\s+(.*)$/) {
1197 ($author, $author_encoding) = unquote_rfc2047($1);
1198 next if $suppress_cc{'author'};
1199 next if $suppress_cc{'self'} and $author eq $sender;
1200 printf("(mbox) Adding cc: %s from line '%s'\n",
1201 $1, $_) unless $quiet;
1202 push @cc, $1;
e6b0964a 1203 }
5012699d
JS
1204 elsif (/^Cc:\s+(.*)$/) {
1205 foreach my $addr (parse_address_line($1)) {
1206 if (unquote_rfc2047($addr) eq $sender) {
65648283 1207 next if ($suppress_cc{'self'});
65648283
DB
1208 } else {
1209 next if ($suppress_cc{'cc'});
8a8e6235 1210 }
83b24437 1211 printf("(mbox) Adding cc: %s from line '%s'\n",
5012699d
JS
1212 $addr, $_) unless $quiet;
1213 push @cc, $addr;
83b24437 1214 }
5012699d
JS
1215 }
1216 elsif (/^Content-type:/i) {
1217 $has_content_type = 1;
1218 if (/charset="?([^ "]+)/) {
1219 $body_encoding = $1;
83b24437 1220 }
5012699d 1221 push @xh, $_;
83b24437 1222 }
5012699d
JS
1223 elsif (/^Message-Id: (.*)/i) {
1224 $message_id = $1;
83b24437 1225 }
5012699d
JS
1226 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
1227 push @xh, $_;
1228 }
1229
83b24437 1230 } else {
5012699d
JS
1231 # In the traditional
1232 # "send lots of email" format,
1233 # line 1 = cc
1234 # line 2 = subject
1235 # So let's support that, too.
1236 $input_format = 'lots';
1237 if (@cc == 0 && !$suppress_cc{'cc'}) {
1238 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1239 $_, $_) unless $quiet;
1240 push @cc, $_;
1241 } elsif (!defined $subject) {
1242 $subject = $_;
83b24437
RA
1243 }
1244 }
1245 }
5012699d
JS
1246 # Now parse the message body
1247 while(<F>) {
1248 $message .= $_;
1249 if (/^(Signed-off-by|Cc): (.*)$/i) {
5012699d 1250 chomp;
3531e270 1251 my ($what, $c) = ($1, $2);
5012699d 1252 chomp $c;
3531e270
JS
1253 if ($c eq $sender) {
1254 next if ($suppress_cc{'self'});
1255 } else {
1256 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1257 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1258 }
5012699d 1259 push @cc, $c;
3531e270 1260 printf("(body) Adding cc: %s from line '%s'\n",
5012699d
JS
1261 $c, $_) unless $quiet;
1262 }
1263 }
83b24437 1264 close F;
324a8bd0 1265
6e74e075
JP
1266 push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1267 if defined $to_cmd;
1268 push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1269 if defined $cc_cmd && !$suppress_cc{'cccmd'};
324a8bd0 1270
3cae7e5b
TR
1271 if ($broken_encoding{$t} && !$has_content_type) {
1272 $has_content_type = 1;
1273 push @xh, "MIME-Version: 1.0",
1274 "Content-Type: text/plain; charset=$auto_8bit_encoding",
1275 "Content-Transfer-Encoding: 8bit";
1276 $body_encoding = $auto_8bit_encoding;
1277 }
1278
1279 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1280 $subject = quote_rfc2047($subject, $auto_8bit_encoding);
1281 }
1282
5012699d 1283 if (defined $author and $author ne $sender) {
94638f89 1284 $message = "From: $author\n\n$message";
8291db6f
JK
1285 if (defined $author_encoding) {
1286 if ($has_content_type) {
1287 if ($body_encoding eq $author_encoding) {
1288 # ok, we already have the right encoding
1289 }
1290 else {
1291 # uh oh, we should re-encode
1292 }
1293 }
1294 else {
3cae7e5b 1295 $has_content_type = 1;
8291db6f
JK
1296 push @xh,
1297 'MIME-Version: 1.0',
8641ee3d
JK
1298 "Content-Type: text/plain; charset=$author_encoding",
1299 'Content-Transfer-Encoding: 8bit';
8291db6f
JK
1300 }
1301 }
8a8e6235 1302 }
83b24437 1303
c1f2aa45
JS
1304 $needs_confirm = (
1305 $confirm eq "always" or
1306 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1307 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1308 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1309
1310 @cc = (@initial_cc, @cc);
1311
15da1084 1312 my $message_was_sent = send_message();
83b24437
RA
1313
1314 # set up for the next message
95a877a3 1315 if ($thread && $message_was_sent &&
528fb087 1316 (chain_reply_to() || !defined $reply_to || length($reply_to) == 0)) {
78488b2c 1317 $reply_to = $message_id;
7ccf7927 1318 if (length $references > 0) {
a925b89c 1319 $references .= "\n $message_id";
7ccf7927
RA
1320 } else {
1321 $references = "$message_id";
1322 }
78488b2c 1323 }
4f3d3703 1324 $message_id = undef;
83b24437 1325}
e205735d 1326
6e74e075
JP
1327# Execute a command (e.g. $to_cmd) to get a list of email addresses
1328# and return a results array
1329sub recipients_cmd {
1330 my ($prefix, $what, $cmd, $file) = @_;
1331
1332 my $sanitized_sender = sanitize_address($sender);
1333 my @addresses = ();
1334 open(F, "$cmd \Q$file\E |")
1335 or die "($prefix) Could not execute '$cmd'";
1336 while(<F>) {
1337 my $address = $_;
1338 $address =~ s/^\s*//g;
1339 $address =~ s/\s*$//g;
1340 $address = sanitize_address($address);
1341 next if ($address eq $sanitized_sender and $suppress_from);
1342 push @addresses, $address;
1343 printf("($prefix) Adding %s: %s from: '%s'\n",
1344 $what, $address, $cmd) unless $quiet;
1345 }
1346 close F
1347 or die "($prefix) failed to close pipe to '$cmd'";
1348 return @addresses;
1349}
1350
c1f2aa45 1351cleanup_compose_files();
1f038a0c
RA
1352
1353sub cleanup_compose_files() {
c1f2aa45 1354 unlink($compose_filename, $compose_filename . ".final") if $compose;
1f038a0c
RA
1355}
1356
4bc87a28 1357$smtp->quit if $smtp;
e205735d
RA
1358
1359sub unique_email_list(@) {
1360 my %seen;
1361 my @emails;
1362
1363 foreach my $entry (@_) {
db3106b2
EW
1364 if (my $clean = extract_valid_address($entry)) {
1365 $seen{$clean} ||= 0;
1366 next if $seen{$clean}++;
1367 push @emails, $entry;
1368 } else {
1369 print STDERR "W: unable to extract a valid address",
1370 " from: $entry\n";
1371 }
e205735d
RA
1372 }
1373 return @emails;
1374}
747bbff9
JK
1375
1376sub validate_patch {
1377 my $fn = shift;
1378 open(my $fh, '<', $fn)
1379 or die "unable to open $fn: $!\n";
1380 while (my $line = <$fh>) {
1381 if (length($line) > 998) {
1382 return "$.: patch contains a line longer than 998 characters";
1383 }
1384 }
1385 return undef;
1386}
0706bd19
JK
1387
1388sub file_has_nonascii {
1389 my $fn = shift;
1390 open(my $fh, '<', $fn)
1391 or die "unable to open $fn: $!\n";
1392 while (my $line = <$fh>) {
1393 return 1 if $line =~ /[^[:ascii:]]/;
1394 }
1395 return 0;
1396}
3cae7e5b
TR
1397
1398sub body_or_subject_has_nonascii {
1399 my $fn = shift;
1400 open(my $fh, '<', $fn)
1401 or die "unable to open $fn: $!\n";
1402 while (my $line = <$fh>) {
1403 last if $line =~ /^$/;
1404 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1405 }
1406 while (my $line = <$fh>) {
1407 return 1 if $line =~ /[^[:ascii:]]/;
1408 }
1409 return 0;
1410}