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