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