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