THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

2026 lines
57KB

  1. #!/usr/bin/perl
  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. use 5.008;
  19. use strict;
  20. use warnings;
  21. use POSIX qw/strftime/;
  22. use Term::ReadLine;
  23. use Getopt::Long;
  24. use Text::ParseWords;
  25. use Term::ANSIColor;
  26. use File::Temp qw/ tempdir tempfile /;
  27. use File::Spec::Functions qw(catdir catfile);
  28. use Git::LoadCPAN::Error qw(:try);
  29. use Cwd qw(abs_path cwd);
  30. use Git;
  31. use Git::I18N;
  32. use Net::Domain ();
  33. use Net::SMTP ();
  34. use Git::LoadCPAN::Mail::Address;
  35. Getopt::Long::Configure qw/ pass_through /;
  36. package FakeTerm;
  37. sub new {
  38. my ($class, $reason) = @_;
  39. return bless \$reason, shift;
  40. }
  41. sub readline {
  42. my $self = shift;
  43. die "Cannot use readline on FakeTerm: $$self";
  44. }
  45. package main;
  46. sub usage {
  47. print <<EOT;
  48. git send-email [options] <file | directory | rev-list options >
  49. git send-email --dump-aliases
  50. Composing:
  51. --from <str> * Email From:
  52. --[no-]to <str> * Email To:
  53. --[no-]cc <str> * Email Cc:
  54. --[no-]bcc <str> * Email Bcc:
  55. --subject <str> * Email "Subject:"
  56. --reply-to <str> * Email "Reply-To:"
  57. --in-reply-to <str> * Email "In-Reply-To:"
  58. --[no-]xmailer * Add "X-Mailer:" header (default).
  59. --[no-]annotate * Review each patch that will be sent in an editor.
  60. --compose * Open an editor for introduction.
  61. --compose-encoding <str> * Encoding to assume for introduction.
  62. --8bit-encoding <str> * Encoding to assume 8bit mails if undeclared
  63. --transfer-encoding <str> * Transfer encoding to use (quoted-printable, 8bit, base64)
  64. Sending:
  65. --envelope-sender <str> * Email envelope sender.
  66. --smtp-server <str:int> * Outgoing SMTP server to use. The port
  67. is optional. Default 'localhost'.
  68. --smtp-server-option <str> * Outgoing SMTP server option to use.
  69. --smtp-server-port <int> * Outgoing SMTP server port.
  70. --smtp-user <str> * Username for SMTP-AUTH.
  71. --smtp-pass <str> * Password for SMTP-AUTH; not necessary.
  72. --smtp-encryption <str> * tls or ssl; anything else disables.
  73. --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'.
  74. --smtp-ssl-cert-path <str> * Path to ca-certificates (either directory or file).
  75. Pass an empty string to disable certificate
  76. verification.
  77. --smtp-domain <str> * The domain name sent to HELO/EHLO handshake
  78. --smtp-auth <str> * Space-separated list of allowed AUTH mechanisms, or
  79. "none" to disable authentication.
  80. This setting forces to use one of the listed mechanisms.
  81. --no-smtp-auth Disable SMTP authentication. Shorthand for
  82. `--smtp-auth=none`
  83. --smtp-debug <0|1> * Disable, enable Net::SMTP debug.
  84. --batch-size <int> * send max <int> message per connection.
  85. --relogin-delay <int> * delay <int> seconds between two successive login.
  86. This option can only be used with --batch-size
  87. Automating:
  88. --identity <str> * Use the sendemail.<id> options.
  89. --to-cmd <str> * Email To: via `<str> \$patch_path`
  90. --cc-cmd <str> * Email Cc: via `<str> \$patch_path`
  91. --suppress-cc <str> * author, self, sob, cc, cccmd, body, bodycc, misc-by, all.
  92. --[no-]cc-cover * Email Cc: addresses in the cover letter.
  93. --[no-]to-cover * Email To: addresses in the cover letter.
  94. --[no-]signed-off-by-cc * Send to Signed-off-by: addresses. Default on.
  95. --[no-]suppress-from * Send to self. Default off.
  96. --[no-]chain-reply-to * Chain In-Reply-To: fields. Default off.
  97. --[no-]thread * Use In-Reply-To: field. Default on.
  98. Administering:
  99. --confirm <str> * Confirm recipients before sending;
  100. auto, cc, compose, always, or never.
  101. --quiet * Output one line of info per email.
  102. --dry-run * Don't actually send the emails.
  103. --[no-]validate * Perform patch sanity checks. Default on.
  104. --[no-]format-patch * understand any non optional arguments as
  105. `git format-patch` ones.
  106. --force * Send even if safety checks would prevent it.
  107. Information:
  108. --dump-aliases * Dump configured aliases and exit.
  109. EOT
  110. exit(1);
  111. }
  112. sub completion_helper {
  113. print Git::command('format-patch', '--git-completion-helper');
  114. exit(0);
  115. }
  116. # most mail servers generate the Date: header, but not all...
  117. sub 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. return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
  140. qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
  141. $localtm[3],
  142. qw(Jan Feb Mar Apr May Jun
  143. Jul Aug Sep Oct Nov Dec)[$localtm[4]],
  144. $localtm[5]+1900,
  145. $localtm[2],
  146. $localtm[1],
  147. $localtm[0],
  148. ($offset >= 0) ? '+' : '-',
  149. abs($offhour),
  150. $offmin,
  151. );
  152. }
  153. my $have_email_valid = eval { require Email::Valid; 1 };
  154. my $smtp;
  155. my $auth;
  156. my $num_sent = 0;
  157. # Regexes for RFC 2047 productions.
  158. my $re_token = qr/[^][()<>@,;:\\"\/?.= \000-\037\177-\377]+/;
  159. my $re_encoded_text = qr/[^? \000-\037\177-\377]+/;
  160. my $re_encoded_word = qr/=\?($re_token)\?($re_token)\?($re_encoded_text)\?=/;
  161. # Variables we fill in automatically, or via prompting:
  162. my (@to,@cc,@xh,$envelope_sender,
  163. $initial_in_reply_to,$reply_to,$initial_subject,@files,
  164. $author,$sender,$smtp_authpass,$annotate,$compose,$time);
  165. # Things we either get from config, *or* are overridden on the
  166. # command-line.
  167. my ($no_cc, $no_to, $no_bcc, $no_identity);
  168. my (@config_to, @getopt_to);
  169. my (@config_cc, @getopt_cc);
  170. my (@config_bcc, @getopt_bcc);
  171. # Example reply to:
  172. #$initial_in_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
  173. my $repo = eval { Git->repository() };
  174. my @repo = $repo ? ($repo) : ();
  175. my $term = eval {
  176. $ENV{"GIT_SEND_EMAIL_NOTTY"}
  177. ? new Term::ReadLine 'git-send-email', \*STDIN, \*STDOUT
  178. : new Term::ReadLine 'git-send-email';
  179. };
  180. if ($@) {
  181. $term = new FakeTerm "$@: going non-interactive";
  182. }
  183. # Behavior modification variables
  184. my ($quiet, $dry_run) = (0, 0);
  185. my $format_patch;
  186. my $compose_filename;
  187. my $force = 0;
  188. my $dump_aliases = 0;
  189. # Handle interactive edition of files.
  190. my $multiedit;
  191. my $editor;
  192. sub do_edit {
  193. if (!defined($editor)) {
  194. $editor = Git::command_oneline('var', 'GIT_EDITOR');
  195. }
  196. if (defined($multiedit) && !$multiedit) {
  197. map {
  198. system('sh', '-c', $editor.' "$@"', $editor, $_);
  199. if (($? & 127) || ($? >> 8)) {
  200. die(__("the editor exited uncleanly, aborting everything"));
  201. }
  202. } @_;
  203. } else {
  204. system('sh', '-c', $editor.' "$@"', $editor, @_);
  205. if (($? & 127) || ($? >> 8)) {
  206. die(__("the editor exited uncleanly, aborting everything"));
  207. }
  208. }
  209. }
  210. # Variables with corresponding config settings
  211. my ($suppress_from, $signed_off_by_cc);
  212. my ($cover_cc, $cover_to);
  213. my ($to_cmd, $cc_cmd);
  214. my ($smtp_server, $smtp_server_port, @smtp_server_options);
  215. my ($smtp_authuser, $smtp_encryption, $smtp_ssl_cert_path);
  216. my ($batch_size, $relogin_delay);
  217. my ($identity, $aliasfiletype, @alias_files, $smtp_domain, $smtp_auth);
  218. my ($confirm);
  219. my (@suppress_cc);
  220. my ($auto_8bit_encoding);
  221. my ($compose_encoding);
  222. # Variables with corresponding config settings & hardcoded defaults
  223. my ($debug_net_smtp) = 0; # Net::SMTP, see send_message()
  224. my $thread = 1;
  225. my $chain_reply_to = 0;
  226. my $use_xmailer = 1;
  227. my $validate = 1;
  228. my $target_xfer_encoding = 'auto';
  229. my %config_bool_settings = (
  230. "thread" => \$thread,
  231. "chainreplyto" => \$chain_reply_to,
  232. "suppressfrom" => \$suppress_from,
  233. "signedoffbycc" => \$signed_off_by_cc,
  234. "cccover" => \$cover_cc,
  235. "tocover" => \$cover_to,
  236. "signedoffcc" => \$signed_off_by_cc,
  237. "validate" => \$validate,
  238. "multiedit" => \$multiedit,
  239. "annotate" => \$annotate,
  240. "xmailer" => \$use_xmailer,
  241. );
  242. my %config_settings = (
  243. "smtpserver" => \$smtp_server,
  244. "smtpserverport" => \$smtp_server_port,
  245. "smtpserveroption" => \@smtp_server_options,
  246. "smtpuser" => \$smtp_authuser,
  247. "smtppass" => \$smtp_authpass,
  248. "smtpdomain" => \$smtp_domain,
  249. "smtpauth" => \$smtp_auth,
  250. "smtpbatchsize" => \$batch_size,
  251. "smtprelogindelay" => \$relogin_delay,
  252. "to" => \@config_to,
  253. "tocmd" => \$to_cmd,
  254. "cc" => \@config_cc,
  255. "cccmd" => \$cc_cmd,
  256. "aliasfiletype" => \$aliasfiletype,
  257. "bcc" => \@config_bcc,
  258. "suppresscc" => \@suppress_cc,
  259. "envelopesender" => \$envelope_sender,
  260. "confirm" => \$confirm,
  261. "from" => \$sender,
  262. "assume8bitencoding" => \$auto_8bit_encoding,
  263. "composeencoding" => \$compose_encoding,
  264. "transferencoding" => \$target_xfer_encoding,
  265. );
  266. my %config_path_settings = (
  267. "aliasesfile" => \@alias_files,
  268. "smtpsslcertpath" => \$smtp_ssl_cert_path,
  269. );
  270. # Handle Uncouth Termination
  271. sub signal_handler {
  272. # Make text normal
  273. print color("reset"), "\n";
  274. # SMTP password masked
  275. system "stty echo";
  276. # tmp files from --compose
  277. if (defined $compose_filename) {
  278. if (-e $compose_filename) {
  279. printf __("'%s' contains an intermediate version ".
  280. "of the email you were composing.\n"),
  281. $compose_filename;
  282. }
  283. if (-e ($compose_filename . ".final")) {
  284. printf __("'%s.final' contains the composed email.\n"),
  285. $compose_filename;
  286. }
  287. }
  288. exit;
  289. };
  290. $SIG{TERM} = \&signal_handler;
  291. $SIG{INT} = \&signal_handler;
  292. # Read our sendemail.* config
  293. sub read_config {
  294. my ($configured, $prefix) = @_;
  295. foreach my $setting (keys %config_bool_settings) {
  296. my $target = $config_bool_settings{$setting};
  297. my $v = Git::config_bool(@repo, "$prefix.$setting");
  298. next unless defined $v;
  299. next if $configured->{$setting}++;
  300. $$target = $v;
  301. }
  302. foreach my $setting (keys %config_path_settings) {
  303. my $target = $config_path_settings{$setting};
  304. if (ref($target) eq "ARRAY") {
  305. my @values = Git::config_path(@repo, "$prefix.$setting");
  306. next unless @values;
  307. next if $configured->{$setting}++;
  308. @$target = @values;
  309. }
  310. else {
  311. my $v = Git::config_path(@repo, "$prefix.$setting");
  312. next unless defined $v;
  313. next if $configured->{$setting}++;
  314. $$target = $v;
  315. }
  316. }
  317. foreach my $setting (keys %config_settings) {
  318. my $target = $config_settings{$setting};
  319. if (ref($target) eq "ARRAY") {
  320. my @values = Git::config(@repo, "$prefix.$setting");
  321. next unless @values;
  322. next if $configured->{$setting}++;
  323. @$target = @values;
  324. }
  325. else {
  326. my $v = Git::config(@repo, "$prefix.$setting");
  327. next unless defined $v;
  328. next if $configured->{$setting}++;
  329. $$target = $v;
  330. }
  331. }
  332. if (!defined $smtp_encryption) {
  333. my $setting = "$prefix.smtpencryption";
  334. my $enc = Git::config(@repo, $setting);
  335. return unless defined $enc;
  336. return if $configured->{$setting}++;
  337. if (defined $enc) {
  338. $smtp_encryption = $enc;
  339. } elsif (Git::config_bool(@repo, "$prefix.smtpssl")) {
  340. $smtp_encryption = 'ssl';
  341. }
  342. }
  343. }
  344. # sendemail.identity yields to --identity. We must parse this
  345. # special-case first before the rest of the config is read.
  346. $identity = Git::config(@repo, "sendemail.identity");
  347. my $rc = GetOptions(
  348. "identity=s" => \$identity,
  349. "no-identity" => \$no_identity,
  350. );
  351. usage() unless $rc;
  352. undef $identity if $no_identity;
  353. # Now we know enough to read the config
  354. {
  355. my %configured;
  356. read_config(\%configured, "sendemail.$identity") if defined $identity;
  357. read_config(\%configured, "sendemail");
  358. }
  359. # Begin by accumulating all the variables (defined above), that we will end up
  360. # needing, first, from the command line:
  361. my $help;
  362. my $git_completion_helper;
  363. $rc = GetOptions("h" => \$help,
  364. "dump-aliases" => \$dump_aliases);
  365. usage() unless $rc;
  366. die __("--dump-aliases incompatible with other options\n")
  367. if !$help and $dump_aliases and @ARGV;
  368. $rc = GetOptions(
  369. "sender|from=s" => \$sender,
  370. "in-reply-to=s" => \$initial_in_reply_to,
  371. "reply-to=s" => \$reply_to,
  372. "subject=s" => \$initial_subject,
  373. "to=s" => \@getopt_to,
  374. "to-cmd=s" => \$to_cmd,
  375. "no-to" => \$no_to,
  376. "cc=s" => \@getopt_cc,
  377. "no-cc" => \$no_cc,
  378. "bcc=s" => \@getopt_bcc,
  379. "no-bcc" => \$no_bcc,
  380. "chain-reply-to!" => \$chain_reply_to,
  381. "no-chain-reply-to" => sub {$chain_reply_to = 0},
  382. "smtp-server=s" => \$smtp_server,
  383. "smtp-server-option=s" => \@smtp_server_options,
  384. "smtp-server-port=s" => \$smtp_server_port,
  385. "smtp-user=s" => \$smtp_authuser,
  386. "smtp-pass:s" => \$smtp_authpass,
  387. "smtp-ssl" => sub { $smtp_encryption = 'ssl' },
  388. "smtp-encryption=s" => \$smtp_encryption,
  389. "smtp-ssl-cert-path=s" => \$smtp_ssl_cert_path,
  390. "smtp-debug:i" => \$debug_net_smtp,
  391. "smtp-domain:s" => \$smtp_domain,
  392. "smtp-auth=s" => \$smtp_auth,
  393. "no-smtp-auth" => sub {$smtp_auth = 'none'},
  394. "annotate!" => \$annotate,
  395. "no-annotate" => sub {$annotate = 0},
  396. "compose" => \$compose,
  397. "quiet" => \$quiet,
  398. "cc-cmd=s" => \$cc_cmd,
  399. "suppress-from!" => \$suppress_from,
  400. "no-suppress-from" => sub {$suppress_from = 0},
  401. "suppress-cc=s" => \@suppress_cc,
  402. "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc,
  403. "no-signed-off-cc|no-signed-off-by-cc" => sub {$signed_off_by_cc = 0},
  404. "cc-cover|cc-cover!" => \$cover_cc,
  405. "no-cc-cover" => sub {$cover_cc = 0},
  406. "to-cover|to-cover!" => \$cover_to,
  407. "no-to-cover" => sub {$cover_to = 0},
  408. "confirm=s" => \$confirm,
  409. "dry-run" => \$dry_run,
  410. "envelope-sender=s" => \$envelope_sender,
  411. "thread!" => \$thread,
  412. "no-thread" => sub {$thread = 0},
  413. "validate!" => \$validate,
  414. "no-validate" => sub {$validate = 0},
  415. "transfer-encoding=s" => \$target_xfer_encoding,
  416. "format-patch!" => \$format_patch,
  417. "no-format-patch" => sub {$format_patch = 0},
  418. "8bit-encoding=s" => \$auto_8bit_encoding,
  419. "compose-encoding=s" => \$compose_encoding,
  420. "force" => \$force,
  421. "xmailer!" => \$use_xmailer,
  422. "no-xmailer" => sub {$use_xmailer = 0},
  423. "batch-size=i" => \$batch_size,
  424. "relogin-delay=i" => \$relogin_delay,
  425. "git-completion-helper" => \$git_completion_helper,
  426. );
  427. # Munge any "either config or getopt, not both" variables
  428. my @initial_to = @getopt_to ? @getopt_to : ($no_to ? () : @config_to);
  429. my @initial_cc = @getopt_cc ? @getopt_cc : ($no_cc ? () : @config_cc);
  430. my @initial_bcc = @getopt_bcc ? @getopt_bcc : ($no_bcc ? () : @config_bcc);
  431. usage() if $help;
  432. completion_helper() if $git_completion_helper;
  433. unless ($rc) {
  434. usage();
  435. }
  436. die __("Cannot run git format-patch from outside a repository\n")
  437. if $format_patch and not $repo;
  438. die __("`batch-size` and `relogin` must be specified together " .
  439. "(via command-line or configuration option)\n")
  440. if defined $relogin_delay and not defined $batch_size;
  441. # 'default' encryption is none -- this only prevents a warning
  442. $smtp_encryption = '' unless (defined $smtp_encryption);
  443. # Set CC suppressions
  444. my(%suppress_cc);
  445. if (@suppress_cc) {
  446. foreach my $entry (@suppress_cc) {
  447. # Please update $__git_send_email_suppresscc_options
  448. # in git-completion.bash when you add new options.
  449. die sprintf(__("Unknown --suppress-cc field: '%s'\n"), $entry)
  450. unless $entry =~ /^(?:all|cccmd|cc|author|self|sob|body|bodycc|misc-by)$/;
  451. $suppress_cc{$entry} = 1;
  452. }
  453. }
  454. if ($suppress_cc{'all'}) {
  455. foreach my $entry (qw (cccmd cc author self sob body bodycc misc-by)) {
  456. $suppress_cc{$entry} = 1;
  457. }
  458. delete $suppress_cc{'all'};
  459. }
  460. # If explicit old-style ones are specified, they trump --suppress-cc.
  461. $suppress_cc{'self'} = $suppress_from if defined $suppress_from;
  462. $suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc;
  463. if ($suppress_cc{'body'}) {
  464. foreach my $entry (qw (sob bodycc misc-by)) {
  465. $suppress_cc{$entry} = 1;
  466. }
  467. delete $suppress_cc{'body'};
  468. }
  469. # Set confirm's default value
  470. my $confirm_unconfigured = !defined $confirm;
  471. if ($confirm_unconfigured) {
  472. $confirm = scalar %suppress_cc ? 'compose' : 'auto';
  473. };
  474. # Please update $__git_send_email_confirm_options in
  475. # git-completion.bash when you add new options.
  476. die sprintf(__("Unknown --confirm setting: '%s'\n"), $confirm)
  477. unless $confirm =~ /^(?:auto|cc|compose|always|never)/;
  478. # Debugging, print out the suppressions.
  479. if (0) {
  480. print "suppressions:\n";
  481. foreach my $entry (keys %suppress_cc) {
  482. printf " %-5s -> $suppress_cc{$entry}\n", $entry;
  483. }
  484. }
  485. my ($repoauthor, $repocommitter);
  486. ($repoauthor) = Git::ident_person(@repo, 'author');
  487. ($repocommitter) = Git::ident_person(@repo, 'committer');
  488. sub parse_address_line {
  489. return map { $_->format } Mail::Address->parse($_[0]);
  490. }
  491. sub split_addrs {
  492. return quotewords('\s*,\s*', 1, @_);
  493. }
  494. my %aliases;
  495. sub parse_sendmail_alias {
  496. local $_ = shift;
  497. if (/"/) {
  498. printf STDERR __("warning: sendmail alias with quotes is not supported: %s\n"), $_;
  499. } elsif (/:include:/) {
  500. printf STDERR __("warning: `:include:` not supported: %s\n"), $_;
  501. } elsif (/[\/|]/) {
  502. printf STDERR __("warning: `/file` or `|pipe` redirection not supported: %s\n"), $_;
  503. } elsif (/^(\S+?)\s*:\s*(.+)$/) {
  504. my ($alias, $addr) = ($1, $2);
  505. $aliases{$alias} = [ split_addrs($addr) ];
  506. } else {
  507. printf STDERR __("warning: sendmail line is not recognized: %s\n"), $_;
  508. }
  509. }
  510. sub parse_sendmail_aliases {
  511. my $fh = shift;
  512. my $s = '';
  513. while (<$fh>) {
  514. chomp;
  515. next if /^\s*$/ || /^\s*#/;
  516. $s .= $_, next if $s =~ s/\\$// || s/^\s+//;
  517. parse_sendmail_alias($s) if $s;
  518. $s = $_;
  519. }
  520. $s =~ s/\\$//; # silently tolerate stray '\' on last line
  521. parse_sendmail_alias($s) if $s;
  522. }
  523. my %parse_alias = (
  524. # multiline formats can be supported in the future
  525. mutt => sub { my $fh = shift; while (<$fh>) {
  526. if (/^\s*alias\s+(?:-group\s+\S+\s+)*(\S+)\s+(.*)$/) {
  527. my ($alias, $addr) = ($1, $2);
  528. $addr =~ s/#.*$//; # mutt allows # comments
  529. # commas delimit multiple addresses
  530. my @addr = split_addrs($addr);
  531. # quotes may be escaped in the file,
  532. # unescape them so we do not double-escape them later.
  533. s/\\"/"/g foreach @addr;
  534. $aliases{$alias} = \@addr
  535. }}},
  536. mailrc => sub { my $fh = shift; while (<$fh>) {
  537. if (/^alias\s+(\S+)\s+(.*?)\s*$/) {
  538. # spaces delimit multiple addresses
  539. $aliases{$1} = [ quotewords('\s+', 0, $2) ];
  540. }}},
  541. pine => sub { my $fh = shift; my $f='\t[^\t]*';
  542. for (my $x = ''; defined($x); $x = $_) {
  543. chomp $x;
  544. $x .= $1 while(defined($_ = <$fh>) && /^ +(.*)$/);
  545. $x =~ /^(\S+)$f\t\(?([^\t]+?)\)?(:?$f){0,2}$/ or next;
  546. $aliases{$1} = [ split_addrs($2) ];
  547. }},
  548. elm => sub { my $fh = shift;
  549. while (<$fh>) {
  550. if (/^(\S+)\s+=\s+[^=]+=\s(\S+)/) {
  551. my ($alias, $addr) = ($1, $2);
  552. $aliases{$alias} = [ split_addrs($addr) ];
  553. }
  554. } },
  555. sendmail => \&parse_sendmail_aliases,
  556. gnus => sub { my $fh = shift; while (<$fh>) {
  557. if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
  558. $aliases{$1} = [ $2 ];
  559. }}}
  560. # Please update _git_config() in git-completion.bash when you
  561. # add new MUAs.
  562. );
  563. if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
  564. foreach my $file (@alias_files) {
  565. open my $fh, '<', $file or die "opening $file: $!\n";
  566. $parse_alias{$aliasfiletype}->($fh);
  567. close $fh;
  568. }
  569. }
  570. if ($dump_aliases) {
  571. print "$_\n" for (sort keys %aliases);
  572. exit(0);
  573. }
  574. # is_format_patch_arg($f) returns 0 if $f names a patch, or 1 if
  575. # $f is a revision list specification to be passed to format-patch.
  576. sub is_format_patch_arg {
  577. return unless $repo;
  578. my $f = shift;
  579. try {
  580. $repo->command('rev-parse', '--verify', '--quiet', $f);
  581. if (defined($format_patch)) {
  582. return $format_patch;
  583. }
  584. die sprintf(__ <<EOF, $f, $f);
  585. File '%s' exists but it could also be the range of commits
  586. to produce patches for. Please disambiguate by...
  587. * Saying "./%s" if you mean a file; or
  588. * Giving --format-patch option if you mean a range.
  589. EOF
  590. } catch Git::Error::Command with {
  591. # Not a valid revision. Treat it as a filename.
  592. return 0;
  593. }
  594. }
  595. # Now that all the defaults are set, process the rest of the command line
  596. # arguments and collect up the files that need to be processed.
  597. my @rev_list_opts;
  598. while (defined(my $f = shift @ARGV)) {
  599. if ($f eq "--") {
  600. push @rev_list_opts, "--", @ARGV;
  601. @ARGV = ();
  602. } elsif (-d $f and !is_format_patch_arg($f)) {
  603. opendir my $dh, $f
  604. or die sprintf(__("Failed to opendir %s: %s"), $f, $!);
  605. push @files, grep { -f $_ } map { catfile($f, $_) }
  606. sort readdir $dh;
  607. closedir $dh;
  608. } elsif ((-f $f or -p $f) and !is_format_patch_arg($f)) {
  609. push @files, $f;
  610. } else {
  611. push @rev_list_opts, $f;
  612. }
  613. }
  614. if (@rev_list_opts) {
  615. die __("Cannot run git format-patch from outside a repository\n")
  616. unless $repo;
  617. push @files, $repo->command('format-patch', '-o', tempdir(CLEANUP => 1), @rev_list_opts);
  618. }
  619. @files = handle_backup_files(@files);
  620. if ($validate) {
  621. foreach my $f (@files) {
  622. unless (-p $f) {
  623. my $error = validate_patch($f, $target_xfer_encoding);
  624. $error and die sprintf(__("fatal: %s: %s\nwarning: no patches were sent\n"),
  625. $f, $error);
  626. }
  627. }
  628. }
  629. if (@files) {
  630. unless ($quiet) {
  631. print $_,"\n" for (@files);
  632. }
  633. } else {
  634. print STDERR __("\nNo patch files specified!\n\n");
  635. usage();
  636. }
  637. sub get_patch_subject {
  638. my $fn = shift;
  639. open (my $fh, '<', $fn);
  640. while (my $line = <$fh>) {
  641. next unless ($line =~ /^Subject: (.*)$/);
  642. close $fh;
  643. return "GIT: $1\n";
  644. }
  645. close $fh;
  646. die sprintf(__("No subject line in %s?"), $fn);
  647. }
  648. if ($compose) {
  649. # Note that this does not need to be secure, but we will make a small
  650. # effort to have it be unique
  651. $compose_filename = ($repo ?
  652. tempfile(".gitsendemail.msg.XXXXXX", DIR => $repo->repo_path()) :
  653. tempfile(".gitsendemail.msg.XXXXXX", DIR => "."))[1];
  654. open my $c, ">", $compose_filename
  655. or die sprintf(__("Failed to open for writing %s: %s"), $compose_filename, $!);
  656. my $tpl_sender = $sender || $repoauthor || $repocommitter || '';
  657. my $tpl_subject = $initial_subject || '';
  658. my $tpl_in_reply_to = $initial_in_reply_to || '';
  659. my $tpl_reply_to = $reply_to || '';
  660. print $c <<EOT1, Git::prefix_lines("GIT: ", __ <<EOT2), <<EOT3;
  661. From $tpl_sender # This line is ignored.
  662. EOT1
  663. Lines beginning in "GIT:" will be removed.
  664. Consider including an overall diffstat or table of contents
  665. for the patch you are writing.
  666. Clear the body content if you don't wish to send a summary.
  667. EOT2
  668. From: $tpl_sender
  669. Reply-To: $tpl_reply_to
  670. Subject: $tpl_subject
  671. In-Reply-To: $tpl_in_reply_to
  672. EOT3
  673. for my $f (@files) {
  674. print $c get_patch_subject($f);
  675. }
  676. close $c;
  677. if ($annotate) {
  678. do_edit($compose_filename, @files);
  679. } else {
  680. do_edit($compose_filename);
  681. }
  682. open $c, "<", $compose_filename
  683. or die sprintf(__("Failed to open %s: %s"), $compose_filename, $!);
  684. if (!defined $compose_encoding) {
  685. $compose_encoding = "UTF-8";
  686. }
  687. my %parsed_email;
  688. while (my $line = <$c>) {
  689. next if $line =~ m/^GIT:/;
  690. parse_header_line($line, \%parsed_email);
  691. if ($line =~ /^$/) {
  692. $parsed_email{'body'} = filter_body($c);
  693. }
  694. }
  695. close $c;
  696. open my $c2, ">", $compose_filename . ".final"
  697. or die sprintf(__("Failed to open %s.final: %s"), $compose_filename, $!);
  698. if ($parsed_email{'From'}) {
  699. $sender = delete($parsed_email{'From'});
  700. }
  701. if ($parsed_email{'In-Reply-To'}) {
  702. $initial_in_reply_to = delete($parsed_email{'In-Reply-To'});
  703. }
  704. if ($parsed_email{'Reply-To'}) {
  705. $reply_to = delete($parsed_email{'Reply-To'});
  706. }
  707. if ($parsed_email{'Subject'}) {
  708. $initial_subject = delete($parsed_email{'Subject'});
  709. print $c2 "Subject: " .
  710. quote_subject($initial_subject, $compose_encoding) .
  711. "\n";
  712. }
  713. if ($parsed_email{'MIME-Version'}) {
  714. print $c2 "MIME-Version: $parsed_email{'MIME-Version'}\n",
  715. "Content-Type: $parsed_email{'Content-Type'};\n",
  716. "Content-Transfer-Encoding: $parsed_email{'Content-Transfer-Encoding'}\n";
  717. delete($parsed_email{'MIME-Version'});
  718. delete($parsed_email{'Content-Type'});
  719. delete($parsed_email{'Content-Transfer-Encoding'});
  720. } elsif (file_has_nonascii($compose_filename)) {
  721. my $content_type = (delete($parsed_email{'Content-Type'}) or
  722. "text/plain; charset=$compose_encoding");
  723. print $c2 "MIME-Version: 1.0\n",
  724. "Content-Type: $content_type\n",
  725. "Content-Transfer-Encoding: 8bit\n";
  726. }
  727. # Preserve unknown headers
  728. foreach my $key (keys %parsed_email) {
  729. next if $key eq 'body';
  730. print $c2 "$key: $parsed_email{$key}";
  731. }
  732. if ($parsed_email{'body'}) {
  733. print $c2 "\n$parsed_email{'body'}\n";
  734. delete($parsed_email{'body'});
  735. } else {
  736. print __("Summary email is empty, skipping it\n");
  737. $compose = -1;
  738. }
  739. close $c2;
  740. } elsif ($annotate) {
  741. do_edit(@files);
  742. }
  743. sub ask {
  744. my ($prompt, %arg) = @_;
  745. my $valid_re = $arg{valid_re};
  746. my $default = $arg{default};
  747. my $confirm_only = $arg{confirm_only};
  748. my $resp;
  749. my $i = 0;
  750. return defined $default ? $default : undef
  751. unless defined $term->IN and defined fileno($term->IN) and
  752. defined $term->OUT and defined fileno($term->OUT);
  753. while ($i++ < 10) {
  754. $resp = $term->readline($prompt);
  755. if (!defined $resp) { # EOF
  756. print "\n";
  757. return defined $default ? $default : undef;
  758. }
  759. if ($resp eq '' and defined $default) {
  760. return $default;
  761. }
  762. if (!defined $valid_re or $resp =~ /$valid_re/) {
  763. return $resp;
  764. }
  765. if ($confirm_only) {
  766. my $yesno = $term->readline(
  767. # TRANSLATORS: please keep [y/N] as is.
  768. sprintf(__("Are you sure you want to use <%s> [y/N]? "), $resp));
  769. if (defined $yesno && $yesno =~ /y/i) {
  770. return $resp;
  771. }
  772. }
  773. }
  774. return;
  775. }
  776. sub parse_header_line {
  777. my $lines = shift;
  778. my $parsed_line = shift;
  779. my $addr_pat = join "|", qw(To Cc Bcc);
  780. foreach (split(/\n/, $lines)) {
  781. if (/^($addr_pat):\s*(.+)$/i) {
  782. $parsed_line->{$1} = [ parse_address_line($2) ];
  783. } elsif (/^([^:]*):\s*(.+)\s*$/i) {
  784. $parsed_line->{$1} = $2;
  785. }
  786. }
  787. }
  788. sub filter_body {
  789. my $c = shift;
  790. my $body = "";
  791. while (my $body_line = <$c>) {
  792. if ($body_line !~ m/^GIT:/) {
  793. $body .= $body_line;
  794. }
  795. }
  796. return $body;
  797. }
  798. my %broken_encoding;
  799. sub file_declares_8bit_cte {
  800. my $fn = shift;
  801. open (my $fh, '<', $fn);
  802. while (my $line = <$fh>) {
  803. last if ($line =~ /^$/);
  804. return 1 if ($line =~ /^Content-Transfer-Encoding: .*8bit.*$/);
  805. }
  806. close $fh;
  807. return 0;
  808. }
  809. foreach my $f (@files) {
  810. next unless (body_or_subject_has_nonascii($f)
  811. && !file_declares_8bit_cte($f));
  812. $broken_encoding{$f} = 1;
  813. }
  814. if (!defined $auto_8bit_encoding && scalar %broken_encoding) {
  815. print __("The following files are 8bit, but do not declare " .
  816. "a Content-Transfer-Encoding.\n");
  817. foreach my $f (sort keys %broken_encoding) {
  818. print " $f\n";
  819. }
  820. $auto_8bit_encoding = ask(__("Which 8bit encoding should I declare [UTF-8]? "),
  821. valid_re => qr/.{4}/, confirm_only => 1,
  822. default => "UTF-8");
  823. }
  824. if (!$force) {
  825. for my $f (@files) {
  826. if (get_patch_subject($f) =~ /\Q*** SUBJECT HERE ***\E/) {
  827. die sprintf(__("Refusing to send because the patch\n\t%s\n"
  828. . "has the template subject '*** SUBJECT HERE ***'. "
  829. . "Pass --force if you really want to send.\n"), $f);
  830. }
  831. }
  832. }
  833. if (defined $sender) {
  834. $sender =~ s/^\s+|\s+$//g;
  835. ($sender) = expand_aliases($sender);
  836. } else {
  837. $sender = $repoauthor || $repocommitter || '';
  838. }
  839. # $sender could be an already sanitized address
  840. # (e.g. sendemail.from could be manually sanitized by user).
  841. # But it's a no-op to run sanitize_address on an already sanitized address.
  842. $sender = sanitize_address($sender);
  843. my $to_whom = __("To whom should the emails be sent (if anyone)?");
  844. my $prompting = 0;
  845. if (!@initial_to && !defined $to_cmd) {
  846. my $to = ask("$to_whom ",
  847. default => "",
  848. valid_re => qr/\@.*\./, confirm_only => 1);
  849. push @initial_to, parse_address_line($to) if defined $to; # sanitized/validated later
  850. $prompting++;
  851. }
  852. sub expand_aliases {
  853. return map { expand_one_alias($_) } @_;
  854. }
  855. my %EXPANDED_ALIASES;
  856. sub expand_one_alias {
  857. my $alias = shift;
  858. if ($EXPANDED_ALIASES{$alias}) {
  859. die sprintf(__("fatal: alias '%s' expands to itself\n"), $alias);
  860. }
  861. local $EXPANDED_ALIASES{$alias} = 1;
  862. return $aliases{$alias} ? expand_aliases(@{$aliases{$alias}}) : $alias;
  863. }
  864. @initial_to = process_address_list(@initial_to);
  865. @initial_cc = process_address_list(@initial_cc);
  866. @initial_bcc = process_address_list(@initial_bcc);
  867. if ($thread && !defined $initial_in_reply_to && $prompting) {
  868. $initial_in_reply_to = ask(
  869. __("Message-ID to be used as In-Reply-To for the first email (if any)? "),
  870. default => "",
  871. valid_re => qr/\@.*\./, confirm_only => 1);
  872. }
  873. if (defined $initial_in_reply_to) {
  874. $initial_in_reply_to =~ s/^\s*<?//;
  875. $initial_in_reply_to =~ s/>?\s*$//;
  876. $initial_in_reply_to = "<$initial_in_reply_to>" if $initial_in_reply_to ne '';
  877. }
  878. if (defined $reply_to) {
  879. $reply_to =~ s/^\s+|\s+$//g;
  880. ($reply_to) = expand_aliases($reply_to);
  881. $reply_to = sanitize_address($reply_to);
  882. }
  883. if (!defined $smtp_server) {
  884. my @sendmail_paths = qw( /usr/sbin/sendmail /usr/lib/sendmail );
  885. push @sendmail_paths, map {"$_/sendmail"} split /:/, $ENV{PATH};
  886. foreach (@sendmail_paths) {
  887. if (-x $_) {
  888. $smtp_server = $_;
  889. last;
  890. }
  891. }
  892. $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
  893. }
  894. if ($compose && $compose > 0) {
  895. @files = ($compose_filename . ".final", @files);
  896. }
  897. # Variables we set as part of the loop over files
  898. our ($message_id, %mail, $subject, $in_reply_to, $references, $message,
  899. $needs_confirm, $message_num, $ask_default);
  900. sub extract_valid_address {
  901. my $address = shift;
  902. my $local_part_regexp = qr/[^<>"\s@]+/;
  903. my $domain_regexp = qr/[^.<>"\s@]+(?:\.[^.<>"\s@]+)+/;
  904. # check for a local address:
  905. return $address if ($address =~ /^($local_part_regexp)$/);
  906. $address =~ s/^\s*<(.*)>\s*$/$1/;
  907. if ($have_email_valid) {
  908. return scalar Email::Valid->address($address);
  909. }
  910. # less robust/correct than the monster regexp in Email::Valid,
  911. # but still does a 99% job, and one less dependency
  912. return $1 if $address =~ /($local_part_regexp\@$domain_regexp)/;
  913. return;
  914. }
  915. sub extract_valid_address_or_die {
  916. my $address = shift;
  917. $address = extract_valid_address($address);
  918. die sprintf(__("error: unable to extract a valid address from: %s\n"), $address)
  919. if !$address;
  920. return $address;
  921. }
  922. sub validate_address {
  923. my $address = shift;
  924. while (!extract_valid_address($address)) {
  925. printf STDERR __("error: unable to extract a valid address from: %s\n"), $address;
  926. # TRANSLATORS: Make sure to include [q] [d] [e] in your
  927. # translation. The program will only accept English input
  928. # at this point.
  929. $_ = ask(__("What to do with this address? ([q]uit|[d]rop|[e]dit): "),
  930. valid_re => qr/^(?:quit|q|drop|d|edit|e)/i,
  931. default => 'q');
  932. if (/^d/i) {
  933. return undef;
  934. } elsif (/^q/i) {
  935. cleanup_compose_files();
  936. exit(0);
  937. }
  938. $address = ask("$to_whom ",
  939. default => "",
  940. valid_re => qr/\@.*\./, confirm_only => 1);
  941. }
  942. return $address;
  943. }
  944. sub validate_address_list {
  945. return (grep { defined $_ }
  946. map { validate_address($_) } @_);
  947. }
  948. # Usually don't need to change anything below here.
  949. # we make a "fake" message id by taking the current number
  950. # of seconds since the beginning of Unix time and tacking on
  951. # a random number to the end, in case we are called quicker than
  952. # 1 second since the last time we were called.
  953. # We'll setup a template for the message id, using the "from" address:
  954. my ($message_id_stamp, $message_id_serial);
  955. sub make_message_id {
  956. my $uniq;
  957. if (!defined $message_id_stamp) {
  958. $message_id_stamp = strftime("%Y%m%d%H%M%S.$$", gmtime(time));
  959. $message_id_serial = 0;
  960. }
  961. $message_id_serial++;
  962. $uniq = "$message_id_stamp-$message_id_serial";
  963. my $du_part;
  964. for ($sender, $repocommitter, $repoauthor) {
  965. $du_part = extract_valid_address(sanitize_address($_));
  966. last if (defined $du_part and $du_part ne '');
  967. }
  968. if (not defined $du_part or $du_part eq '') {
  969. require Sys::Hostname;
  970. $du_part = 'user@' . Sys::Hostname::hostname();
  971. }
  972. my $message_id_template = "<%s-%s>";
  973. $message_id = sprintf($message_id_template, $uniq, $du_part);
  974. #print "new message id = $message_id\n"; # Was useful for debugging
  975. }
  976. $time = time - scalar $#files;
  977. sub unquote_rfc2047 {
  978. local ($_) = @_;
  979. my $charset;
  980. my $sep = qr/[ \t]+/;
  981. s{$re_encoded_word(?:$sep$re_encoded_word)*}{
  982. my @words = split $sep, $&;
  983. foreach (@words) {
  984. m/$re_encoded_word/;
  985. $charset = $1;
  986. my $encoding = $2;
  987. my $text = $3;
  988. if ($encoding eq 'q' || $encoding eq 'Q') {
  989. $_ = $text;
  990. s/_/ /g;
  991. s/=([0-9A-F]{2})/chr(hex($1))/egi;
  992. } else {
  993. # other encodings not supported yet
  994. }
  995. }
  996. join '', @words;
  997. }eg;
  998. return wantarray ? ($_, $charset) : $_;
  999. }
  1000. sub quote_rfc2047 {
  1001. local $_ = shift;
  1002. my $encoding = shift || 'UTF-8';
  1003. s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
  1004. s/(.*)/=\?$encoding\?q\?$1\?=/;
  1005. return $_;
  1006. }
  1007. sub is_rfc2047_quoted {
  1008. my $s = shift;
  1009. length($s) <= 75 &&
  1010. $s =~ m/^(?:"[[:ascii:]]*"|$re_encoded_word)$/o;
  1011. }
  1012. sub subject_needs_rfc2047_quoting {
  1013. my $s = shift;
  1014. return ($s =~ /[^[:ascii:]]/) || ($s =~ /=\?/);
  1015. }
  1016. sub quote_subject {
  1017. local $subject = shift;
  1018. my $encoding = shift || 'UTF-8';
  1019. if (subject_needs_rfc2047_quoting($subject)) {
  1020. return quote_rfc2047($subject, $encoding);
  1021. }
  1022. return $subject;
  1023. }
  1024. # use the simplest quoting being able to handle the recipient
  1025. sub sanitize_address {
  1026. my ($recipient) = @_;
  1027. # remove garbage after email address
  1028. $recipient =~ s/(.*>).*$/$1/;
  1029. my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
  1030. if (not $recipient_name) {
  1031. return $recipient;
  1032. }
  1033. # if recipient_name is already quoted, do nothing
  1034. if (is_rfc2047_quoted($recipient_name)) {
  1035. return $recipient;
  1036. }
  1037. # remove non-escaped quotes
  1038. $recipient_name =~ s/(^|[^\\])"/$1/g;
  1039. # rfc2047 is needed if a non-ascii char is included
  1040. if ($recipient_name =~ /[^[:ascii:]]/) {
  1041. $recipient_name = quote_rfc2047($recipient_name);
  1042. }
  1043. # double quotes are needed if specials or CTLs are included
  1044. elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
  1045. $recipient_name =~ s/([\\\r])/\\$1/g;
  1046. $recipient_name = qq["$recipient_name"];
  1047. }
  1048. return "$recipient_name $recipient_addr";
  1049. }
  1050. sub strip_garbage_one_address {
  1051. my ($addr) = @_;
  1052. chomp $addr;
  1053. if ($addr =~ /^(("[^"]*"|[^"<]*)? *<[^>]*>).*/) {
  1054. # "Foo Bar" <foobar@example.com> [possibly garbage here]
  1055. # Foo Bar <foobar@example.com> [possibly garbage here]
  1056. return $1;
  1057. }
  1058. if ($addr =~ /^(<[^>]*>).*/) {
  1059. # <foo@example.com> [possibly garbage here]
  1060. # if garbage contains other addresses, they are ignored.
  1061. return $1;
  1062. }
  1063. if ($addr =~ /^([^"#,\s]*)/) {
  1064. # address without quoting: remove anything after the address
  1065. return $1;
  1066. }
  1067. return $addr;
  1068. }
  1069. sub sanitize_address_list {
  1070. return (map { sanitize_address($_) } @_);
  1071. }
  1072. sub process_address_list {
  1073. my @addr_list = map { parse_address_line($_) } @_;
  1074. @addr_list = expand_aliases(@addr_list);
  1075. @addr_list = sanitize_address_list(@addr_list);
  1076. @addr_list = validate_address_list(@addr_list);
  1077. return @addr_list;
  1078. }
  1079. # Returns the local Fully Qualified Domain Name (FQDN) if available.
  1080. #
  1081. # Tightly configured MTAa require that a caller sends a real DNS
  1082. # domain name that corresponds the IP address in the HELO/EHLO
  1083. # handshake. This is used to verify the connection and prevent
  1084. # spammers from trying to hide their identity. If the DNS and IP don't
  1085. # match, the receiveing MTA may deny the connection.
  1086. #
  1087. # Here is a deny example of Net::SMTP with the default "localhost.localdomain"
  1088. #
  1089. # Net::SMTP=GLOB(0x267ec28)>>> EHLO localhost.localdomain
  1090. # Net::SMTP=GLOB(0x267ec28)<<< 550 EHLO argument does not match calling host
  1091. #
  1092. # This maildomain*() code is based on ideas in Perl library Test::Reporter
  1093. # /usr/share/perl5/Test/Reporter/Mail/Util.pm ==> sub _maildomain ()
  1094. sub valid_fqdn {
  1095. my $domain = shift;
  1096. return defined $domain && !($^O eq 'darwin' && $domain =~ /\.local$/) && $domain =~ /\./;
  1097. }
  1098. sub maildomain_net {
  1099. my $maildomain;
  1100. my $domain = Net::Domain::domainname();
  1101. $maildomain = $domain if valid_fqdn($domain);
  1102. return $maildomain;
  1103. }
  1104. sub maildomain_mta {
  1105. my $maildomain;
  1106. for my $host (qw(mailhost localhost)) {
  1107. my $smtp = Net::SMTP->new($host);
  1108. if (defined $smtp) {
  1109. my $domain = $smtp->domain;
  1110. $smtp->quit;
  1111. $maildomain = $domain if valid_fqdn($domain);
  1112. last if $maildomain;
  1113. }
  1114. }
  1115. return $maildomain;
  1116. }
  1117. sub maildomain {
  1118. return maildomain_net() || maildomain_mta() || 'localhost.localdomain';
  1119. }
  1120. sub smtp_host_string {
  1121. if (defined $smtp_server_port) {
  1122. return "$smtp_server:$smtp_server_port";
  1123. } else {
  1124. return $smtp_server;
  1125. }
  1126. }
  1127. # Returns 1 if authentication succeeded or was not necessary
  1128. # (smtp_user was not specified), and 0 otherwise.
  1129. sub smtp_auth_maybe {
  1130. if (!defined $smtp_authuser || $auth || (defined $smtp_auth && $smtp_auth eq "none")) {
  1131. return 1;
  1132. }
  1133. # Workaround AUTH PLAIN/LOGIN interaction defect
  1134. # with Authen::SASL::Cyrus
  1135. eval {
  1136. require Authen::SASL;
  1137. Authen::SASL->import(qw(Perl));
  1138. };
  1139. # Check mechanism naming as defined in:
  1140. # https://tools.ietf.org/html/rfc4422#page-8
  1141. if ($smtp_auth && $smtp_auth !~ /^(\b[A-Z0-9-_]{1,20}\s*)*$/) {
  1142. die "invalid smtp auth: '${smtp_auth}'";
  1143. }
  1144. # TODO: Authentication may fail not because credentials were
  1145. # invalid but due to other reasons, in which we should not
  1146. # reject credentials.
  1147. $auth = Git::credential({
  1148. 'protocol' => 'smtp',
  1149. 'host' => smtp_host_string(),
  1150. 'username' => $smtp_authuser,
  1151. # if there's no password, "git credential fill" will
  1152. # give us one, otherwise it'll just pass this one.
  1153. 'password' => $smtp_authpass
  1154. }, sub {
  1155. my $cred = shift;
  1156. if ($smtp_auth) {
  1157. my $sasl = Authen::SASL->new(
  1158. mechanism => $smtp_auth,
  1159. callback => {
  1160. user => $cred->{'username'},
  1161. pass => $cred->{'password'},
  1162. authname => $cred->{'username'},
  1163. }
  1164. );
  1165. return !!$smtp->auth($sasl);
  1166. }
  1167. return !!$smtp->auth($cred->{'username'}, $cred->{'password'});
  1168. });
  1169. return $auth;
  1170. }
  1171. sub ssl_verify_params {
  1172. eval {
  1173. require IO::Socket::SSL;
  1174. IO::Socket::SSL->import(qw/SSL_VERIFY_PEER SSL_VERIFY_NONE/);
  1175. };
  1176. if ($@) {
  1177. print STDERR "Not using SSL_VERIFY_PEER due to out-of-date IO::Socket::SSL.\n";
  1178. return;
  1179. }
  1180. if (!defined $smtp_ssl_cert_path) {
  1181. # use the OpenSSL defaults
  1182. return (SSL_verify_mode => SSL_VERIFY_PEER());
  1183. }
  1184. if ($smtp_ssl_cert_path eq "") {
  1185. return (SSL_verify_mode => SSL_VERIFY_NONE());
  1186. } elsif (-d $smtp_ssl_cert_path) {
  1187. return (SSL_verify_mode => SSL_VERIFY_PEER(),
  1188. SSL_ca_path => $smtp_ssl_cert_path);
  1189. } elsif (-f $smtp_ssl_cert_path) {
  1190. return (SSL_verify_mode => SSL_VERIFY_PEER(),
  1191. SSL_ca_file => $smtp_ssl_cert_path);
  1192. } else {
  1193. die sprintf(__("CA path \"%s\" does not exist"), $smtp_ssl_cert_path);
  1194. }
  1195. }
  1196. sub file_name_is_absolute {
  1197. my ($path) = @_;
  1198. # msys does not grok DOS drive-prefixes
  1199. if ($^O eq 'msys') {
  1200. return ($path =~ m#^/# || $path =~ m#^[a-zA-Z]\:#)
  1201. }
  1202. require File::Spec::Functions;
  1203. return File::Spec::Functions::file_name_is_absolute($path);
  1204. }
  1205. # Prepares the email, then asks the user what to do.
  1206. #
  1207. # If the user chooses to send the email, it's sent and 1 is returned.
  1208. # If the user chooses not to send the email, 0 is returned.
  1209. # If the user decides they want to make further edits, -1 is returned and the
  1210. # caller is expected to call send_message again after the edits are performed.
  1211. #
  1212. # If an error occurs sending the email, this just dies.
  1213. sub send_message {
  1214. my @recipients = unique_email_list(@to);
  1215. @cc = (grep { my $cc = extract_valid_address_or_die($_);
  1216. not grep { $cc eq $_ || $_ =~ /<\Q${cc}\E>$/ } @recipients
  1217. }
  1218. @cc);
  1219. my $to = join (",\n\t", @recipients);
  1220. @recipients = unique_email_list(@recipients,@cc,@initial_bcc);
  1221. @recipients = (map { extract_valid_address_or_die($_) } @recipients);
  1222. my $date = format_2822_time($time++);
  1223. my $gitversion = '@@GIT_VERSION@@';
  1224. if ($gitversion =~ m/..GIT_VERSION../) {
  1225. $gitversion = Git::version();
  1226. }
  1227. my $cc = join(",\n\t", unique_email_list(@cc));
  1228. my $ccline = "";
  1229. if ($cc ne '') {
  1230. $ccline = "\nCc: $cc";
  1231. }
  1232. make_message_id() unless defined($message_id);
  1233. my $header = "From: $sender
  1234. To: $to${ccline}
  1235. Subject: $subject
  1236. Date: $date
  1237. Message-Id: $message_id
  1238. ";
  1239. if ($use_xmailer) {
  1240. $header .= "X-Mailer: git-send-email $gitversion\n";
  1241. }
  1242. if ($in_reply_to) {
  1243. $header .= "In-Reply-To: $in_reply_to\n";
  1244. $header .= "References: $references\n";
  1245. }
  1246. if ($reply_to) {
  1247. $header .= "Reply-To: $reply_to\n";
  1248. }
  1249. if (@xh) {
  1250. $header .= join("\n", @xh) . "\n";
  1251. }
  1252. my @sendmail_parameters = ('-i', @recipients);
  1253. my $raw_from = $sender;
  1254. if (defined $envelope_sender && $envelope_sender ne "auto") {
  1255. $raw_from = $envelope_sender;
  1256. }
  1257. $raw_from = extract_valid_address($raw_from);
  1258. unshift (@sendmail_parameters,
  1259. '-f', $raw_from) if(defined $envelope_sender);
  1260. if ($needs_confirm && !$dry_run) {
  1261. print "\n$header\n";
  1262. if ($needs_confirm eq "inform") {
  1263. $confirm_unconfigured = 0; # squelch this message for the rest of this run
  1264. $ask_default = "y"; # assume yes on EOF since user hasn't explicitly asked for confirmation
  1265. print __ <<EOF ;
  1266. The Cc list above has been expanded by additional
  1267. addresses found in the patch commit message. By default
  1268. send-email prompts before sending whenever this occurs.
  1269. This behavior is controlled by the sendemail.confirm
  1270. configuration setting.
  1271. For additional information, run 'git send-email --help'.
  1272. To retain the current behavior, but squelch this message,
  1273. run 'git config --global sendemail.confirm auto'.
  1274. EOF
  1275. }
  1276. # TRANSLATORS: Make sure to include [y] [n] [e] [q] [a] in your
  1277. # translation. The program will only accept English input
  1278. # at this point.
  1279. $_ = ask(__("Send this email? ([y]es|[n]o|[e]dit|[q]uit|[a]ll): "),
  1280. valid_re => qr/^(?:yes|y|no|n|edit|e|quit|q|all|a)/i,
  1281. default => $ask_default);
  1282. die __("Send this email reply required") unless defined $_;
  1283. if (/^n/i) {
  1284. return 0;
  1285. } elsif (/^e/i) {
  1286. return -1;
  1287. } elsif (/^q/i) {
  1288. cleanup_compose_files();
  1289. exit(0);
  1290. } elsif (/^a/i) {
  1291. $confirm = 'never';
  1292. }
  1293. }
  1294. unshift (@sendmail_parameters, @smtp_server_options);
  1295. if ($dry_run) {
  1296. # We don't want to send the email.
  1297. } elsif (file_name_is_absolute($smtp_server)) {
  1298. my $pid = open my $sm, '|-';
  1299. defined $pid or die $!;
  1300. if (!$pid) {
  1301. exec($smtp_server, @sendmail_parameters) or die $!;
  1302. }
  1303. print $sm "$header\n$message";
  1304. close $sm or die $!;
  1305. } else {
  1306. if (!defined $smtp_server) {
  1307. die __("The required SMTP server is not properly defined.")
  1308. }
  1309. require Net::SMTP;
  1310. my $use_net_smtp_ssl = version->parse($Net::SMTP::VERSION) < version->parse("2.34");
  1311. $smtp_domain ||= maildomain();
  1312. if ($smtp_encryption eq 'ssl') {
  1313. $smtp_server_port ||= 465; # ssmtp
  1314. require IO::Socket::SSL;
  1315. # Suppress "variable accessed once" warning.
  1316. {
  1317. no warnings 'once';
  1318. $IO::Socket::SSL::DEBUG = 1;
  1319. }
  1320. # Net::SMTP::SSL->new() does not forward any SSL options
  1321. IO::Socket::SSL::set_client_defaults(
  1322. ssl_verify_params());
  1323. if ($use_net_smtp_ssl) {
  1324. require Net::SMTP::SSL;
  1325. $smtp ||= Net::SMTP::SSL->new($smtp_server,
  1326. Hello => $smtp_domain,
  1327. Port => $smtp_server_port,
  1328. Debug => $debug_net_smtp);
  1329. }
  1330. else {
  1331. $smtp ||= Net::SMTP->new($smtp_server,
  1332. Hello => $smtp_domain,
  1333. Port => $smtp_server_port,
  1334. Debug => $debug_net_smtp,
  1335. SSL => 1);
  1336. }
  1337. }
  1338. elsif (!$smtp) {
  1339. $smtp_server_port ||= 25;
  1340. $smtp ||= Net::SMTP->new($smtp_server,
  1341. Hello => $smtp_domain,
  1342. Debug => $debug_net_smtp,
  1343. Port => $smtp_server_port);
  1344. if ($smtp_encryption eq 'tls' && $smtp) {
  1345. if ($use_net_smtp_ssl) {
  1346. $smtp->command('STARTTLS');
  1347. $smtp->response();
  1348. if ($smtp->code != 220) {
  1349. die sprintf(__("Server does not support STARTTLS! %s"), $smtp->message);
  1350. }
  1351. require Net::SMTP::SSL;
  1352. $smtp = Net::SMTP::SSL->start_SSL($smtp,
  1353. ssl_verify_params())
  1354. or die sprintf(__("STARTTLS failed! %s"), IO::Socket::SSL::errstr());
  1355. }
  1356. else {
  1357. $smtp->starttls(ssl_verify_params())
  1358. or die sprintf(__("STARTTLS failed! %s"), IO::Socket::SSL::errstr());
  1359. }
  1360. # Send EHLO again to receive fresh
  1361. # supported commands
  1362. $smtp->hello($smtp_domain);
  1363. }
  1364. }
  1365. if (!$smtp) {
  1366. die __("Unable to initialize SMTP properly. Check config and use --smtp-debug."),
  1367. " VALUES: server=$smtp_server ",
  1368. "encryption=$smtp_encryption ",
  1369. "hello=$smtp_domain",
  1370. defined $smtp_server_port ? " port=$smtp_server_port" : "";
  1371. }
  1372. smtp_auth_maybe or die $smtp->message;
  1373. $smtp->mail( $raw_from ) or die $smtp->message;
  1374. $smtp->to( @recipients ) or die $smtp->message;
  1375. $smtp->data or die $smtp->message;
  1376. $smtp->datasend("$header\n") or die $smtp->message;
  1377. my @lines = split /^/, $message;
  1378. foreach my $line (@lines) {
  1379. $smtp->datasend("$line") or die $smtp->message;
  1380. }
  1381. $smtp->dataend() or die $smtp->message;
  1382. $smtp->code =~ /250|200/ or die sprintf(__("Failed to send %s\n"), $subject).$smtp->message;
  1383. }
  1384. if ($quiet) {
  1385. printf($dry_run ? __("Dry-Sent %s\n") : __("Sent %s\n"), $subject);
  1386. } else {
  1387. print($dry_run ? __("Dry-OK. Log says:\n") : __("OK. Log says:\n"));
  1388. if (!file_name_is_absolute($smtp_server)) {
  1389. print "Server: $smtp_server\n";
  1390. print "MAIL FROM:<$raw_from>\n";
  1391. foreach my $entry (@recipients) {
  1392. print "RCPT TO:<$entry>\n";
  1393. }
  1394. } else {
  1395. print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
  1396. }
  1397. print $header, "\n";
  1398. if ($smtp) {
  1399. print __("Result: "), $smtp->code, ' ',
  1400. ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
  1401. } else {
  1402. print __("Result: OK\n");
  1403. }
  1404. }
  1405. return 1;
  1406. }
  1407. $in_reply_to = $initial_in_reply_to;
  1408. $references = $initial_in_reply_to || '';
  1409. $subject = $initial_subject;
  1410. $message_num = 0;
  1411. # Prepares the email, prompts the user, sends it out
  1412. # Returns 0 if an edit was done and the function should be called again, or 1
  1413. # otherwise.
  1414. sub process_file {
  1415. my ($t) = @_;
  1416. open my $fh, "<", $t or die sprintf(__("can't open file %s"), $t);
  1417. my $author = undef;
  1418. my $sauthor = undef;
  1419. my $author_encoding;
  1420. my $has_content_type;
  1421. my $body_encoding;
  1422. my $xfer_encoding;
  1423. my $has_mime_version;
  1424. @to = ();
  1425. @cc = ();
  1426. @xh = ();
  1427. my $input_format = undef;
  1428. my @header = ();
  1429. $message = "";
  1430. $message_num++;
  1431. # First unfold multiline header fields
  1432. while(<$fh>) {
  1433. last if /^\s*$/;
  1434. if (/^\s+\S/ and @header) {
  1435. chomp($header[$#header]);
  1436. s/^\s+/ /;
  1437. $header[$#header] .= $_;
  1438. } else {
  1439. push(@header, $_);
  1440. }
  1441. }
  1442. # Now parse the header
  1443. foreach(@header) {
  1444. if (/^From /) {
  1445. $input_format = 'mbox';
  1446. next;
  1447. }
  1448. chomp;
  1449. if (!defined $input_format && /^[-A-Za-z]+:\s/) {
  1450. $input_format = 'mbox';
  1451. }
  1452. if (defined $input_format && $input_format eq 'mbox') {
  1453. if (/^Subject:\s+(.*)$/i) {
  1454. $subject = $1;
  1455. }
  1456. elsif (/^From:\s+(.*)$/i) {
  1457. ($author, $author_encoding) = unquote_rfc2047($1);
  1458. $sauthor = sanitize_address($author);
  1459. next if $suppress_cc{'author'};
  1460. next if $suppress_cc{'self'} and $sauthor eq $sender;
  1461. printf(__("(mbox) Adding cc: %s from line '%s'\n"),
  1462. $1, $_) unless $quiet;
  1463. push @cc, $1;
  1464. }
  1465. elsif (/^To:\s+(.*)$/i) {
  1466. foreach my $addr (parse_address_line($1)) {
  1467. printf(__("(mbox) Adding to: %s from line '%s'\n"),
  1468. $addr, $_) unless $quiet;
  1469. push @to, $addr;
  1470. }
  1471. }
  1472. elsif (/^Cc:\s+(.*)$/i) {
  1473. foreach my $addr (parse_address_line($1)) {
  1474. my $qaddr = unquote_rfc2047($addr);
  1475. my $saddr = sanitize_address($qaddr);
  1476. if ($saddr eq $sender) {
  1477. next if ($suppress_cc{'self'});
  1478. } else {
  1479. next if ($suppress_cc{'cc'});
  1480. }
  1481. printf(__("(mbox) Adding cc: %s from line '%s'\n"),
  1482. $addr, $_) unless $quiet;
  1483. push @cc, $addr;
  1484. }
  1485. }
  1486. elsif (/^Content-type:/i) {
  1487. $has_content_type = 1;
  1488. if (/charset="?([^ "]+)/) {
  1489. $body_encoding = $1;
  1490. }
  1491. push @xh, $_;
  1492. }
  1493. elsif (/^MIME-Version/i) {
  1494. $has_mime_version = 1;
  1495. push @xh, $_;
  1496. }
  1497. elsif (/^Message-Id: (.*)/i) {
  1498. $message_id = $1;
  1499. }
  1500. elsif (/^Content-Transfer-Encoding: (.*)/i) {
  1501. $xfer_encoding = $1 if not defined $xfer_encoding;
  1502. }
  1503. elsif (/^In-Reply-To: (.*)/i) {
  1504. $in_reply_to = $1;
  1505. }
  1506. elsif (/^References: (.*)/i) {
  1507. $references = $1;
  1508. }
  1509. elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
  1510. push @xh, $_;
  1511. }
  1512. } else {
  1513. # In the traditional
  1514. # "send lots of email" format,
  1515. # line 1 = cc
  1516. # line 2 = subject
  1517. # So let's support that, too.
  1518. $input_format = 'lots';
  1519. if (@cc == 0 && !$suppress_cc{'cc'}) {
  1520. printf(__("(non-mbox) Adding cc: %s from line '%s'\n"),
  1521. $_, $_) unless $quiet;
  1522. push @cc, $_;
  1523. } elsif (!defined $subject) {
  1524. $subject = $_;
  1525. }
  1526. }
  1527. }
  1528. # Now parse the message body
  1529. while(<$fh>) {
  1530. $message .= $_;
  1531. if (/^([a-z][a-z-]*-by|Cc): (.*)/i) {
  1532. chomp;
  1533. my ($what, $c) = ($1, $2);
  1534. # strip garbage for the address we'll use:
  1535. $c = strip_garbage_one_address($c);
  1536. # sanitize a bit more to decide whether to suppress the address:
  1537. my $sc = sanitize_address($c);
  1538. if ($sc eq $sender) {
  1539. next if ($suppress_cc{'self'});
  1540. } else {
  1541. if ($what =~ /^Signed-off-by$/i) {
  1542. next if $suppress_cc{'sob'};
  1543. } elsif ($what =~ /-by$/i) {
  1544. next if $suppress_cc{'misc-by'};
  1545. } elsif ($what =~ /Cc/i) {
  1546. next if $suppress_cc{'bodycc'};
  1547. }
  1548. }
  1549. if ($c !~ /.+@.+|<.+>/) {
  1550. printf("(body) Ignoring %s from line '%s'\n",
  1551. $what, $_) unless $quiet;
  1552. next;
  1553. }
  1554. push @cc, $c;
  1555. printf(__("(body) Adding cc: %s from line '%s'\n"),
  1556. $c, $_) unless $quiet;
  1557. }
  1558. }
  1559. close $fh;
  1560. push @to, recipients_cmd("to-cmd", "to", $to_cmd, $t)
  1561. if defined $to_cmd;
  1562. push @cc, recipients_cmd("cc-cmd", "cc", $cc_cmd, $t)
  1563. if defined $cc_cmd && !$suppress_cc{'cccmd'};
  1564. if ($broken_encoding{$t} && !$has_content_type) {
  1565. $xfer_encoding = '8bit' if not defined $xfer_encoding;
  1566. $has_content_type = 1;
  1567. push @xh, "Content-Type: text/plain; charset=$auto_8bit_encoding";
  1568. $body_encoding = $auto_8bit_encoding;
  1569. }
  1570. if ($broken_encoding{$t} && !is_rfc2047_quoted($subject)) {
  1571. $subject = quote_subject($subject, $auto_8bit_encoding);
  1572. }
  1573. if (defined $sauthor and $sauthor ne $sender) {
  1574. $message = "From: $author\n\n$message";
  1575. if (defined $author_encoding) {
  1576. if ($has_content_type) {
  1577. if ($body_encoding eq $author_encoding) {
  1578. # ok, we already have the right encoding
  1579. }
  1580. else {
  1581. # uh oh, we should re-encode
  1582. }
  1583. }
  1584. else {
  1585. $xfer_encoding = '8bit' if not defined $xfer_encoding;
  1586. $has_content_type = 1;
  1587. push @xh,
  1588. "Content-Type: text/plain; charset=$author_encoding";
  1589. }
  1590. }
  1591. }
  1592. $xfer_encoding = '8bit' if not defined $xfer_encoding;
  1593. ($message, $xfer_encoding) = apply_transfer_encoding(
  1594. $message, $xfer_encoding, $target_xfer_encoding);
  1595. push @xh, "Content-Transfer-Encoding: $xfer_encoding";
  1596. unshift @xh, 'MIME-Version: 1.0' unless $has_mime_version;
  1597. $needs_confirm = (
  1598. $confirm eq "always" or
  1599. ($confirm =~ /^(?:auto|cc)$/ && @cc) or
  1600. ($confirm =~ /^(?:auto|compose)$/ && $compose && $message_num == 1));
  1601. $needs_confirm = "inform" if ($needs_confirm && $confirm_unconfigured && @cc);
  1602. @to = process_address_list(@to);
  1603. @cc = process_address_list(@cc);
  1604. @to = (@initial_to, @to);
  1605. @cc = (@initial_cc, @cc);
  1606. if ($message_num == 1) {
  1607. if (defined $cover_cc and $cover_cc) {
  1608. @initial_cc = @cc;
  1609. }
  1610. if (defined $cover_to and $cover_to) {
  1611. @initial_to = @to;
  1612. }
  1613. }
  1614. my $message_was_sent = send_message();
  1615. if ($message_was_sent == -1) {
  1616. do_edit($t);
  1617. return 0;
  1618. }
  1619. # set up for the next message
  1620. if ($thread && $message_was_sent &&
  1621. ($chain_reply_to || !defined $in_reply_to || length($in_reply_to) == 0 ||
  1622. $message_num == 1)) {
  1623. $in_reply_to = $message_id;
  1624. if (length $references > 0) {
  1625. $references .= "\n $message_id";
  1626. } else {
  1627. $references = "$message_id";
  1628. }
  1629. }
  1630. $message_id = undef;
  1631. $num_sent++;
  1632. if (defined $batch_size && $num_sent == $batch_size) {
  1633. $num_sent = 0;
  1634. $smtp->quit if defined $smtp;
  1635. undef $smtp;
  1636. undef $auth;
  1637. sleep($relogin_delay) if defined $relogin_delay;
  1638. }
  1639. return 1;
  1640. }
  1641. foreach my $t (@files) {
  1642. while (!process_file($t)) {
  1643. # user edited the file
  1644. }
  1645. }
  1646. # Execute a command (e.g. $to_cmd) to get a list of email addresses
  1647. # and return a results array
  1648. sub recipients_cmd {
  1649. my ($prefix, $what, $cmd, $file) = @_;
  1650. my @addresses = ();
  1651. open my $fh, "-|", "$cmd \Q$file\E"
  1652. or die sprintf(__("(%s) Could not execute '%s'"), $prefix, $cmd);
  1653. while (my $address = <$fh>) {
  1654. $address =~ s/^\s*//g;
  1655. $address =~ s/\s*$//g;
  1656. $address = sanitize_address($address);
  1657. next if ($address eq $sender and $suppress_cc{'self'});
  1658. push @addresses, $address;
  1659. printf(__("(%s) Adding %s: %s from: '%s'\n"),
  1660. $prefix, $what, $address, $cmd) unless $quiet;
  1661. }
  1662. close $fh
  1663. or die sprintf(__("(%s) failed to close pipe to '%s'"), $prefix, $cmd);
  1664. return @addresses;
  1665. }
  1666. cleanup_compose_files();
  1667. sub cleanup_compose_files {
  1668. unlink($compose_filename, $compose_filename . ".final") if $compose;
  1669. }
  1670. $smtp->quit if $smtp;
  1671. sub apply_transfer_encoding {
  1672. my $message = shift;
  1673. my $from = shift;
  1674. my $to = shift;
  1675. return ($message, $to) if ($from eq $to and $from ne '7bit');
  1676. require MIME::QuotedPrint;
  1677. require MIME::Base64;
  1678. $message = MIME::QuotedPrint::decode($message)
  1679. if ($from eq 'quoted-printable');
  1680. $message = MIME::Base64::decode($message)
  1681. if ($from eq 'base64');
  1682. $to = ($message =~ /(?:.{999,}|\r)/) ? 'quoted-printable' : '8bit'
  1683. if $to eq 'auto';
  1684. die __("cannot send message as 7bit")
  1685. if ($to eq '7bit' and $message =~ /[^[:ascii:]]/);
  1686. return ($message, $to)
  1687. if ($to eq '7bit' or $to eq '8bit');
  1688. return (MIME::QuotedPrint::encode($message, "\n", 0), $to)
  1689. if ($to eq 'quoted-printable');
  1690. return (MIME::Base64::encode($message, "\n"), $to)
  1691. if ($to eq 'base64');
  1692. die __("invalid transfer encoding");
  1693. }
  1694. sub unique_email_list {
  1695. my %seen;
  1696. my @emails;
  1697. foreach my $entry (@_) {
  1698. my $clean = extract_valid_address_or_die($entry);
  1699. $seen{$clean} ||= 0;
  1700. next if $seen{$clean}++;
  1701. push @emails, $entry;
  1702. }
  1703. return @emails;
  1704. }
  1705. sub validate_patch {
  1706. my ($fn, $xfer_encoding) = @_;
  1707. if ($repo) {
  1708. my $validate_hook = catfile(catdir($repo->repo_path(), 'hooks'),
  1709. 'sendemail-validate');
  1710. my $hook_error;
  1711. if (-x $validate_hook) {
  1712. my $target = abs_path($fn);
  1713. # The hook needs a correct cwd and GIT_DIR.
  1714. my $cwd_save = cwd();
  1715. chdir($repo->wc_path() or $repo->repo_path())
  1716. or die("chdir: $!");
  1717. local $ENV{"GIT_DIR"} = $repo->repo_path();
  1718. $hook_error = "rejected by sendemail-validate hook"
  1719. if system($validate_hook, $target);
  1720. chdir($cwd_save) or die("chdir: $!");
  1721. }
  1722. return $hook_error if $hook_error;
  1723. }
  1724. # Any long lines will be automatically fixed if we use a suitable transfer
  1725. # encoding.
  1726. unless ($xfer_encoding =~ /^(?:auto|quoted-printable|base64)$/) {
  1727. open(my $fh, '<', $fn)
  1728. or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
  1729. while (my $line = <$fh>) {
  1730. if (length($line) > 998) {
  1731. return sprintf(__("%s: patch contains a line longer than 998 characters"), $.);
  1732. }
  1733. }
  1734. }
  1735. return;
  1736. }
  1737. sub handle_backup {
  1738. my ($last, $lastlen, $file, $known_suffix) = @_;
  1739. my ($suffix, $skip);
  1740. $skip = 0;
  1741. if (defined $last &&
  1742. ($lastlen < length($file)) &&
  1743. (substr($file, 0, $lastlen) eq $last) &&
  1744. ($suffix = substr($file, $lastlen)) !~ /^[a-z0-9]/i) {
  1745. if (defined $known_suffix && $suffix eq $known_suffix) {
  1746. printf(__("Skipping %s with backup suffix '%s'.\n"), $file, $known_suffix);
  1747. $skip = 1;
  1748. } else {
  1749. # TRANSLATORS: please keep "[y|N]" as is.
  1750. my $answer = ask(sprintf(__("Do you really want to send %s? [y|N]: "), $file),
  1751. valid_re => qr/^(?:y|n)/i,
  1752. default => 'n');
  1753. $skip = ($answer ne 'y');
  1754. if ($skip) {
  1755. $known_suffix = $suffix;
  1756. }
  1757. }
  1758. }
  1759. return ($skip, $known_suffix);
  1760. }
  1761. sub handle_backup_files {
  1762. my @file = @_;
  1763. my ($last, $lastlen, $known_suffix, $skip, @result);
  1764. for my $file (@file) {
  1765. ($skip, $known_suffix) = handle_backup($last, $lastlen,
  1766. $file, $known_suffix);
  1767. push @result, $file unless $skip;
  1768. $last = $file;
  1769. $lastlen = length($file);
  1770. }
  1771. return @result;
  1772. }
  1773. sub file_has_nonascii {
  1774. my $fn = shift;
  1775. open(my $fh, '<', $fn)
  1776. or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
  1777. while (my $line = <$fh>) {
  1778. return 1 if $line =~ /[^[:ascii:]]/;
  1779. }
  1780. return 0;
  1781. }
  1782. sub body_or_subject_has_nonascii {
  1783. my $fn = shift;
  1784. open(my $fh, '<', $fn)
  1785. or die sprintf(__("unable to open %s: %s\n"), $fn, $!);
  1786. while (my $line = <$fh>) {
  1787. last if $line =~ /^$/;
  1788. return 1 if $line =~ /^Subject.*[^[:ascii:]]/;
  1789. }
  1790. while (my $line = <$fh>) {
  1791. return 1 if $line =~ /[^[:ascii:]]/;
  1792. }
  1793. return 0;
  1794. }