]> git.ipfire.org Git - thirdparty/git.git/blame - git-send-email.perl
Documentation: fix typos, grammar, asciidoc syntax
[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;
1b1dd23f 41git send-email [options] <file | directory>...
1b0baf14
MC
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
fa835cd5
TR
316# 'default' encryption is none -- this only prevents a warning
317$smtp_encryption = '' unless (defined $smtp_encryption);
318
65648283
DB
319# Set CC suppressions
320my(%suppress_cc);
321if (@suppress_cc) {
322 foreach my $entry (@suppress_cc) {
323 die "Unknown --suppress-cc field: '$entry'\n"
324 unless $entry =~ /^(all|cccmd|cc|author|self|sob)$/;
325 $suppress_cc{$entry} = 1;
326 }
327}
328
329if ($suppress_cc{'all'}) {
330 foreach my $entry (qw (ccmd cc author self sob)) {
331 $suppress_cc{$entry} = 1;
332 }
333 delete $suppress_cc{'all'};
334}
335
336# If explicit old-style ones are specified, they trump --suppress-cc.
337$suppress_cc{'self'} = $suppress_from if defined $suppress_from;
ba51795c 338$suppress_cc{'sob'} = !$signed_off_cc if defined $signed_off_cc;
65648283
DB
339
340# Debugging, print out the suppressions.
341if (0) {
342 print "suppressions:\n";
343 foreach my $entry (keys %suppress_cc) {
344 printf " %-5s -> $suppress_cc{$entry}\n", $entry;
345 }
346}
347
ad79c024
FL
348my ($repoauthor, $repocommitter);
349($repoauthor) = Git::ident_person(@repo, 'author');
350($repocommitter) = Git::ident_person(@repo, 'committer');
34cc60ce 351
79ee555b
EB
352# Verify the user input
353
354foreach my $entry (@to) {
355 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
356}
357
358foreach my $entry (@initial_cc) {
359 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
360}
361
362foreach my $entry (@bcclist) {
363 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
364}
365
994d6c66 366my %aliases;
994d6c66
EW
367my %parse_alias = (
368 # multiline formats can be supported in the future
369 mutt => sub { my $fh = shift; while (<$fh>) {
504ceab6 370 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
994d6c66
EW
371 my ($alias, $addr) = ($1, $2);
372 $addr =~ s/#.*$//; # mutt allows # comments
373 # commas delimit multiple addresses
374 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
375 }}},
376 mailrc => sub { my $fh = shift; while (<$fh>) {
377 if (/^alias\s+(\S+)\s+(.*)$/) {
378 # spaces delimit multiple addresses
379 $aliases{$1} = [ split(/\s+/, $2) ];
380 }}},
381 pine => sub { my $fh = shift; while (<$fh>) {
2d8ae400 382 if (/^(\S+)\t.*\t(.*)$/) {
994d6c66
EW
383 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
384 }}},
385 gnus => sub { my $fh = shift; while (<$fh>) {
386 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
387 $aliases{$1} = [ $2 ];
388 }}}
389);
390
3cb8caf7 391if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
994d6c66
EW
392 foreach my $file (@alias_files) {
393 open my $fh, '<', $file or die "opening $file: $!\n";
394 $parse_alias{$aliasfiletype}->($fh);
395 close $fh;
396 }
397}
398
94638f89 399($sender) = expand_aliases($sender) if defined $sender;
ae740a58 400
aa54892f
JK
401# Now that all the defaults are set, process the rest of the command line
402# arguments and collect up the files that need to be processed.
403for my $f (@ARGV) {
404 if (-d $f) {
405 opendir(DH,$f)
406 or die "Failed to opendir $f: $!";
407
408 push @files, grep { -f $_ } map { +$f . "/" . $_ }
409 sort readdir(DH);
8c178687 410 closedir(DH);
300913bd 411 } elsif (-f $f or -p $f) {
aa54892f 412 push @files, $f;
aa54892f
JK
413 } else {
414 print STDERR "Skipping $f - not found.\n";
415 }
416}
417
c764a0c2
JK
418if (!$no_validate) {
419 foreach my $f (@files) {
300913bd
KB
420 unless (-p $f) {
421 my $error = validate_patch($f);
422 $error and die "fatal: $f: $error\nwarning: no patches were sent\n";
423 }
c764a0c2 424 }
747bbff9
JK
425}
426
aa54892f
JK
427if (@files) {
428 unless ($quiet) {
429 print $_,"\n" for (@files);
430 }
431} else {
432 print STDERR "\nNo patch files specified!\n\n";
433 usage();
434}
435
1f038a0c 436my $prompting = 0;
94638f89 437if (!defined $sender) {
ad79c024 438 $sender = $repoauthor || $repocommitter || '';
8a7c56e1
MW
439
440 while (1) {
94638f89 441 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
8a7c56e1
MW
442 last if defined $_;
443 print "\n";
444 }
8037d1a3 445
94638f89
UKK
446 $sender = $_ if ($_);
447 print "Emails will be sent from: ", $sender, "\n";
1f038a0c 448 $prompting++;
83b24437
RA
449}
450
451if (!@to) {
8a7c56e1
MW
452
453
454 while (1) {
455 $_ = $term->readline("Who should the emails be sent to? ", "");
456 last if defined $_;
457 print "\n";
458 }
459
83b24437 460 my $to = $_;
d1eb35b6 461 push @to, split /,\s*/, $to;
1f038a0c 462 $prompting++;
83b24437
RA
463}
464
994d6c66
EW
465sub expand_aliases {
466 my @cur = @_;
467 my @last;
468 do {
469 @last = @cur;
470 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
471 } while (join(',',@cur) ne join(',',@last));
472 return @cur;
473}
474
475@to = expand_aliases(@to);
5b56aaa2 476@to = (map { sanitize_address($_) } @to);
994d6c66 477@initial_cc = expand_aliases(@initial_cc);
58063245 478@bcclist = expand_aliases(@bcclist);
994d6c66 479
1f038a0c 480if (!defined $initial_subject && $compose) {
8a7c56e1
MW
481 while (1) {
482 $_ = $term->readline("What subject should the initial email start with? ", $initial_subject);
483 last if defined $_;
484 print "\n";
485 }
486
83b24437 487 $initial_subject = $_;
1f038a0c 488 $prompting++;
83b24437
RA
489}
490
5483c71d 491if ($thread && !defined $initial_reply_to && $prompting) {
8a7c56e1
MW
492 while (1) {
493 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ", $initial_reply_to);
494 last if defined $_;
495 print "\n";
496 }
8037d1a3 497
83b24437
RA
498 $initial_reply_to = $_;
499}
1ca3d6ed 500if (defined $initial_reply_to) {
0fb7fc75
JS
501 $initial_reply_to =~ s/^\s*<?//;
502 $initial_reply_to =~ s/>?\s*$//;
503 $initial_reply_to = "<$initial_reply_to>" if $initial_reply_to ne '';
ace9c2a9 504}
ace72086 505
34cc60ce 506if (!defined $smtp_server) {
aca7ad76
EW
507 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
508 if (-x $_) {
509 $smtp_server = $_;
510 last;
511 }
512 }
513 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
3342d850
RA
514}
515
1f038a0c
RA
516if ($compose) {
517 # Note that this does not need to be secure, but we will make a small
518 # effort to have it be unique
519 open(C,">",$compose_filename)
520 or die "Failed to open for writing $compose_filename: $!";
94638f89 521 print C "From $sender # This line is ignored.\n";
1f038a0c
RA
522 printf C "Subject: %s\n\n", $initial_subject;
523 printf C <<EOT;
524GIT: Please enter your email below.
525GIT: Lines beginning in "GIT: " will be removed.
526GIT: Consider including an overall diffstat or table of contents
527GIT: for the patch you are writing.
528
529EOT
530 close(C);
531
ad79c024 532 my $editor = $ENV{GIT_EDITOR} || Git::config(@repo, "core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
065096c2 533 system('sh', '-c', $editor.' "$@"', $editor, $compose_filename);
1f038a0c
RA
534
535 open(C2,">",$compose_filename . ".final")
536 or die "Failed to open $compose_filename.final : " . $!;
537
538 open(C,"<",$compose_filename)
539 or die "Failed to open $compose_filename : " . $!;
540
0706bd19
JK
541 my $need_8bit_cte = file_has_nonascii($compose_filename);
542 my $in_body = 0;
1f038a0c
RA
543 while(<C>) {
544 next if m/^GIT: /;
0706bd19
JK
545 if (!$in_body && /^\n$/) {
546 $in_body = 1;
547 if ($need_8bit_cte) {
548 print C2 "MIME-Version: 1.0\n",
549 "Content-Type: text/plain; ",
550 "charset=utf-8\n",
551 "Content-Transfer-Encoding: 8bit\n";
552 }
553 }
554 if (!$in_body && /^MIME-Version:/i) {
555 $need_8bit_cte = 0;
556 }
d54eaaa2
JK
557 if (!$in_body && /^Subject: ?(.*)/i) {
558 my $subject = $1;
559 $_ = "Subject: " .
560 ($subject =~ /[^[:ascii:]]/ ?
561 quote_rfc2047($subject) :
562 $subject) .
563 "\n";
564 }
1f038a0c
RA
565 print C2 $_;
566 }
567 close(C);
568 close(C2);
569
8a7c56e1 570 while (1) {
1f038a0c 571 $_ = $term->readline("Send this email? (y|n) ");
8a7c56e1
MW
572 last if defined $_;
573 print "\n";
574 }
1f038a0c
RA
575
576 if (uc substr($_,0,1) ne 'Y') {
577 cleanup_compose_files();
578 exit(0);
579 }
580
97394ee4 581 @files = ($compose_filename . ".final", @files);
1f038a0c
RA
582}
583
83b24437 584# Variables we set as part of the loop over files
af068d27 585our ($message_id, %mail, $subject, $reply_to, $references, $message);
83b24437 586
567ffeb7
EW
587sub extract_valid_address {
588 my $address = shift;
ad9c18f5 589 my $local_part_regexp = '[^<>"\s@]+';
09302e17 590 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
db3106b2
EW
591
592 # check for a local address:
ad9c18f5 593 return $address if ($address =~ /^($local_part_regexp)$/);
db3106b2 594
155197e6 595 $address =~ s/^\s*<(.*)>\s*$/$1/;
567ffeb7 596 if ($have_email_valid) {
ad9c18f5 597 return scalar Email::Valid->address($address);
567ffeb7
EW
598 } else {
599 # less robust/correct than the monster regexp in Email::Valid,
600 # but still does a 99% job, and one less dependency
ad9c18f5 601 $address =~ /($local_part_regexp\@$domain_regexp)/;
e96fd305 602 return $1;
567ffeb7
EW
603 }
604}
83b24437
RA
605
606# Usually don't need to change anything below here.
607
608# we make a "fake" message id by taking the current number
609# of seconds since the beginning of Unix time and tacking on
610# a random number to the end, in case we are called quicker than
611# 1 second since the last time we were called.
8037d1a3
RA
612
613# We'll setup a template for the message id, using the "from" address:
8037d1a3 614
be510cfe 615my ($message_id_stamp, $message_id_serial);
83b24437
RA
616sub make_message_id
617{
be510cfe
JH
618 my $uniq;
619 if (!defined $message_id_stamp) {
620 $message_id_stamp = sprintf("%s-%s", time, $$);
621 $message_id_serial = 0;
622 }
623 $message_id_serial++;
624 $uniq = "$message_id_stamp-$message_id_serial";
625
aeb59328 626 my $du_part;
94638f89
UKK
627 for ($sender, $repocommitter, $repoauthor) {
628 $du_part = extract_valid_address(sanitize_address($_));
629 last if (defined $du_part and $du_part ne '');
aeb59328 630 }
94638f89 631 if (not defined $du_part or $du_part eq '') {
aeb59328
JH
632 use Sys::Hostname qw();
633 $du_part = 'user@' . Sys::Hostname::hostname();
634 }
be510cfe
JH
635 my $message_id_template = "<%s-git-send-email-%s>";
636 $message_id = sprintf($message_id_template, $uniq, $du_part);
8037d1a3 637 #print "new message id = $message_id\n"; # Was useful for debugging
83b24437
RA
638}
639
640
641
a5370b16 642$time = time - scalar $#files;
83b24437 643
374c5905
JR
644sub unquote_rfc2047 {
645 local ($_) = @_;
8291db6f
JK
646 my $encoding;
647 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
648 $encoding = $1;
374c5905
JR
649 s/_/ /g;
650 s/=([0-9A-F]{2})/chr(hex($1))/eg;
651 }
8291db6f 652 return wantarray ? ($_, $encoding) : $_;
374c5905
JR
653}
654
d54eaaa2
JK
655sub quote_rfc2047 {
656 local $_ = shift;
657 my $encoding = shift || 'utf-8';
658 s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
659 s/(.*)/=\?$encoding\?q\?$1\?=/;
660 return $_;
661}
662
5b56aaa2
UKK
663# use the simplest quoting being able to handle the recipient
664sub sanitize_address
732263d4
RJ
665{
666 my ($recipient) = @_;
5b56aaa2
UKK
667 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
668
669 if (not $recipient_name) {
670 return "$recipient";
671 }
672
673 # if recipient_name is already quoted, do nothing
674 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
675 return $recipient;
676 }
677
678 # rfc2047 is needed if a non-ascii char is included
679 if ($recipient_name =~ /[^[:ascii:]]/) {
d54eaaa2 680 $recipient_name = quote_rfc2047($recipient_name);
732263d4 681 }
5b56aaa2
UKK
682
683 # double quotes are needed if specials or CTLs are included
684 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
18023c20 685 $recipient_name =~ s/(["\\\r])/\\$1/g;
5b56aaa2
UKK
686 $recipient_name = "\"$recipient_name\"";
687 }
688
689 return "$recipient_name $recipient_addr";
690
732263d4
RJ
691}
692
83b24437
RA
693sub send_message
694{
4bc87a28 695 my @recipients = unique_email_list(@to);
7ac17529
ABH
696 @cc = (grep { my $cc = extract_valid_address($_);
697 not grep { $cc eq $_ } @recipients
698 }
699 map { sanitize_address($_) }
700 @cc);
4bc87a28 701 my $to = join (",\n\t", @recipients);
58063245 702 @recipients = unique_email_list(@recipients,@cc,@bcclist);
c38f0247 703 @recipients = (map { extract_valid_address($_) } @recipients);
6bdca890 704 my $date = format_2822_time($time++);
e923effb
ML
705 my $gitversion = '@@GIT_VERSION@@';
706 if ($gitversion =~ m/..GIT_VERSION../) {
3cb8caf7 707 $gitversion = Git::version();
e923effb 708 }
4bc87a28 709
af068d27 710 my $cc = join(", ", unique_email_list(@cc));
f06a6a49
JH
711 my $ccline = "";
712 if ($cc ne '') {
713 $ccline = "\nCc: $cc";
714 }
94638f89 715 my $sanitized_sender = sanitize_address($sender);
4f3d3703 716 make_message_id() unless defined($message_id);
aeb59328 717
94638f89 718 my $header = "From: $sanitized_sender
f06a6a49 719To: $to${ccline}
4bc87a28 720Subject: $subject
4bc87a28
EW
721Date: $date
722Message-Id: $message_id
e923effb 723X-Mailer: git-send-email $gitversion
4bc87a28 724";
5483c71d 725 if ($thread && $reply_to) {
7ccf7927
RA
726
727 $header .= "In-Reply-To: $reply_to\n";
728 $header .= "References: $references\n";
729 }
ce91c2f6
JH
730 if (@xh) {
731 $header .= join("\n", @xh) . "\n";
732 }
4bc87a28 733
c38f0247 734 my @sendmail_parameters = ('-i', @recipients);
94638f89 735 my $raw_from = $sanitized_sender;
f073a592
RJ
736 $raw_from = $envelope_sender if (defined $envelope_sender);
737 $raw_from = extract_valid_address($raw_from);
738 unshift (@sendmail_parameters,
739 '-f', $raw_from) if(defined $envelope_sender);
8e3d436b 740
6130259c
MW
741 if ($dry_run) {
742 # We don't want to send the email.
743 } elsif ($smtp_server =~ m#^/#) {
aca7ad76
EW
744 my $pid = open my $sm, '|-';
745 defined $pid or die $!;
746 if (!$pid) {
8e3d436b 747 exec($smtp_server, @sendmail_parameters) or die $!;
aca7ad76
EW
748 }
749 print $sm "$header\n$message";
750 close $sm or die $?;
751 } else {
44b2476a
JH
752
753 if (!defined $smtp_server) {
754 die "The required SMTP server is not properly defined."
755 }
756
f6bebd12 757 if ($smtp_encryption eq 'ssl') {
44b2476a 758 $smtp_server_port ||= 465; # ssmtp
34cc60ce 759 require Net::SMTP::SSL;
44b2476a 760 $smtp ||= Net::SMTP::SSL->new($smtp_server, Port => $smtp_server_port);
34cc60ce
DS
761 }
762 else {
763 require Net::SMTP;
44b2476a
JH
764 $smtp ||= Net::SMTP->new((defined $smtp_server_port)
765 ? "$smtp_server:$smtp_server_port"
766 : $smtp_server);
f6bebd12
TR
767 if ($smtp_encryption eq 'tls') {
768 require Net::SMTP::SSL;
769 $smtp->command('STARTTLS');
770 $smtp->response();
771 if ($smtp->code == 220) {
772 $smtp = Net::SMTP::SSL->start_SSL($smtp)
773 or die "STARTTLS failed! ".$smtp->message;
6cbf8b00 774 $smtp_encryption = '';
9d1ccf5e
RS
775 # Send EHLO again to receive fresh
776 # supported commands
777 $smtp->hello();
f6bebd12
TR
778 } else {
779 die "Server does not support STARTTLS! ".$smtp->message;
780 }
781 }
44b2476a
JH
782 }
783
784 if (!$smtp) {
785 die "Unable to initialize SMTP properly. Is there something wrong with your config?";
786 }
787
2363d746
MW
788 if (defined $smtp_authuser) {
789
790 if (!defined $smtp_authpass) {
791
792 system "stty -echo";
793
794 do {
795 print "Password: ";
796 $_ = <STDIN>;
797 print "\n";
798 } while (!defined $_);
799
800 chomp($smtp_authpass = $_);
801
802 system "stty echo";
803 }
804
5f5b6118 805 $auth ||= $smtp->auth( $smtp_authuser, $smtp_authpass ) or die $smtp->message;
34cc60ce 806 }
2363d746 807
2b69bfc2 808 $smtp->mail( $raw_from ) or die $smtp->message;
aca7ad76
EW
809 $smtp->to( @recipients ) or die $smtp->message;
810 $smtp->data or die $smtp->message;
811 $smtp->datasend("$header\n$message") or die $smtp->message;
812 $smtp->dataend() or die $smtp->message;
813 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
814 }
2718435b 815 if ($quiet) {
71c7da94 816 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
2718435b 817 } else {
b7f30e0a 818 print (($dry_run ? "Dry-" : "")."OK. Log says:\n");
2b69bfc2 819 if ($smtp_server !~ m#^/#) {
aca7ad76 820 print "Server: $smtp_server\n";
2b69bfc2
RJ
821 print "MAIL FROM:<$raw_from>\n";
822 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
aca7ad76 823 } else {
8e3d436b 824 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
aca7ad76 825 }
b7f30e0a 826 print $header, "\n";
aca7ad76
EW
827 if ($smtp) {
828 print "Result: ", $smtp->code, ' ',
829 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
830 } else {
831 print "Result: OK\n";
832 }
30d08b34 833 }
83b24437
RA
834}
835
83b24437 836$reply_to = $initial_reply_to;
2186d566 837$references = $initial_reply_to || '';
83b24437
RA
838$subject = $initial_subject;
839
840foreach my $t (@files) {
83b24437
RA
841 open(F,"<",$t) or die "can't open file $t";
842
94638f89 843 my $author = undef;
8291db6f
JK
844 my $author_encoding;
845 my $has_content_type;
846 my $body_encoding;
da140f8b 847 @cc = @initial_cc;
ce91c2f6 848 @xh = ();
e6b0964a 849 my $input_format = undef;
83b24437
RA
850 my $header_done = 0;
851 $message = "";
852 while(<F>) {
853 if (!$header_done) {
e6b0964a
JH
854 if (/^From /) {
855 $input_format = 'mbox';
856 next;
857 }
83b24437 858 chomp;
e6b0964a
JH
859 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
860 $input_format = 'mbox';
861 }
83b24437 862
e6b0964a 863 if (defined $input_format && $input_format eq 'mbox') {
83b24437
RA
864 if (/^Subject:\s+(.*)$/) {
865 $subject = $1;
866
867 } elsif (/^(Cc|From):\s+(.*)$/) {
94638f89 868 if (unquote_rfc2047($2) eq $sender) {
65648283 869 next if ($suppress_cc{'self'});
8a8e6235 870 }
68d42c41 871 elsif ($1 eq 'From') {
8291db6f
JK
872 ($author, $author_encoding)
873 = unquote_rfc2047($2);
65648283
DB
874 next if ($suppress_cc{'author'});
875 } else {
876 next if ($suppress_cc{'cc'});
8a8e6235 877 }
83b24437 878 printf("(mbox) Adding cc: %s from line '%s'\n",
2718435b 879 $2, $_) unless $quiet;
83b24437
RA
880 push @cc, $2;
881 }
8291db6f
JK
882 elsif (/^Content-type:/i) {
883 $has_content_type = 1;
8892048d 884 if (/charset="?([^ "]+)/) {
8291db6f
JK
885 $body_encoding = $1;
886 }
887 push @xh, $_;
888 }
4f3d3703
JK
889 elsif (/^Message-Id: (.*)/i) {
890 $message_id = $1;
891 }
1d6a003a 892 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
ce91c2f6
JH
893 push @xh, $_;
894 }
83b24437
RA
895
896 } else {
897 # In the traditional
898 # "send lots of email" format,
899 # line 1 = cc
900 # line 2 = subject
901 # So let's support that, too.
e6b0964a 902 $input_format = 'lots';
65648283 903 if (@cc == 0 && !$suppress_cc{'cc'}) {
83b24437 904 printf("(non-mbox) Adding cc: %s from line '%s'\n",
2718435b 905 $_, $_) unless $quiet;
83b24437
RA
906
907 push @cc, $_;
908
909 } elsif (!defined $subject) {
910 $subject = $_;
911 }
912 }
5825e5b2 913
83b24437
RA
914 # A whitespace line will terminate the headers
915 if (m/^\s*$/) {
916 $header_done = 1;
917 }
918 } else {
919 $message .= $_;
65648283
DB
920 if (/^(Signed-off-by|Cc): (.*)$/i) {
921 next if ($suppress_cc{'sob'});
ba51795c 922 chomp;
abec100c 923 my $c = $2;
83b24437 924 chomp $c;
65648283 925 next if ($c eq $sender and $suppress_cc{'self'});
83b24437
RA
926 push @cc, $c;
927 printf("(sob) Adding cc: %s from line '%s'\n",
2718435b 928 $c, $_) unless $quiet;
83b24437
RA
929 }
930 }
931 }
932 close F;
324a8bd0 933
65648283 934 if (defined $cc_cmd && !$suppress_cc{'cccmd'}) {
324a8bd0
JP
935 open(F, "$cc_cmd $t |")
936 or die "(cc-cmd) Could not execute '$cc_cmd'";
937 while(<F>) {
938 my $c = $_;
939 $c =~ s/^\s*//g;
940 $c =~ s/\n$//g;
620bb245 941 next if ($c eq $sender and $suppress_from);
324a8bd0
JP
942 push @cc, $c;
943 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
944 $c, $cc_cmd) unless $quiet;
945 }
946 close F
947 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
948 }
949
94638f89
UKK
950 if (defined $author) {
951 $message = "From: $author\n\n$message";
8291db6f
JK
952 if (defined $author_encoding) {
953 if ($has_content_type) {
954 if ($body_encoding eq $author_encoding) {
955 # ok, we already have the right encoding
956 }
957 else {
958 # uh oh, we should re-encode
959 }
960 }
961 else {
962 push @xh,
963 'MIME-Version: 1.0',
8641ee3d
JK
964 "Content-Type: text/plain; charset=$author_encoding",
965 'Content-Transfer-Encoding: 8bit';
8291db6f
JK
966 }
967 }
8a8e6235 968 }
83b24437 969
83b24437
RA
970 send_message();
971
972 # set up for the next message
bc108f63 973 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
78488b2c 974 $reply_to = $message_id;
7ccf7927 975 if (length $references > 0) {
a925b89c 976 $references .= "\n $message_id";
7ccf7927
RA
977 } else {
978 $references = "$message_id";
979 }
78488b2c 980 }
4f3d3703 981 $message_id = undef;
83b24437 982}
e205735d 983
1f038a0c
RA
984if ($compose) {
985 cleanup_compose_files();
986}
987
988sub cleanup_compose_files() {
989 unlink($compose_filename, $compose_filename . ".final");
990
991}
992
4bc87a28 993$smtp->quit if $smtp;
e205735d
RA
994
995sub unique_email_list(@) {
996 my %seen;
997 my @emails;
998
999 foreach my $entry (@_) {
db3106b2
EW
1000 if (my $clean = extract_valid_address($entry)) {
1001 $seen{$clean} ||= 0;
1002 next if $seen{$clean}++;
1003 push @emails, $entry;
1004 } else {
1005 print STDERR "W: unable to extract a valid address",
1006 " from: $entry\n";
1007 }
e205735d
RA
1008 }
1009 return @emails;
1010}
747bbff9
JK
1011
1012sub validate_patch {
1013 my $fn = shift;
1014 open(my $fh, '<', $fn)
1015 or die "unable to open $fn: $!\n";
1016 while (my $line = <$fh>) {
1017 if (length($line) > 998) {
1018 return "$.: patch contains a line longer than 998 characters";
1019 }
1020 }
1021 return undef;
1022}
0706bd19
JK
1023
1024sub file_has_nonascii {
1025 my $fn = shift;
1026 open(my $fh, '<', $fn)
1027 or die "unable to open $fn: $!\n";
1028 while (my $line = <$fh>) {
1029 return 1 if $line =~ /[^[:ascii:]]/;
1030 }
1031 return 0;
1032}