vacation.pl 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. #!/usr/bin/perl -w
  2. #
  3. # Virtual Vacation 4.0r1
  4. #
  5. # $Revision: 1676 $
  6. # Originally by Mischa Peters <mischa at high5 dot net>
  7. #
  8. # Copyright (c) 2002 - 2005 High5!
  9. # Licensed under GPL for more info check GPL-LICENSE.TXT
  10. #
  11. # Additions:
  12. # 2004/07/13 David Osborn <ossdev at daocon.com>
  13. # strict, processes domain level aliases, more
  14. # subroutines, send reply from original to address
  15. #
  16. # 2004/11/09 David Osborn <ossdev at daocon.com>
  17. # Added syslog support
  18. # Slightly better logging which includes messageid
  19. # Avoid infinite loops with domain aliases
  20. #
  21. # 2005-01-19 Troels Arvin <troels at arvin.dk>
  22. # PostgreSQL-version.
  23. # Normalized DB schema from one vacation table ("vacation")
  24. # to two ("vacation", "vacation_notification"). Uses
  25. # referential integrity CASCADE action to simplify cleanup
  26. # when a user is no longer on vacation.
  27. # Inserting variables into queries stricly by prepare()
  28. # to try to avoid SQL injection.
  29. # International characters are now handled well.
  30. #
  31. # 2005-01-21 Troels Arvin <troels at arvin.dk>
  32. # Uses the Email::Valid package to avoid sending notices
  33. # to obviously invalid addresses.
  34. #
  35. # 2007-08-15 David Goodwin <david at palepurple.co.uk>
  36. # Use the Perl Mail::Sendmail module for sending mail
  37. # Check for headers that start with blank lines (patch from forum)
  38. #
  39. # 2007-08-20 Martin Ambroz <amsys at trustica.cz>
  40. # Added initial Unicode support
  41. #
  42. # 2008-05-09 Fabio Bonelli <fabiobonelli at libero.it>
  43. # Properly handle failed queries to vacation_notification.
  44. # Fixed log reporting.
  45. #
  46. # 2008-07-29 Patch from Luxten to add repeat notification after timeout. See:
  47. # https://sourceforge.net/tracker/index.php?func=detail&aid=2031631&group_id=191583&atid=937966
  48. #
  49. # 2008-08-01 Luigi Iotti <luigi at iotti dot biz>
  50. # Use envelope sender/recipient instead of using
  51. # From: and To: header fields;
  52. # Support to good vacation behavior as in
  53. # http://www.irbs.net/internet/postfix/0707/0954.html
  54. # (needs to be tested);
  55. #
  56. # 2008-08-04 David Goodwin <david at palepurple dot co dot uk>
  57. # Use Log4Perl
  58. # Added better testing (and -t option)
  59. #
  60. # 2009-06-29 Stevan Bajic <stevan at bajic.ch>
  61. # Add Mail::Sender for SMTP auth + more flexibility
  62. #
  63. # 2009-07-07 Stevan Bajic <stevan at bajic.ch>
  64. # Add better alias lookups
  65. # Check for more heades from Anti-Virus/Anti-Spam solutions
  66. #
  67. # 2009-08-10 Sebastian <reg9009 at yahoo dot de>
  68. # Adjust SQL query for vacation timeframe. It is now possible to set from/until date for vacation message.
  69. #
  70. # 2012-04-1 Nikolaos Topp <info at ichier.de>
  71. # Add configuration parameter $smtp_client in order to get mails through
  72. # postfix helo-checks, using check_helo_access whitelist without permitting 'localhost' default style stuff
  73. #
  74. # 2012-04-19 Jan Kruis <jan at crossreference dot nl>
  75. # change SQL query for vacation into function.
  76. # Add sub get_interval()
  77. # Gives the user the option to set the interval time ( 0 = one reply, 1 = autoreply, > 1 = Delay reply )
  78. # See https://sourceforge.net/tracker/?func=detail&aid=3508083&group_id=191583&atid=937966
  79. #
  80. # 2012-06-18 Christoph Lechleitner <christoph.lechleitner@iteg.at>
  81. # Add capability to include the subject of the original mail in the subject of the vacation message.
  82. # A good vacation subject could be: 'Re: $SUBJECT'
  83. # Also corrected log entry about "Already informed ..." to show the $orig_from, not $email
  84. #
  85. # Requirements - the following perl modules are required:
  86. # DBD::Pg or DBD::mysql
  87. # Mail::Sender, Email::Valid MIME::Charset, Log::Log4perl, Log::Dispatch, MIME::EncWords and GetOpt::Std
  88. #
  89. # You may install these via CPAN, or through your package tool.
  90. # CPAN: 'perl -MCPAN -e shell', then 'install Module::Whatever'
  91. #
  92. # On Debian based systems :
  93. # libmail-sender-perl
  94. # libdbd-pg-perl
  95. # libemail-valid-perl
  96. # libmime-perl
  97. # liblog-log4perl-perl
  98. # liblog-dispatch-perl
  99. # libgetopt-argvfile-perl
  100. # libmime-charset-perl (currently in testing, see instructions below)
  101. # libmime-encwords-perl (currently in testing, see instructions below)
  102. #
  103. # Note: When you use this module, you may start seeing error messages
  104. # like "Cannot insert a duplicate key into unique index
  105. # vacation_notification_pkey" in your system logs. This is expected
  106. # behavior, and not an indication of trouble (see the "already_notified"
  107. # subroutine for an explanation).
  108. #
  109. # You must also have the Email::Valid and MIME-tools perl-packages
  110. # installed. They are available in some package collections, under the
  111. # names 'perl-Email-Valid' and 'perl-MIME-tools', respectively.
  112. # One such package collection (for Linux) is:
  113. # http://dag.wieers.com/home-made/apt/packages.php
  114. #
  115. use DBI;
  116. use MIME::Base64;
  117. use MIME::EncWords qw(:all);
  118. use Email::Valid;
  119. use strict;
  120. use Mail::Sender;
  121. use Getopt::Std;
  122. use Log::Log4perl qw(get_logger :levels);
  123. use File::Basename;
  124. # ========== begin configuration ==========
  125. # IMPORTANT: If you put passwords into this script, then remember
  126. # to restrict access to the script, so that only the vacation user
  127. # can read it.
  128. # db_type - uncomment one of these
  129. our $db_type = 'Pg';
  130. #our $db_type = 'mysql';
  131. # leave empty for connection via UNIX socket
  132. our $db_host = '';
  133. # connection details
  134. our $db_username = 'user';
  135. our $db_password = 'password';
  136. our $db_name = 'postfix';
  137. our $vacation_domain = 'autoreply.example.org';
  138. # smtp server used to send vacation e-mails
  139. our $smtp_server = 'localhost';
  140. our $smtp_server_port = 25;
  141. # this is the helo we [the vacation script] use on connection; you may need to change this to your hostname or something,
  142. # depending upon what smtp helo restrictions you have in place within Postfix.
  143. our $smtp_client = 'localhost';
  144. # SMTP authentication protocol used for sending.
  145. # Can be 'PLAIN', 'LOGIN', 'CRAM-MD5' or 'NTLM'
  146. # see "perldoc Mail::Sender" (search for "auth") for more options and details
  147. # Leave it blank if you don't use authentication
  148. our $smtp_auth = undef;
  149. # username used to login to the server
  150. our $smtp_authid = 'someuser';
  151. # password used to login to the server
  152. our $smtp_authpwd = 'somepass';
  153. # This specifies the mail 'from' name which is shown to recipients of vacation replies.
  154. # If you leave it empty, the vacation mail will contain:
  155. # From: <original@recipient.domain>
  156. # If you specify something here you'd instead see something like :
  157. # From: Some Friendly Name <original@recipient.domain>
  158. our $friendly_from = '';
  159. # use TLS for the SMTP connection?
  160. # while in general this would be a good idea, TLS with Mail::Sender 0.8.22 is buggy - https://rt.cpan.org/Public/Bug/Display.html?id=85438
  161. our $smtp_tls_allowed = 0;
  162. # Set to 1 to enable logging to syslog.
  163. our $syslog = 0;
  164. # path to logfile, when empty logging is suppressed
  165. # change to e.g. /dev/null if you want nothing logged.
  166. # if we can't write to this, and $log_to_file is 1 (below) the script will abort.
  167. our $logfile='/var/log/vacation.log';
  168. # 2 = debug + info, 1 = info only, 0 = error only
  169. our $log_level = 2;
  170. # Whether to log to file or not, 0 = do not write to a log file
  171. our $log_to_file = 0;
  172. # notification interval, in seconds
  173. # set to 0 to notify only once
  174. # e.g. 1 day ...
  175. #our $interval = 60*60*24;
  176. # disabled by default
  177. our $interval = 0;
  178. # Send vacation mails to do-not-reply email addresses.
  179. # By default vacation email addresses will be sent.
  180. # For now emails from bounce|do-not-reply|facebook|linkedin|list-|myspace|twitter won't
  181. # be answered when $custom_noreply_pattern is set to 1.
  182. # default = 0
  183. our $custom_noreply_pattern = 0;
  184. our $noreply_pattern = 'bounce|do-not-reply|facebook|linkedin|list-|myspace|twitter';
  185. # instead of changing this script, you can put your settings to /etc/mail/postfixadmin/vacation.conf
  186. # or /etc/postfixadmin/vacation.conf just use Perl syntax there to fill the variables listed above
  187. # (without the "our" keyword). Example:
  188. # $db_username = 'mail';
  189. if (-f '/etc/mail/postfixadmin/vacation.conf') {
  190. require '/etc/mail/postfixadmin/vacation.conf';
  191. } elsif (-f '/etc/postfixadmin/vacation.conf') {
  192. require '/etc/postfixadmin/vacation.conf';
  193. }
  194. # =========== end configuration ===========
  195. if($log_to_file == 1) {
  196. if (( ! -w $logfile ) && (! -w dirname($logfile))) {
  197. # Cannot log; no where to write to.
  198. die("Cannot create logfile : $logfile");
  199. }
  200. }
  201. my ($from, $to, $cc, $replyto , $subject, $messageid, $lastheader, $smtp_sender, $smtp_recipient, %opts, $test_mode, $logger);
  202. $subject='';
  203. $messageid='unknown';
  204. # Setup a logger...
  205. #
  206. getopts('f:t:', \%opts) or die "Usage: $0 [-t yes] -f sender -- recipient\n\t-t for testing only\n";
  207. $opts{f} and $smtp_sender = $opts{f} or die '-f sender not present on command line';
  208. $test_mode = 0;
  209. $opts{t} and $test_mode = 1;
  210. $smtp_recipient = shift or die 'recipient not given on command line';
  211. my $log_layout = Log::Log4perl::Layout::PatternLayout->new('%d %p> %F:%L %M - %m%n');
  212. if($test_mode == 1) {
  213. $logger = get_logger();
  214. # log to stdout
  215. my $appender = Log::Log4perl::Appender->new('Log::Dispatch::Screen');
  216. $appender->layout($log_layout);
  217. $logger->add_appender($appender);
  218. $logger->debug('Test mode enabled');
  219. } else {
  220. $logger = get_logger();
  221. if($log_to_file == 1) {
  222. # log to file
  223. my $appender = Log::Log4perl::Appender->new(
  224. 'Log::Dispatch::File',
  225. filename => $logfile,
  226. mode => 'append');
  227. $appender->layout($log_layout);
  228. $logger->add_appender($appender);
  229. }
  230. if($syslog == 1) {
  231. my $syslog_appender = Log::Log4perl::Appender->new(
  232. 'Log::Dispatch::Syslog',
  233. facility => 'mail',
  234. );
  235. $logger->add_appender($syslog_appender);
  236. }
  237. }
  238. # change to $DEBUG, $INFO or $ERROR depending on how much logging you want.
  239. $logger->level($ERROR);
  240. if($log_level == 1) {
  241. $logger->level($INFO);
  242. }
  243. if($log_level == 2) {
  244. $logger->level($DEBUG);
  245. }
  246. binmode (STDIN,':encoding(UTF-8)');
  247. my $dbh;
  248. if ($db_host) {
  249. $dbh = DBI->connect("DBI:$db_type:dbname=$db_name;host=$db_host","$db_username", "$db_password", { RaiseError => 1 });
  250. } else {
  251. $dbh = DBI->connect("DBI:$db_type:dbname=$db_name","$db_username", "$db_password", { RaiseError => 1 });
  252. }
  253. if (!$dbh) {
  254. $logger->error('Could not connect to database'); # eval { } etc better here?
  255. exit(0);
  256. }
  257. my $db_true; # MySQL and PgSQL use different values for TRUE, and unicode support...
  258. if ($db_type eq 'mysql') {
  259. $dbh->do('SET CHARACTER SET utf8;');
  260. $db_true = '1';
  261. } else { # Pg
  262. $dbh->do("SET CLIENT_ENCODING TO 'UTF8'");
  263. $db_true = 'True';
  264. }
  265. # used to detect infinite address lookup loops
  266. my $loopcount=0;
  267. #
  268. # Get interval_time for email user from the vacation table
  269. #
  270. sub get_interval {
  271. my ($to) = @_;
  272. my $query = qq{SELECT interval_time FROM vacation WHERE email=? };
  273. my $stm = $dbh->prepare($query) or panic_prepare($query);
  274. $stm->execute($to) or panic_execute($query," 'email='$to'");
  275. my $rv = $stm->rows;
  276. if ($rv == 1) {
  277. my @row = $stm->fetchrow_array;
  278. my $interval = $row[0] ;
  279. return $interval ;
  280. } else {
  281. return 0 ;
  282. }
  283. }
  284. sub already_notified {
  285. my ($to, $from) = @_;
  286. my $logger = get_logger();
  287. my $query;
  288. # delete old notifications
  289. if ($db_type eq 'Pg') {
  290. $query = qq{DELETE FROM vacation_notification USING vacation WHERE vacation.email = vacation_notification.on_vacation AND on_vacation = ? AND notified = ? AND notified_at < vacation.activefrom;};
  291. } else { # mysql
  292. $query = qq{DELETE vacation_notification.* FROM vacation_notification LEFT JOIN vacation ON vacation.email = vacation_notification.on_vacation WHERE on_vacation = ? AND notified = ? AND notified_at < vacation.activefrom};
  293. }
  294. my $stm = $dbh->prepare($query);
  295. if (!$stm) {
  296. $logger->error("Could not prepare query (trying to delete old vacation notifications) :'$query' to: $to, from:$from");
  297. return 1;
  298. }
  299. $stm->execute($to,$from);
  300. $query = qq{INSERT into vacation_notification (on_vacation,notified) values (?,?)};
  301. $stm = $dbh->prepare($query);
  302. if (!$stm) {
  303. $logger->error("Could not prepare query '$query' to: $to, from:$from");
  304. return 1;
  305. }
  306. $stm->{'PrintError'} = 0;
  307. $stm->{'RaiseError'} = 0;
  308. if (!$stm->execute($to,$from)) {
  309. my $e=$dbh->errstr;
  310. # Violation of a primary key constraint may happen here, and that's
  311. # fine. All other error conditions are not fine, however.
  312. if ($e !~ /(?:_pkey|^Duplicate entry)/) {
  313. $logger->error("Failed to insert into vacation_notification table (to:$to from:$from error:'$e' query:'$query')");
  314. # Let's play safe and notify anyway
  315. return 1;
  316. }
  317. $interval = get_interval($to);
  318. if ($interval) {
  319. if ($db_type eq 'Pg') {
  320. $query = qq{SELECT extract( epoch from (NOW()-notified_at))::int FROM vacation_notification WHERE on_vacation=? AND notified=?};
  321. } else { # mysql
  322. $query = qq{SELECT NOW()-notified_at FROM vacation_notification WHERE on_vacation=? AND notified=?};
  323. }
  324. $stm = $dbh->prepare($query) or panic_prepare($query);
  325. $stm->execute($to,$from) or panic_execute($query,"on_vacation='$to', notified='$from'");
  326. my @row = $stm->fetchrow_array;
  327. my $int = $row[0];
  328. if ($int > $interval) {
  329. $logger->info("[Interval elapsed, sending the message]: From: $from To:$to");
  330. $query = qq{UPDATE vacation_notification SET notified_at=NOW() WHERE on_vacation=? AND notified=?};
  331. $stm = $dbh->prepare($query);
  332. if (!$stm) {
  333. $logger->error("Could not prepare query '$query' (to: '$to', from: '$from')");
  334. return 0;
  335. }
  336. if (!$stm->execute($to,$from)) {
  337. $e=$dbh->errstr;
  338. $logger->error("Error from running query '$query' (to: '$to', from: '$from', error: '$e')");
  339. }
  340. return 0;
  341. } else {
  342. $logger->debug("Notification interval not elapsed; not sending vacation reply (to: '$to', from: '$from')");
  343. return 1;
  344. }
  345. } else {
  346. return 1;
  347. }
  348. }
  349. return 0;
  350. }
  351. #
  352. # Check to see if there is a vacation record against a specific email address.
  353. #
  354. sub check_for_vacation {
  355. my ($email_to_check) =@_;
  356. my $query = qq{SELECT email FROM vacation WHERE email=? and active=$db_true and activefrom <= NOW() and activeuntil >= NOW()};
  357. my $stm = $dbh->prepare($query) or panic_prepare($query);
  358. $stm->execute($email_to_check) or panic_execute($query,"email='$email_to_check'");
  359. my $rv = $stm->rows;
  360. return $rv;
  361. }
  362. # try and determine if email address has vacation turned on; we
  363. # have to do alias searching, and domain aliasing resolution for this.
  364. # If found, return ($num_matches, $real_email);
  365. sub find_real_address {
  366. my ($email) = @_;
  367. my $logger = get_logger();
  368. if (++$loopcount > 20) {
  369. $logger->error("find_real_address loop! (more than 20 attempts!) currently: $email");
  370. exit(1);
  371. }
  372. my $realemail = '';
  373. my $rv = check_for_vacation($email);
  374. # Recipient has vacation
  375. if ($rv == 1) {
  376. $realemail = $email;
  377. $logger->debug("Found '$email' has vacation active");
  378. } else {
  379. my $vemail = $email;
  380. $vemail =~ s/\@/#/g;
  381. $vemail = $vemail . "\@" . $vacation_domain;
  382. $logger->debug("Looking for alias records that '$email' resolves to with vacation turned on");
  383. my $query = qq{SELECT goto FROM alias WHERE address=? AND (goto LIKE ? OR goto LIKE ? OR goto LIKE ? OR goto = ?)};
  384. my $stm = $dbh->prepare($query) or panic_prepare($query);
  385. $stm->execute($email,"$vemail,%","%,$vemail","%,$vemail,%", "$vemail") or panic_execute($query,"address='$email'");
  386. $rv = $stm->rows;
  387. # Recipient is an alias, check if mailbox has vacation
  388. if ($rv == 1) {
  389. my @row = $stm->fetchrow_array;
  390. my $alias = $row[0];
  391. if ($alias =~ /,/) {
  392. for (split(/\s*,\s*/, lc($alias))) {
  393. my $singlealias = $_;
  394. $logger->debug("Found alias \'$singlealias\' for email \'$email\'. Looking if vacation is on for alias.");
  395. $rv = check_for_vacation($singlealias);
  396. # Alias has vacation
  397. if ($rv == 1) {
  398. $realemail = $singlealias;
  399. last;
  400. }
  401. }
  402. } else {
  403. $rv = check_for_vacation($alias);
  404. # Alias has vacation
  405. if ($rv == 1) {
  406. $realemail = $alias;
  407. }
  408. }
  409. # We have to look for alias domain (domain1 -> domain2)
  410. } else {
  411. my ($user, $domain) = split(/@/, $email);
  412. $logger->debug("Looking for alias domain for $domain / $email / $user");
  413. $query = qq{SELECT target_domain FROM alias_domain WHERE alias_domain=?};
  414. $stm = $dbh->prepare($query) or panic_prepare($query);
  415. $stm->execute($domain) or panic_execute($query,"alias_domain='$domain'");
  416. $rv = $stm->rows;
  417. # The domain has a alias domain level alias
  418. if ($rv == 1) {
  419. my @row = $stm->fetchrow_array;
  420. my $alias_domain_dest = $row[0];
  421. ($rv, $realemail) = find_real_address ("$user\@$alias_domain_dest");
  422. # We still have to look for domain level aliases...
  423. } else {
  424. my ($user, $domain) = split(/@/, $email);
  425. $logger->debug("Looking for domain level aliases for $domain / $email / $user");
  426. $query = qq{SELECT goto FROM alias WHERE address=?};
  427. $stm = $dbh->prepare($query) or panic_prepare($query);
  428. $stm->execute("\@$domain") or panic_execute($query,"address='\@$domain'");
  429. $rv = $stm->rows;
  430. # The recipient has a domain level alias
  431. if ($rv == 1) {
  432. my @row = $stm->fetchrow_array;
  433. my $wildcard_dest = $row[0];
  434. my ($wilduser, $wilddomain) = split(/@/, $wildcard_dest);
  435. # Check domain alias
  436. if ($wilduser) {
  437. ($rv, $realemail) = find_real_address ($wildcard_dest);
  438. } else {
  439. ($rv, $realemail) = find_real_address ("$user\@$wilddomain");
  440. }
  441. } else {
  442. $logger->debug("No domain level alias present for $domain / $email / $user");
  443. }
  444. }
  445. }
  446. }
  447. return ($rv, $realemail);
  448. }
  449. # sends the vacation mail to the original sender.
  450. #
  451. sub send_vacation_email {
  452. my ($email, $orig_from, $orig_to, $orig_messageid, $orig_subject, $test_mode) = @_;
  453. my $logger = get_logger();
  454. $logger->debug("Asked to send vacation reply to $email thanks to $orig_messageid");
  455. my $query = qq{SELECT subject,body FROM vacation WHERE email=?};
  456. my $stm = $dbh->prepare($query) or panic_prepare($query);
  457. $stm->execute($email) or panic_execute($query,"email='$email'");
  458. my $rv = $stm->rows;
  459. if ($rv == 1) {
  460. my @row = $stm->fetchrow_array;
  461. if (already_notified($email, $orig_from) == 1) {
  462. $logger->debug("Already notified $orig_from, or some error prevented us from doing so");
  463. return;
  464. }
  465. $logger->debug("Will send vacation response for $orig_messageid: FROM: $email (orig_to: $orig_to), TO: $orig_from; VACATION SUBJECT: $row[0] ; VACATION BODY: $row[1]");
  466. my $subject = $row[0];
  467. $subject =~ s/\$SUBJECT/$orig_subject/g;
  468. if ($subject ne $row[0]) {
  469. $logger->debug("Patched Subject of vacation message to: $subject");
  470. }
  471. my $body = $row[1];
  472. my $from = $email;
  473. my $to = $orig_from;
  474. my %smtp_connection;
  475. %smtp_connection = (
  476. 'smtp' => $smtp_server,
  477. 'port' => $smtp_server_port,
  478. 'auth' => $smtp_auth,
  479. 'authid' => $smtp_authid,
  480. 'authpwd' => $smtp_authpwd,
  481. 'tls_allowed' => $smtp_tls_allowed,
  482. 'smtp_client' => $smtp_client,
  483. 'skip_bad_recipients' => 'true',
  484. 'encoding' => 'Base64',
  485. 'ctype' => 'text/plain; charset=UTF-8',
  486. 'headers' => 'Precedence: junk',
  487. 'headers' => 'X-Loop: Postfix Admin Virtual Vacation',
  488. 'on_errors' => 'die', # raise exception on error
  489. );
  490. my %mail;
  491. %mail = (
  492. 'subject' => encode_mimewords($subject, 'Charset', 'UTF-8'),
  493. 'from' => $from,
  494. 'fake_from' => $friendly_from . " <$from>",
  495. 'to' => $to,
  496. 'msg' => encode_base64($body)
  497. );
  498. if($test_mode == 1) {
  499. $logger->info("** TEST MODE ** : Vacation response sent to $to from $from subject $subject (not) sent\n");
  500. $logger->info(%mail);
  501. return 0;
  502. }
  503. eval {
  504. $Mail::Sender::NO_X_MAILER = 1;
  505. my $sender = new Mail::Sender({%smtp_connection});
  506. $sender->Open({%mail});
  507. $sender->SendLineEnc($body);
  508. $sender->Close();
  509. $logger->debug("Vacation response sent to $to, from $from");
  510. };
  511. if ($@) {
  512. $logger->error("Failed to send vacation response: $@ / " . $Mail::Sender::Error);
  513. }
  514. }
  515. }
  516. # Convert a (list of) email address(es) from RFC 822 style addressing to
  517. # RFC 821 style addressing. e.g. convert:
  518. # "John Jones" <JJones@acme.com>, "Jane Doe/Sales/ACME" <JDoe@acme.com>
  519. # to:
  520. # jjones@acme.com, jdoe@acme.com
  521. sub strip_address {
  522. my ($arg) = @_;
  523. if(!$arg) {
  524. return '';
  525. }
  526. my @ok;
  527. $logger = get_logger();
  528. my @list;
  529. @list = $arg =~ m/([\w\.\-\+\'\=_\^\|\$\/\{\}~\?\*\\&\!`\%]+\@[\w\.\-]+\w+)/g;
  530. foreach(@list) {
  531. #$logger->debug("Checking: $_");
  532. my $temp = Email::Valid->address( -address => $_, -mxcheck => 0);
  533. if($temp) {
  534. push(@ok, $temp);
  535. } else {
  536. $logger->debug("Email not valid : $Email::Valid::Details");
  537. }
  538. }
  539. # remove duplicates
  540. my %seen = ();
  541. my @uniq;
  542. foreach my $item (@ok) {
  543. push(@uniq, $item) unless $seen{$item}++
  544. }
  545. my $result = lc(join(', ', @uniq));
  546. #$logger->debug("Result: $result");
  547. return $result;
  548. }
  549. sub panic_prepare {
  550. my ($arg) = @_;
  551. my $logger = get_logger();
  552. $logger->error("Could not prepare sql statement: '$arg'");
  553. exit(0);
  554. }
  555. sub panic_execute {
  556. my ($arg,$param) = @_;
  557. my $logger = get_logger();
  558. $logger->error("Could not execute sql statement - '$arg' with parameters '$param'");
  559. exit(0);
  560. }
  561. # Make sure the email wasn't sent by someone who could be a mailing list etc; if it was,
  562. # then we abort after appropriate logging.
  563. sub check_and_clean_from_address {
  564. my ($address) = @_;
  565. my $logger = get_logger();
  566. if($address =~ /^(noreply|postmaster|mailer\-daemon|listserv|majordomo|owner\-|request\-|bounces\-)/i ||
  567. $address =~ /\-(owner|request|bounces)\@/i ||
  568. ($custom_noreply_pattern == 1 && $address =~ /^.*($noreply_pattern).*/i) ) {
  569. $logger->debug("sender $address contains $1 - will not send vacation message");
  570. exit(0);
  571. }
  572. $address = strip_address($address);
  573. if($address eq '') {
  574. $logger->error("Address $address is not valid; exiting");
  575. exit(0);
  576. }
  577. #$logger->debug("Address cleaned up to $address");
  578. return $address;
  579. }
  580. ########################### main #################################
  581. # Take headers apart
  582. $cc = '';
  583. $replyto = '';
  584. $logger->debug("Script argument SMTP recipient is : '$smtp_recipient' and smtp_sender : '$smtp_sender'");
  585. while (<STDIN>) {
  586. last if (/^$/);
  587. if (/^\s+(.*)/ and $lastheader) { $$lastheader .= " $1"; next; }
  588. elsif (/^from:\s*(.*)\n$/i) { $from = $1; $lastheader = \$from; }
  589. elsif (/^to:\s*(.*)\n$/i) { $to = $1; $lastheader = \$to; }
  590. elsif (/^cc:\s*(.*)\n$/i) { $cc = $1; $lastheader = \$cc; }
  591. elsif (/^Reply\-to:\s*(.*)\s*\n$/i) { $replyto = $1; $lastheader = \$replyto; }
  592. elsif (/^subject:\s*(.*)\n$/i) { $subject = $1; $lastheader = \$subject; }
  593. elsif (/^message\-id:\s*(.*)\s*\n$/i) { $messageid = $1; $lastheader = \$messageid; }
  594. elsif (/^x\-spam\-(flag|status):\s+yes/i) { $logger->debug("x-spam-$1: yes found; exiting"); exit (0); }
  595. elsif (/^x\-facebook\-notify:/i) { $logger->debug('Mail from facebook, ignoring'); exit(0); }
  596. elsif (/^precedence:\s+(bulk|list|junk)/i) { $logger->debug("precedence: $1 found; exiting"); exit (0); }
  597. elsif (/^x\-loop:\s+postfix\ admin\ virtual\ vacation/i) { $logger->debug('x-loop: postfix admin virtual vacation found; exiting'); exit (0); }
  598. elsif (/^Auto\-Submitted:\s*no/i) { next; }
  599. elsif (/^Auto\-Submitted:/i) { $logger->debug('Auto-Submitted: something found; exiting'); exit (0); }
  600. elsif (/^List\-(Id|Post|Unsubscribe):/i) { $logger->debug("List-$1: found; exiting"); exit (0); }
  601. elsif (/^(x\-(barracuda\-)?spam\-status):\s+(yes)/i) { $logger->debug("$1: $3 found; exiting"); exit (0); }
  602. elsif (/^(x\-dspam\-result):\s+(spam|bl[ao]cklisted)/i) { $logger->debug("$1: $2 found; exiting"); exit (0); }
  603. elsif (/^(x\-(anti|avas\-)?virus\-status):\s+(infected)/i) { $logger->debug("$1: $3 found; exiting"); exit (0); }
  604. elsif (/^(x\-(avas\-spam|spamtest|crm114|razor|pyzor)\-status):\s+(spam)/i) { $logger->debug("$1: $3 found; exiting"); exit (0); }
  605. elsif (/^(x\-osbf\-lua\-score):\s+[0-9\/\.\-\+]+\s+\[([-S])\]/i) { $logger->debug("$1: $2 found; exiting"); exit (0); }
  606. else {$lastheader = '' ; }
  607. }
  608. if($smtp_recipient =~ /\@$vacation_domain/) {
  609. # the regexp used here could probably be improved somewhat, for now hope that people won't use # as a valid mailbox character.
  610. my $tmp = $smtp_recipient;
  611. $tmp =~ s/\@$vacation_domain//;
  612. $tmp =~ s/#/\@/;
  613. $logger->debug("Converted autoreply mailbox back to normal style - from $smtp_recipient to $tmp");
  614. $smtp_recipient = $tmp;
  615. undef $tmp;
  616. }
  617. # If either From: or To: are not set, exit
  618. if(!$from || !$to || !$messageid || !$smtp_sender || !$smtp_recipient) {
  619. $logger->info("One of from=$from, to=$to, messageid=$messageid, smtp sender=$smtp_sender, smtp recipient=$smtp_recipient empty");
  620. exit(0);
  621. }
  622. $logger->debug("Email headers have to: '$to' and From: '$from'");
  623. $to = strip_address($to);
  624. $cc = strip_address($cc);
  625. $from = check_and_clean_from_address($from);
  626. if($replyto ne '') {
  627. # if reply-to is invalid, or looks like a mailing list, then we probably don't want to send a reply.
  628. $replyto = check_and_clean_from_address($replyto);
  629. }
  630. $smtp_sender = check_and_clean_from_address($smtp_sender);
  631. $smtp_recipient = check_and_clean_from_address($smtp_recipient);
  632. if ($smtp_sender eq $smtp_recipient) {
  633. $logger->debug("smtp sender $smtp_sender and recipient $smtp_recipient are the same; aborting");
  634. exit(0);
  635. }
  636. for (split(/,\s*/, lc($to)), split(/,\s*/, lc($cc))) {
  637. my $header_recipient = strip_address($_);
  638. if ($smtp_sender eq $header_recipient) {
  639. $logger->debug("sender header $smtp_sender contains recipient $header_recipient (mailing myself?)");
  640. exit(0);
  641. }
  642. }
  643. my ($rv, $email) = find_real_address($smtp_recipient);
  644. if ($rv == 1) {
  645. $logger->debug("Attempting to send vacation response for: $messageid to: $smtp_sender, $smtp_recipient, $email (test_mode = $test_mode)");
  646. send_vacation_email($email, $smtp_sender, $smtp_recipient, $messageid, $subject, $test_mode);
  647. } else {
  648. $logger->debug("SMTP recipient $smtp_recipient which resolves to $email does not have an active vacation (rv: $rv, email: $email)");
  649. }
  650. 0;
  651. #/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */