1#!/usr/bin/perl -w 2# 3# Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com> 4# Copyright 2005 Ryan Anderson <ryan@michonline.com> 5# 6# GPL v2 (See COPYING) 7# 8# Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com> 9# 10# Sends a collection of emails to the given email addresses, disturbingly fast. 11# 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: 15# first line of the message is who to CC, 16# and second line is the subject of the message. 17# 18 19use strict; 20use warnings; 21use Term::ReadLine; 22use Getopt::Long; 23use Data::Dumper; 24use Term::ANSIColor; 25use Git; 26 27$SIG{INT} =sub{print color("reset"),"\n";exit}; 28 29package FakeTerm; 30sub new { 31my($class,$reason) =@_; 32returnbless \$reason,shift; 33} 34subreadline{ 35my$self=shift; 36die"Cannot use readline on FakeTerm:$$self"; 37} 38package main; 39 40 41sub usage { 42print<<EOT; 43git-send-email [options] <file | directory>... 44Options: 45 --from Specify the "From:" line of the email to be sent. 46 47 --to Specify the primary "To:" line of the email. 48 49 --cc Specify an initial "Cc:" list for the entire series 50 of emails. 51 52 --cc-cmd Specify a command to execute per file which adds 53 per file specific cc address entries 54 55 --bcc Specify a list of email addresses that should be Bcc: 56 on all the emails. 57 58 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUALto edit 59 an introductory message for the patch series. 60 61 --subject Specify the initial "Subject:" line. 62 Only necessary if --compose is also set. If --compose 63 is not set, this will be prompted for. 64 65 --in-reply-to Specify the first "In-Reply-To:" header line. 66 Only used if --compose is also set. If --compose is not 67 set, this will be prompted for. 68 69 --chain-reply-to If set, the replies will all be to the previous 70 email sent, rather than to the first email sent. 71 Defaults to on. 72 73 --signed-off-cc Automatically add email addresses that appear in 74 Signed-off-by: or Cc: lines to the cc: list. Defaults to on. 75 76 --smtp-server If set, specifies the outgoing SMTP server to use. 77 Defaults to localhost. 78 79 --suppress-from Suppress sending emails to yourself if your address 80 appears in a From: line. Defaults to off. 81 82 --thread Specify that the "In-Reply-To:" header should be set on all 83 emails. Defaults to on. 84 85 --quiet Make git-send-email less verbose. One line per email 86 should be all that is output. 87 88 --dry-run Do everything except actually send the emails. 89 90 --envelope-sender Specify the envelope sender used to send the emails. 91 92EOT 93exit(1); 94} 95 96# most mail servers generate the Date: header, but not all... 97sub format_2822_time { 98my($time) =@_; 99my@localtm=localtime($time); 100my@gmttm=gmtime($time); 101my$localmin=$localtm[1] +$localtm[2] *60; 102my$gmtmin=$gmttm[1] +$gmttm[2] *60; 103if($localtm[0] !=$gmttm[0]) { 104die"local zone differs from GMT by a non-minute interval\n"; 105} 106if((($gmttm[6] +1) %7) ==$localtm[6]) { 107$localmin+=1440; 108}elsif((($gmttm[6] -1) %7) ==$localtm[6]) { 109$localmin-=1440; 110}elsif($gmttm[6] !=$localtm[6]) { 111die"local time offset greater than or equal to 24 hours\n"; 112} 113my$offset=$localmin-$gmtmin; 114my$offhour=$offset/60; 115my$offmin=abs($offset%60); 116if(abs($offhour) >=24) { 117die("local time offset greater than or equal to 24 hours\n"); 118} 119 120returnsprintf("%s,%2d%s%d%02d:%02d:%02d%s%02d%02d", 121qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]], 122$localtm[3], 123qw(Jan Feb Mar Apr May Jun 124 Jul Aug Sep Oct Nov Dec)[$localtm[4]], 125$localtm[5]+1900, 126$localtm[2], 127$localtm[1], 128$localtm[0], 129($offset>=0) ?'+':'-', 130abs($offhour), 131$offmin, 132); 133} 134 135my$have_email_valid=eval{require Email::Valid;1}; 136my$smtp; 137 138sub unique_email_list(@); 139sub cleanup_compose_files(); 140 141# Constants (essentially) 142my$compose_filename=".msg.$$"; 143 144# Variables we fill in automatically, or via prompting: 145my(@to,@cc,@initial_cc,@bcclist,@xh, 146$initial_reply_to,$initial_subject,@files,$author,$sender,$compose,$time); 147 148my$smtp_server; 149my$envelope_sender; 150 151# Example reply to: 152#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>'; 153 154my$repo= Git->repository(); 155my$term=eval{ 156 new Term::ReadLine 'git-send-email'; 157}; 158if($@) { 159$term= new FakeTerm "$@: going non-interactive"; 160} 161 162# Behavior modification variables 163my($quiet,$dry_run) = (0,0); 164 165# Variables with corresponding config settings 166my($thread,$chain_reply_to,$suppress_from,$signed_off_cc,$cc_cmd); 167 168my%config_settings= ( 169"thread"=> [\$thread,1], 170"chainreplyto"=> [\$chain_reply_to,1], 171"suppressfrom"=> [\$suppress_from,0], 172"signedoffcc"=> [\$signed_off_cc,1], 173"cccmd"=> [\$cc_cmd,""], 174); 175 176foreachmy$setting(keys%config_settings) { 177my$config=$repo->config_bool("sendemail.$setting"); 178${$config_settings{$setting}->[0]} = (defined$config) ?$config:$config_settings{$setting}->[1]; 179} 180 181@bcclist=$repo->config('sendemail.bcc'); 182if(!@bcclistor!$bcclist[0]) { 183@bcclist= (); 184} 185 186# Begin by accumulating all the variables (defined above), that we will end up 187# needing, first, from the command line: 188 189my$rc= GetOptions("sender|from=s"=> \$sender, 190"in-reply-to=s"=> \$initial_reply_to, 191"subject=s"=> \$initial_subject, 192"to=s"=> \@to, 193"cc=s"=> \@initial_cc, 194"bcc=s"=> \@bcclist, 195"chain-reply-to!"=> \$chain_reply_to, 196"smtp-server=s"=> \$smtp_server, 197"compose"=> \$compose, 198"quiet"=> \$quiet, 199"cc-cmd=s"=> \$cc_cmd, 200"suppress-from!"=> \$suppress_from, 201"signed-off-cc|signed-off-by-cc!"=> \$signed_off_cc, 202"dry-run"=> \$dry_run, 203"envelope-sender=s"=> \$envelope_sender, 204"thread!"=> \$thread, 205); 206 207unless($rc) { 208 usage(); 209} 210 211# Verify the user input 212 213foreachmy$entry(@to) { 214die"Comma in --to entry:$entry'\n"unless$entry!~m/,/; 215} 216 217foreachmy$entry(@initial_cc) { 218die"Comma in --cc entry:$entry'\n"unless$entry!~m/,/; 219} 220 221foreachmy$entry(@bcclist) { 222die"Comma in --bcclist entry:$entry'\n"unless$entry!~m/,/; 223} 224 225# Now, let's fill any that aren't set in with defaults: 226 227my($repoauthor) =$repo->ident_person('author'); 228my($repocommitter) =$repo->ident_person('committer'); 229 230my%aliases; 231my@alias_files=$repo->config('sendemail.aliasesfile'); 232my$aliasfiletype=$repo->config('sendemail.aliasfiletype'); 233my%parse_alias= ( 234# multiline formats can be supported in the future 235 mutt =>sub{my$fh=shift;while(<$fh>) { 236if(/^\s*alias\s+(\S+)\s+(.*)$/) { 237my($alias,$addr) = ($1,$2); 238$addr=~s/#.*$//;# mutt allows # comments 239# commas delimit multiple addresses 240$aliases{$alias} = [split(/\s*,\s*/,$addr) ]; 241}}}, 242 mailrc =>sub{my$fh=shift;while(<$fh>) { 243if(/^alias\s+(\S+)\s+(.*)$/) { 244# spaces delimit multiple addresses 245$aliases{$1} = [split(/\s+/,$2) ]; 246}}}, 247 pine =>sub{my$fh=shift;while(<$fh>) { 248if(/^(\S+)\t.*\t(.*)$/) { 249$aliases{$1} = [split(/\s*,\s*/,$2) ]; 250}}}, 251 gnus =>sub{my$fh=shift;while(<$fh>) { 252if(/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) { 253$aliases{$1} = [$2]; 254}}} 255); 256 257if(@alias_filesand$aliasfiletypeand defined$parse_alias{$aliasfiletype}) { 258foreachmy$file(@alias_files) { 259open my$fh,'<',$fileor die"opening$file:$!\n"; 260$parse_alias{$aliasfiletype}->($fh); 261close$fh; 262} 263} 264 265($sender) = expand_aliases($sender)ifdefined$sender; 266 267my$prompting=0; 268if(!defined$sender) { 269$sender=$repoauthor||$repocommitter; 270do{ 271$_=$term->readline("Who should the emails appear to be from? [$sender] "); 272}while(!defined$_); 273 274$sender=$_if($_); 275print"Emails will be sent from: ",$sender,"\n"; 276$prompting++; 277} 278 279if(!@to) { 280do{ 281$_=$term->readline("Who should the emails be sent to? ", 282""); 283}while(!defined$_); 284my$to=$_; 285push@to,split/,/,$to; 286$prompting++; 287} 288 289sub expand_aliases { 290my@cur=@_; 291my@last; 292do{ 293@last=@cur; 294@cur=map{$aliases{$_} ? @{$aliases{$_}} :$_}@last; 295}while(join(',',@cur)ne join(',',@last)); 296return@cur; 297} 298 299@to= expand_aliases(@to); 300@to= (map{ sanitize_address($_) }@to); 301@initial_cc= expand_aliases(@initial_cc); 302@bcclist= expand_aliases(@bcclist); 303 304if(!defined$initial_subject&&$compose) { 305do{ 306$_=$term->readline("What subject should the emails start with? ", 307$initial_subject); 308}while(!defined$_); 309$initial_subject=$_; 310$prompting++; 311} 312 313if($thread&& !defined$initial_reply_to&&$prompting) { 314do{ 315$_=$term->readline("Message-ID to be used as In-Reply-To for the first email? ", 316$initial_reply_to); 317}while(!defined$_); 318 319$initial_reply_to=$_; 320$initial_reply_to=~s/(^\s+|\s+$)//g; 321} 322 323if(!$smtp_server) { 324$smtp_server=$repo->config('sendemail.smtpserver'); 325} 326if(!$smtp_server) { 327foreach(qw( /usr/sbin/sendmail /usr/lib/sendmail )) { 328if(-x $_) { 329$smtp_server=$_; 330last; 331} 332} 333$smtp_server||='localhost';# could be 127.0.0.1, too... *shrug* 334} 335 336if($compose) { 337# Note that this does not need to be secure, but we will make a small 338# effort to have it be unique 339open(C,">",$compose_filename) 340or die"Failed to open for writing$compose_filename:$!"; 341print C "From$sender# This line is ignored.\n"; 342printf C "Subject:%s\n\n",$initial_subject; 343printf C <<EOT; 344GIT: Please enter your email below. 345GIT: Lines beginning in "GIT: " will be removed. 346GIT: Consider including an overall diffstat or table of contents 347GIT: for the patch you are writing. 348 349EOT 350close(C); 351 352my$editor=$ENV{GIT_EDITOR} ||$repo->config("core.editor") ||$ENV{VISUAL} ||$ENV{EDITOR} ||"vi"; 353system($editor,$compose_filename); 354 355open(C2,">",$compose_filename.".final") 356or die"Failed to open$compose_filename.final : ".$!; 357 358open(C,"<",$compose_filename) 359or die"Failed to open$compose_filename: ".$!; 360 361while(<C>) { 362next ifm/^GIT: /; 363print C2 $_; 364} 365close(C); 366close(C2); 367 368do{ 369$_=$term->readline("Send this email? (y|n) "); 370}while(!defined$_); 371 372if(uc substr($_,0,1)ne'Y') { 373 cleanup_compose_files(); 374exit(0); 375} 376 377@files= ($compose_filename.".final"); 378} 379 380 381# Now that all the defaults are set, process the rest of the command line 382# arguments and collect up the files that need to be processed. 383formy$f(@ARGV) { 384if(-d $f) { 385opendir(DH,$f) 386or die"Failed to opendir$f:$!"; 387 388push@files,grep{ -f $_}map{ +$f."/".$_} 389sort readdir(DH); 390 391}elsif(-f $f) { 392push@files,$f; 393 394}else{ 395print STDERR "Skipping$f- not found.\n"; 396} 397} 398 399if(@files) { 400unless($quiet) { 401print$_,"\n"for(@files); 402} 403}else{ 404print STDERR "\nNo patch files specified!\n\n"; 405 usage(); 406} 407 408# Variables we set as part of the loop over files 409our($message_id,%mail,$subject,$reply_to,$references,$message); 410 411sub extract_valid_address { 412my$address=shift; 413my$local_part_regexp='[^<>"\s@]+'; 414my$domain_regexp='[^.<>"\s@]+(?:\.[^.<>"\s@]+)+'; 415 416# check for a local address: 417return$addressif($address=~/^($local_part_regexp)$/); 418 419$address=~s/^\s*<(.*)>\s*$/$1/; 420if($have_email_valid) { 421returnscalar Email::Valid->address($address); 422}else{ 423# less robust/correct than the monster regexp in Email::Valid, 424# but still does a 99% job, and one less dependency 425$address=~/($local_part_regexp\@$domain_regexp)/; 426return$1; 427} 428} 429 430# Usually don't need to change anything below here. 431 432# we make a "fake" message id by taking the current number 433# of seconds since the beginning of Unix time and tacking on 434# a random number to the end, in case we are called quicker than 435# 1 second since the last time we were called. 436 437# We'll setup a template for the message id, using the "from" address: 438 439sub make_message_id 440{ 441my$date=time; 442my$pseudo_rand=int(rand(4200)); 443my$du_part; 444for($sender,$repocommitter,$repoauthor) { 445$du_part= extract_valid_address(sanitize_address($_)); 446last if(defined$du_partand$du_partne''); 447} 448if(not defined$du_partor$du_parteq'') { 449use Sys::Hostname qw(); 450$du_part='user@'. Sys::Hostname::hostname(); 451} 452my$message_id_template="<%s-git-send-email-$du_part>"; 453$message_id=sprintf$message_id_template,"$date$pseudo_rand"; 454#print "new message id = $message_id\n"; # Was useful for debugging 455} 456 457 458 459$time=time-scalar$#files; 460 461sub unquote_rfc2047 { 462local($_) =@_; 463if(s/=\?utf-8\?q\?(.*)\?=/$1/g) { 464s/_/ /g; 465s/=([0-9A-F]{2})/chr(hex($1))/eg; 466} 467return"$_"; 468} 469 470# use the simplest quoting being able to handle the recipient 471sub sanitize_address 472{ 473my($recipient) =@_; 474my($recipient_name,$recipient_addr) = ($recipient=~/^(.*?)\s*(<.*)/); 475 476if(not$recipient_name) { 477return"$recipient"; 478} 479 480# if recipient_name is already quoted, do nothing 481if($recipient_name=~/^(".*"|=\?utf-8\?q\?.*\?=)$/) { 482return$recipient; 483} 484 485# rfc2047 is needed if a non-ascii char is included 486if($recipient_name=~/[^[:ascii:]]/) { 487$recipient_name=~s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X",ord($1))/eg; 488$recipient_name=~s/(.*)/=\?utf-8\?q\?$1\?=/; 489} 490 491# double quotes are needed if specials or CTLs are included 492elsif($recipient_name=~/[][()<>@,;:\\".\000-\037\177]/) { 493$recipient_name=~s/(["\\\r])/\\$1/; 494$recipient_name="\"$recipient_name\""; 495} 496 497return"$recipient_name$recipient_addr"; 498 499} 500 501sub send_message 502{ 503my@recipients= unique_email_list(@to); 504@cc= (map{ sanitize_address($_) }@cc); 505my$to=join(",\n\t",@recipients); 506@recipients= unique_email_list(@recipients,@cc,@bcclist); 507@recipients= (map{ extract_valid_address($_) }@recipients); 508my$date= format_2822_time($time++); 509my$gitversion='@@GIT_VERSION@@'; 510if($gitversion=~m/..GIT_VERSION../) { 511$gitversion= Git::version(); 512} 513 514my$cc=join(", ", unique_email_list(@cc)); 515my$ccline=""; 516if($ccne'') { 517$ccline="\nCc:$cc"; 518} 519my$sanitized_sender= sanitize_address($sender); 520 make_message_id(); 521 522my$header="From:$sanitized_sender 523To:$to${ccline} 524Subject:$subject 525Date:$date 526Message-Id:$message_id 527X-Mailer: git-send-email$gitversion 528"; 529if($thread&&$reply_to) { 530 531$header.="In-Reply-To:$reply_to\n"; 532$header.="References:$references\n"; 533} 534if(@xh) { 535$header.=join("\n",@xh) ."\n"; 536} 537 538my@sendmail_parameters= ('-i',@recipients); 539my$raw_from=$sanitized_sender; 540$raw_from=$envelope_senderif(defined$envelope_sender); 541$raw_from= extract_valid_address($raw_from); 542unshift(@sendmail_parameters, 543'-f',$raw_from)if(defined$envelope_sender); 544 545if($dry_run) { 546# We don't want to send the email. 547}elsif($smtp_server=~ m#^/#) { 548my$pid=open my$sm,'|-'; 549defined$pidor die$!; 550if(!$pid) { 551exec($smtp_server,@sendmail_parameters)or die$!; 552} 553print$sm"$header\n$message"; 554close$smor die$?; 555}else{ 556require Net::SMTP; 557$smtp||= Net::SMTP->new($smtp_server); 558$smtp->mail($raw_from)or die$smtp->message; 559$smtp->to(@recipients)or die$smtp->message; 560$smtp->dataor die$smtp->message; 561$smtp->datasend("$header\n$message")or die$smtp->message; 562$smtp->dataend()or die$smtp->message; 563$smtp->okor die"Failed to send$subject\n".$smtp->message; 564} 565if($quiet) { 566printf(($dry_run?"Dry-":"")."Sent%s\n",$subject); 567}else{ 568print(($dry_run?"Dry-":"")."OK. Log says:\nDate:$date\n"); 569if($smtp_server!~ m#^/#) { 570print"Server:$smtp_server\n"; 571print"MAIL FROM:<$raw_from>\n"; 572print"RCPT TO:".join(',',(map{"<$_>"}@recipients))."\n"; 573}else{ 574print"Sendmail:$smtp_server".join(' ',@sendmail_parameters)."\n"; 575} 576print"From:$sanitized_sender\nSubject:$subject\nCc:$cc\nTo:$to\n\n"; 577if($smtp) { 578print"Result: ",$smtp->code,' ', 579($smtp->message=~/\n([^\n]+\n)$/s),"\n"; 580}else{ 581print"Result: OK\n"; 582} 583} 584} 585 586$reply_to=$initial_reply_to; 587$references=$initial_reply_to||''; 588$subject=$initial_subject; 589 590foreachmy$t(@files) { 591open(F,"<",$t)or die"can't open file$t"; 592 593my$author=undef; 594@cc=@initial_cc; 595@xh= (); 596my$input_format=undef; 597my$header_done=0; 598$message=""; 599while(<F>) { 600if(!$header_done) { 601if(/^From /) { 602$input_format='mbox'; 603next; 604} 605chomp; 606if(!defined$input_format&&/^[-A-Za-z]+:\s/) { 607$input_format='mbox'; 608} 609 610if(defined$input_format&&$input_formateq'mbox') { 611if(/^Subject:\s+(.*)$/) { 612$subject=$1; 613 614}elsif(/^(Cc|From):\s+(.*)$/) { 615if(unquote_rfc2047($2)eq$sender) { 616next if($suppress_from); 617} 618elsif($1eq'From') { 619$author= unquote_rfc2047($2); 620} 621printf("(mbox) Adding cc:%sfrom line '%s'\n", 622$2,$_)unless$quiet; 623push@cc,$2; 624} 625elsif(!/^Date:\s/&&/^[-A-Za-z]+:\s+\S/) { 626push@xh,$_; 627} 628 629}else{ 630# In the traditional 631# "send lots of email" format, 632# line 1 = cc 633# line 2 = subject 634# So let's support that, too. 635$input_format='lots'; 636if(@cc==0) { 637printf("(non-mbox) Adding cc:%sfrom line '%s'\n", 638$_,$_)unless$quiet; 639 640push@cc,$_; 641 642}elsif(!defined$subject) { 643$subject=$_; 644} 645} 646 647# A whitespace line will terminate the headers 648if(m/^\s*$/) { 649$header_done=1; 650} 651}else{ 652$message.=$_; 653if(/^(Signed-off-by|Cc): (.*)$/i&&$signed_off_cc) { 654my$c=$2; 655chomp$c; 656push@cc,$c; 657printf("(sob) Adding cc:%sfrom line '%s'\n", 658$c,$_)unless$quiet; 659} 660} 661} 662close F; 663 664if($cc_cmdne"") { 665open(F,"$cc_cmd$t|") 666or die"(cc-cmd) Could not execute '$cc_cmd'"; 667while(<F>) { 668my$c=$_; 669$c=~s/^\s*//g; 670$c=~s/\n$//g; 671push@cc,$c; 672printf("(cc-cmd) Adding cc:%sfrom: '%s'\n", 673$c,$cc_cmd)unless$quiet; 674} 675close F 676or die"(cc-cmd) failed to close pipe to '$cc_cmd'"; 677} 678 679if(defined$author) { 680$message="From:$author\n\n$message"; 681} 682 683 send_message(); 684 685# set up for the next message 686if($chain_reply_to|| !defined$reply_to||length($reply_to) ==0) { 687$reply_to=$message_id; 688if(length$references>0) { 689$references.="\n$message_id"; 690}else{ 691$references="$message_id"; 692} 693} 694} 695 696if($compose) { 697 cleanup_compose_files(); 698} 699 700sub cleanup_compose_files() { 701unlink($compose_filename,$compose_filename.".final"); 702 703} 704 705$smtp->quitif$smtp; 706 707sub unique_email_list(@) { 708my%seen; 709my@emails; 710 711foreachmy$entry(@_) { 712if(my$clean= extract_valid_address($entry)) { 713$seen{$clean} ||=0; 714next if$seen{$clean}++; 715push@emails,$entry; 716}else{ 717print STDERR "W: unable to extract a valid address", 718" from:$entry\n"; 719} 720} 721return@emails; 722}