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