1#!/usr/bin/perl
2#
3# Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4# Copyright 2005 Ryan Anderson <ryan@michonline.com>
5#
6# GPL v2 (See COPYING)
7#
8# Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
9#
10# Sends a collection of emails to the given email addresses, disturbingly fast.
11#
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:
15# first line of the message is who to CC,
16# and second line is the subject of the message.
17#
18
19use 5.008;
20use strict;
21use warnings;
22use Term::ReadLine;
23use Getopt::Long;
24use Text::ParseWords;
25use Data::Dumper;
26use Term::ANSIColor;
27use File::Temp qw/ tempdir tempfile /;
28use File::Spec::Functions qw(catfile);
29use Error qw(:try);
30use Git;
31
32Getopt::Long::Configure qw/ pass_through /;
33
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
45
46sub usage {
47 print <<EOT;
48git send-email [options] <file | directory | rev-list options >
49
50 Composing:
51 --from <str> * Email From:
52 --[no-]to <str> * Email To:
53 --[no-]cc <str> * Email Cc:
54 --[no-]bcc <str> * Email Bcc:
55 --subject <str> * Email "Subject:"
56 --in-reply-to <str> * Email "In-Reply-To:"
57 --[no-]annotate * Review each patch that will be sent in an editor.
58 --compose * Open an editor for introduction.
59 --compose-encoding <str> * Encoding to assume for introduction.
60 --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
61 --transfer-encoding <str> * Transfer encoding to use (quoted-printable, 8bit, base64)
62
63 Sending:
64 --envelope-sender <str> * Email envelope sender.
65 --smtp-server <str:int> * Outgoing SMTP server to use. The port
66 is optional. Default 'localhost'.
67 --smtp-server-option <str> * Outgoing SMTP server option to use.
68 --smtp-server-port <int> * Outgoing SMTP server port.
69 --smtp-user <str> * Username for SMTP-AUTH.
70 --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
71 --smtp-encryption <str> * tls or ssl; anything else disables.
72 --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
73 --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
74 Pass an empty string to disable certificate
75 verification.
76 --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
77 --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
78
79 Automating:
80 --identity <str> * Use the sendemail.<id> options.
81 --to-cmd <str> * Email To: via `<str> \$patch_path`
82 --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
83 --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, all.
84 --[no-]cc-cover * Email Cc: addresses in the cover letter.
85 --[no-]to-cover * Email To: addresses in the cover letter.
86 --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
87 --[no-]suppress-from * Send to self. Default off.
88 --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
89 --[no-]thread * Use In-Reply-To: field. Default on.
90
91 Administering:
92 --confirm <str> * Confirm recipients before sending;
93 auto, cc, compose, always, or never.
94 --quiet * Output one line of info per email.
95 --dry-run * Don't actually send the emails.
96 --[no-]validate * Perform patch sanity checks. Default on.
97 --[no-]format-patch * understand any non optional arguments as
98 `git format-patch` ones.
99 --force * Send even if safety checks would prevent it.
100
101EOT
102 exit(1);
103}
104
105# most mail servers generate the Date: header, but not all...
106sub format_2822_time {
107 my ($time) = @_;
108 my @localtm = localtime($time);
109 my @gmttm = gmtime($time);
110 my $localmin = $localtm[1] + $localtm[2] * 60;
111 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
112 if ($localtm[0] != $gmttm[0]) {
113 die "local zone differs from GMT by a non-minute interval\n";
114 }
115 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
116 $localmin += 1440;
117 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
118 $localmin -= 1440;
119 } elsif ($gmttm[6] != $localtm[6]) {
120 die "local time offset greater than or equal to 24 hours\n";
121 }
122 my $offset = $localmin - $gmtmin;
123 my $offhour = $offset / 60;
124 my $offmin = abs($offset % 60);
125 if (abs($offhour) >= 24) {
126 die ("local time offset greater than or equal to 24 hours\n");
127 }
128
129 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
130 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
131 $localtm[3],
132 qw(Jan Feb Mar Apr May Jun
133 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
134 $localtm[5]+1900,
135 $localtm[2],
136 $localtm[1],
137 $localtm[0],
138 ($offset >= 0) ? '+' : '-',
139 abs($offhour),
140 $offmin,
141 );
142}
143
144my $have_email_valid = eval { require Email::Valid; 1 };
145my $have_mail_address = eval { require Mail::Address; 1 };
146my $smtp;
147my $auth;
148
149# Variables we fill in automatically, or via prompting:
150my (@to,$no_to,@initial_to,@cc,$no_cc,@initial_cc,@bcclist,$no_bcc,@xh,
151 $initial_reply_to,$initial_subject,@files,
152 $author,$sender,$smtp_authpass,$annotate,$compose,$time);
153
154my $envelope_sender;
155
156# Example reply to:
157#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
158
159my $repo = eval { Git->repository() };
160my @repo = $repo ? ($repo) : ();
161my $term = eval {
162 $ENV{"GIT_SEND_EMAIL_NOTTY"}
163 ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
164 : new Term::ReadLine 'git-send-email';
165};
166if ($@) {
167 $term = new FakeTerm "$@: going non-interactive";
168}
169
170# Behavior modification variables
171my ($quiet, $dry_run) = (0, 0);
172my $format_patch;
173my $compose_filename;
174my $force = 0;
175
176# Handle interactive edition of files.
177my $multiedit;
178my $editor;
179
180sub do_edit {
181 if (!defined($editor)) {
182 $editor = Git::command_oneline('var', 'GIT_EDITOR');
183 }
184 if (defined($multiedit) && !$multiedit) {
185 map {
186 system('sh', '-c', $editor.' "$@"', $editor, $_);
187 if (($? & 127) || ($? >> 8)) {
188 die("the editor exited uncleanly, aborting everything");
189 }
190 } @_;
191 } else {
192 system('sh', '-c', $editor.' "$@"', $editor, @_);
193 if (($? & 127) || ($? >> 8)) {
194 die("the editor exited uncleanly, aborting everything");
195 }
196 }
197}
198
199# Variables with corresponding config settings
200my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc);
201my ($cover_cc, $cover_to);
202my ($to_cmd, $cc_cmd);
203my ($smtp_server, $smtp_server_port, @smtp_server_options);
204my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
205my ($identity, $aliasfiletype, @alias_files, $smtp_domain);
206my ($validate, $confirm);
207my (@suppress_cc);
208my ($auto_8bit_encoding);
209my ($compose_encoding);
210my ($target_xfer_encoding);
211
212my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
213
214my %config_bool_settings = (
215 "thread" => [\$thread, 1],
216 "chainreplyto" => [\$chain_reply_to, 0],
217 "suppressfrom" => [\$suppress_from, undef],
218 "signedoffbycc" => [\$signed_off_by_cc, undef],
219 "cccover" => [\$cover_cc, undef],
220 "tocover" => [\$cover_to, undef],
221 "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated
222 "validate" => [\$validate, 1],
223 "multiedit" => [\$multiedit, undef],
224 "annotate" => [\$annotate, undef]
225);
226
227my %config_settings = (
228 "smtpserver" => \$smtp_server,
229 "smtpserverport" => \$smtp_server_port,
230 "smtpserveroption" => \@smtp_server_options,
231 "smtpuser" => \$smtp_authuser,
232 "smtppass" => \$smtp_authpass,
233 "smtpsslcertpath" => \$smtp_ssl_cert_path,
234 "smtpdomain" => \$smtp_domain,
235 "to" => \@initial_to,
236 "tocmd" => \$to_cmd,
237 "cc" => \@initial_cc,
238 "cccmd" => \$cc_cmd,
239 "aliasfiletype" => \$aliasfiletype,
240 "bcc" => \@bcclist,
241 "suppresscc" => \@suppress_cc,
242 "envelopesender" => \$envelope_sender,
243 "confirm" => \$confirm,
244 "from" => \$sender,
245 "assume8bitencoding" => \$auto_8bit_encoding,
246 "composeencoding" => \$compose_encoding,
247 "transferencoding" => \$target_xfer_encoding,
248);
249
250my %config_path_settings = (
251 "aliasesfile" => \@alias_files,
252);
253
254# Handle Uncouth Termination
255sub signal_handler {
256
257 # Make text normal
258 print color("reset"), "\n";
259
260 # SMTP password masked
261 system "stty echo";
262
263 # tmp files from --compose
264 if (defined $compose_filename) {
265 if (-e $compose_filename) {
266 print "'$compose_filename' contains an intermediate version of the email you were composing.\n";
267 }
268 if (-e ($compose_filename . ".final")) {
269 print "'$compose_filename.final' contains the composed email.\n"
270 }
271 }
272
273 exit;
274};
275
276$SIG{TERM} = \&signal_handler;
277$SIG{INT} = \&signal_handler;
278
279# Begin by accumulating all the variables (defined above), that we will end up
280# needing, first, from the command line:
281
282my $help;
283my $rc = GetOptions("h" => \$help,
284 "sender|from=s" => \$sender,
285 "in-reply-to=s" => \$initial_reply_to,
286 "subject=s" => \$initial_subject,
287 "to=s" => \@initial_to,
288 "to-cmd=s" => \$to_cmd,
289 "no-to" => \$no_to,
290 "cc=s" => \@initial_cc,
291 "no-cc" => \$no_cc,
292 "bcc=s" => \@bcclist,
293 "no-bcc" => \$no_bcc,
294 "chain-reply-to!" => \$chain_reply_to,
295 "smtp-server=s" => \$smtp_server,
296 "smtp-server-option=s" => \@smtp_server_options,
297 "smtp-server-port=s" => \$smtp_server_port,
298 "smtp-user=s" => \$smtp_authuser,
299 "smtp-pass:s" => \$smtp_authpass,
300 "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
301 "smtp-encryption=s" => \$smtp_encryption,
302 "smtp-ssl-cert-path=s" => \$smtp_ssl_cert_path,
303 "smtp-debug:i" => \$debug_net_smtp,
304 "smtp-domain:s" => \$smtp_domain,
305 "identity=s" => \$identity,
306 "annotate!" => \$annotate,
307 "compose" => \$compose,
308 "quiet" => \$quiet,
309 "cc-cmd=s" => \$cc_cmd,
310 "suppress-from!" => \$suppress_from,
311 "suppress-cc=s" => \@suppress_cc,
312 "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
313 "cc-cover|cc-cover!" => \$cover_cc,
314 "to-cover|to-cover!" => \$cover_to,
315 "confirm=s" => \$confirm,
316 "dry-run" => \$dry_run,
317 "envelope-sender=s" => \$envelope_sender,
318 "thread!" => \$thread,
319 "validate!" => \$validate,
320 "transfer-encoding=s" => \$target_xfer_encoding,
321 "format-patch!" => \$format_patch,
322 "8bit-encoding=s" => \$auto_8bit_encoding,
323 "compose-encoding=s" => \$compose_encoding,
324 "force" => \$force,
325 );
326
327usage() if $help;
328unless ($rc) {
329 usage();
330}
331
332die "Cannot run git format-patch from outside a repository\n"
333 if $format_patch and not $repo;
334
335# Now, let's fill any that aren't set in with defaults:
336
337sub read_config {
338 my ($prefix) = @_;
339
340 foreach my $setting (keys %config_bool_settings) {
341 my $target = $config_bool_settings{$setting}->[0];
342 $$target = Git::config_bool(@repo, "$prefix.$setting") unless (defined $$target);
343 }
344
345 foreach my $setting (keys %config_path_settings) {
346 my $target = $config_path_settings{$setting};
347 if (ref($target) eq "ARRAY") {
348 unless (@$target) {
349 my @values = Git::config_path(@repo, "$prefix.$setting");
350 @$target = @values if (@values && defined $values[0]);
351 }
352 }
353 else {
354 $$target = Git::config_path(@repo, "$prefix.$setting") unless (defined $$target);
355 }
356 }
357
358 foreach my $setting (keys %config_settings) {
359 my $target = $config_settings{$setting};
360 next if $setting eq "to" and defined $no_to;
361 next if $setting eq "cc" and defined $no_cc;
362 next if $setting eq "bcc" and defined $no_bcc;
363 if (ref($target) eq "ARRAY") {
364 unless (@$target) {
365 my @values = Git::config(@repo, "$prefix.$setting");
366 @$target = @values if (@values && defined $values[0]);
367 }
368 }
369 else {
370 $$target = Git::config(@repo, "$prefix.$setting") unless (defined $$target);
371 }
372 }
373
374 if (!defined $smtp_encryption) {
375 my $enc = Git::config(@repo, "$prefix.smtpencryption");
376 if (defined $enc) {
377 $smtp_encryption = $enc;
378 } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
379 $smtp_encryption = 'ssl';
380 }
381 }
382}
383
384# read configuration from [sendemail "$identity"], fall back on [sendemail]
385$identity = Git::config(@repo, "sendemail.identity") unless (defined $identity);
386read_config("sendemail.$identity") if (defined $identity);
387read_config("sendemail");
388
389# fall back on builtin bool defaults
390foreach my $setting (values %config_bool_settings) {
391 ${$setting->[0]} = $setting->[1] unless (defined (${$setting->[0]}));
392}
393
394# 'default' encryption is none -- this only prevents a warning
395$smtp_encryption = '' unless (defined $smtp_encryption);
396
397# Set CC suppressions
398my(%suppress_cc);
399if (@suppress_cc) {
400 foreach my $entry (@suppress_cc) {
401 die "Unknown --suppress-cc field: '$entry'\n"
402 unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc)$/;
403 $suppress_cc{$entry} = 1;
404 }
405}
406
407if ($suppress_cc{'all'}) {
408 foreach my $entry (qw (cccmd cc author self sob body bodycc)) {
409 $suppress_cc{$entry} = 1;
410 }
411 delete $suppress_cc{'all'};
412}
413
414# If explicit old-style ones are specified, they trump --suppress-cc.
415$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
416$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
417
418if ($suppress_cc{'body'}) {
419 foreach my $entry (qw (sob bodycc)) {
420 $suppress_cc{$entry} = 1;
421 }
422 delete $suppress_cc{'body'};
423}
424
425# Set confirm's default value
426my $confirm_unconfigured = !defined $confirm;
427if ($confirm_unconfigured) {
428 $confirm = scalar %suppress_cc ? 'compose' : 'auto';
429};
430die "Unknown --confirm setting: '$confirm'\n"
431 unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
432
433# Debugging, print out the suppressions.
434if (0) {
435 print "suppressions:\n";
436 foreach my $entry (keys %suppress_cc) {
437 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
438 }
439}
440
441my ($repoauthor, $repocommitter);
442($repoauthor) = Git::ident_person(@repo, 'author');
443($repocommitter) = Git::ident_person(@repo, 'committer');
444
445# Verify the user input
446
447foreach my $entry (@initial_to) {
448 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
449}
450
451foreach my $entry (@initial_cc) {
452 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
453}
454
455foreach my $entry (@bcclist) {
456 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
457}
458
459sub parse_address_line {
460 if ($have_mail_address) {
461 return map { $_->format } Mail::Address->parse($_[0]);
462 } else {
463 return split_addrs($_[0]);
464 }
465}
466
467sub split_addrs {
468 return quotewords('\s*,\s*', 1, @_);
469}
470
471my %aliases;
472my %parse_alias = (
473 # multiline formats can be supported in the future
474 mutt => sub { my $fh = shift; while (<$fh>) {
475 if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
476 my ($alias, $addr) = ($1, $2);
477 $addr =~ s/#.*$//; # mutt allows # comments
478 # commas delimit multiple addresses
479 $aliases{$alias} = [ split_addrs($addr) ];
480 }}},
481 mailrc => sub { my $fh = shift; while (<$fh>) {
482 if (/^alias\s+(\S+)\s+(.*)$/) {
483 # spaces delimit multiple addresses
484 $aliases{$1} = [ quotewords('\s+', 0, $2) ];
485 }}},
486 pine => sub { my $fh = shift; my $f='\t[^\t]*';
487 for (my $x = ''; defined($x); $x = $_) {
488 chomp $x;
489 $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
490 $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
491 $aliases{$1} = [ split_addrs($2) ];
492 }},
493 elm => sub { my $fh = shift;
494 while (<$fh>) {
495 if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
496 my ($alias, $addr) = ($1, $2);
497 $aliases{$alias} = [ split_addrs($addr) ];
498 }
499 } },
500
501 gnus => sub { my $fh = shift; while (<$fh>) {
502 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
503 $aliases{$1} = [ $2 ];
504 }}}
505);
506
507if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
508 foreach my $file (@alias_files) {
509 open my $fh, '<', $file or die "opening $file: $!\n";
510 $parse_alias{$aliasfiletype}->($fh);
511 close $fh;
512 }
513}
514
515($sender) = expand_aliases($sender) if defined $sender;
516
517# is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
518# $f is a revision list specification to be passed to format-patch.
519sub is_format_patch_arg {
520 return unless $repo;
521 my $f = shift;
522 try {
523 $repo->command('rev-parse', '--verify', '--quiet', $f);
524 if (defined($format_patch)) {
525 return $format_patch;
526 }
527 die(<<EOF);
528File '$f' exists but it could also be the range of commits
529to produce patches for. Please disambiguate by...
530
531 * Saying "./$f" if you mean a file; or
532 * Giving --format-patch option if you mean a range.
533EOF
534 } catch Git::Error::Command with {
535 # Not a valid revision. Treat it as a filename.
536 return 0;
537 }
538}
539
540# Now that all the defaults are set, process the rest of the command line
541# arguments and collect up the files that need to be processed.
542my @rev_list_opts;
543while (defined(my $f = shift @ARGV)) {
544 if ($f eq "--") {
545 push @rev_list_opts, "--", @ARGV;
546 @ARGV = ();
547 } elsif (-d $f and !is_format_patch_arg($f)) {
548 opendir my $dh, $f
549 or die "Failed to opendir $f: $!";
550
551 push @files, grep { -f $_ } map { catfile($f, $_) }
552 sort readdir $dh;
553 closedir $dh;
554 } elsif ((-f $f or -p $f) and !is_format_patch_arg($f)) {
555 push @files, $f;
556 } else {
557 push @rev_list_opts, $f;
558 }
559}
560
561if (@rev_list_opts) {
562 die "Cannot run git format-patch from outside a repository\n"
563 unless $repo;
564 push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
565}
566
567if ($validate) {
568 foreach my $f (@files) {
569 unless (-p $f) {
570 my $error = validate_patch($f);
571 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
572 }
573 }
574}
575
576if (@files) {
577 unless ($quiet) {
578 print $_,"\n" for (@files);
579 }
580} else {
581 print STDERR "\nNo patch files specified!\n\n";
582 usage();
583}
584
585sub get_patch_subject {
586 my $fn = shift;
587 open (my $fh, '<', $fn);
588 while (my $line = <$fh>) {
589 next unless ($line =~ /^Subject: (.*)$/);
590 close $fh;
591 return "GIT: $1\n";
592 }
593 close $fh;
594 die "No subject line in $fn ?";
595}
596
597if ($compose) {
598 # Note that this does not need to be secure, but we will make a small
599 # effort to have it be unique
600 $compose_filename = ($repo ?
601 tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
602 tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
603 open my $c, ">", $compose_filename
604 or die "Failed to open for writing $compose_filename: $!";
605
606
607 my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
608 my $tpl_subject = $initial_subject || '';
609 my $tpl_reply_to = $initial_reply_to || '';
610
611 print $c <<EOT;
612From $tpl_sender # This line is ignored.
613GIT: Lines beginning in "GIT:" will be removed.
614GIT: Consider including an overall diffstat or table of contents
615GIT: for the patch you are writing.
616GIT:
617GIT: Clear the body content if you don't wish to send a summary.
618From: $tpl_sender
619Subject: $tpl_subject
620In-Reply-To: $tpl_reply_to
621
622EOT
623 for my $f (@files) {
624 print $c get_patch_subject($f);
625 }
626 close $c;
627
628 if ($annotate) {
629 do_edit($compose_filename, @files);
630 } else {
631 do_edit($compose_filename);
632 }
633
634 open my $c2, ">", $compose_filename . ".final"
635 or die "Failed to open $compose_filename.final : " . $!;
636
637 open $c, "<", $compose_filename
638 or die "Failed to open $compose_filename : " . $!;
639
640 my $need_8bit_cte = file_has_nonascii($compose_filename);
641 my $in_body = 0;
642 my $summary_empty = 1;
643 if (!defined $compose_encoding) {
644 $compose_encoding = "UTF-8";
645 }
646 while(<$c>) {
647 next if m/^GIT:/;
648 if ($in_body) {
649 $summary_empty = 0 unless (/^\n$/);
650 } elsif (/^\n$/) {
651 $in_body = 1;
652 if ($need_8bit_cte) {
653 print $c2 "MIME-Version: 1.0\n",
654 "Content-Type: text/plain; ",
655 "charset=$compose_encoding\n",
656 "Content-Transfer-Encoding: 8bit\n";
657 }
658 } elsif (/^MIME-Version:/i) {
659 $need_8bit_cte = 0;
660 } elsif (/^Subject:\s*(.+)\s*$/i) {
661 $initial_subject = $1;
662 my $subject = $initial_subject;
663 $_ = "Subject: " .
664 quote_subject($subject, $compose_encoding) .
665 "\n";
666 } elsif (/^In-Reply-To:\s*(.+)\s*$/i) {
667 $initial_reply_to = $1;
668 next;
669 } elsif (/^From:\s*(.+)\s*$/i) {
670 $sender = $1;
671 next;
672 } elsif (/^(?:To|Cc|Bcc):/i) {
673 print "To/Cc/Bcc fields are not interpreted yet, they have been ignored\n";
674 next;
675 }
676 print $c2 $_;
677 }
678 close $c;
679 close $c2;
680
681 if ($summary_empty) {
682 print "Summary email is empty, skipping it\n";
683 $compose = -1;
684 }
685} elsif ($annotate) {
686 do_edit(@files);
687}
688
689sub ask {
690 my ($prompt, %arg) = @_;
691 my $valid_re = $arg{valid_re};
692 my $default = $arg{default};
693 my $confirm_only = $arg{confirm_only};
694 my $resp;
695 my $i = 0;
696 return defined $default ? $default : undef
697 unless defined $term->IN and defined fileno($term->IN) and
698 defined $term->OUT and defined fileno($term->OUT);
699 while ($i++ < 10) {
700 $resp = $term->readline($prompt);
701 if (!defined $resp) { # EOF
702 print "\n";
703 return defined $default ? $default : undef;
704 }
705 if ($resp eq '' and defined $default) {
706 return $default;
707 }
708 if (!defined $valid_re or $resp =~ /$valid_re/) {
709 return $resp;
710 }
711 if ($confirm_only) {
712 my $yesno = $term->readline("Are you sure you want to use <$resp> [y/N]? ");
713 if (defined $yesno && $yesno =~ /y/i) {
714 return $resp;
715 }
716 }
717 }
718 return;
719}
720
721my %broken_encoding;
722
723sub file_declares_8bit_cte {
724 my $fn = shift;
725 open (my $fh, '<', $fn);
726 while (my $line = <$fh>) {
727 last if ($line =~ /^$/);
728 return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
729 }
730 close $fh;
731 return 0;
732}
733
734foreach my $f (@files) {
735 next unless (body_or_subject_has_nonascii($f)
736 && !file_declares_8bit_cte($f));
737 $broken_encoding{$f} = 1;
738}
739
740if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
741 print "The following files are 8bit, but do not declare " .
742 "a Content-Transfer-Encoding.\n";
743 foreach my $f (sort keys %broken_encoding) {
744 print " $f\n";
745 }
746 $auto_8bit_encoding = ask("Which 8bit encoding should I declare [UTF-8]? ",
747 default => "UTF-8");
748}
749
750if (!$force) {
751 for my $f (@files) {
752 if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
753 die "Refusing to send because the patch\n\t$f\n"
754 . "has the template subject '*** SUBJECT HERE ***'. "
755 . "Pass --force if you really want to send.\n";
756 }
757 }
758}
759
760if (!defined $sender) {
761 $sender = $repoauthor || $repocommitter || '';
762}
763
764# $sender could be an already sanitized address
765# (e.g. sendemail.from could be manually sanitized by user).
766# But it's a no-op to run sanitize_address on an already sanitized address.
767$sender = sanitize_address($sender);
768
769my $prompting = 0;
770if (!@initial_to && !defined $to_cmd) {
771 my $to = ask("Who should the emails be sent to (if any)? ",
772 default => "",
773 valid_re => qr/\@.*\./, confirm_only => 1);
774 push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
775 $prompting++;
776}
777
778sub expand_aliases {
779 return map { expand_one_alias($_) } @_;
780}
781
782my %EXPANDED_ALIASES;
783sub expand_one_alias {
784 my $alias = shift;
785 if ($EXPANDED_ALIASES{$alias}) {
786 die "fatal: alias '$alias' expands to itself\n";
787 }
788 local $EXPANDED_ALIASES{$alias} = 1;
789 return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
790}
791
792@initial_to = expand_aliases(@initial_to);
793@initial_to = validate_address_list(sanitize_address_list(@initial_to));
794@initial_cc = expand_aliases(@initial_cc);
795@initial_cc = validate_address_list(sanitize_address_list(@initial_cc));
796@bcclist = expand_aliases(@bcclist);
797@bcclist = validate_address_list(sanitize_address_list(@bcclist));
798
799if ($thread && !defined $initial_reply_to && $prompting) {
800 $initial_reply_to = ask(
801 "Message-ID to be used as In-Reply-To for the first email (if any)? ",
802 default => "",
803 valid_re => qr/\@.*\./, confirm_only => 1);
804}
805if (defined $initial_reply_to) {
806 $initial_reply_to =~ s/^\s*<?//;
807 $initial_reply_to =~ s/>?\s*$//;
808 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
809}
810
811if (!defined $smtp_server) {
812 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
813 if (-x $_) {
814 $smtp_server = $_;
815 last;
816 }
817 }
818 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
819}
820
821if ($compose && $compose > 0) {
822 @files = ($compose_filename . ".final", @files);
823}
824
825# Variables we set as part of the loop over files
826our ($message_id, %mail, $subject, $reply_to, $references, $message,
827 $needs_confirm, $message_num, $ask_default);
828
829sub extract_valid_address {
830 my $address = shift;
831 my $local_part_regexp = qr/[^<>"\s@]+/;
832 my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
833
834 # check for a local address:
835 return $address if ($address =~ /^($local_part_regexp)$/);
836
837 $address =~ s/^\s*<(.*)>\s*$/$1/;
838 if ($have_email_valid) {
839 return scalar Email::Valid->address($address);
840 }
841
842 # less robust/correct than the monster regexp in Email::Valid,
843 # but still does a 99% job, and one less dependency
844 return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
845 return;
846}
847
848sub extract_valid_address_or_die {
849 my $address = shift;
850 $address = extract_valid_address($address);
851 die "error: unable to extract a valid address from: $address\n"
852 if !$address;
853 return $address;
854}
855
856sub validate_address {
857 my $address = shift;
858 while (!extract_valid_address($address)) {
859 print STDERR "error: unable to extract a valid address from: $address\n";
860 $_ = ask("What to do with this address? ([q]uit|[d]rop|[e]dit): ",
861 valid_re => qr/^(?:quit|q|drop|d|edit|e)/i,
862 default => 'q');
863 if (/^d/i) {
864 return undef;
865 } elsif (/^q/i) {
866 cleanup_compose_files();
867 exit(0);
868 }
869 $address = ask("Who should the email be sent to (if any)? ",
870 default => "",
871 valid_re => qr/\@.*\./, confirm_only => 1);
872 }
873 return $address;
874}
875
876sub validate_address_list {
877 return (grep { defined $_ }
878 map { validate_address($_) } @_);
879}
880
881# Usually don't need to change anything below here.
882
883# we make a "fake" message id by taking the current number
884# of seconds since the beginning of Unix time and tacking on
885# a random number to the end, in case we are called quicker than
886# 1 second since the last time we were called.
887
888# We'll setup a template for the message id, using the "from" address:
889
890my ($message_id_stamp, $message_id_serial);
891sub make_message_id {
892 my $uniq;
893 if (!defined $message_id_stamp) {
894 $message_id_stamp = sprintf("%s-%s", time, $$);
895 $message_id_serial = 0;
896 }
897 $message_id_serial++;
898 $uniq = "$message_id_stamp-$message_id_serial";
899
900 my $du_part;
901 for ($sender, $repocommitter, $repoauthor) {
902 $du_part = extract_valid_address(sanitize_address($_));
903 last if (defined $du_part and $du_part ne '');
904 }
905 if (not defined $du_part or $du_part eq '') {
906 require Sys::Hostname;
907 $du_part = 'user@' . Sys::Hostname::hostname();
908 }
909 my $message_id_template = "<%s-git-send-email-%s>";
910 $message_id = sprintf($message_id_template, $uniq, $du_part);
911 #print "new message id = $message_id\n"; # Was useful for debugging
912}
913
914
915
916$time = time - scalar $#files;
917
918sub unquote_rfc2047 {
919 local ($_) = @_;
920 my $encoding;
921 s{=\?([^?]+)\?q\?(.*?)\?=}{
922 $encoding = $1;
923 my $e = $2;
924 $e =~ s/_/ /g;
925 $e =~ s/=([0-9A-F]{2})/chr(hex($1))/eg;
926 $e;
927 }eg;
928 return wantarray ? ($_, $encoding) : $_;
929}
930
931sub quote_rfc2047 {
932 local $_ = shift;
933 my $encoding = shift || 'UTF-8';
934 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
935 s/(.*)/=\?$encoding\?q\?$1\?=/;
936 return $_;
937}
938
939sub is_rfc2047_quoted {
940 my $s = shift;
941 my $token = qr/[^][()<>@,;:"\/?.= \000-\037\177-\377]+/;
942 my $encoded_text = qr/[!->@-~]+/;
943 length($s) <= 75 &&
944 $s =~ m/^(?:"[[:ascii:]]*"|=\?$token\?$token\?$encoded_text\?=)$/o;
945}
946
947sub subject_needs_rfc2047_quoting {
948 my $s = shift;
949
950 return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
951}
952
953sub quote_subject {
954 local $subject = shift;
955 my $encoding = shift || 'UTF-8';
956
957 if (subject_needs_rfc2047_quoting($subject)) {
958 return quote_rfc2047($subject, $encoding);
959 }
960 return $subject;
961}
962
963# use the simplest quoting being able to handle the recipient
964sub sanitize_address {
965 my ($recipient) = @_;
966
967 # remove garbage after email address
968 $recipient =~ s/(.*>).*$/$1/;
969
970 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
971
972 if (not $recipient_name) {
973 return $recipient;
974 }
975
976 # if recipient_name is already quoted, do nothing
977 if (is_rfc2047_quoted($recipient_name)) {
978 return $recipient;
979 }
980
981 # rfc2047 is needed if a non-ascii char is included
982 if ($recipient_name =~ /[^[:ascii:]]/) {
983 $recipient_name =~ s/^"(.*)"$/$1/;
984 $recipient_name = quote_rfc2047($recipient_name);
985 }
986
987 # double quotes are needed if specials or CTLs are included
988 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
989 $recipient_name =~ s/(["\\\r])/\\$1/g;
990 $recipient_name = qq["$recipient_name"];
991 }
992
993 return "$recipient_name $recipient_addr";
994
995}
996
997sub sanitize_address_list {
998 return (map { sanitize_address($_) } @_);
999}
1000
1001# Returns the local Fully Qualified Domain Name (FQDN) if available.
1002#
1003# Tightly configured MTAa require that a caller sends a real DNS
1004# domain name that corresponds the IP address in the HELO/EHLO
1005# handshake. This is used to verify the connection and prevent
1006# spammers from trying to hide their identity. If the DNS and IP don't
1007# match, the receiveing MTA may deny the connection.
1008#
1009# Here is a deny example of Net::SMTP with the default "localhost.localdomain"
1010#
1011# Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
1012# Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
1013#
1014# This maildomain*() code is based on ideas in Perl library Test::Reporter
1015# /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
1016
1017sub valid_fqdn {
1018 my $domain = shift;
1019 return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
1020}
1021
1022sub maildomain_net {
1023 my $maildomain;
1024
1025 if (eval { require Net::Domain; 1 }) {
1026 my $domain = Net::Domain::domainname();
1027 $maildomain = $domain if valid_fqdn($domain);
1028 }
1029
1030 return $maildomain;
1031}
1032
1033sub maildomain_mta {
1034 my $maildomain;
1035
1036 if (eval { require Net::SMTP; 1 }) {
1037 for my $host (qw(mailhost localhost)) {
1038 my $smtp = Net::SMTP->new($host);
1039 if (defined $smtp) {
1040 my $domain = $smtp->domain;
1041 $smtp->quit;
1042
1043 $maildomain = $domain if valid_fqdn($domain);
1044
1045 last if $maildomain;
1046 }
1047 }
1048 }
1049
1050 return $maildomain;
1051}
1052
1053sub maildomain {
1054 return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
1055}
1056
1057sub smtp_host_string {
1058 if (defined $smtp_server_port) {
1059 return "$smtp_server:$smtp_server_port";
1060 } else {
1061 return $smtp_server;
1062 }
1063}
1064
1065# Returns 1 if authentication succeeded or was not necessary
1066# (smtp_user was not specified), and 0 otherwise.
1067
1068sub smtp_auth_maybe {
1069 if (!defined $smtp_authuser || $auth) {
1070 return 1;
1071 }
1072
1073 # Workaround AUTH PLAIN/LOGIN interaction defect
1074 # with Authen::SASL::Cyrus
1075 eval {
1076 require Authen::SASL;
1077 Authen::SASL->import(qw(Perl));
1078 };
1079
1080 # TODO: Authentication may fail not because credentials were
1081 # invalid but due to other reasons, in which we should not
1082 # reject credentials.
1083 $auth = Git::credential({
1084 'protocol' => 'smtp',
1085 'host' => smtp_host_string(),
1086 'username' => $smtp_authuser,
1087 # if there's no password, "git credential fill" will
1088 # give us one, otherwise it'll just pass this one.
1089 'password' => $smtp_authpass
1090 }, sub {
1091 my $cred = shift;
1092 return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
1093 });
1094
1095 return $auth;
1096}
1097
1098sub ssl_verify_params {
1099 eval {
1100 require IO::Socket::SSL;
1101 IO::Socket::SSL->import(qw/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
1102 };
1103 if ($@) {
1104 print STDERR "Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
1105 return;
1106 }
1107
1108 if (!defined $smtp_ssl_cert_path) {
1109 # use the OpenSSL defaults
1110 return (SSL_verify_mode => SSL_VERIFY_PEER());
1111 }
1112
1113 if ($smtp_ssl_cert_path eq "") {
1114 return (SSL_verify_mode => SSL_VERIFY_NONE());
1115 } elsif (-d $smtp_ssl_cert_path) {
1116 return (SSL_verify_mode => SSL_VERIFY_PEER(),
1117 SSL_ca_path => $smtp_ssl_cert_path);
1118 } elsif (-f $smtp_ssl_cert_path) {
1119 return (SSL_verify_mode => SSL_VERIFY_PEER(),
1120 SSL_ca_file => $smtp_ssl_cert_path);
1121 } else {
1122 print STDERR "Not using SSL_VERIFY_PEER because the CA path does not exist.\n";
1123 return (SSL_verify_mode => SSL_VERIFY_NONE());
1124 }
1125}
1126
1127sub file_name_is_absolute {
1128 my ($path) = @_;
1129
1130 # msys does not grok DOS drive-prefixes
1131 if ($^O eq 'msys') {
1132 return ($path =~ m#^/# || $path =~ m#^[a-zA-Z]\:#)
1133 }
1134
1135 require File::Spec::Functions;
1136 return File::Spec::Functions::file_name_is_absolute($path);
1137}
1138
1139# Returns 1 if the message was sent, and 0 otherwise.
1140# In actuality, the whole program dies when there
1141# is an error sending a message.
1142
1143sub send_message {
1144 my @recipients = unique_email_list(@to);
1145 @cc = (grep { my $cc = extract_valid_address_or_die($_);
1146 not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
1147 }
1148 @cc);
1149 my $to = join (",\n\t", @recipients);
1150 @recipients = unique_email_list(@recipients,@cc,@bcclist);
1151 @recipients = (map { extract_valid_address_or_die($_) } @recipients);
1152 my $date = format_2822_time($time++);
1153 my $gitversion = '@@GIT_VERSION@@';
1154 if ($gitversion =~ m/..GIT_VERSION../) {
1155 $gitversion = Git::version();
1156 }
1157
1158 my $cc = join(",\n\t", unique_email_list(@cc));
1159 my $ccline = "";
1160 if ($cc ne '') {
1161 $ccline = "\nCc: $cc";
1162 }
1163 make_message_id() unless defined($message_id);
1164
1165 my $header = "From: $sender
1166To: $to${ccline}
1167Subject: $subject
1168Date: $date
1169Message-Id: $message_id
1170X-Mailer: git-send-email $gitversion
1171";
1172 if ($reply_to) {
1173
1174 $header .= "In-Reply-To: $reply_to\n";
1175 $header .= "References: $references\n";
1176 }
1177 if (@xh) {
1178 $header .= join("\n", @xh) . "\n";
1179 }
1180
1181 my @sendmail_parameters = ('-i', @recipients);
1182 my $raw_from = $sender;
1183 if (defined $envelope_sender && $envelope_sender ne "auto") {
1184 $raw_from = $envelope_sender;
1185 }
1186 $raw_from = extract_valid_address($raw_from);
1187 unshift (@sendmail_parameters,
1188 '-f', $raw_from) if(defined $envelope_sender);
1189
1190 if ($needs_confirm && !$dry_run) {
1191 print "\n$header\n";
1192 if ($needs_confirm eq "inform") {
1193 $confirm_unconfigured = 0; # squelch this message for the rest of this run
1194 $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
1195 print " The Cc list above has been expanded by additional\n";
1196 print " addresses found in the patch commit message. By default\n";
1197 print " send-email prompts before sending whenever this occurs.\n";
1198 print " This behavior is controlled by the sendemail.confirm\n";
1199 print " configuration setting.\n";
1200 print "\n";
1201 print " For additional information, run 'git send-email --help'.\n";
1202 print " To retain the current behavior, but squelch this message,\n";
1203 print " run 'git config --global sendemail.confirm auto'.\n\n";
1204 }
1205 $_ = ask("Send this email? ([y]es|[n]o|[q]uit|[a]ll): ",
1206 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
1207 default => $ask_default);
1208 die "Send this email reply required" unless defined $_;
1209 if (/^n/i) {
1210 return 0;
1211 } elsif (/^q/i) {
1212 cleanup_compose_files();
1213 exit(0);
1214 } elsif (/^a/i) {
1215 $confirm = 'never';
1216 }
1217 }
1218
1219 unshift (@sendmail_parameters, @smtp_server_options);
1220
1221 if ($dry_run) {
1222 # We don't want to send the email.
1223 } elsif (file_name_is_absolute($smtp_server)) {
1224 my $pid = open my $sm, '|-';
1225 defined $pid or die $!;
1226 if (!$pid) {
1227 exec($smtp_server, @sendmail_parameters) or die $!;
1228 }
1229 print $sm "$header\n$message";
1230 close $sm or die $!;
1231 } else {
1232
1233 if (!defined $smtp_server) {
1234 die "The required SMTP server is not properly defined."
1235 }
1236
1237 if ($smtp_encryption eq 'ssl') {
1238 $smtp_server_port ||= 465; # ssmtp
1239 require Net::SMTP::SSL;
1240 $smtp_domain ||= maildomain();
1241 require IO::Socket::SSL;
1242 # Net::SMTP::SSL->new() does not forward any SSL options
1243 IO::Socket::SSL::set_client_defaults(
1244 ssl_verify_params());
1245 $smtp ||= Net::SMTP::SSL->new($smtp_server,
1246 Hello => $smtp_domain,
1247 Port => $smtp_server_port,
1248 Debug => $debug_net_smtp);
1249 }
1250 else {
1251 require Net::SMTP;
1252 $smtp_domain ||= maildomain();
1253 $smtp_server_port ||= 25;
1254 $smtp ||= Net::SMTP->new($smtp_server,
1255 Hello => $smtp_domain,
1256 Debug => $debug_net_smtp,
1257 Port => $smtp_server_port);
1258 if ($smtp_encryption eq 'tls' && $smtp) {
1259 require Net::SMTP::SSL;
1260 $smtp->command('STARTTLS');
1261 $smtp->response();
1262 if ($smtp->code == 220) {
1263 $smtp = Net::SMTP::SSL->start_SSL($smtp,
1264 ssl_verify_params())
1265 or die "STARTTLS failed! ".IO::Socket::SSL::errstr();
1266 $smtp_encryption = '';
1267 # Send EHLO again to receive fresh
1268 # supported commands
1269 $smtp->hello($smtp_domain);
1270 } else {
1271 die "Server does not support STARTTLS! ".$smtp->message;
1272 }
1273 }
1274 }
1275
1276 if (!$smtp) {
1277 die "Unable to initialize SMTP properly. Check config and use --smtp-debug. ",
1278 "VALUES: server=$smtp_server ",
1279 "encryption=$smtp_encryption ",
1280 "hello=$smtp_domain",
1281 defined $smtp_server_port ? " port=$smtp_server_port" : "";
1282 }
1283
1284 smtp_auth_maybe or die $smtp->message;
1285
1286 $smtp->mail( $raw_from ) or die $smtp->message;
1287 $smtp->to( @recipients ) or die $smtp->message;
1288 $smtp->data or die $smtp->message;
1289 $smtp->datasend("$header\n$message") or die $smtp->message;
1290 $smtp->dataend() or die $smtp->message;
1291 $smtp->code =~ /250|200/ or die "Failed to send $subject\n".$smtp->message;
1292 }
1293 if ($quiet) {
1294 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
1295 } else {
1296 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
1297 if (!file_name_is_absolute($smtp_server)) {
1298 print "Server: $smtp_server\n";
1299 print "MAIL FROM:<$raw_from>\n";
1300 foreach my $entry (@recipients) {
1301 print "RCPT TO:<$entry>\n";
1302 }
1303 } else {
1304 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
1305 }
1306 print $header, "\n";
1307 if ($smtp) {
1308 print "Result: ", $smtp->code, ' ',
1309 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
1310 } else {
1311 print "Result: OK\n";
1312 }
1313 }
1314
1315 return 1;
1316}
1317
1318$reply_to = $initial_reply_to;
1319$references = $initial_reply_to || '';
1320$subject = $initial_subject;
1321$message_num = 0;
1322
1323foreach my $t (@files) {
1324 open my $fh, "<", $t or die "can't open file $t";
1325
1326 my $author = undef;
1327 my $sauthor = undef;
1328 my $author_encoding;
1329 my $has_content_type;
1330 my $body_encoding;
1331 my $xfer_encoding;
1332 my $has_mime_version;
1333 @to = ();
1334 @cc = ();
1335 @xh = ();
1336 my $input_format = undef;
1337 my @header = ();
1338 $message = "";
1339 $message_num++;
1340 # First unfold multiline header fields
1341 while(<$fh>) {
1342 last if /^\s*$/;
1343 if (/^\s+\S/ and @header) {
1344 chomp($header[$#header]);
1345 s/^\s+/ /;
1346 $header[$#header] .= $_;
1347 } else {
1348 push(@header, $_);
1349 }
1350 }
1351 # Now parse the header
1352 foreach(@header) {
1353 if (/^From /) {
1354 $input_format = 'mbox';
1355 next;
1356 }
1357 chomp;
1358 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
1359 $input_format = 'mbox';
1360 }
1361
1362 if (defined $input_format && $input_format eq 'mbox') {
1363 if (/^Subject:\s+(.*)$/i) {
1364 $subject = $1;
1365 }
1366 elsif (/^From:\s+(.*)$/i) {
1367 ($author, $author_encoding) = unquote_rfc2047($1);
1368 $sauthor = sanitize_address($author);
1369 next if $suppress_cc{'author'};
1370 next if $suppress_cc{'self'} and $sauthor eq $sender;
1371 printf("(mbox) Adding cc: %s from line '%s'\n",
1372 $1, $_) unless $quiet;
1373 push @cc, $1;
1374 }
1375 elsif (/^To:\s+(.*)$/i) {
1376 foreach my $addr (parse_address_line($1)) {
1377 printf("(mbox) Adding to: %s from line '%s'\n",
1378 $addr, $_) unless $quiet;
1379 push @to, $addr;
1380 }
1381 }
1382 elsif (/^Cc:\s+(.*)$/i) {
1383 foreach my $addr (parse_address_line($1)) {
1384 my $qaddr = unquote_rfc2047($addr);
1385 my $saddr = sanitize_address($qaddr);
1386 if ($saddr eq $sender) {
1387 next if ($suppress_cc{'self'});
1388 } else {
1389 next if ($suppress_cc{'cc'});
1390 }
1391 printf("(mbox) Adding cc: %s from line '%s'\n",
1392 $addr, $_) unless $quiet;
1393 push @cc, $addr;
1394 }
1395 }
1396 elsif (/^Content-type:/i) {
1397 $has_content_type = 1;
1398 if (/charset="?([^ "]+)/) {
1399 $body_encoding = $1;
1400 }
1401 push @xh, $_;
1402 }
1403 elsif (/^MIME-Version/i) {
1404 $has_mime_version = 1;
1405 push @xh, $_;
1406 }
1407 elsif (/^Message-Id: (.*)/i) {
1408 $message_id = $1;
1409 }
1410 elsif (/^Content-Transfer-Encoding: (.*)/i) {
1411 $xfer_encoding = $1 if not defined $xfer_encoding;
1412 }
1413 elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
1414 push @xh, $_;
1415 }
1416
1417 } else {
1418 # In the traditional
1419 # "send lots of email" format,
1420 # line 1 = cc
1421 # line 2 = subject
1422 # So let's support that, too.
1423 $input_format = 'lots';
1424 if (@cc == 0 && !$suppress_cc{'cc'}) {
1425 printf("(non-mbox) Adding cc: %s from line '%s'\n",
1426 $_, $_) unless $quiet;
1427 push @cc, $_;
1428 } elsif (!defined $subject) {
1429 $subject = $_;
1430 }
1431 }
1432 }
1433 # Now parse the message body
1434 while(<$fh>) {
1435 $message .= $_;
1436 if (/^(Signed-off-by|Cc): (.*)$/i) {
1437 chomp;
1438 my ($what, $c) = ($1, $2);
1439 chomp $c;
1440 my $sc = sanitize_address($c);
1441 if ($sc eq $sender) {
1442 next if ($suppress_cc{'self'});
1443 } else {
1444 next if $suppress_cc{'sob'} and $what =~ /Signed-off-by/i;
1445 next if $suppress_cc{'bodycc'} and $what =~ /Cc/i;
1446 }
1447 push @cc, $c;
1448 printf("(body) Adding cc: %s from line '%s'\n",
1449 $c, $_) unless $quiet;
1450 }
1451 }
1452 close $fh;
1453
1454 push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
1455 if defined $to_cmd;
1456 push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
1457 if defined $cc_cmd && !$suppress_cc{'cccmd'};
1458
1459 if ($broken_encoding{$t} && !$has_content_type) {
1460 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1461 $has_content_type = 1;
1462 push @xh, "Content-Type: text/plain; charset=$auto_8bit_encoding";
1463 $body_encoding = $auto_8bit_encoding;
1464 }
1465
1466 if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
1467 $subject = quote_subject($subject, $auto_8bit_encoding);
1468 }
1469
1470 if (defined $sauthor and $sauthor ne $sender) {
1471 $message = "From: $author\n\n$message";
1472 if (defined $author_encoding) {
1473 if ($has_content_type) {
1474 if ($body_encoding eq $author_encoding) {
1475 # ok, we already have the right encoding
1476 }
1477 else {
1478 # uh oh, we should re-encode
1479 }
1480 }
1481 else {
1482 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1483 $has_content_type = 1;
1484 push @xh,
1485 "Content-Type: text/plain; charset=$author_encoding";
1486 }
1487 }
1488 }
1489 if (defined $target_xfer_encoding) {
1490 $xfer_encoding = '8bit' if not defined $xfer_encoding;
1491 $message = apply_transfer_encoding(
1492 $message, $xfer_encoding, $target_xfer_encoding);
1493 $xfer_encoding = $target_xfer_encoding;
1494 }
1495 if (defined $xfer_encoding) {
1496 push @xh, "Content-Transfer-Encoding: $xfer_encoding";
1497 }
1498 if (defined $xfer_encoding or $has_content_type) {
1499 unshift @xh, 'MIME-Version: 1.0' unless $has_mime_version;
1500 }
1501
1502 $needs_confirm = (
1503 $confirm eq "always" or
1504 ($confirm =~ /^(?:auto|cc)$/ && @cc) or
1505 ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
1506 $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
1507
1508 @to = validate_address_list(sanitize_address_list(@to));
1509 @cc = validate_address_list(sanitize_address_list(@cc));
1510
1511 @to = (@initial_to, @to);
1512 @cc = (@initial_cc, @cc);
1513
1514 if ($message_num == 1) {
1515 if (defined $cover_cc and $cover_cc) {
1516 @initial_cc = @cc;
1517 }
1518 if (defined $cover_to and $cover_to) {
1519 @initial_to = @to;
1520 }
1521 }
1522
1523 my $message_was_sent = send_message();
1524
1525 # set up for the next message
1526 if ($thread && $message_was_sent &&
1527 ($chain_reply_to || !defined $reply_to || length($reply_to) == 0 ||
1528 $message_num == 1)) {
1529 $reply_to = $message_id;
1530 if (length $references > 0) {
1531 $references .= "\n $message_id";
1532 } else {
1533 $references = "$message_id";
1534 }
1535 }
1536 $message_id = undef;
1537}
1538
1539# Execute a command (e.g. $to_cmd) to get a list of email addresses
1540# and return a results array
1541sub recipients_cmd {
1542 my ($prefix, $what, $cmd, $file) = @_;
1543
1544 my @addresses = ();
1545 open my $fh, "-|", "$cmd \Q$file\E"
1546 or die "($prefix) Could not execute '$cmd'";
1547 while (my $address = <$fh>) {
1548 $address =~ s/^\s*//g;
1549 $address =~ s/\s*$//g;
1550 $address = sanitize_address($address);
1551 next if ($address eq $sender and $suppress_cc{'self'});
1552 push @addresses, $address;
1553 printf("($prefix) Adding %s: %s from: '%s'\n",
1554 $what, $address, $cmd) unless $quiet;
1555 }
1556 close $fh
1557 or die "($prefix) failed to close pipe to '$cmd'";
1558 return @addresses;
1559}
1560
1561cleanup_compose_files();
1562
1563sub cleanup_compose_files {
1564 unlink($compose_filename, $compose_filename . ".final") if $compose;
1565}
1566
1567$smtp->quit if $smtp;
1568
1569sub apply_transfer_encoding {
1570 my $message = shift;
1571 my $from = shift;
1572 my $to = shift;
1573
1574 return $message if ($from eq $to and $from ne '7bit');
1575
1576 require MIME::QuotedPrint;
1577 require MIME::Base64;
1578
1579 $message = MIME::QuotedPrint::decode($message)
1580 if ($from eq 'quoted-printable');
1581 $message = MIME::Base64::decode($message)
1582 if ($from eq 'base64');
1583
1584 die "cannot send message as 7bit"
1585 if ($to eq '7bit' and $message =~ /[^[:ascii:]]/);
1586 return $message
1587 if ($to eq '7bit' or $to eq '8bit');
1588 return MIME::QuotedPrint::encode($message, "\n", 0)
1589 if ($to eq 'quoted-printable');
1590 return MIME::Base64::encode($message, "\n")
1591 if ($to eq 'base64');
1592 die "invalid transfer encoding";
1593}
1594
1595sub unique_email_list {
1596 my %seen;
1597 my @emails;
1598
1599 foreach my $entry (@_) {
1600 my $clean = extract_valid_address_or_die($entry);
1601 $seen{$clean} ||= 0;
1602 next if $seen{$clean}++;
1603 push @emails, $entry;
1604 }
1605 return @emails;
1606}
1607
1608sub validate_patch {
1609 my $fn = shift;
1610 open(my $fh, '<', $fn)
1611 or die "unable to open $fn: $!\n";
1612 while (my $line = <$fh>) {
1613 if (length($line) > 998) {
1614 return "$.: patch contains a line longer than 998 characters";
1615 }
1616 }
1617 return;
1618}
1619
1620sub file_has_nonascii {
1621 my $fn = shift;
1622 open(my $fh, '<', $fn)
1623 or die "unable to open $fn: $!\n";
1624 while (my $line = <$fh>) {
1625 return 1 if $line =~ /[^[:ascii:]]/;
1626 }
1627 return 0;
1628}
1629
1630sub body_or_subject_has_nonascii {
1631 my $fn = shift;
1632 open(my $fh, '<', $fn)
1633 or die "unable to open $fn: $!\n";
1634 while (my $line = <$fh>) {
1635 last if $line =~ /^$/;
1636 return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
1637 }
1638 while (my $line = <$fh>) {
1639 return 1 if $line =~ /[^[:ascii:]]/;
1640 }
1641 return 0;
1642}