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