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