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