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