home *** CD-ROM | disk | FTP | other *** search
/ ftp.f-secure.com / 2014.06.ftp.f-secure.com.tar / ftp.f-secure.com / support / hotfix / fsis / IS-SpamControl.fsfix / iufssc / lib / Mail / SpamAssassin.pm
Text File  |  2006-11-29  |  54KB  |  1,876 lines

  1. # <@LICENSE>
  2. # Licensed to the Apache Software Foundation (ASF) under one or more
  3. # contributor license agreements.  See the NOTICE file distributed with
  4. # this work for additional information regarding copyright ownership.
  5. # The ASF licenses this file to you under the Apache License, Version 2.0
  6. # (the "License"); you may not use this file except in compliance with
  7. # the License.  You may obtain a copy of the License at:
  8. #     http://www.apache.org/licenses/LICENSE-2.0
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # </@LICENSE>
  15.  
  16. =head1 NAME
  17.  
  18. Mail::SpamAssassin - Spam detector and markup engine
  19.  
  20. =head1 SYNOPSIS
  21.  
  22.   my $spamtest = Mail::SpamAssassin->new();
  23.   my $mail = $spamtest->parse($message);
  24.   my $status = $spamtest->check($mail);
  25.  
  26.   if ($status->is_spam()) {
  27.     $message = $status->rewrite_mail();
  28.   }
  29.   else {
  30.     ...
  31.   }
  32.   ...
  33.  
  34.   $status->finish();
  35.   $mail->finish();
  36.  
  37. =head1 DESCRIPTION
  38.  
  39. Mail::SpamAssassin is a module to identify spam using several methods
  40. including text analysis, internet-based realtime blacklists, statistical
  41. analysis, and internet-based hashing algorithms.
  42.  
  43. Using its rule base, it uses a wide range of heuristic tests on mail
  44. headers and body text to identify "spam", also known as unsolicited bulk
  45. email.  Once identified as spam, the mail can then be tagged as spam for
  46. later filtering using the user's own mail user agent application or at
  47. the mail transfer agent.
  48.  
  49. If you wish to use a command-line filter tool, try the C<spamassassin>
  50. or the C<spamd>/C<spamc> tools provided.
  51.  
  52. =head1 METHODS
  53.  
  54. =over 4
  55.  
  56. =cut
  57.  
  58. package Mail::SpamAssassin;
  59. use strict;
  60. use warnings;
  61. use bytes;
  62.  
  63. require 5.006_001;
  64.  
  65. use Mail::SpamAssassin::Logger;
  66. use Mail::SpamAssassin::Constants;
  67. use Mail::SpamAssassin::Conf;
  68. use Mail::SpamAssassin::Conf::SQL;
  69. use Mail::SpamAssassin::Conf::LDAP;
  70. use Mail::SpamAssassin::PerMsgStatus;
  71. use Mail::SpamAssassin::Message;
  72. use Mail::SpamAssassin::Bayes;
  73. use Mail::SpamAssassin::PluginHandler;
  74. use Mail::SpamAssassin::DnsResolver;
  75.  
  76. use File::Basename;
  77. use File::Path;
  78. use File::Spec 0.8;
  79. use File::Copy;
  80. use Cwd;
  81. use Config;
  82.  
  83. # Load Time::HiRes if it's available
  84. BEGIN {
  85.   eval { require Time::HiRes };
  86.   Time::HiRes->import( qw(time) ) unless $@;
  87. }
  88.  
  89. use vars qw{
  90.   @ISA $VERSION $SUB_VERSION @EXTRA_VERSION $IS_DEVEL_BUILD $HOME_URL
  91.   @default_rules_path @default_prefs_path
  92.   @default_userprefs_path @default_userstate_dir
  93.   @site_rules_path
  94. };
  95.  
  96. $VERSION = "3.001007";      # update after release (same format as perl $])
  97. $IS_DEVEL_BUILD = 1;        # change for release versions
  98.  
  99. @ISA = qw();
  100.  
  101. # SUB_VERSION is now just <yyyy>-<mm>-<dd>
  102. $SUB_VERSION = (split(/\s+/,'$LastChangedDate: 2005-09-23 19:01:09 +0300 (pe, 23 syys 2005) $ updated by SVN'))[1];
  103.  
  104. # If you hacked up your SA, you should add a version_tag to your .cf files.
  105. # This variable should not be modified directly.
  106. @EXTRA_VERSION = qw();
  107. if (defined $IS_DEVEL_BUILD && $IS_DEVEL_BUILD) {
  108.   push(@EXTRA_VERSION,
  109.        ('r' . qw{$LastChangedRevision: 2022 $ updated by SVN}[1]));
  110. }
  111.  
  112. sub Version {
  113.   $VERSION =~ /^(\d+)\.(\d\d\d)(\d\d\d)$/;
  114.   return join('-', sprintf("%d.%d.%d", $1, $2, $3), @EXTRA_VERSION);
  115. }
  116.  
  117. $HOME_URL = "http://spamassassin.apache.org/";
  118.  
  119. # note that the CWD takes priority.  This is required in case a user
  120. # is testing a new version of SpamAssassin on a machine with an older
  121. # version installed.  Unless you can come up with a fix for this that
  122. # allows "make test" to work, don't change this.
  123. @default_rules_path = (
  124.   './rules',              # REMOVEFORINST
  125.   '../rules',             # REMOVEFORINST
  126.   '__local_state_dir__/__version__',
  127.   '__def_rules_dir__',
  128.   '__prefix__/share/spamassassin',
  129.   '/usr/local/share/spamassassin',
  130.   '/usr/share/spamassassin',
  131. );
  132.  
  133. # first 3 are BSDish, latter 2 Linuxish
  134. @site_rules_path = (
  135.   '__local_rules_dir__',
  136.   '__prefix__/etc/mail/spamassassin',
  137.   '__prefix__/etc/spamassassin',
  138.   '/usr/local/etc/spamassassin',
  139.   '/usr/pkg/etc/spamassassin',
  140.   '/usr/etc/spamassassin',
  141.   '/etc/mail/spamassassin',
  142.   '/etc/spamassassin',
  143. );
  144.  
  145. @default_prefs_path = (
  146.   '__local_rules_dir__/user_prefs.template',
  147.   '__prefix__/etc/mail/spamassassin/user_prefs.template',
  148.   '__prefix__/share/spamassassin/user_prefs.template',
  149.   '/etc/spamassassin/user_prefs.template',
  150.   '/etc/mail/spamassassin/user_prefs.template',
  151.   '/usr/local/share/spamassassin/user_prefs.template',
  152.   '/usr/share/spamassassin/user_prefs.template',
  153. );
  154.  
  155. @default_userprefs_path = (
  156.   '~/.spamassassin/user_prefs',
  157. );
  158.  
  159. @default_userstate_dir = (
  160.   '~/.spamassassin',
  161. );
  162.  
  163. ###########################################################################
  164.  
  165. =item $t = Mail::SpamAssassin->new( { opt => val, ... } )
  166.  
  167. Constructs a new C<Mail::SpamAssassin> object.  You may pass a hash
  168. reference to the constructor which may contain the following attribute-
  169. value pairs.
  170.  
  171. =over 4
  172.  
  173. =item debug
  174.  
  175. This is the debug options used to determine logging level.  It exists to
  176. allow sections of debug messages (called "facilities") to be enabled or
  177. disabled.  If this is a string, it is treated as a comma-delimited list
  178. of the debug facilities.  If it's a hash reference, then the keys are
  179. treated as the list of debug facilities and if it's a array reference,
  180. then the elements are treated as the list of debug facilities.
  181.  
  182. There are also two special cases: (1) if the special case of "info" is
  183. passed as a debug facility, then all informational messages are enabled;
  184. (2) if the special case of "all" is passed as a debug facility, then all
  185. debugging facilities are enabled.
  186.  
  187. =item rules_filename
  188.  
  189. The filename/directory to load spam-identifying rules from. (optional)
  190.  
  191. =item site_rules_filename
  192.  
  193. The directory to load site-specific spam-identifying rules from. (optional)
  194.  
  195. =item userprefs_filename
  196.  
  197. The filename to load preferences from. (optional)
  198.  
  199. =item userstate_dir
  200.  
  201. The directory user state is stored in. (optional)
  202.  
  203. =item config_text
  204.  
  205. The text of all rules and preferences.  If you prefer not to load the rules
  206. from files, read them in yourself and set this instead.  As a result, this will
  207. override the settings for C<rules_filename>, C<site_rules_filename>,
  208. and C<userprefs_filename>.
  209.  
  210. =item languages_filename
  211.  
  212. If you want to be able to use the language-guessing rule
  213. C<UNWANTED_LANGUAGE_BODY>, and are using C<config_text> instead of
  214. C<rules_filename>, C<site_rules_filename>, and C<userprefs_filename>, you will
  215. need to set this.  It should be the path to the B<languages> file normally
  216. found in the SpamAssassin B<rules> directory.
  217.  
  218. =item local_tests_only
  219.  
  220. If set to 1, no tests that require internet access will be performed. (default:
  221. 0)
  222.  
  223. =item dont_copy_prefs
  224.  
  225. If set to 1, the user preferences file will not be created if it doesn't
  226. already exist. (default: 0)
  227.  
  228. =item save_pattern_hits
  229.  
  230. If set to 1, the patterns hit can be retrieved from the
  231. C<Mail::SpamAssassin::PerMsgStatus> object.  Used for debugging.
  232.  
  233. =item home_dir_for_helpers
  234.  
  235. If set, the B<HOME> environment variable will be set to this value
  236. when using test applications that require their configuration data,
  237. such as Razor, Pyzor and DCC.
  238.  
  239. =item username
  240.  
  241. If set, the C<username> attribute will use this as the current user's name.
  242. Otherwise, the default is taken from the runtime environment (ie. this process'
  243. effective UID under UNIX).
  244.  
  245. =back
  246.  
  247. If none of C<rules_filename>, C<site_rules_filename>, C<userprefs_filename>, or
  248. C<config_text> is set, the C<Mail::SpamAssassin> module will search for the
  249. configuration files in the usual installed locations using the below variable
  250. definitions which can be passed in.
  251.  
  252. =over 4
  253.  
  254. =item PREFIX
  255.  
  256. Used as the root for certain directory paths such as:
  257.  
  258.   '__prefix__/etc/mail/spamassassin'
  259.   '__prefix__/etc/spamassassin'
  260.  
  261. Defaults to "@@PREFIX@@".
  262.  
  263. =item DEF_RULES_DIR
  264.  
  265. Location where the default rules are installed.  Defaults to
  266. "@@DEF_RULES_DIR@@".
  267.  
  268. =item LOCAL_RULES_DIR
  269.  
  270. Location where the local site rules are installed.  Defaults to
  271. "@@LOCAL_RULES_DIR@@".
  272.  
  273. =item LOCAL_STATE_DIR
  274.  
  275. Location of the local state directory, mainly used for installing updates via
  276. C<sa-update>.  Defaults to "@@LOCAL_STATE_DIR@@".
  277.  
  278. =back
  279.  
  280.  
  281. =cut
  282.  
  283. sub new {
  284.   my $class = shift;
  285.   $class = ref($class) || $class;
  286.  
  287.   my $self = shift;
  288.   if (!defined $self) { $self = { }; }
  289.   bless ($self, $class);
  290.  
  291.   # basic backwards compatibility; debug used to be a boolean.
  292.   # translate that into 'all', which is what it meant before 3.1.0.
  293.   if ($self->{debug} && $self->{debug} eq '1') {
  294.     $self->{debug} = 'all';
  295.   }
  296.  
  297.   # enable or disable debugging
  298.   Mail::SpamAssassin::Logger::add_facilities($self->{debug});
  299.  
  300.   # first debugging information possibly printed should be the version
  301.   dbg("generic: SpamAssassin version " . Version());
  302.  
  303.   # if the libs are installed in an alternate location, and the caller
  304.   # didn't set PREFIX, we should have an estimated guess ready, values
  305.   # substituted at 'make' time
  306.   $self->{PREFIX}        ||= '@@PREFIX@@';
  307.   $self->{DEF_RULES_DIR}    ||= '@@DEF_RULES_DIR@@';
  308.   $self->{LOCAL_RULES_DIR}    ||= '@@LOCAL_RULES_DIR@@';
  309.   $self->{LOCAL_STATE_DIR}    ||= '@@LOCAL_STATE_DIR@@';
  310.  
  311.   $self->{conf} ||= new Mail::SpamAssassin::Conf ($self);
  312.   $self->{plugins} = Mail::SpamAssassin::PluginHandler->new ($self);
  313.  
  314.   $self->{save_pattern_hits} ||= 0;
  315.  
  316.   # Make sure that we clean $PATH if we're tainted
  317.   Mail::SpamAssassin::Util::clean_path_in_taint_mode();
  318.  
  319.   # TODO: this should be in Conf!
  320.   $self->{encapsulated_content_description} = 'original message before SpamAssassin';
  321.  
  322.   if (!defined $self->{username}) {
  323.     $self->{username} = (Mail::SpamAssassin::Util::portable_getpwuid ($>))[0];
  324.   }
  325.  
  326.   $self->create_locker();
  327.  
  328.   # argh.  this is only used to perform DNS lookups in
  329.   # Mail::SpamAssassin::Message::Metadata::Received. TODO! we need to get
  330.   # Dns.pm code into a class that is NOT part of
  331.   # Mail::SpamAssassin::PerMsgStatus to avoid this crap!
  332.   my $tmpmsg = $self->parse([ ], 1);
  333.   $self->{parser_dns_pms} = Mail::SpamAssassin::PerMsgStatus->new($self, $tmpmsg);
  334.  
  335.   $self->{resolver} = Mail::SpamAssassin::DnsResolver->new($self);
  336.  
  337.   $self;
  338. }
  339.  
  340. sub create_locker {
  341.   my ($self) = @_;
  342.  
  343.   my $class;
  344.   my $m = $self->{conf}->{lock_method};
  345.  
  346.   # let people choose what they want -- even if they may not work on their
  347.   # OS.  (they could be using cygwin!)
  348.   if ($m eq 'win32') { $class = 'Win32'; }
  349.   elsif ($m eq 'flock') { $class = 'Flock'; }
  350.   elsif ($m eq 'nfssafe') { $class = 'UnixNFSSafe'; }
  351.   else {
  352.     # OS-specific defaults
  353.     if (Mail::SpamAssassin::Util::am_running_on_windows()) {
  354.       $class = 'Win32';
  355.     } else {
  356.       $class = 'UnixNFSSafe';
  357.     }
  358.   }
  359.  
  360.   # this could probably be made a little faster; for now I'm going
  361.   # for slow but safe, by keeping in quotes
  362.   eval '
  363.     use Mail::SpamAssassin::Locker::'.$class.';
  364.     $self->{locker} = new Mail::SpamAssassin::Locker::'.$class.' ($self);
  365.   '; ($@) and die $@;
  366.  
  367.   if (!defined $self->{locker}) { die "locker: oops! no locker"; }
  368. }
  369.  
  370. ###########################################################################
  371.  
  372. =item parse($message, $parse_now)
  373.  
  374. Parse will return a Mail::SpamAssassin::Message object with just the
  375. headers parsed.  When calling this function, there are two optional
  376. parameters that can be passed in: $message is either undef (which will
  377. use STDIN), a scalar of the entire message, an array reference of the
  378. message with 1 line per array element, or a file glob which holds the
  379. entire contents of the message; and $parse_now, which specifies whether
  380. or not to create the MIME tree at parse time or later as necessary.
  381.  
  382. The I<$parse_now> option, by default, is set to false (0).  This
  383. allows SpamAssassin to not have to generate the tree of internal
  384. data nodes if the information is not going to be used.  This is
  385. handy, for instance, when running C<spamassassin -d>, which only
  386. needs the pristine header and body which is always parsed and stored
  387. by this function.
  388.  
  389. For more information, please see the C<Mail::SpamAssassin::Message>
  390. and C<Mail::SpamAssassin::Message::Node> POD.
  391.  
  392. =cut
  393.  
  394. sub parse {
  395.   my($self, $message, $parsenow) = @_;
  396.   my $msg = Mail::SpamAssassin::Message->new({message=>$message, parsenow=>$parsenow});
  397.   return $msg;
  398. }
  399.  
  400.  
  401. ###########################################################################
  402.  
  403. =item $status = $f->check ($mail)
  404.  
  405. Check a mail, encapsulated in a C<Mail::SpamAssassin::Message> object,
  406. to determine if it is spam or not.
  407.  
  408. Returns a C<Mail::SpamAssassin::PerMsgStatus> object which can be
  409. used to test or manipulate the mail message.
  410.  
  411. Note that the C<Mail::SpamAssassin> object can be re-used for further messages
  412. without affecting this check; in OO terminology, the C<Mail::SpamAssassin>
  413. object is a "factory".   However, if you do this, be sure to call the
  414. C<finish()> method on the status objects when you're done with them.
  415.  
  416. =cut
  417.  
  418. sub check {
  419.   my ($self, $mail_obj) = @_;
  420.   local ($_);
  421.  
  422.   $self->init(1);
  423.   my $msg = Mail::SpamAssassin::PerMsgStatus->new($self, $mail_obj);
  424.   $msg->check();
  425.   $msg;
  426. }
  427.  
  428. =item $status = $f->check_message_text ($mailtext)
  429.  
  430. Check a mail, encapsulated in a plain string C<$mailtext>, to determine if it
  431. is spam or not.
  432.  
  433. Otherwise identical to C<check()> above.
  434.  
  435. =cut
  436.  
  437. sub check_message_text {
  438.   my ($self, $mailtext) = @_;
  439.   my $msg = $self->parse($mailtext, 1);
  440.   my $result = $self->check($msg);
  441.  
  442.   # Kill off the metadata ...
  443.   # Do _NOT_ call normal finish() here.  PerMsgStatus has a copy of
  444.   # the message.  So killing it here will cause things like
  445.   # rewrite_message() to fail. <grrr>
  446.   #
  447.   $msg->finish_metadata();
  448.  
  449.   return $result;
  450. }
  451.  
  452. ###########################################################################
  453.  
  454. =item $status = $f->learn ($mail, $id, $isspam, $forget)
  455.  
  456. Learn from a mail, encapsulated in a C<Mail::SpamAssassin::Message> object.
  457.  
  458. If C<$isspam> is set, the mail is assumed to be spam, otherwise it will
  459. be learnt as non-spam.
  460.  
  461. If C<$forget> is set, the attributes of the mail will be removed from
  462. both the non-spam and spam learning databases.
  463.  
  464. C<$id> is an optional message-identification string, used internally
  465. to tag the message.  If it is C<undef>, the Message-Id of the message
  466. will be used.  It should be unique to that message.
  467.  
  468. Returns a C<Mail::SpamAssassin::PerMsgLearner> object which can be used to
  469. manipulate the learning process for each mail.
  470.  
  471. Note that the C<Mail::SpamAssassin> object can be re-used for further messages
  472. without affecting this check; in OO terminology, the C<Mail::SpamAssassin>
  473. object is a "factory".   However, if you do this, be sure to call the
  474. C<finish()> method on the learner objects when you're done with them.
  475.  
  476. C<learn()> and C<check()> can be run using the same factory.  C<init_learner()>
  477. must be called before using this method.
  478.  
  479. =cut
  480.  
  481. sub learn {
  482.   my ($self, $mail_obj, $id, $isspam, $forget) = @_;
  483.   local ($_);
  484.  
  485.   require Mail::SpamAssassin::PerMsgLearner;
  486.   $self->init(1);
  487.   my $msg = Mail::SpamAssassin::PerMsgLearner->new($self, $mail_obj);
  488.  
  489.   if ($forget) {
  490.     dbg("learn: forgetting message");
  491.     $msg->forget($id);
  492.   } elsif ($isspam) {
  493.     dbg("learn: learning spam");
  494.     $msg->learn_spam($id);
  495.   } else {
  496.     dbg("learn: learning ham");
  497.     $msg->learn_ham($id);
  498.   }
  499.  
  500.   $msg;
  501. }
  502.  
  503. ###########################################################################
  504.  
  505. =item $f->init_learner ( [ { opt => val, ... } ] )
  506.  
  507. Initialise learning.  You may pass the following attribute-value pairs to this
  508. method.
  509.  
  510. =over 4
  511.  
  512. =item caller_will_untie
  513.  
  514. Whether or not the code calling this method will take care of untie'ing
  515. from the Bayes databases (by calling C<finish_learner()>) (optional, default 0).
  516.  
  517. =item force_expire
  518.  
  519. Should an expiration run be forced to occur immediately? (optional, default 0).
  520.  
  521. =item learn_to_journal
  522.  
  523. Should learning data be written to the journal, instead of directly to the
  524. databases? (optional, default 0).
  525.  
  526. =item wait_for_lock
  527.  
  528. Whether or not to wait a long time for locks to complete (optional, default 0).
  529.  
  530. =item opportunistic_expire_check_only
  531.  
  532. During the opportunistic journal sync and expire check, don't actually do the
  533. expire but report back whether or not it should occur (optional, default 0).
  534.  
  535. =item no_relearn
  536.  
  537. If doing a learn operation, and the message has already been learned as
  538. the opposite type, don't re-learn the message.
  539.  
  540. =back
  541.  
  542. =cut
  543.  
  544. sub init_learner {
  545.   my $self = shift;
  546.   my $opts = shift;
  547.   dbg("learn: initializing learner");
  548.  
  549.   # Make sure we're already initialized ...
  550.   $self->init(1);
  551.  
  552.   my %kv = (
  553.     'force_expire'            => 'learn_force_expire',
  554.     'learn_to_journal'            => 'learn_to_journal',
  555.     'caller_will_untie'            => 'learn_caller_will_untie',
  556.     'wait_for_lock'            => 'learn_wait_for_lock',
  557.     'opportunistic_expire_check_only'    => 'opportunistic_expire_check_only',
  558.     'no_relearn'            => 'learn_no_relearn',
  559.   );
  560.  
  561.   my %ret;
  562.  
  563.   # Set any other options that need setting ...
  564.   while( my($k,$v) = each %kv ) {
  565.     $ret{$k} = $self->{$v};
  566.     if (exists $opts->{$k}) { $self->{$v} = $opts->{$k}; }
  567.   }
  568.  
  569.   return \%ret;
  570. }
  571.  
  572. ###########################################################################
  573.  
  574. =item $f->rebuild_learner_caches ({ opt => val })
  575.  
  576. Rebuild any cache databases; should be called after the learning process.
  577. Options include: C<verbose>, which will output diagnostics to C<stdout>
  578. if set to 1.
  579.  
  580. =cut
  581.  
  582. sub rebuild_learner_caches {
  583.   my $self = shift;
  584.   my $opts = shift;
  585.   $self->{bayes_scanner}->sync(1,1,$opts);
  586.   1;
  587. }
  588.  
  589. =item $f->finish_learner ()
  590.  
  591. Finish learning.
  592.  
  593. =cut
  594.  
  595. sub finish_learner {
  596.   my $self = shift;
  597.   $self->{bayes_scanner}->sanity_check_is_untied(1);
  598.   1;
  599. }
  600.  
  601. =item $f->dump_bayes_db()
  602.  
  603. Dump the contents of the Bayes DB
  604.  
  605. =cut
  606.  
  607. sub dump_bayes_db {
  608.   my($self,@opts) = @_;
  609.   $self->{bayes_scanner}->dump_bayes_db(@opts);
  610. }
  611.  
  612. =item $f->signal_user_changed ( [ { opt => val, ... } ] )
  613.  
  614. Signals that the current user has changed (possibly using C<setuid>), meaning
  615. that SpamAssassin should close any per-user databases it has open, and re-open
  616. using ones appropriate for the new user.
  617.  
  618. Note that this should be called I<after> reading any per-user configuration, as
  619. that data may override some paths opened in this method.  You may pass the
  620. following attribute-value pairs:
  621.  
  622. =over 4
  623.  
  624. =item username
  625.  
  626. The username of the user.  This will be used for the C<username> attribute.
  627.  
  628. =item user_dir
  629.  
  630. A directory to use as a 'home directory' for the current user's data,
  631. overriding the system default.  This directory must be readable and writable by
  632. the process.  Note that the resulting C<userstate_dir> will be the
  633. C<.spamassassin> subdirectory of this dir.
  634.  
  635. =item userstate_dir
  636.  
  637. A directory to use as a directory for the current user's data, overriding the
  638. system default.  This directory must be readable and writable by the process.
  639. The default is C<user_dir/.spamassassin>.
  640.  
  641. =back
  642.  
  643. =cut
  644.  
  645. sub signal_user_changed {
  646.   my $self = shift;
  647.   my $opts = shift;
  648.   my $set = 0;
  649.  
  650.   dbg("info: user has changed");
  651.  
  652.   if (defined $opts && $opts->{username}) {
  653.     $self->{username} = $opts->{username};
  654.   }
  655.   if (defined $opts && $opts->{user_dir}) {
  656.     $self->{user_dir} = $opts->{user_dir};
  657.   }
  658.   if (defined $opts && $opts->{userstate_dir}) {
  659.     $self->{userstate_dir} = $opts->{userstate_dir};
  660.   }
  661.  
  662.   # reopen bayes dbs for this user
  663.   $self->{bayes_scanner}->finish();
  664.   $self->{bayes_scanner} = new Mail::SpamAssassin::Bayes ($self);
  665.  
  666.   # this user may have a different learn_to_journal setting, so reset appropriately
  667.   $self->{'learn_to_journal'} = $self->{conf}->{bayes_learn_to_journal};
  668.  
  669.   $set |= 1 unless $self->{local_tests_only};
  670.   $set |= 2 if $self->{bayes_scanner}->is_scan_available();
  671.  
  672.   $self->{conf}->set_score_set ($set);
  673.  
  674.   $self->call_plugins ("signal_user_changed", {
  675.         username => $self->{username},
  676.         userstate_dir => $self->{userstate_dir},
  677.         user_dir => $self->{user_dir},
  678.           });
  679.  
  680.   1;
  681. }
  682.  
  683. ###########################################################################
  684.  
  685. =item $f->report_as_spam ($mail, $options)
  686.  
  687. Report a mail, encapsulated in a C<Mail::SpamAssassin::Message> object, as
  688. human-verified spam.  This will submit the mail message to live,
  689. collaborative, spam-blocker databases, allowing other users to block this
  690. message.
  691.  
  692. It will also submit the mail to SpamAssassin's Bayesian learner.
  693.  
  694. Options is an optional reference to a hash of options.  Currently these
  695. can be:
  696.  
  697. =over 4
  698.  
  699. =item dont_report_to_dcc
  700.  
  701. Inhibits reporting of the spam to DCC.
  702.  
  703. =item dont_report_to_pyzor
  704.  
  705. Inhibits reporting of the spam to Pyzor.
  706.  
  707. =item dont_report_to_razor
  708.  
  709. Inhibits reporting of the spam to Razor.
  710.  
  711. =item dont_report_to_spamcop
  712.  
  713. Inhibits reporting of the spam to SpamCop.
  714.  
  715. =back
  716.  
  717. =cut
  718.  
  719. sub report_as_spam {
  720.   my ($self, $mail, $options) = @_;
  721.   local ($_);
  722.  
  723.   $self->init(1);
  724.  
  725.   # learn as spam if enabled
  726.   if ( $self->{conf}->{bayes_learn_during_report} ) {
  727.     $self->learn ($mail, undef, 1, 0);
  728.   }
  729.  
  730.   require Mail::SpamAssassin::Reporter;
  731.   $mail = Mail::SpamAssassin::Reporter->new($self, $mail, $options);
  732.   $mail->report();
  733. }
  734.  
  735. ###########################################################################
  736.  
  737. =item $f->revoke_as_spam ($mail, $options)
  738.  
  739. Revoke a mail, encapsulated in a C<Mail::SpamAssassin::Message> object, as
  740. human-verified ham (non-spam).  This will revoke the mail message from live,
  741. collaborative, spam-blocker databases, allowing other users to block this
  742. message.
  743.  
  744. It will also submit the mail to SpamAssassin's Bayesian learner as nonspam.
  745.  
  746. Options is an optional reference to a hash of options.  Currently these
  747. can be:
  748.  
  749. =over 4
  750.  
  751. =item dont_report_to_razor
  752.  
  753. Inhibits revoking of the spam to Razor.
  754.  
  755.  
  756. =back
  757.  
  758. =cut
  759.  
  760. sub revoke_as_spam {
  761.   my ($self, $mail, $options) = @_;
  762.   local ($_);
  763.  
  764.   $self->init(1);
  765.  
  766.   # learn as nonspam
  767.   $self->learn ($mail, undef, 0, 0);
  768.  
  769.   require Mail::SpamAssassin::Reporter;
  770.   $mail = Mail::SpamAssassin::Reporter->new($self, $mail, $options);
  771.   $mail->revoke ();
  772. }
  773.  
  774. ###########################################################################
  775.  
  776. =item $f->add_address_to_whitelist ($addr)
  777.  
  778. Given a string containing an email address, add it to the automatic
  779. whitelist database.
  780.  
  781. =cut
  782.  
  783. sub add_address_to_whitelist {
  784.   my ($self, $addr) = @_;
  785.  
  786.   $self->call_plugins("whitelist_address", { address => $addr });
  787. }
  788.  
  789. ###########################################################################
  790.  
  791. =item $f->add_all_addresses_to_whitelist ($mail)
  792.  
  793. Given a mail message, find as many addresses in the usual headers (To, Cc, From
  794. etc.), and the message body, and add them to the automatic whitelist database.
  795.  
  796. =cut
  797.  
  798. sub add_all_addresses_to_whitelist {
  799.   my ($self, $mail_obj) = @_;
  800.  
  801.   foreach my $addr ($self->find_all_addrs_in_mail ($mail_obj)) {
  802.     $self->call_plugins("whitelist_address", { address => $addr });
  803.   }
  804. }
  805.  
  806. ###########################################################################
  807.  
  808. =item $f->remove_address_from_whitelist ($addr)
  809.  
  810. Given a string containing an email address, remove it from the automatic
  811. whitelist database.
  812.  
  813. =cut
  814.  
  815. sub remove_address_from_whitelist {
  816.   my ($self, $addr) = @_;
  817.  
  818.   $self->call_plugins("remove_address", { address => $addr });
  819. }
  820.  
  821. ###########################################################################
  822.  
  823. =item $f->remove_all_addresses_from_whitelist ($mail)
  824.  
  825. Given a mail message, find as many addresses in the usual headers (To, Cc, From
  826. etc.), and the message body, and remove them from the automatic whitelist
  827. database.
  828.  
  829. =cut
  830.  
  831. sub remove_all_addresses_from_whitelist {
  832.   my ($self, $mail_obj) = @_;
  833.  
  834.   foreach my $addr ($self->find_all_addrs_in_mail ($mail_obj)) {
  835.     $self->call_plugins("remove_address", { address => $addr });
  836.   }
  837. }
  838.  
  839. ###########################################################################
  840.  
  841. =item $f->add_address_to_blacklist ($addr)
  842.  
  843. Given a string containing an email address, add it to the automatic
  844. whitelist database with a high score, effectively blacklisting them.
  845.  
  846. =cut
  847.  
  848. sub add_address_to_blacklist {
  849.   my ($self, $addr) = @_;
  850.   $self->call_plugins("blacklist_address", { address => $addr });
  851. }
  852.  
  853. ###########################################################################
  854.  
  855. =item $f->add_all_addresses_to_blacklist ($mail)
  856.  
  857. Given a mail message, find addresses in the From headers and add them to the
  858. automatic whitelist database with a high score, effectively blacklisting them.
  859.  
  860. Note that To and Cc addresses are not used.
  861.  
  862. =cut
  863.  
  864. sub add_all_addresses_to_blacklist {
  865.   my ($self, $mail_obj) = @_;
  866.  
  867.   $self->init(1);
  868.  
  869.   my @addrlist = ();
  870.   my @hdrs = $mail_obj->get_header ('From');
  871.   if ($#hdrs >= 0) {
  872.     push (@addrlist, $self->find_all_addrs_in_line (join (" ", @hdrs)));
  873.   }
  874.  
  875.   foreach my $addr (@addrlist) {
  876.     $self->call_plugins("blacklist_address", { address => $addr });
  877.   }
  878.  
  879. }
  880.  
  881. ###########################################################################
  882.  
  883. =item $text = $f->remove_spamassassin_markup ($mail)
  884.  
  885. Returns the text of the message, with any SpamAssassin-added text (such
  886. as the report, or X-Spam-Status headers) stripped.
  887.  
  888. Note that the B<$mail> object is not modified.
  889.  
  890. =cut
  891.  
  892. sub remove_spamassassin_markup {
  893.   my ($self, $mail_obj) = @_;
  894.   local ($_);
  895.  
  896.   my $mbox = $mail_obj->get_mbox_separator() || '';
  897.  
  898.   dbg("markup: removing markup");
  899.  
  900.   # Go looking for a "report_safe" encapsulated message.  Abort out ASAP
  901.   # if we have definitive proof it's not an encapsulated message.
  902.   my $ct = $mail_obj->get_header("Content-Type") || '';
  903.   if ( $ct =~ m!^\s*multipart/mixed;\s+boundary\s*=\s*["']?(.+?)["']?(?:;|$)!i ) {
  904.  
  905.     # Ok, this is a possible encapsulated message, search for the
  906.     # appropriate mime part and deal with it if necessary.
  907.     my $boundary = "\Q$1\E";
  908.     my @msg = split(/^/,$mail_obj->get_pristine_body());
  909.  
  910.     my $flag = 0;
  911.     $ct   = '';
  912.     my $cd = '';
  913.     for ( my $i = 0 ; $i <= $#msg ; $i++ ) {
  914.       # only look at mime part headers
  915.       next unless ( $msg[$i] =~ /^--$boundary\r?$/ || $flag );
  916.  
  917.       if ( $msg[$i] =~ /^\s*$/ ) {    # end of mime header
  918.  
  919.         # Ok, we found the encapsulated piece ...
  920.     if ($ct =~ m@^(?:message/rfc822|text/plain);\s+x-spam-type=original@ ||
  921.         ($ct eq "message/rfc822" &&
  922.          $cd eq $self->{'encapsulated_content_description'}))
  923.         {
  924.           splice @msg, 0, $i+1;  # remove the front part, including the blank line
  925.  
  926.           # find the end and chop it off
  927.           for ( $i = 0 ; $i <= $#msg ; $i++ ) {
  928.             if ( $msg[$i] =~ /^--$boundary/ ) {
  929.               splice @msg, ($msg[$i-1] =~ /\S/ ? $i : $i-1);
  930.           # will remove the blank line (not sure it'll always be
  931.           # there) and everything below.  don't worry, the splice
  932.           # guarantees the for will stop ...
  933.             }
  934.           }
  935.  
  936.       # Ok, we're done.  Return the rewritten message.
  937.       return join('', $mbox, @msg);
  938.         }
  939.  
  940.         $flag = 0;
  941.         $ct   = '';
  942.         $cd   = '';
  943.         next;
  944.       }
  945.  
  946.       # Ok, we're in the mime header ...  Capture the appropriate headers...
  947.       $flag = 1;
  948.       if ( $msg[$i] =~ /^Content-Type:\s+(.+?)\s*$/i ) {
  949.         $ct = $1;
  950.       }
  951.       elsif ( $msg[$i] =~ /^Content-Description:\s+(.+?)\s*$/i ) {
  952.         $cd = $1;
  953.       }
  954.     }
  955.   }
  956.  
  957.   # Ok, if we got here, the message wasn't a report_safe encapsulated message.
  958.   # So treat it like a "report_safe 0" message.
  959.   my $hdrs = $mail_obj->get_pristine_header();
  960.   my $body = $mail_obj->get_pristine_body();
  961.  
  962.   # remove DOS line endings
  963.   $hdrs =~ s/\r//gs;
  964.  
  965.   # unfold SA added headers, but not X-Spam-Prev headers ...
  966.   $hdrs = "\n".$hdrs;   # simplifies regexp below
  967.   1 while $hdrs =~ s/(\nX-Spam-(?!Prev).+?)\n[ \t]+(\S.*\n)/$1 $2/g;
  968.   $hdrs =~ s/^\n//;
  969.  
  970. ###########################################################################
  971.   # Backward Compatibilty, pre 3.0.x.
  972.  
  973.   # deal with rewritten headers w/out X-Spam-Prev- versions ...
  974.   $self->init(1);
  975.   foreach my $header ( keys %{$self->{conf}->{rewrite_header}} ) {
  976.     # let the 3.0 decoding do it...
  977.     next if ($hdrs =~ /^X-Spam-Prev-$header:/im);
  978.  
  979.     dbg("markup: removing markup in $header");
  980.     if ($header eq 'Subject') {
  981.       my $tag = $self->{conf}->{rewrite_header}->{'Subject'};
  982.       $tag = quotemeta($tag);
  983.       $tag =~ s/_HITS_/\\d{2}\\.\\d{2}/g;
  984.       $tag =~ s/_SCORE_/\\d{2}\\.\\d{2}/g;
  985.       $tag =~ s/_REQD_/\\d{2}\\.\\d{2}/g;
  986.       1 while $hdrs =~ s/^Subject: ${tag} /Subject: /gm;
  987.     } else {
  988.       $hdrs =~ s/^(${header}:[ \t].*?)\t\([^)]*\)$/$1/gm;
  989.     }
  990.   }
  991.  
  992.   # Now deal with report cleansing from 2.4x and previous.
  993.   # possibly a blank line, "SPAM: ----.+", followed by "SPAM: stuff" lines,
  994.   # followed by another "SPAM: ----.+" line, followed by a blank line.
  995.   1 while ($body =~ s/^\n?SPAM: ----.+\n(?:SPAM:.*\n)*SPAM: ----.+\n\n//);
  996. ###########################################################################
  997.  
  998.   # 3.0 version -- support for previously-nonexistent Subject hdr.
  999.   # ensure the Subject line didn't *really* contain "(nonexistent)" in
  1000.   # the original message!
  1001.   if ($hdrs =~ /^X-Spam-Prev-Subject:\s*\(nonexistent\)$/m
  1002.         && $hdrs !~ /^Subject:.*\(nonexistent\).*$/m)
  1003.   {
  1004.     $hdrs =~ s/(^|\n)X-Spam-Prev-Subject:\s*\(nonexistent\)\n/$1\n/s;
  1005.     $hdrs =~ s/(^|\n)Subject:\s*[ \t]*.*\n(?:\s+\S.*\n)*/$1\n/s;
  1006.   }
  1007.  
  1008.   # 3.0 version -- revert from X-Spam-Prev to original ...
  1009.   while ($hdrs =~ s/^X-Spam-Prev-(([^:]+:)[ \t]*.*\n(?:\s+\S.*\n)*)//m) {
  1010.     my($hdr, $name) = ($1,$2);
  1011.  
  1012.     # If the rewritten version doesn't exist, we should deal with it anyway...
  1013.     unless ($hdrs =~ s/^$name[ \t]*.*\n(?:\s+\S.*\n)*/$hdr/m) {
  1014.       $hdrs =~ s/\n\n/\n$hdr\n/;
  1015.     }
  1016.   }
  1017.  
  1018.   # remove any other X-Spam headers we added, will be unfolded
  1019.   $hdrs = "\n".$hdrs;   # simplifies regexp below
  1020.   1 while $hdrs =~ s/\nX-Spam-.*\n/\n/g;
  1021.   $hdrs =~ s/^\n//;
  1022.  
  1023.   # Put the whole thing back together ...
  1024.   return join ('', $mbox, $hdrs, $body);
  1025. }
  1026.  
  1027. ###########################################################################
  1028.  
  1029. =item $f->read_scoreonly_config ($filename)
  1030.  
  1031. Read a configuration file and parse user preferences from it.
  1032.  
  1033. User preferences are as defined in the C<Mail::SpamAssassin::Conf> manual page.
  1034. In other words, they include scoring options, scores, whitelists and
  1035. blacklists, and so on, but do not include rule definitions, privileged
  1036. settings, etc. unless C<allow_user_rules> is enabled; and they never include
  1037. the administrator settings.
  1038.  
  1039. =cut
  1040.  
  1041. sub read_scoreonly_config {
  1042.   my ($self, $filename) = @_;
  1043.  
  1044.   if (!open(IN,"<$filename")) {
  1045.     # the file may not exist; this should not be verbose
  1046.     dbg("config: read_scoreonly_config: cannot open \"$filename\": $!");
  1047.     return;
  1048.   }
  1049.  
  1050.   my $text = "file start $filename\n"
  1051.         . join ('', <IN>)
  1052.         # add an extra \n in case file did not end in one.
  1053.         . "\nfile end $filename\n";
  1054.  
  1055.   close IN;
  1056.  
  1057.   $self->{conf}->{main} = $self;
  1058.   $self->{conf}->parse_scores_only ($text);
  1059.   if ($self->{conf}->{allow_user_rules}) {
  1060.       dbg("config: finishing parsing!");
  1061.       $self->{conf}->finish_parsing();
  1062.   }
  1063.   delete $self->{conf}->{main};    # to allow future GC'ing
  1064. }
  1065.  
  1066. ###########################################################################
  1067.  
  1068. =item $f->load_scoreonly_sql ($username)
  1069.  
  1070. Read configuration paramaters from SQL database and parse scores from it.  This
  1071. will only take effect if the perl C<DBI> module is installed, and the
  1072. configuration parameters C<user_scores_dsn>, C<user_scores_sql_username>, and
  1073. C<user_scores_sql_password> are set correctly.
  1074.  
  1075. The username in C<$username> will also be used for the C<username> attribute of
  1076. the Mail::SpamAssassin object.
  1077.  
  1078. =cut
  1079.  
  1080. sub load_scoreonly_sql {
  1081.   my ($self, $username) = @_;
  1082.  
  1083.   my $src = Mail::SpamAssassin::Conf::SQL->new ($self);
  1084.   $self->{username} = $username;
  1085.   unless ($src->load($username)) {
  1086.     return 0;
  1087.   }
  1088.   return 1;
  1089. }
  1090.  
  1091. ###########################################################################
  1092.  
  1093. =item $f->load_scoreonly_ldap ($username)
  1094.  
  1095. Read configuration paramaters from an LDAP server and parse scores from it.
  1096. This will only take effect if the perl C<Net::LDAP> and C<URI> modules are
  1097. installed, and the configuration parameters C<user_scores_dsn>,
  1098. C<user_scores_ldap_username>, and C<user_scores_ldap_password> are set
  1099. correctly.
  1100.  
  1101. The username in C<$username> will also be used for the C<username> attribute of
  1102. the Mail::SpamAssassin object.
  1103.  
  1104. =cut
  1105.  
  1106. sub load_scoreonly_ldap {
  1107.   my ($self, $username) = @_;
  1108.  
  1109.   dbg("config: load_scoreonly_ldap($username)");
  1110.   my $src = Mail::SpamAssassin::Conf::LDAP->new ($self);
  1111.   $self->{username} = $username;
  1112.   $src->load($username);
  1113. }
  1114.  
  1115. ###########################################################################
  1116.  
  1117. =item $f->set_persistent_address_list_factory ($factoryobj)
  1118.  
  1119. Set the persistent address list factory, used to create objects for the
  1120. automatic whitelist algorithm's persistent-storage back-end.  See
  1121. C<Mail::SpamAssassin::PersistentAddrList> for the API these factory objects
  1122. must implement, and the API the objects they produce must implement.
  1123.  
  1124. =cut
  1125.  
  1126. sub set_persistent_address_list_factory {
  1127.   my ($self, $fac) = @_;
  1128.   $self->{pers_addr_list_factory} = $fac;
  1129. }
  1130.  
  1131. ###########################################################################
  1132.  
  1133. =item $f->compile_now ($use_user_prefs, $keep_userstate)
  1134.  
  1135. Compile all patterns, load all configuration files, and load all
  1136. possibly-required Perl modules.
  1137.  
  1138. Normally, Mail::SpamAssassin uses lazy evaluation where possible, but if you
  1139. plan to fork() or start a new perl interpreter thread to process a message,
  1140. this is suboptimal, as each process/thread will have to perform these actions.
  1141.  
  1142. Call this function in the master thread or process to perform the actions
  1143. straightaway, so that the sub-processes will not have to.
  1144.  
  1145. If C<$use_user_prefs> is 0, this will initialise the SpamAssassin
  1146. configuration without reading the per-user configuration file and it will
  1147. assume that you will call C<read_scoreonly_config> at a later point.
  1148.  
  1149. If C<$keep_userstate> is true, compile_now() will revert any configuration
  1150. options which have a default with I<__userstate__> in it post-init(),
  1151. and then re-change the option before returning.  This lets you change
  1152. I<$ENV{'HOME'}> to a temp directory, have compile_now() and create any
  1153. files there as necessary without disturbing the actual files as changed
  1154. by a configuration option.  By default, this is disabled.
  1155.  
  1156. =cut
  1157.  
  1158. sub compile_now {
  1159.   my ($self, $use_user_prefs, $deal_with_userstate) = @_;
  1160.  
  1161.   # note: this may incur network access. Good.  We want to make sure
  1162.   # as much as possible is preloaded!
  1163.   my @testmsg = ("From: ignore\@compiling.spamassassin.taint.org\n", 
  1164.     "Message-Id:  <".time."\@spamassassin_spamd_init>\n", "\n",
  1165.     "I need to make this message body somewhat long so TextCat preloads\n"x20);
  1166.  
  1167.   dbg("ignore: test message to precompile patterns and load modules");
  1168.  
  1169.   # Backup default values which deal with userstate.
  1170.   # This is done so we can create any new files in, presumably, a temp dir.
  1171.   # see bug 2762 for more details.
  1172.   my %backup = ();
  1173.   if (defined $deal_with_userstate && $deal_with_userstate) {
  1174.     while(my($k,$v) = each %{$self->{conf}}) {
  1175.       $backup{$k} = $v if (defined $v && !ref($v) && $v =~/__userstate__/);
  1176.     }
  1177.   }
  1178.  
  1179.   $self->init($use_user_prefs);
  1180.  
  1181.   # if init() didn't change the value from default, forget about it.
  1182.   # if the value is different, remember the new version, and reset the default.
  1183.   while(my($k,$v) = each %backup) {
  1184.     if ($self->{conf}->{$k} eq $v) {
  1185.       delete $backup{$k};
  1186.     }
  1187.     else {
  1188.       my $backup = $backup{$k};
  1189.       $backup{$k} = $self->{conf}->{$k};
  1190.       $self->{conf}->{$k} = $backup;
  1191.     }
  1192.   }
  1193.  
  1194.   my $mail = $self->parse(\@testmsg, 1);
  1195.   my $status = Mail::SpamAssassin::PerMsgStatus->new($self, $mail,
  1196.                         { disable_auto_learning => 1 } );
  1197.   $status->word_is_in_dictionary("aba"); # load triplets.txt into memory
  1198.   # We want to turn off the bayes rules for this test msg
  1199.   my $use_bayes_rules_value = $self->{conf}->{use_bayes_rules};
  1200.   $self->{conf}->{use_bayes_rules} = 0;
  1201.   $status->check();
  1202.   $self->{conf}->{use_bayes_rules} = $use_bayes_rules_value;
  1203.   $status->finish();
  1204.   $mail->finish();
  1205.   $self->finish_learner();
  1206.  
  1207.   # load SQL modules now as well
  1208.   my $dsn = $self->{conf}->{user_scores_dsn};
  1209.   if ($dsn ne '') {
  1210.     if ($dsn =~ /^ldap:/i) {
  1211.       Mail::SpamAssassin::Conf::LDAP::load_modules();
  1212.     } else {
  1213.       Mail::SpamAssassin::Conf::SQL::load_modules();
  1214.     }
  1215.   }
  1216.  
  1217.   $self->{bayes_scanner}->sanity_check_is_untied();
  1218.  
  1219.   # Reset any non-default values to the post-init() version.
  1220.   while(my($k,$v) = each %backup) {
  1221.     $self->{conf}->{$k} = $v;
  1222.   }
  1223.  
  1224.   # clear sed_path_cache
  1225.   delete $self->{conf}->{sed_path_cache};
  1226.  
  1227.   1;
  1228. }
  1229.  
  1230. ###########################################################################
  1231.  
  1232. =item $f->debug_diagnostics ()
  1233.  
  1234. Output some diagnostic information, useful for debugging SpamAssassin
  1235. problems.
  1236.  
  1237. =cut
  1238.  
  1239. sub debug_diagnostics {
  1240.   my ($self) = @_;
  1241.  
  1242.   # load this class lazily, to avoid overhead when this method isn't
  1243.   # called.
  1244.   eval {
  1245.     require Mail::SpamAssassin::Util::DependencyInfo;
  1246.     dbg(Mail::SpamAssassin::Util::DependencyInfo::debug_diagnostics($self));
  1247.   };
  1248. }
  1249.  
  1250. ###########################################################################
  1251.  
  1252. =item $failed = $f->lint_rules ()
  1253.  
  1254. Syntax-check the current set of rules.  Returns the number of 
  1255. syntax errors discovered, or 0 if the configuration is valid.
  1256.  
  1257. =cut
  1258.  
  1259. sub lint_rules {
  1260.     1;
  1261. }
  1262.  
  1263. sub lint_rules_really {
  1264.   my ($self) = @_;
  1265.  
  1266.   dbg("ignore: using a test message to lint rules");
  1267.   my @testmsg = ("From: ignore\@compiling.spamassassin.taint.org\n", 
  1268.     "Subject: \n",
  1269.     "Message-Id:  <".CORE::time()."\@lint_rules>\n", "\n",
  1270.     "I need to make this message body somewhat long so TextCat preloads\n"x20);
  1271.  
  1272.   $self->{lint_rules} = $self->{conf}->{lint_rules} = 1;
  1273.   $self->{syntax_errors} = 0;
  1274.  
  1275.   my $olddcp = $self->{dont_copy_prefs};
  1276.   $self->{dont_copy_prefs} = 1;
  1277.  
  1278.   $self->init(1);
  1279.   $self->{syntax_errors} += $self->{conf}->{errors};
  1280.  
  1281.   $self->{dont_copy_prefs} = $olddcp;       # revert back to previous
  1282.  
  1283.   # bug 5048: override settings to ensure a faster lint
  1284.   $self->{'conf'}->{'use_auto_whitelist'} = 0;
  1285.   $self->{'conf'}->{'bayes_auto_learn'} = 0;
  1286.  
  1287.   my $mail = $self->parse(\@testmsg, 1);
  1288.   my $status = Mail::SpamAssassin::PerMsgStatus->new($self, $mail,
  1289.                         { disable_auto_learning => 1 } );
  1290.   $status->check();
  1291.  
  1292.   $self->{syntax_errors} += $status->{rule_errors};
  1293.   $status->finish();
  1294.   $mail->finish();
  1295.  
  1296.   return ($self->{syntax_errors});
  1297. }
  1298.  
  1299. ###########################################################################
  1300.  
  1301. =item $f->finish()
  1302.  
  1303. Destroy this object, so that it will be garbage-collected once it
  1304. goes out of scope.  The object will no longer be usable after this
  1305. method is called.
  1306.  
  1307. =cut
  1308.  
  1309. sub finish {
  1310.   my ($self) = @_;
  1311.  
  1312.   $self->{parser_dns_pms}->finish();
  1313.   Mail::SpamAssassin::PerMsgStatus::finish_tests($self->{conf});
  1314.   $self->{conf}->finish(); delete $self->{conf};
  1315.   $self->{plugins}->finish(); delete $self->{plugins};
  1316.  
  1317.   if ($self->{bayes_scanner}) {
  1318.     $self->{bayes_scanner}->finish();
  1319.     delete $self->{bayes_scanner};
  1320.   }
  1321.  
  1322.   $self->{resolver}->finish();
  1323.  
  1324.   foreach(keys %{$self}) {
  1325.     delete $self->{$_};
  1326.   }
  1327. }
  1328.  
  1329. ###########################################################################
  1330. # non-public methods.
  1331.  
  1332. sub init {
  1333.   my ($self, $use_user_pref) = @_;
  1334.  
  1335.   # Allow init() to be called multiple times, but only run once.
  1336.   if (defined $self->{_initted}) {
  1337.     # If the PID changes, reseed the PRNG and the DNS ID counter
  1338.     if ($self->{_initted} != $$) {
  1339.       $self->{_initted} = $$;
  1340.       srand;
  1341.       $self->{resolver}->reinit_post_fork();
  1342.     }
  1343.     return;
  1344.   }
  1345.  
  1346.   # Note that this PID has run init()
  1347.   $self->{_initted} = $$;
  1348.  
  1349.   #fix spamd reading root prefs file
  1350.   if (!defined $use_user_pref) {
  1351.     $use_user_pref = 1;
  1352.   }
  1353.  
  1354.   if (!defined $self->{config_text}) {
  1355.     $self->{config_text} = '';
  1356.  
  1357.     my $fname;
  1358.  
  1359.     # read a file called "init.pre" in site rules dir *before* all others;
  1360.     # even the system config.
  1361.     my $siterules = $self->{site_rules_filename};
  1362.     $siterules ||= $self->first_existing_path (@site_rules_path);
  1363.  
  1364.     my $sysrules = $self->{rules_filename};
  1365.     $sysrules ||= $self->first_existing_path (@default_rules_path);
  1366.  
  1367.     if ($siterules) {
  1368.       $self->{config_text} .= $self->read_pre($siterules, 'site rules pre files');
  1369.     }
  1370.     else {
  1371.       warn "config: could not find site rules directory\n";
  1372.     }
  1373.  
  1374.     if ($sysrules) {
  1375.       $self->{config_text} .= $self->read_pre($sysrules, 'sys rules pre files');
  1376.     }
  1377.     else {
  1378.       warn "config: could not find sys rules directory\n";
  1379.     }
  1380.  
  1381.     $fname = $sysrules;
  1382.     if ($fname) {
  1383.       $self->{config_text} .= $self->read_cf ($fname, 'default rules dir');
  1384.       }
  1385.  
  1386.     if (!$self->{languages_filename}) {
  1387.       $self->{languages_filename} = $self->find_rule_support_file("languages");
  1388.     }
  1389.  
  1390.     $fname = $siterules;
  1391.     if ($fname) {
  1392.       $self->{config_text} .= $self->read_cf ($fname, 'site rules dir');
  1393.     }
  1394.  
  1395.     if ( $use_user_pref != 0 ) {
  1396.       $self->get_and_create_userstate_dir();
  1397.  
  1398.       # user prefs file
  1399.       $fname = $self->{userprefs_filename};
  1400.       $fname ||= $self->first_existing_path (@default_userprefs_path);
  1401.  
  1402.       if (!$self->{dont_copy_prefs}) {
  1403.         # bug 4932: if the userprefs path doesn't exist, we need to make it, so
  1404.         # just use the last entry in the array as the default path.
  1405.         $fname ||= $self->sed_path($default_userprefs_path[-1]);
  1406.  
  1407.     if (!-f $fname && !$self->create_default_prefs($fname)) {
  1408.           warn "config: failed to create default user preference file $fname\n";
  1409.         }
  1410.       }
  1411.  
  1412.       $self->{config_text} .= $self->read_cf ($fname, 'user prefs file');
  1413.     }
  1414.   }
  1415.  
  1416.   if ($self->{config_text} !~ /\S/) {
  1417.     warn "config: no configuration text or files found! please check your setup\n";
  1418.   }
  1419.  
  1420.   # Go and parse the config!
  1421.   $self->{conf}->{main} = $self;
  1422.   $self->{conf}->parse_rules ($self->{config_text});
  1423.   $self->{conf}->finish_parsing ();
  1424.   delete $self->{conf}->{main};    # to allow future GC'ing
  1425.  
  1426.   undef $self->{config_text};   # ensure it's actually freed
  1427.   delete $self->{config_text};
  1428.  
  1429.   # Initialize the Bayes subsystem
  1430.   $self->{bayes_scanner} = new Mail::SpamAssassin::Bayes ($self);
  1431.   $self->{'learn_to_journal'} = $self->{conf}->{bayes_learn_to_journal};
  1432.  
  1433.   # Figure out/set our initial scoreset
  1434.   my $set = 0;
  1435.   $set |= 1 unless $self->{local_tests_only};
  1436.   $set |= 2 if $self->{bayes_scanner}->is_scan_available();
  1437.   $self->{conf}->set_score_set ($set);
  1438.  
  1439.   if ($self->{only_these_rules}) {
  1440.     $self->{conf}->trim_rules($self->{only_these_rules});
  1441.   }
  1442.  
  1443.   # TODO -- open DNS cache etc. if necessary
  1444. }
  1445.  
  1446. sub read_cf {
  1447.   my ($self, $path, $desc) = @_;
  1448.  
  1449.   return '' unless defined ($path);
  1450.  
  1451.   dbg("config: using \"$path\" for $desc");
  1452.   my $txt = '';
  1453.  
  1454.   if (-d $path) {
  1455.     foreach my $file ($self->get_cf_files_in_dir ($path)) {
  1456.       $txt .= read_cf_file($file);
  1457.     }
  1458.  
  1459.   } elsif (-f $path && -s _ && -r _) {
  1460.     $txt .= read_cf_file($path);
  1461.   }
  1462.  
  1463.   return $txt;
  1464. }
  1465.  
  1466.  
  1467. sub read_pre {
  1468.   my ($self, $path, $desc) = @_;
  1469.  
  1470.   return '' unless defined ($path);
  1471.  
  1472.   dbg("config: using \"$path\" for $desc");
  1473.   my $txt = '';
  1474.  
  1475.   if (-d $path) {
  1476.     foreach my $file ($self->get_pre_files_in_dir($path)) {
  1477.       $txt .= read_cf_file($file); # ok to use read_cf_file at this point
  1478.     }
  1479.  
  1480.   } elsif (-f $path && -s _ && -r _) {
  1481.     $txt .= read_cf_file($path);
  1482.   }
  1483.  
  1484.   return $txt;
  1485. }
  1486.  
  1487. sub read_cf_file {
  1488.   my($path) = @_;
  1489.   my $txt = '';
  1490.  
  1491.   if (open (IN, "<".$path)) {
  1492.     $txt = "file start $path\n";
  1493.     $txt .= join ('', <IN>);
  1494.     # add an extra \n in case file did not end in one.
  1495.     $txt .= "\nfile end $path\n";
  1496.     close IN;
  1497.     dbg("config: read file $path");
  1498.   }
  1499.   else {
  1500.     warn "config: cannot open \"$path\": $!\n";
  1501.   }
  1502.  
  1503.   return $txt;
  1504. }
  1505.  
  1506. sub get_and_create_userstate_dir {
  1507.   my ($self) = @_;
  1508.  
  1509.   my $fname;
  1510.  
  1511.   # If vpopmail is enabled then set fname to virtual homedir
  1512.   # precedence: userstate_dir, derive from user_dir, system default
  1513.   if (defined $self->{userstate_dir}) {
  1514.     $fname = $self->{userstate_dir};
  1515.   }
  1516.   elsif (defined $self->{user_dir}) {
  1517.     $fname = File::Spec->catdir ($self->{user_dir}, ".spamassassin");
  1518.   }
  1519.  
  1520.   $fname ||= $self->first_existing_path (@default_userstate_dir);
  1521.  
  1522.   # bug 4932: use the last default_userstate_dir entry if none of the others
  1523.   # already exist
  1524.   $fname ||= $self->sed_path($default_userstate_dir[-1]);
  1525.  
  1526.   if (!$self->{dont_copy_prefs}) {
  1527.     dbg("config: using \"$fname\" for user state dir");
  1528.   }
  1529.  
  1530.   # bug 4932: we always want to make the userstate directory, even if
  1531.   # dont_copy_prefs is true for things like bayes, awl, etc.
  1532.   if (!-d $fname) {
  1533.     # not being able to create the *dir* is not worth a warning at all times
  1534.     eval { mkpath($fname, 0, 0700) } or dbg("config: mkdir $fname failed: $@ $!\n");
  1535.   }
  1536.  
  1537.   $fname;
  1538. }
  1539.  
  1540. =item $fullpath = $f->find_rule_support_file ($filename)
  1541.  
  1542. Find a rule-support file, such as C<languages> or C<triplets.txt>,
  1543. in the system-wide rules directory, and return its full path if
  1544. it exists, or undef if it doesn't exist.
  1545.  
  1546. (This API was added in SpamAssassin 3.1.1.)
  1547.  
  1548. =cut
  1549.  
  1550. sub find_rule_support_file {
  1551.   my ($self, $filename) = @_;
  1552.  
  1553.   # take a copy to avoid modifying the real one (stupid map { } side-effect)
  1554.   my @paths = @default_rules_path;
  1555.   return $self->first_existing_path (map {
  1556.       s/$/\/${filename}/;
  1557.       $_;
  1558.     } @paths);
  1559. }
  1560.  
  1561. =item $f->create_default_prefs ($filename, $username [ , $userdir ] )
  1562.  
  1563. Copy default preferences file into home directory for later use and
  1564. modification, if it does not already exist and C<dont_copy_prefs> is
  1565. not set.
  1566.  
  1567. =cut
  1568.  
  1569. sub create_default_prefs {
  1570.   # $userdir will only exist if vpopmail config is enabled thru spamd
  1571.   # Its value will be the virtual user's maildir
  1572.   #
  1573.   my ($self, $fname, $user, $userdir) = @_;
  1574.  
  1575.   if ($self->{dont_copy_prefs}) {
  1576.     return(0);
  1577.   }
  1578.  
  1579.   if ($userdir && $userdir ne $self->{user_dir}) {
  1580.     warn "config: oops! user_dirs don't match! '$userdir' vs '$self->{user_dir}'\n";
  1581.   }
  1582.  
  1583.   if (!-f $fname)
  1584.   {
  1585.     # Pass on the value of $userdir for virtual users in vpopmail
  1586.     # otherwise it is empty and the user's normal homedir is used
  1587.     $self->get_and_create_userstate_dir();
  1588.  
  1589.     # copy in the default one for later editing
  1590.     my $defprefs = $self->first_existing_path (@Mail::SpamAssassin::default_prefs_path);
  1591.  
  1592.     if (defined $defprefs && open (IN, "<$defprefs")) {
  1593.       $fname = Mail::SpamAssassin::Util::untaint_file_path($fname);
  1594.       if (open (OUT, ">$fname")) {
  1595.         while (<IN>) {
  1596.           /^\#\* / and next;
  1597.           print OUT;
  1598.         }
  1599.         close OUT;
  1600.         close IN;
  1601.  
  1602.         if (($< == 0) && ($> == 0) && defined($user)) { # chown it
  1603.           my ($uid,$gid) = (getpwnam($user))[2,3];
  1604.           unless (chown($uid, $gid, $fname)) {
  1605.             warn "config: couldn't chown $fname to $uid:$gid for $user: $!\n";
  1606.           }
  1607.         }
  1608.         warn "config: created user preferences file: $fname\n";
  1609.         return(1);
  1610.       }
  1611.       else {
  1612.         warn "config: cannot write to $fname: $!\n";
  1613.       }
  1614.     }
  1615.     elsif (defined $defprefs) {
  1616.       warn "config: cannot open $defprefs: $!\n";
  1617.     }
  1618.     else {
  1619.       warn "config: can not determine default prefs path\n";
  1620.     }
  1621.   }
  1622.  
  1623.   return(0);
  1624. }
  1625.  
  1626. ###########################################################################
  1627.  
  1628. sub expand_name ($) {
  1629.   my ($self, $name) = @_;
  1630.   my $home = $self->{user_dir} || $ENV{HOME} || '';
  1631.  
  1632.   if (Mail::SpamAssassin::Util::am_running_on_windows()) {
  1633.     my $userprofile = $ENV{USERPROFILE} || '';
  1634.  
  1635.     return $userprofile if ($userprofile && $userprofile =~ m/^[a-z]\:[\/\\]/oi);
  1636.     return $userprofile if ($userprofile =~ m/^\\\\/o);
  1637.  
  1638.     return $home if ($home && $home =~ m/^[a-z]\:[\/\\]/oi);
  1639.     return $home if ($home =~ m/^\\\\/o);
  1640.  
  1641.     return '';
  1642.   } else {
  1643.     return $home if ($home && $home =~ /\//o);
  1644.     return (getpwnam($name))[7] if ($name ne '');
  1645.     return (getpwuid($>))[7];
  1646.   }
  1647. }
  1648.  
  1649. sub sed_path {
  1650.   my ($self, $path) = @_;
  1651.   return undef if (!defined $path);
  1652.  
  1653.   if (exists($self->{conf}->{sed_path_cache}->{$path})) {
  1654.     return $self->{conf}->{sed_path_cache}->{$path};
  1655.   }
  1656.  
  1657.   my $orig_path = $path;
  1658.  
  1659.   $path =~ s/__local_rules_dir__/$self->{LOCAL_RULES_DIR} || ''/ges;
  1660.   $path =~ s/__local_state_dir__/$self->{LOCAL_STATE_DIR} || ''/ges;
  1661.   $path =~ s/__def_rules_dir__/$self->{DEF_RULES_DIR} || ''/ges;
  1662.   $path =~ s{__prefix__}{$self->{PREFIX} || $Config{prefix} || '/usr'}ges;
  1663.   $path =~ s{__userstate__}{$self->get_and_create_userstate_dir() || ''}ges;
  1664.   $path =~ s/__version__/${VERSION}/gs;
  1665.   $path =~ s/^\~([^\/]*)/$self->expand_name($1)/es;
  1666.  
  1667.   $path = Mail::SpamAssassin::Util::untaint_file_path ($path);
  1668.   $self->{conf}->{sed_path_cache}->{$orig_path} = $path;
  1669.   return $path;
  1670. }
  1671.  
  1672. sub first_existing_path {
  1673.   my $self = shift;
  1674.   my $path;
  1675.   foreach my $p (@_) {
  1676.     $path = $self->sed_path ($p);
  1677.     if (defined $path && -e $path) { return $path; }
  1678.   }
  1679.   return;
  1680. }
  1681.  
  1682. sub get_cf_files_in_dir {
  1683.   my ($self, $dir) = @_;
  1684.  
  1685.   opendir(SA_CF_DIR, $dir) or warn "config: cannot opendir $dir: $!\n";
  1686.   my @cfs = grep { /\.cf$/i && -f "$dir/$_" } readdir(SA_CF_DIR);
  1687.   closedir SA_CF_DIR;
  1688.  
  1689.   return map { "$dir/$_" } sort { $a cmp $b } @cfs;
  1690. }
  1691.  
  1692. sub get_pre_files_in_dir {
  1693.   my ($self, $dir) = @_;
  1694.  
  1695.   opendir(SA_PRE_DIR, $dir) or warn "config: cannot opendir $dir: $!\n";
  1696.   my @cfs = grep { /\.pre$/i && -f "$dir/$_" } readdir(SA_PRE_DIR);
  1697.   closedir SA_PRE_DIR;
  1698.  
  1699.   return map { "$dir/$_" } sort { $a cmp $b } @cfs;
  1700. }
  1701.  
  1702. ###########################################################################
  1703.  
  1704. sub call_plugins {
  1705.   my $self = shift;
  1706.  
  1707.   # We could potentially get called after a finish(), so just return.
  1708.   return unless $self->{plugins};
  1709.  
  1710.   my $subname = shift;
  1711.   return $self->{plugins}->callback ($subname, @_);
  1712. }
  1713.  
  1714. ###########################################################################
  1715.  
  1716. sub find_all_addrs_in_mail {
  1717.   my ($self, $mail_obj) = @_;
  1718.  
  1719.   $self->init(1);
  1720.  
  1721.   my @addrlist = ();
  1722.   foreach my $header (qw(To From Cc Reply-To Sender
  1723.                   Errors-To Mail-Followup-To))
  1724.   {
  1725.     my @hdrs = $mail_obj->get_header ($header);
  1726.     if ($#hdrs < 0) { next; }
  1727.     push (@addrlist, $self->find_all_addrs_in_line (join (" ", @hdrs)));
  1728.   }
  1729.  
  1730.   # find addrs in body, too
  1731.   foreach my $line (@{$mail_obj->get_body()}) {
  1732.     push (@addrlist, $self->find_all_addrs_in_line ($line));
  1733.   }
  1734.  
  1735.   my @ret = ();
  1736.   my %done = ();
  1737.  
  1738.   foreach $_ (@addrlist) {
  1739.     s/^mailto://;       # from Outlook "forwarded" message
  1740.     next if defined ($done{$_}); $done{$_} = 1;
  1741.     push (@ret, $_);
  1742.   }
  1743.  
  1744.   @ret;
  1745. }
  1746.  
  1747. sub find_all_addrs_in_line {
  1748.   my ($self, $line) = @_;
  1749.  
  1750.   # a more permissive pattern based on "dot-atom" as per RFC2822
  1751.   my $ID_PATTERN   = '[-a-z0-9_\+\:\=\!\#\$\%\&\*\^\?\{\}\|\~\/\.]+';
  1752.   my $HOST_PATTERN = '[-a-z0-9_\+\:\/]+';
  1753.  
  1754.   my @addrs = ();
  1755.   my %seen = ();
  1756.   while ($line =~ s/(?:mailto:)?\s*
  1757.           ($ID_PATTERN \@
  1758.           $HOST_PATTERN(?:\.$HOST_PATTERN)+)//oix) 
  1759.   {
  1760.     my $addr = $1;
  1761.     $addr =~ s/^mailto://;
  1762.     next if (defined ($seen{$addr})); $seen{$addr} = 1;
  1763.     push (@addrs, $addr);
  1764.   }
  1765.  
  1766.   return @addrs;
  1767. }
  1768.  
  1769. ###########################################################################
  1770.  
  1771. # sa_die -- used to die with a useful exit code.
  1772.  
  1773. sub sa_die {
  1774.   my $exitcode = shift;
  1775.   warn @_;
  1776.   exit $exitcode;
  1777. }
  1778.  
  1779. ###########################################################################
  1780.  
  1781. =item $f->copy_config ( [ $source ], [ $dest ] )
  1782.  
  1783. Used for daemons to keep a persistent Mail::SpamAssassin object's
  1784. configuration correct if switching between users.  Pass an associative
  1785. array reference as either $source or $dest, and set the other to 'undef'
  1786. so that the object will use its current configuration.  i.e.:
  1787.  
  1788.   # create object w/ configuration
  1789.   my $spamtest = Mail::SpamAssassin->new( ... );
  1790.  
  1791.   # backup configuration to %conf_backup
  1792.   my %conf_backup = ();
  1793.   $spamtest->copy_config(undef, \%conf_backup) ||
  1794.     die "config: error returned from copy_config!\n";
  1795.  
  1796.   ... do stuff, perhaps modify the config, etc ...
  1797.  
  1798.   # reset the configuration back to the original
  1799.   $spamtest->copy_config(\%conf_backup, undef) ||
  1800.     die "config: error returned from copy_config!\n";
  1801.  
  1802. Note that the contents of the associative arrays should be considered
  1803. opaque by calling code.
  1804.  
  1805. =cut
  1806.  
  1807. sub copy_config {
  1808.   my ($self, $source, $dest) = @_;
  1809.  
  1810.   # At least one of either source or dest needs to be a hash reference ...
  1811.   unless ((defined $source && ref($source) eq 'HASH') ||
  1812.           (defined $dest && ref($dest) eq 'HASH'))
  1813.   {
  1814.     return 0;
  1815.   }
  1816.  
  1817.   # let the Conf object itself do all the heavy lifting.  It's better
  1818.   # than having this class know all about that class' internals...
  1819.   if (defined $source) {
  1820.     dbg ("config: copying current conf from backup");
  1821.   }
  1822.   else {
  1823.     dbg ("config: copying current conf to backup");
  1824.   }
  1825.   return $self->{conf}->clone($source, $dest);
  1826. }
  1827.  
  1828.  
  1829. 1;
  1830. __END__
  1831.  
  1832. ###########################################################################
  1833.  
  1834. =back
  1835.  
  1836. =head1 PREREQUISITES
  1837.  
  1838. C<HTML::Parser>
  1839. C<Sys::Syslog>
  1840.  
  1841. =head1 MORE DOCUMENTATION
  1842.  
  1843. See also E<lt>http://spamassassin.apache.org/E<gt> and
  1844. E<lt>http://wiki.apache.org/spamassassin/E<gt> for more information.
  1845.  
  1846. =head1 SEE ALSO
  1847.  
  1848. Mail::SpamAssassin::Conf(3)
  1849. Mail::SpamAssassin::PerMsgStatus(3)
  1850. spamassassin(1)
  1851. sa-update(1)
  1852.  
  1853. =head1 BUGS
  1854.  
  1855. See E<lt>http://issues.apache.org/SpamAssassin/E<gt>
  1856.  
  1857. =head1 AUTHORS
  1858.  
  1859. The SpamAssassin(tm) Project E<lt>http://spamassassin.apache.org/E<gt>
  1860.  
  1861. =head1 COPYRIGHT
  1862.  
  1863. SpamAssassin is distributed under the Apache License, Version 2.0, as
  1864. described in the file C<LICENSE> included with the distribution.
  1865.  
  1866. =head1 AVAILABILITY
  1867.  
  1868. The latest version of this library is likely to be available from CPAN
  1869. as well as:
  1870.  
  1871.   E<lt>http://spamassassin.apache.org/E<gt>
  1872.  
  1873. =cut
  1874.