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