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 / BayesStore / DBM.pm next >
Text File  |  2006-11-29  |  59KB  |  1,921 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. package Mail::SpamAssassin::BayesStore::DBM;
  17.  
  18. use strict;
  19. use warnings;
  20. use bytes;
  21. use Fcntl;
  22.  
  23. use Mail::SpamAssassin;
  24. use Mail::SpamAssassin::Util;
  25. use Mail::SpamAssassin::BayesStore;
  26. use Mail::SpamAssassin::Logger;
  27. use Digest::SHA1 qw(sha1);
  28. use File::Basename;
  29. use File::Spec;
  30. use File::Path;
  31.  
  32. use constant MAGIC_RE    => qr/^\015\001\007\011\003/;
  33.  
  34. use vars qw{
  35.   @ISA
  36.   @DBNAMES
  37.   $NSPAM_MAGIC_TOKEN $NHAM_MAGIC_TOKEN $LAST_EXPIRE_MAGIC_TOKEN $LAST_JOURNAL_SYNC_MAGIC_TOKEN
  38.   $NTOKENS_MAGIC_TOKEN $OLDEST_TOKEN_AGE_MAGIC_TOKEN $LAST_EXPIRE_REDUCE_MAGIC_TOKEN
  39.   $RUNNING_EXPIRE_MAGIC_TOKEN $DB_VERSION_MAGIC_TOKEN $LAST_ATIME_DELTA_MAGIC_TOKEN
  40.   $NEWEST_TOKEN_AGE_MAGIC_TOKEN
  41. };
  42.  
  43. @ISA = qw( Mail::SpamAssassin::BayesStore );
  44.  
  45. # db layout (quoting Matt):
  46. #
  47. # > need five db files though to make it real fast:
  48. # [probs] 1. ngood and nbad (two entries, so could be a flat file rather 
  49. # than a db file).    (now 2 entries in db_toks)
  50. # [toks]  2. good token -> number seen
  51. # [toks]  3. bad token -> number seen (both are packed into 1 entry in 1 db)
  52. # [probs]  4. Consolidated good token -> probability
  53. # [probs]  5. Consolidated bad token -> probability
  54. # > As you add new mails, you update the entry in 2 or 3, then regenerate
  55. # > the entry for that token in 4 or 5.
  56. # > Then as you test a new mail, you just need to pull the probability
  57. # > direct from 4 and 5, and generate the overall probability. A simple and
  58. # > very fast operation. 
  59. #
  60. # jm: we use probs as overall probability. <0.5 = ham, >0.5 = spam
  61. #
  62. # update: probs is no longer maintained as a db, to keep on-disk and in-core
  63. # usage down.
  64. #
  65. # also, added a new one to support forgetting, auto-learning, and
  66. # auto-forgetting for refiled mails:
  67. # [seen]  6. a list of Message-IDs of messages already learnt from. values
  68. # are 's' for learnt-as-spam, 'h' for learnt-as-ham.
  69. #
  70. # and another, called [scancount] to model the scan-count for expiry.
  71. # This is not a database.  Instead it increases by one byte for each
  72. # message scanned (note: scanned, not learned).
  73.  
  74. @DBNAMES = qw(toks seen);
  75.  
  76. # These are the magic tokens we use to track stuff in the DB.
  77. # The format is '^M^A^G^I^C' followed by any string you want.
  78. # None of the control chars will be in a real token.
  79. $DB_VERSION_MAGIC_TOKEN        = "\015\001\007\011\003DBVERSION";
  80. $LAST_ATIME_DELTA_MAGIC_TOKEN    = "\015\001\007\011\003LASTATIMEDELTA";
  81. $LAST_EXPIRE_MAGIC_TOKEN    = "\015\001\007\011\003LASTEXPIRE";
  82. $LAST_EXPIRE_REDUCE_MAGIC_TOKEN    = "\015\001\007\011\003LASTEXPIREREDUCE";
  83. $LAST_JOURNAL_SYNC_MAGIC_TOKEN    = "\015\001\007\011\003LASTJOURNALSYNC";
  84. $NEWEST_TOKEN_AGE_MAGIC_TOKEN    = "\015\001\007\011\003NEWESTAGE";
  85. $NHAM_MAGIC_TOKEN        = "\015\001\007\011\003NHAM";
  86. $NSPAM_MAGIC_TOKEN        = "\015\001\007\011\003NSPAM";
  87. $NTOKENS_MAGIC_TOKEN        = "\015\001\007\011\003NTOKENS";
  88. $OLDEST_TOKEN_AGE_MAGIC_TOKEN    = "\015\001\007\011\003OLDESTAGE";
  89. $RUNNING_EXPIRE_MAGIC_TOKEN    = "\015\001\007\011\003RUNNINGEXPIRE";
  90.  
  91. sub HAS_DBM_MODULE {
  92.   my ($self) = @_;
  93.   if (exists($self->{has_dbm_module})) {
  94.     return $self->{has_dbm_module};
  95.   }
  96.   $self->{has_dbm_module} = eval { require DB_File; };
  97. }
  98.  
  99. sub DBM_MODULE {
  100.   return "DB_File";
  101. }
  102.  
  103. # Possible file extensions used by the kinds of database files DB_File
  104. # might create.  We need these so we can create a new file and rename
  105. # it into place.
  106. sub DB_EXTENSIONS {
  107.   return ('', '.db');
  108. }
  109.  
  110. ###########################################################################
  111.  
  112. sub new {
  113.   my $class = shift;
  114.   $class = ref($class) || $class;
  115.  
  116.   my $self = $class->SUPER::new(@_);
  117.  
  118.   $self->{supported_db_version} = 3;
  119.  
  120.   $self->{already_tied} = 0;
  121.   $self->{is_locked} = 0;
  122.   $self->{string_to_journal} = '';
  123.  
  124.   $self;
  125. }
  126.  
  127. ###########################################################################
  128.  
  129. sub tie_db_readonly {
  130.   my ($self) = @_;
  131.  
  132.   if (!$self->HAS_DBM_MODULE) {
  133.     dbg("bayes: " . $self->DBM_MODULE . " module not installed, cannot use bayes");
  134.     return 0;
  135.   }
  136.  
  137.   # return if we've already tied to the db's, using the same mode
  138.   # (locked/unlocked) as before.
  139.   return 1 if ($self->{already_tied} && $self->{is_locked} == 0);
  140.  
  141.   my $main = $self->{bayes}->{main};
  142.   if (!defined($main->{conf}->{bayes_path})) {
  143.     dbg("bayes: bayes_path not defined");
  144.     return 0;
  145.   }
  146.  
  147.   $self->read_db_configs();
  148.  
  149.   my $path = $main->sed_path($main->{conf}->{bayes_path});
  150.  
  151.   my $found = 0;
  152.   for my $ext ($self->DB_EXTENSIONS) {
  153.     if (-f $path.'_toks'.$ext) {
  154.       $found = 1;
  155.       last;
  156.     }
  157.   }
  158.  
  159.   if (!$found) {
  160.     dbg("bayes: no dbs present, cannot tie DB R/O: ${path}_toks");
  161.     return 0;
  162.   }
  163.  
  164.   foreach my $dbname (@DBNAMES) {
  165.     my $name = $path.'_'.$dbname;
  166.     my $db_var = 'db_'.$dbname;
  167.     dbg("bayes: tie-ing to DB file R/O $name");
  168.  
  169.     # untie %{$self->{$db_var}} if (tied %{$self->{$db_var}});
  170.     if (!tie %{$self->{$db_var}},$self->DBM_MODULE, $name, O_RDONLY,
  171.          (oct($main->{conf}->{bayes_file_mode}) & 0666))
  172.     {
  173.       # bug 2975: it's acceptable for the db_seen to not be present,
  174.       # to allow it to be recycled.  if that's the case, just create
  175.       # a new, empty one. we don't need to lock it, since we won't
  176.       # be writing to it; let the R/W api deal with that case.
  177.  
  178.       if ($dbname eq 'seen') {
  179.         tie %{$self->{$db_var}},$self->DBM_MODULE, $name, O_RDWR|O_CREAT,
  180.                     (oct($main->{conf}->{bayes_file_mode}) & 0666)
  181.           or goto failed_to_tie;
  182.       }
  183.       else {
  184.         goto failed_to_tie;
  185.       }
  186.     }
  187.   }
  188.  
  189.   $self->{db_version} = ($self->get_storage_variables())[6];
  190.   dbg("bayes: found bayes db version ".$self->{db_version});
  191.  
  192.   # If the DB version is one we don't understand, abort!
  193.   if ($self->_check_db_version() != 0) {
  194.     warn("bayes: bayes db version ".$self->{db_version}." is not able to be used, aborting!");
  195.     $self->untie_db();
  196.     return 0;
  197.   }
  198.  
  199.   $self->{already_tied} = 1;
  200.   return 1;
  201.  
  202. failed_to_tie:
  203.   warn "bayes: cannot open bayes databases ${path}_* R/O: tie failed: $!\n";
  204.   foreach my $dbname (@DBNAMES) {
  205.     my $db_var = 'db_'.$dbname;
  206.     next unless exists $self->{$db_var};
  207.     dbg("bayes: untie-ing DB file $dbname");
  208.     untie %{$self->{$db_var}};
  209.   }
  210.  
  211.   return 0;
  212. }
  213.  
  214. # tie() to the databases, read-write and locked.  Any callers of
  215. # this should ensure they call untie_db() afterwards!
  216. #
  217. sub tie_db_writable {
  218.   my ($self) = @_;
  219.  
  220.   if (!$self->HAS_DBM_MODULE) {
  221.     dbg("bayes: " . $self->DBM_MODULE . " module not installed, cannot use bayes");
  222.     return 0;
  223.   }
  224.  
  225.   # Useful shortcut ...
  226.   my $main = $self->{bayes}->{main};
  227.  
  228.   # if we've already tied the db's using the same mode
  229.   # (locked/unlocked) as we want now, freshen the lock and return.
  230.   if ($self->{already_tied} && $self->{is_locked} == 1) {
  231.     $main->{locker}->refresh_lock($self->{locked_file});
  232.     return 1;
  233.   }
  234.  
  235.   if (!defined($main->{conf}->{bayes_path})) {
  236.     dbg("bayes: bayes_path not defined");
  237.     return 0;
  238.   }
  239.  
  240.   $self->read_db_configs();
  241.  
  242.   my $path = $main->sed_path($main->{conf}->{bayes_path});
  243.  
  244.   my $found = 0;
  245.   for my $ext ($self->DB_EXTENSIONS) {
  246.     if (-f $path.'_toks'.$ext) {
  247.       $found = 1;
  248.       last;
  249.     }
  250.   }
  251.  
  252.   my $parentdir = dirname($path);
  253.   if (!-d $parentdir) {
  254.     # run in an eval(); if mkpath has no perms, it calls die()
  255.     eval {
  256.       mkpath($parentdir, 0, (oct($main->{conf}->{bayes_file_mode}) & 0777));
  257.     };
  258.   }
  259.  
  260.   my $tout;
  261.   if ($main->{learn_wait_for_lock}) {
  262.     $tout = 300;       # TODO: Dan to write better lock code
  263.   } else {
  264.     $tout = 10;
  265.   }
  266.   if ($main->{locker}->safe_lock($path, $tout, $main->{conf}->{bayes_file_mode}))
  267.   {
  268.     $self->{locked_file} = $path;
  269.     $self->{is_locked} = 1;
  270.   } else {
  271.     warn "bayes: cannot open bayes databases ${path}_* R/W: lock failed: $!\n";
  272.     return 0;
  273.   }
  274.  
  275.   my $umask = umask 0;
  276.   foreach my $dbname (@DBNAMES) {
  277.     my $name = $path.'_'.$dbname;
  278.     my $db_var = 'db_'.$dbname;
  279.     dbg("bayes: tie-ing to DB file R/W $name");
  280.     tie %{$self->{$db_var}},$self->DBM_MODULE,$name, O_RDWR|O_CREAT,
  281.          (oct($main->{conf}->{bayes_file_mode}) & 0666)
  282.        or goto failed_to_tie;
  283.   }
  284.   umask $umask;
  285.  
  286.   # set our cache to what version DB we're using
  287.   $self->{db_version} = ($self->get_storage_variables())[6];
  288.   # don't bother printing this if the db was not found since it is bogus anyway
  289.   dbg("bayes: found bayes db version ".$self->{db_version}) if ($found);
  290.  
  291.   # figure out if we can read the current DB and if we need to do a
  292.   # DB version update and do it if necessary if either has a problem,
  293.   # fail immediately
  294.   #
  295.   if ($found && !$self->_upgrade_db()) {
  296.     $self->untie_db();
  297.     return 0;
  298.   }
  299.   elsif (!$found) { # new DB, make sure we know that ...
  300.     $self->{db_version} = $self->{db_toks}->{$DB_VERSION_MAGIC_TOKEN} = $self->DB_VERSION;
  301.     $self->{db_toks}->{$NTOKENS_MAGIC_TOKEN} = 0; # no tokens in the db ...
  302.     dbg("bayes: new db, set db version ".$self->{db_version}." and 0 tokens");
  303.   }
  304.  
  305.   $self->{already_tied} = 1;
  306.   return 1;
  307.  
  308. failed_to_tie:
  309.   my $err = $!;
  310.   umask $umask;
  311.  
  312.   foreach my $dbname (@DBNAMES) {
  313.     my $db_var = 'db_'.$dbname;
  314.     next unless exists $self->{$db_var};
  315.     dbg("bayes: untie-ing DB file $dbname");
  316.     untie %{$self->{$db_var}};
  317.   }       
  318.  
  319.   if ($self->{is_locked}) {
  320.     $self->{bayes}->{main}->{locker}->safe_unlock($self->{locked_file});
  321.     $self->{is_locked} = 0;
  322.   }
  323.   warn "bayes: cannot open bayes databases ${path}_* R/W: tie failed: $err\n";
  324.   return 0;
  325. }
  326.  
  327. # Do we understand how to deal with this DB version?
  328. sub _check_db_version {
  329.   my ($self) = @_;
  330.  
  331.   # return -1 if older, 0 if current, 1 if newer
  332.   return $self->{db_version} <=> $self->DB_VERSION;
  333. }
  334.  
  335. # Check to see if we need to upgrade the DB, and do so if necessary
  336. sub _upgrade_db {
  337.   my ($self) = @_;
  338.  
  339.   my $verschk = $self->_check_db_version();
  340.   my $res = 0; # used later on for tie() checks
  341.   my $umask; # used later for umask modifications
  342.  
  343.   # If the DB is the latest version, no problem.
  344.   return 1 if ($verschk == 0);
  345.  
  346.   # If the DB is a newer version that we know what to do with ... abort!
  347.   if ($verschk == 1) {
  348.     warn("bayes: bayes db version ".$self->{db_version}." is newer than we understand, aborting!");
  349.     return 0;
  350.   }
  351.  
  352.   # If the current DB version is lower than the new version, upgrade!
  353.   # Do conversions in order so we can go 1 -> 3, make sure to update
  354.   #   $self->{db_version} along the way
  355.  
  356.   dbg("bayes: detected bayes db format ".$self->{db_version}.", upgrading");
  357.  
  358.   # since DB_File will not shrink a database (!!), we need to *create*
  359.   # a new one instead.
  360.   my $main = $self->{bayes}->{main};
  361.   my $path = $main->sed_path($main->{conf}->{bayes_path});
  362.   my $name = $path.'_toks';
  363.  
  364.   # older version's journal files are likely not in the same format as the new ones, so remove it.
  365.   my $jpath = $self->_get_journal_filename();
  366.   if (-f $jpath) {
  367.     dbg("bayes: old journal file found, removing");
  368.     warn "bayes: couldn't remove $jpath: $!" if (!unlink $jpath);
  369.   }
  370.  
  371.   if ($self->{db_version} < 2) {
  372.     dbg("bayes: upgrading database format from v".$self->{db_version}." to v2");
  373.     $self->set_running_expire_tok();
  374.  
  375.     my ($DB_NSPAM_MAGIC_TOKEN, $DB_NHAM_MAGIC_TOKEN, $DB_NTOKENS_MAGIC_TOKEN);
  376.     my ($DB_OLDEST_TOKEN_AGE_MAGIC_TOKEN, $DB_LAST_EXPIRE_MAGIC_TOKEN);
  377.  
  378.     # Magic tokens for version 0, defined as '**[A-Z]+'
  379.     if ($self->{db_version} == 0) {
  380.       $DB_NSPAM_MAGIC_TOKEN            = '**NSPAM';
  381.       $DB_NHAM_MAGIC_TOKEN            = '**NHAM';
  382.       $DB_NTOKENS_MAGIC_TOKEN            = '**NTOKENS';
  383.       #$DB_OLDEST_TOKEN_AGE_MAGIC_TOKEN        = '**OLDESTAGE';
  384.       #$DB_LAST_EXPIRE_MAGIC_TOKEN        = '**LASTEXPIRE';
  385.       #$DB_SCANCOUNT_BASE_MAGIC_TOKEN        = '**SCANBASE';
  386.       #$DB_RUNNING_EXPIRE_MAGIC_TOKEN        = '**RUNNINGEXPIRE';
  387.     }
  388.     else {
  389.       $DB_NSPAM_MAGIC_TOKEN            = "\015\001\007\011\003NSPAM";
  390.       $DB_NHAM_MAGIC_TOKEN            = "\015\001\007\011\003NHAM";
  391.       $DB_NTOKENS_MAGIC_TOKEN            = "\015\001\007\011\003NTOKENS";
  392.       #$DB_OLDEST_TOKEN_AGE_MAGIC_TOKEN        = "\015\001\007\011\003OLDESTAGE";
  393.       #$DB_LAST_EXPIRE_MAGIC_TOKEN        = "\015\001\007\011\003LASTEXPIRE";
  394.       #$DB_SCANCOUNT_BASE_MAGIC_TOKEN        = "\015\001\007\011\003SCANBASE";
  395.       #$DB_RUNNING_EXPIRE_MAGIC_TOKEN        = "\015\001\007\011\003RUNNINGEXPIRE";
  396.     }
  397.  
  398.     # remember when we started ...
  399.     my $started = time;
  400.     my $newatime = $started;
  401.  
  402.     # use O_EXCL to avoid races (bonus paranoia, since we should be locked
  403.     # anyway)
  404.     my %new_toks;
  405.     $umask = umask 0;
  406.     $res = tie %new_toks, $self->DBM_MODULE, "${name}.new", O_RDWR|O_CREAT|O_EXCL,
  407.           (oct($main->{conf}->{bayes_file_mode}) & 0666);
  408.     umask $umask;
  409.     return 0 unless $res;
  410.     undef $res;
  411.  
  412.     # add the magic tokens to the new db.
  413.     $new_toks{$NSPAM_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NSPAM_MAGIC_TOKEN};
  414.     $new_toks{$NHAM_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NHAM_MAGIC_TOKEN};
  415.     $new_toks{$NTOKENS_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NTOKENS_MAGIC_TOKEN};
  416.     $new_toks{$DB_VERSION_MAGIC_TOKEN} = 2; # we're now a DB version 2 file
  417.     $new_toks{$OLDEST_TOKEN_AGE_MAGIC_TOKEN} = $newatime;
  418.     $new_toks{$LAST_EXPIRE_MAGIC_TOKEN} = $newatime;
  419.     $new_toks{$NEWEST_TOKEN_AGE_MAGIC_TOKEN} = $newatime;
  420.     $new_toks{$LAST_JOURNAL_SYNC_MAGIC_TOKEN} = $newatime;
  421.     $new_toks{$LAST_ATIME_DELTA_MAGIC_TOKEN} = 0;
  422.     $new_toks{$LAST_EXPIRE_REDUCE_MAGIC_TOKEN} = 0;
  423.  
  424.     # deal with the data tokens
  425.     my ($tok, $packed);
  426.     my $count = 0;
  427.     while (($tok, $packed) = each %{$self->{db_toks}}) {
  428.       next if ($tok =~ /^(?:\*\*[A-Z]+$|\015\001\007\011\003)/); # skip magic tokens
  429.  
  430.       my ($ts, $th, $atime) = $self->tok_unpack($packed);
  431.       $new_toks{$tok} = $self->tok_pack($ts, $th, $newatime);
  432.  
  433.       # Refresh the lock every so often...
  434.       if (($count++ % 1000) == 0) {
  435.         $self->set_running_expire_tok();
  436.       }
  437.     }
  438.  
  439.  
  440.     # now untie so we can do renames
  441.     untie %{$self->{db_toks}};
  442.     untie %new_toks;
  443.  
  444.     # This is the critical phase (moving files around), so don't allow
  445.     # it to be interrupted.
  446.     local $SIG{'INT'} = 'IGNORE';
  447.     local $SIG{'TERM'} = 'IGNORE';
  448.     local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
  449.  
  450.     # older versions used scancount, so kill the stupid little file ...
  451.     my $msgc = $path.'_msgcount';
  452.     if (-f $msgc) {
  453.       dbg("bayes: old msgcount file found, removing");
  454.       if (!unlink $msgc) {
  455.         warn "bayes: couldn't remove $msgc: $!";
  456.       }
  457.     }
  458.  
  459.     # now rename in the new one.  Try several extensions
  460.     for my $ext ($self->DB_EXTENSIONS) {
  461.       my $newf = $name.'.new'.$ext;
  462.       my $oldf = $name.$ext;
  463.       next unless (-f $newf);
  464.       if (!rename ($newf, $oldf)) {
  465.         warn "bayes: rename $newf to $oldf failed: $!\n";
  466.         return 0;
  467.       }
  468.     }
  469.  
  470.     # re-tie to the new db in read-write mode ...
  471.     $umask = umask 0;
  472.     $res = tie %{$self->{db_toks}},$self->DBM_MODULE, $name, O_RDWR|O_CREAT,
  473.      (oct($main->{conf}->{bayes_file_mode}) & 0666);
  474.     umask $umask;
  475.     return 0 unless $res;
  476.     undef $res;
  477.  
  478.     dbg("bayes: upgraded database format from v".$self->{db_version}." to v2 in ".(time - $started)." seconds");
  479.     $self->{db_version} = 2; # need this for other functions which check
  480.   }
  481.  
  482.   # Version 3 of the database converts all existing tokens to SHA1 hashes
  483.   if ($self->{db_version} == 2) {
  484.     dbg("bayes: upgrading database format from v".$self->{db_version}." to v3");
  485.     $self->set_running_expire_tok();
  486.  
  487.     my $DB_NSPAM_MAGIC_TOKEN          = "\015\001\007\011\003NSPAM";
  488.     my $DB_NHAM_MAGIC_TOKEN          = "\015\001\007\011\003NHAM";
  489.     my $DB_NTOKENS_MAGIC_TOKEN          = "\015\001\007\011\003NTOKENS";
  490.     my $DB_OLDEST_TOKEN_AGE_MAGIC_TOKEN      = "\015\001\007\011\003OLDESTAGE";
  491.     my $DB_LAST_EXPIRE_MAGIC_TOKEN      = "\015\001\007\011\003LASTEXPIRE";
  492.     my $DB_NEWEST_TOKEN_AGE_MAGIC_TOKEN      = "\015\001\007\011\003NEWESTAGE";
  493.     my $DB_LAST_JOURNAL_SYNC_MAGIC_TOKEN  = "\015\001\007\011\003LASTJOURNALSYNC";
  494.     my $DB_LAST_ATIME_DELTA_MAGIC_TOKEN      = "\015\001\007\011\003LASTATIMEDELTA";
  495.     my $DB_LAST_EXPIRE_REDUCE_MAGIC_TOKEN = "\015\001\007\011\003LASTEXPIREREDUCE";
  496.  
  497.     # remember when we started ...
  498.     my $started = time;
  499.  
  500.     # use O_EXCL to avoid races (bonus paranoia, since we should be locked
  501.     # anyway)
  502.     my %new_toks;
  503.     $umask = umask 0;
  504.     $res = tie %new_toks, $self->DBM_MODULE, "${name}.new", O_RDWR|O_CREAT|O_EXCL,
  505.           (oct($main->{conf}->{bayes_file_mode}) & 0666);
  506.     umask $umask;
  507.     return 0 unless $res;
  508.     undef $res;
  509.  
  510.     # add the magic tokens to the new db.
  511.     $new_toks{$NSPAM_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NSPAM_MAGIC_TOKEN};
  512.     $new_toks{$NHAM_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NHAM_MAGIC_TOKEN};
  513.     $new_toks{$NTOKENS_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NTOKENS_MAGIC_TOKEN};
  514.     $new_toks{$DB_VERSION_MAGIC_TOKEN} = 3; # we're now a DB version 3 file
  515.     $new_toks{$OLDEST_TOKEN_AGE_MAGIC_TOKEN} = $self->{db_toks}->{$DB_OLDEST_TOKEN_AGE_MAGIC_TOKEN};
  516.     $new_toks{$LAST_EXPIRE_MAGIC_TOKEN} = $self->{db_toks}->{$DB_LAST_EXPIRE_MAGIC_TOKEN};
  517.     $new_toks{$NEWEST_TOKEN_AGE_MAGIC_TOKEN} = $self->{db_toks}->{$DB_NEWEST_TOKEN_AGE_MAGIC_TOKEN};
  518.     $new_toks{$LAST_JOURNAL_SYNC_MAGIC_TOKEN} = $self->{db_toks}->{$DB_LAST_JOURNAL_SYNC_MAGIC_TOKEN};
  519.     $new_toks{$LAST_ATIME_DELTA_MAGIC_TOKEN} = $self->{db_toks}->{$DB_LAST_ATIME_DELTA_MAGIC_TOKEN};
  520.     $new_toks{$LAST_EXPIRE_REDUCE_MAGIC_TOKEN} =$self->{db_toks}->{$DB_LAST_EXPIRE_REDUCE_MAGIC_TOKEN};
  521.  
  522.     # deal with the data tokens
  523.     my $count = 0;
  524.     while (my ($tok, $packed) = each %{$self->{db_toks}}) {
  525.       next if ($tok =~ /^\015\001\007\011\003/); # skip magic tokens
  526.       my $tok_hash = substr(sha1($tok), -5);
  527.       $new_toks{$tok_hash} = $packed;
  528.  
  529.       # Refresh the lock every so often...
  530.       if (($count++ % 1000) == 0) {
  531.         $self->set_running_expire_tok();
  532.       }
  533.     }
  534.  
  535.     # now untie so we can do renames
  536.     untie %{$self->{db_toks}};
  537.     untie %new_toks;
  538.  
  539.     # This is the critical phase (moving files around), so don't allow
  540.     # it to be interrupted.
  541.     local $SIG{'INT'} = 'IGNORE';
  542.     local $SIG{'TERM'} = 'IGNORE';
  543.     local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
  544.  
  545.     # now rename in the new one.  Try several extensions
  546.     for my $ext ($self->DB_EXTENSIONS) {
  547.       my $newf = $name.'.new'.$ext;
  548.       my $oldf = $name.$ext;
  549.       next unless (-f $newf);
  550.       if (!rename($newf, $oldf)) {
  551.         warn "bayes: rename $newf to $oldf failed: $!\n";
  552.         return 0;
  553.       }
  554.     }
  555.  
  556.     # re-tie to the new db in read-write mode ...
  557.     $umask = umask 0;
  558.     $res = tie %{$self->{db_toks}},$self->DBM_MODULE, $name, O_RDWR|O_CREAT,
  559.      (oct ($main->{conf}->{bayes_file_mode}) & 0666);
  560.     umask $umask;
  561.     return 0 unless $res;
  562.     undef $res;
  563.  
  564.     dbg("bayes: upgraded database format from v".$self->{db_version}." to v3 in ".(time - $started)." seconds");
  565.  
  566.     $self->{db_version} = 3; # need this for other functions which check
  567.   }
  568.  
  569.   # if ($self->{db_version} == 3) {
  570.   #   ...
  571.   #   $self->{db_version} = 4; # need this for other functions which check
  572.   # }
  573.   # ... and so on.
  574.  
  575.   return 1;
  576. }
  577.  
  578. ###########################################################################
  579.  
  580. sub untie_db {
  581.   my $self = shift;
  582.  
  583.   return if (!$self->{already_tied});
  584.  
  585.   dbg("bayes: untie-ing");
  586.  
  587.   foreach my $dbname (@DBNAMES) {
  588.     my $db_var = 'db_'.$dbname;
  589.  
  590.     if (exists $self->{$db_var}) {
  591.       dbg("bayes: untie-ing $db_var");
  592.       untie %{$self->{$db_var}};
  593.       delete $self->{$db_var};
  594.     }
  595.   }
  596.  
  597.   if ($self->{is_locked}) {
  598.     dbg("bayes: files locked, now unlocking lock");
  599.     $self->{bayes}->{main}->{locker}->safe_unlock ($self->{locked_file});
  600.     $self->{is_locked} = 0;
  601.   }
  602.  
  603.   $self->{already_tied} = 0;
  604.   $self->{db_version} = undef;
  605. }
  606.  
  607. ###########################################################################
  608.  
  609. sub calculate_expire_delta {
  610.   my ($self, $newest_atime, $start, $max_expire_mult) = @_;
  611.  
  612.   my %delta = (); # use a hash since an array is going to be very sparse
  613.  
  614.   # do the first pass, figure out atime delta
  615.   my ($tok, $packed);
  616.   while (($tok, $packed) = each %{$self->{db_toks}}) {
  617.     next if ($tok =~ MAGIC_RE); # skip magic tokens
  618.     
  619.     my ($ts, $th, $atime) = $self->tok_unpack ($packed);
  620.  
  621.     # Go through from $start * 1 to $start * 512, mark how many tokens
  622.     # we would expire
  623.     my $token_age = $newest_atime - $atime;
  624.     for (my $i = 1; $i <= $max_expire_mult; $i<<=1) {
  625.       if ($token_age >= $start * $i) {
  626.         $delta{$i}++;
  627.       }
  628.       else {
  629.         # If the token age is less than the expire delta, it'll be
  630.         # less for all upcoming checks too, so abort early.
  631.         last;
  632.       }
  633.     }
  634.   }
  635.   return %delta;
  636. }
  637.  
  638. ###########################################################################
  639.  
  640. sub token_expiration {
  641.   my ($self, $opts, $newdelta, @vars) = @_;
  642.  
  643.   my $deleted = 0;
  644.   my $kept = 0;
  645.   my $num_hapaxes = 0;
  646.   my $num_lowfreq = 0;
  647.  
  648.   # since DB_File will not shrink a database (!!), we need to *create*
  649.   # a new one instead.
  650.   my $main = $self->{bayes}->{main};
  651.   my $path = $main->sed_path($main->{conf}->{bayes_path});
  652.  
  653.   # use a temporary PID-based suffix just in case another one was
  654.   # created previously by an interrupted expire
  655.   my $tmpsuffix = "expire$$";
  656.   my $tmpdbname = $path.'_toks.'.$tmpsuffix;
  657.  
  658.   # clean out any leftover db copies from previous runs
  659.   for my $ext ($self->DB_EXTENSIONS) { unlink ($tmpdbname.$ext); }
  660.  
  661.   # use O_EXCL to avoid races (bonus paranoia, since we should be locked
  662.   # anyway)
  663.   my %new_toks;
  664.   my $umask = umask 0;
  665.   tie %new_toks, $self->DBM_MODULE, $tmpdbname, O_RDWR|O_CREAT|O_EXCL,
  666.               (oct ($main->{conf}->{bayes_file_mode}) & 0666);
  667.   umask $umask;
  668.   my $oldest;
  669.  
  670.   my $showdots = $opts->{showdots};
  671.   if ($showdots) { print STDERR "\n"; }
  672.  
  673.   # We've chosen a new atime delta if we've gotten here, so record it
  674.   # for posterity.
  675.   $new_toks{$LAST_ATIME_DELTA_MAGIC_TOKEN} = $newdelta;
  676.  
  677.   # Figure out how old is too old...
  678.   my $too_old = $vars[10] - $newdelta; # tooold = newest - delta
  679.  
  680.   # Go ahead and do the move to new db/expire run now ...
  681.   my ($tok, $packed);
  682.   while (($tok, $packed) = each %{$self->{db_toks}}) {
  683.     next if ($tok =~ MAGIC_RE); # skip magic tokens
  684.  
  685.     my ($ts, $th, $atime) = $self->tok_unpack ($packed);
  686.  
  687.     if ($atime < $too_old) {
  688.       $deleted++;
  689.     }
  690.     else {
  691.       # if token atime > newest, reset to newest ...
  692.       if ($atime > $vars[10]) {
  693.         $atime = $vars[10];
  694.       }
  695.  
  696.       $new_toks{$tok} = $self->tok_pack ($ts, $th, $atime); $kept++;
  697.       if (!defined($oldest) || $atime < $oldest) { $oldest = $atime; }
  698.       if ($ts + $th == 1) {
  699.     $num_hapaxes++;
  700.       } elsif ($ts < 8 && $th < 8) {
  701.     $num_lowfreq++;
  702.       }
  703.     }
  704.  
  705.     if ((($kept + $deleted) % 1000) == 0) {
  706.       if ($showdots) { print STDERR "."; }
  707.       $self->set_running_expire_tok();
  708.     }
  709.   }
  710.  
  711.   # and add the magic tokens.  don't add the expire_running token.
  712.   $new_toks{$DB_VERSION_MAGIC_TOKEN} = $self->DB_VERSION;
  713.  
  714.   # We haven't changed messages of each type seen, so just copy over.
  715.   $new_toks{$NSPAM_MAGIC_TOKEN} = $vars[1];
  716.   $new_toks{$NHAM_MAGIC_TOKEN} = $vars[2];
  717.  
  718.   # We magically haven't removed the newest token, so just copy that value over.
  719.   $new_toks{$NEWEST_TOKEN_AGE_MAGIC_TOKEN} = $vars[10];
  720.  
  721.   # The rest of these have been modified, so replace as necessary.
  722.   $new_toks{$NTOKENS_MAGIC_TOKEN} = $kept;
  723.   $new_toks{$LAST_EXPIRE_MAGIC_TOKEN} = time();
  724.   $new_toks{$OLDEST_TOKEN_AGE_MAGIC_TOKEN} = $oldest;
  725.   $new_toks{$LAST_EXPIRE_REDUCE_MAGIC_TOKEN} = $deleted;
  726.  
  727.   # Sanity check: if we expired too many tokens, abort!
  728.   if ($kept < 100000) {
  729.     dbg("bayes: token expiration would expire too many tokens, aborting");
  730.     # set the magic tokens appropriately
  731.     # make sure the next expire run does a first pass
  732.     $self->{db_toks}->{$LAST_EXPIRE_MAGIC_TOKEN} = time();
  733.     $self->{db_toks}->{$LAST_EXPIRE_REDUCE_MAGIC_TOKEN} = 0;
  734.     $self->{db_toks}->{$LAST_ATIME_DELTA_MAGIC_TOKEN} = 0;
  735.  
  736.     # remove the new DB
  737.     untie %new_toks;
  738.     for my $ext ($self->DB_EXTENSIONS) { unlink ($tmpdbname.$ext); }
  739.  
  740.     # reset the results for the return
  741.     $kept = $vars[3];
  742.     $deleted = 0;
  743.     $num_hapaxes = 0;
  744.     $num_lowfreq = 0;
  745.   }
  746.   else {
  747.     # now untie so we can do renames
  748.     untie %{$self->{db_toks}};
  749.     untie %new_toks;
  750.  
  751.     # This is the critical phase (moving files around), so don't allow
  752.     # it to be interrupted.  Scope the signal changes.
  753.     {
  754.       local $SIG{'INT'} = 'IGNORE';
  755.       local $SIG{'TERM'} = 'IGNORE';
  756.       local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
  757.  
  758.       # now rename in the new one.  Try several extensions
  759.       for my $ext ($self->DB_EXTENSIONS) {
  760.         my $newf = $tmpdbname.$ext;
  761.         my $oldf = $path.'_toks'.$ext;
  762.         next unless (-f $newf);
  763.         if (!rename ($newf, $oldf)) {
  764.       warn "bayes: rename $newf to $oldf failed: $!\n";
  765.         }
  766.       }
  767.     }
  768.   }
  769.  
  770.   # Call untie_db() so we unlock correctly.
  771.   $self->untie_db();
  772.  
  773.   return ($kept, $deleted, $num_hapaxes, $num_lowfreq);
  774. }
  775.  
  776. ###########################################################################
  777.  
  778. # Is a sync due?
  779. sub sync_due {
  780.   my ($self) = @_;
  781.  
  782.   # don't bother doing old db versions
  783.   return 0 if ($self->{db_version} < $self->DB_VERSION);
  784.  
  785.   my $conf = $self->{bayes}->{main}->{conf};
  786.   return 0 if ($conf->{bayes_journal_max_size} == 0);
  787.  
  788.   my @vars = $self->get_storage_variables();
  789.   dbg("bayes: DB journal sync: last sync: ".$vars[7],'bayes','-1');
  790.  
  791.   ## Ok, should we do a sync?
  792.  
  793.   # Not if the journal file doesn't exist, it's not a file, or it's 0
  794.   # bytes long.
  795.   return 0 unless (stat($self->_get_journal_filename()) && -f _);
  796.  
  797.   # Yes if the file size is larger than the specified maximum size.
  798.   return 1 if (-s _ > $conf->{bayes_journal_max_size});
  799.  
  800.   # Yes there has been a sync before, and if it's been at least a day
  801.   # since that sync.
  802.   return 1 if (($vars[7] > 0) && (time - $vars[7] > 86400));
  803.  
  804.   # No, I guess not.
  805.   return 0;
  806. }
  807.  
  808. ###########################################################################
  809. # db_seen reading APIs
  810.  
  811. sub seen_get {
  812.   my ($self, $msgid) = @_;
  813.   $self->{db_seen}->{$msgid};
  814. }
  815.  
  816. sub seen_put {
  817.   my ($self, $msgid, $seen) = @_;
  818.  
  819.   if ($self->{bayes}->{main}->{learn_to_journal}) {
  820.     $self->defer_update ("m $seen $msgid");
  821.   }
  822.   else {
  823.     $self->_seen_put_direct($msgid, $seen);
  824.   }
  825. }
  826. sub _seen_put_direct {
  827.   my ($self, $msgid, $seen) = @_;
  828.   $self->{db_seen}->{$msgid} = $seen;
  829. }
  830.  
  831. sub seen_delete {
  832.   my ($self, $msgid) = @_;
  833.  
  834.   if ($self->{bayes}->{main}->{learn_to_journal}) {
  835.     $self->defer_update ("m f $msgid");
  836.   }
  837.   else {
  838.     $self->_seen_delete_direct($msgid);
  839.   }
  840. }
  841. sub _seen_delete_direct {
  842.   my ($self, $msgid) = @_;
  843.   delete $self->{db_seen}->{$msgid};
  844. }
  845.  
  846. ###########################################################################
  847. # db reading APIs
  848.  
  849. sub tok_get {
  850.   my ($self, $tok) = @_;
  851.   $self->tok_unpack ($self->{db_toks}->{$tok});
  852. }
  853.  
  854. sub tok_get_all {
  855.   my ($self, @tokens) = @_;
  856.  
  857.   my @tokensdata;
  858.   foreach my $token (@tokens) {
  859.     my ($tok_spam, $tok_ham, $atime) = $self->tok_unpack($self->{db_toks}->{$token});
  860.     push(@tokensdata, [$token, $tok_spam, $tok_ham, $atime]);
  861.   }
  862.   return \@tokensdata;
  863. }
  864.  
  865. # return the magic tokens in a specific order:
  866. # 0: scan count base
  867. # 1: number of spam
  868. # 2: number of ham
  869. # 3: number of tokens in db
  870. # 4: last expire atime
  871. # 5: oldest token in db atime
  872. # 6: db version value
  873. # 7: last journal sync
  874. # 8: last atime delta
  875. # 9: last expire reduction count
  876. # 10: newest token in db atime
  877. #
  878. sub get_storage_variables {
  879.   my ($self) = @_;
  880.   my @values;
  881.  
  882.   my $db_ver = $self->{db_toks}->{$DB_VERSION_MAGIC_TOKEN};
  883.  
  884.   if (!$db_ver || $db_ver =~ /\D/) { $db_ver = 0; }
  885.  
  886.   if ($db_ver >= 2) {
  887.     my $DB2_LAST_ATIME_DELTA_MAGIC_TOKEN    = "\015\001\007\011\003LASTATIMEDELTA";
  888.     my $DB2_LAST_EXPIRE_MAGIC_TOKEN        = "\015\001\007\011\003LASTEXPIRE";
  889.     my $DB2_LAST_EXPIRE_REDUCE_MAGIC_TOKEN    = "\015\001\007\011\003LASTEXPIREREDUCE";
  890.     my $DB2_LAST_JOURNAL_SYNC_MAGIC_TOKEN    = "\015\001\007\011\003LASTJOURNALSYNC";
  891.     my $DB2_NEWEST_TOKEN_AGE_MAGIC_TOKEN    = "\015\001\007\011\003NEWESTAGE";
  892.     my $DB2_NHAM_MAGIC_TOKEN            = "\015\001\007\011\003NHAM";
  893.     my $DB2_NSPAM_MAGIC_TOKEN            = "\015\001\007\011\003NSPAM";
  894.     my $DB2_NTOKENS_MAGIC_TOKEN            = "\015\001\007\011\003NTOKENS";
  895.     my $DB2_OLDEST_TOKEN_AGE_MAGIC_TOKEN    = "\015\001\007\011\003OLDESTAGE";
  896.     my $DB2_RUNNING_EXPIRE_MAGIC_TOKEN        = "\015\001\007\011\003RUNNINGEXPIRE";
  897.  
  898.     @values = (
  899.       0,
  900.       $self->{db_toks}->{$DB2_NSPAM_MAGIC_TOKEN},
  901.       $self->{db_toks}->{$DB2_NHAM_MAGIC_TOKEN},
  902.       $self->{db_toks}->{$DB2_NTOKENS_MAGIC_TOKEN},
  903.       $self->{db_toks}->{$DB2_LAST_EXPIRE_MAGIC_TOKEN},
  904.       $self->{db_toks}->{$DB2_OLDEST_TOKEN_AGE_MAGIC_TOKEN},
  905.       $db_ver,
  906.       $self->{db_toks}->{$DB2_LAST_JOURNAL_SYNC_MAGIC_TOKEN},
  907.       $self->{db_toks}->{$DB2_LAST_ATIME_DELTA_MAGIC_TOKEN},
  908.       $self->{db_toks}->{$DB2_LAST_EXPIRE_REDUCE_MAGIC_TOKEN},
  909.       $self->{db_toks}->{$DB2_NEWEST_TOKEN_AGE_MAGIC_TOKEN},
  910.     );
  911.   }
  912.   elsif ($db_ver == 0) {
  913.     my $DB0_NSPAM_MAGIC_TOKEN = '**NSPAM';
  914.     my $DB0_NHAM_MAGIC_TOKEN = '**NHAM';
  915.     my $DB0_OLDEST_TOKEN_AGE_MAGIC_TOKEN = '**OLDESTAGE';
  916.     my $DB0_LAST_EXPIRE_MAGIC_TOKEN = '**LASTEXPIRE';
  917.     my $DB0_NTOKENS_MAGIC_TOKEN = '**NTOKENS';
  918.     my $DB0_SCANCOUNT_BASE_MAGIC_TOKEN = '**SCANBASE';
  919.  
  920.     @values = (
  921.       $self->{db_toks}->{$DB0_SCANCOUNT_BASE_MAGIC_TOKEN},
  922.       $self->{db_toks}->{$DB0_NSPAM_MAGIC_TOKEN},
  923.       $self->{db_toks}->{$DB0_NHAM_MAGIC_TOKEN},
  924.       $self->{db_toks}->{$DB0_NTOKENS_MAGIC_TOKEN},
  925.       $self->{db_toks}->{$DB0_LAST_EXPIRE_MAGIC_TOKEN},
  926.       $self->{db_toks}->{$DB0_OLDEST_TOKEN_AGE_MAGIC_TOKEN},
  927.       0,
  928.       0,
  929.       0,
  930.       0,
  931.       0,
  932.     );
  933.   }
  934.   elsif ($db_ver == 1) {
  935.     my $DB1_NSPAM_MAGIC_TOKEN            = "\015\001\007\011\003NSPAM";
  936.     my $DB1_NHAM_MAGIC_TOKEN            = "\015\001\007\011\003NHAM";
  937.     my $DB1_OLDEST_TOKEN_AGE_MAGIC_TOKEN    = "\015\001\007\011\003OLDESTAGE";
  938.     my $DB1_LAST_EXPIRE_MAGIC_TOKEN        = "\015\001\007\011\003LASTEXPIRE";
  939.     my $DB1_NTOKENS_MAGIC_TOKEN            = "\015\001\007\011\003NTOKENS";
  940.     my $DB1_SCANCOUNT_BASE_MAGIC_TOKEN        = "\015\001\007\011\003SCANBASE";
  941.  
  942.     @values = (
  943.       $self->{db_toks}->{$DB1_SCANCOUNT_BASE_MAGIC_TOKEN},
  944.       $self->{db_toks}->{$DB1_NSPAM_MAGIC_TOKEN},
  945.       $self->{db_toks}->{$DB1_NHAM_MAGIC_TOKEN},
  946.       $self->{db_toks}->{$DB1_NTOKENS_MAGIC_TOKEN},
  947.       $self->{db_toks}->{$DB1_LAST_EXPIRE_MAGIC_TOKEN},
  948.       $self->{db_toks}->{$DB1_OLDEST_TOKEN_AGE_MAGIC_TOKEN},
  949.       1,
  950.       0,
  951.       0,
  952.       0,
  953.       0,
  954.     );
  955.   }
  956.  
  957.   foreach (@values) {
  958.     if (!$_ || $_ =~ /\D/) {
  959.       $_ = 0;
  960.     }
  961.   }
  962.  
  963.   return @values;
  964. }
  965.  
  966. sub dump_db_toks {
  967.   my ($self, $template, $regex, @vars) = @_;
  968.  
  969.   while (my ($tok, $tokvalue) = each %{$self->{db_toks}}) {
  970.     next if ($tok =~ MAGIC_RE); # skip magic tokens
  971.     next if (defined $regex && ($tok !~ /$regex/o));
  972.  
  973.     # We have the value already, so just unpack it.
  974.     my ($ts, $th, $atime) = $self->tok_unpack ($tokvalue);
  975.     
  976.     my $prob = $self->{bayes}->compute_prob_for_token($tok, $vars[1], $vars[2], $ts, $th);
  977.     $prob ||= 0.5;
  978.     
  979.     my $encoded_tok = unpack("H*",$tok);
  980.     printf $template,$prob,$ts,$th,$atime,$encoded_tok;
  981.   }
  982. }
  983.  
  984. sub set_last_expire {
  985.   my ($self, $time) = @_;
  986.   $self->{db_toks}->{$LAST_EXPIRE_MAGIC_TOKEN} = time();
  987. }
  988.  
  989. ## Don't bother using get_magic_tokens here.  This token should only
  990. ## ever exist when we're running expire, so we don't want to convert it if
  991. ## it's there and we're not expiring ...
  992. sub get_running_expire_tok {
  993.   my ($self) = @_;
  994.   my $running = $self->{db_toks}->{$RUNNING_EXPIRE_MAGIC_TOKEN};
  995.   if (!$running || $running =~ /\D/) { return undef; }
  996.   return $running;
  997. }
  998.  
  999. sub set_running_expire_tok {
  1000.   my ($self) = @_;
  1001.  
  1002.   # update the lock and and running expire magic token
  1003.   $self->{bayes}->{main}->{locker}->refresh_lock ($self->{locked_file});
  1004.   $self->{db_toks}->{$RUNNING_EXPIRE_MAGIC_TOKEN} = time();
  1005. }
  1006.  
  1007. sub remove_running_expire_tok {
  1008.   my ($self) = @_;
  1009.   delete $self->{db_toks}->{$RUNNING_EXPIRE_MAGIC_TOKEN};
  1010. }
  1011.  
  1012. ###########################################################################
  1013.  
  1014. # db abstraction: allow deferred writes, since we will be frequently
  1015. # writing while checking.
  1016.  
  1017. sub tok_count_change {
  1018.   my ($self, $ds, $dh, $tok, $atime) = @_;
  1019.  
  1020.   $atime = 0 unless defined $atime;
  1021.  
  1022.   if ($self->{bayes}->{main}->{learn_to_journal}) {
  1023.     # we can't store the SHA1 binary value in the journal to convert it
  1024.     # to a printable value that can be converted back later
  1025.     my $encoded_tok = unpack("H*",$tok);
  1026.     $self->defer_update ("c $ds $dh $atime $encoded_tok");
  1027.   } else {
  1028.     $self->tok_sync_counters ($ds, $dh, $atime, $tok);
  1029.   }
  1030. }
  1031.  
  1032. sub multi_tok_count_change {
  1033.   my ($self, $ds, $dh, $tokens, $atime) = @_;
  1034.  
  1035.   $atime = 0 unless defined $atime;
  1036.  
  1037.   foreach my $tok (keys %{$tokens}) {
  1038.     if ($self->{bayes}->{main}->{learn_to_journal}) {
  1039.       # we can't store the SHA1 binary value in the journal to convert it
  1040.       # to a printable value that can be converted back later
  1041.       my $encoded_tok = unpack("H*",$tok);
  1042.       $self->defer_update ("c $ds $dh $atime $encoded_tok");
  1043.     } else {
  1044.       $self->tok_sync_counters ($ds, $dh, $atime, $tok);
  1045.     }
  1046.   }
  1047. }
  1048.  
  1049. sub nspam_nham_get {
  1050.   my ($self) = @_;
  1051.   my @vars = $self->get_storage_variables();
  1052.   ($vars[1], $vars[2]);
  1053. }
  1054.  
  1055. sub nspam_nham_change {
  1056.   my ($self, $ds, $dh) = @_;
  1057.  
  1058.   if ($self->{bayes}->{main}->{learn_to_journal}) {
  1059.     $self->defer_update ("n $ds $dh");
  1060.   } else {
  1061.     $self->tok_sync_nspam_nham ($ds, $dh);
  1062.   }
  1063. }
  1064.  
  1065. sub tok_touch {
  1066.   my ($self, $tok, $atime) = @_;
  1067.   # we can't store the SHA1 binary value in the journal to convert it
  1068.   # to a printable value that can be converted back later
  1069.   my $encoded_tok = unpack("H*", $tok);
  1070.   $self->defer_update ("t $atime $encoded_tok");
  1071. }
  1072.  
  1073. sub tok_touch_all {
  1074.   my ($self, $tokens, $atime) = @_;
  1075.  
  1076.   foreach my $token (@{$tokens}) {
  1077.     # we can't store the SHA1 binary value in the journal to convert it
  1078.     # to a printable value that can be converted back later
  1079.     my $encoded_tok = unpack("H*", $token);
  1080.     $self->defer_update ("t $atime $encoded_tok");
  1081.   }
  1082. }
  1083.  
  1084. sub defer_update {
  1085.   my ($self, $str) = @_;
  1086.   $self->{string_to_journal} .= "$str\n";
  1087. }
  1088.  
  1089. ###########################################################################
  1090.  
  1091. sub cleanup {
  1092.   my ($self) = @_;
  1093.  
  1094.   my $nbytes = length ($self->{string_to_journal});
  1095.   return if ($nbytes == 0);
  1096.  
  1097.   my $path = $self->_get_journal_filename();
  1098.  
  1099.   # use append mode, write atomically, then close, so simultaneous updates are
  1100.   # not lost
  1101.   my $conf = $self->{bayes}->{main}->{conf};
  1102.  
  1103.   # set the umask to the inverse of what we want ...
  1104.   my $umask = umask(0777 - (oct ($conf->{bayes_file_mode}) & 0666));
  1105.  
  1106.   if (!open (OUT, ">>".$path)) {
  1107.     warn "bayes: cannot write to $path, bayes db update ignored: $!\n";
  1108.     umask $umask; # reset umask
  1109.     return;
  1110.   }
  1111.   umask $umask; # reset umask
  1112.  
  1113.   # do not use print() here, it will break up the buffer if it's >8192 bytes,
  1114.   # which could result in two sets of tokens getting mixed up and their
  1115.   # touches missed.
  1116.   my $write_failure = 0;
  1117.   my $original_point = tell OUT;
  1118.   my $len;
  1119.   do {
  1120.     $len = syswrite (OUT, $self->{string_to_journal}, $nbytes);
  1121.  
  1122.     # argh, write failure, give up
  1123.     if (!defined $len || $len < 0) {
  1124.       $len = 0 unless (defined $len);
  1125.       warn "bayes: write failed to Bayes journal $path ($len of $nbytes)!\n";
  1126.       last;
  1127.     }
  1128.  
  1129.     # This shouldn't happen, but could if the fs is full...
  1130.     if ($len != $nbytes) {
  1131.       warn "bayes: partial write to bayes journal $path ($len of $nbytes), recovering\n";
  1132.  
  1133.       # we want to be atomic, so revert the journal file back to where
  1134.       # we know it's "good".  if we can't truncate the journal, or we've
  1135.       # tried 5 times to do the write, abort!
  1136.       if (!truncate(OUT, $original_point) || ($write_failure++ > 4)) {
  1137.         warn "bayes: cannot write to bayes journal $path, aborting!\n";
  1138.     last;
  1139.       }
  1140.  
  1141.       # if the fs is full, let's give the system a break
  1142.       sleep 1;
  1143.     }
  1144.   } while ($len != $nbytes);
  1145.  
  1146.   if (!close OUT) {
  1147.     warn "bayes: cannot write to $path, bayes db update ignored\n";
  1148.   }
  1149.  
  1150.   $self->{string_to_journal} = '';
  1151. }
  1152.  
  1153. # Return a qr'd RE to match a token with the correct format's magic token
  1154. sub get_magic_re {
  1155.   my ($self) = @_;
  1156.  
  1157.   if (!defined $self->{db_version} || $self->{db_version} >= 1) {
  1158.     return MAGIC_RE;
  1159.   }
  1160.  
  1161.   # When in doubt, assume v0
  1162.   return qr/^\*\*[A-Z]+$/;
  1163. }
  1164.  
  1165. # provide a more generalized public insterface into the journal sync
  1166.  
  1167. sub sync {
  1168.   my ($self, $opts) = @_;
  1169.  
  1170.   return $self->_sync_journal($opts);
  1171. }
  1172.  
  1173. ###########################################################################
  1174. # And this method reads the journal and applies the changes in one
  1175. # (locked) transaction.
  1176.  
  1177. sub _sync_journal {
  1178.   my ($self, $opts) = @_;
  1179.   my $ret = 0;
  1180.  
  1181.   my $path = $self->_get_journal_filename();
  1182.  
  1183.   # if $path doesn't exist, or it's not a file, or is 0 bytes in length, return
  1184.   if (!stat($path) || !-f _ || -z _) {
  1185.     return 0;
  1186.   }
  1187.  
  1188.   eval {
  1189.     local $SIG{'__DIE__'};    # do not run user die() traps in here
  1190.     if ($self->tie_db_writable()) {
  1191.       $ret = $self->_sync_journal_trapped($opts, $path);
  1192.     }
  1193.   };
  1194.   my $err = $@;
  1195.  
  1196.   # ok, untie from write-mode if we can
  1197.   if (!$self->{bayes}->{main}->{learn_caller_will_untie}) {
  1198.     $self->untie_db();
  1199.   }
  1200.  
  1201.   # handle any errors that may have occurred
  1202.   if ($err) {
  1203.     warn "bayes: $err\n";
  1204.     return 0;
  1205.   }
  1206.  
  1207.   $ret;
  1208. }
  1209.  
  1210. sub _sync_journal_trapped {
  1211.   my ($self, $opts, $path) = @_;
  1212.  
  1213.   # Flag that we're doing work
  1214.   $self->set_running_expire_tok();
  1215.  
  1216.   my $started = time();
  1217.   my $count = 0;
  1218.   my $total_count = 0;
  1219.   my %tokens = ();
  1220.   my $showdots = $opts->{showdots};
  1221.   my $retirepath = $path.".old";
  1222.  
  1223.   # if $path doesn't exist, or it's not a file, or is 0 bytes in length,
  1224.   # return we have to check again since the file may have been removed
  1225.   # by a recent bayes db upgrade ...
  1226.   if (!stat($path) || !-f _ || -z _) {
  1227.     return 0;
  1228.   }
  1229.  
  1230.   if (!-r $path) { # will we be able to read the file?
  1231.     warn "bayes: bad permissions on journal, can't read: $path\n";
  1232.     return 0;
  1233.   }
  1234.  
  1235.   # This is the critical phase (moving files around), so don't allow
  1236.   # it to be interrupted.
  1237.   {
  1238.     local $SIG{'INT'} = 'IGNORE';
  1239.     local $SIG{'TERM'} = 'IGNORE';
  1240.     local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
  1241.  
  1242.     # retire the journal, so we can update the db files from it in peace.
  1243.     # TODO: use locking here
  1244.     if (!rename ($path, $retirepath)) {
  1245.       warn "bayes: failed rename $path to $retirepath\n";
  1246.       return 0;
  1247.     }
  1248.  
  1249.     # now read the retired journal
  1250.     if (!open (JOURNAL, "<$retirepath")) {
  1251.       warn "bayes: cannot open read $retirepath\n";
  1252.       return 0;
  1253.     }
  1254.  
  1255.  
  1256.     # Read the journal
  1257.     while (<JOURNAL>) {
  1258.       $total_count++;
  1259.  
  1260.       if (/^t (\d+) (.+)$/) { # Token timestamp update, cache resultant entries
  1261.     my $tok = pack("H*",$2);
  1262.     $tokens{$tok} = $1+0 if (!exists $tokens{$tok} || $1+0 > $tokens{$tok});
  1263.       } elsif (/^c (-?\d+) (-?\d+) (\d+) (.+)$/) { # Add/full token update
  1264.     my $tok = pack("H*",$4);
  1265.     $self->tok_sync_counters ($1+0, $2+0, $3+0, $tok);
  1266.     $count++;
  1267.       } elsif (/^n (-?\d+) (-?\d+)$/) { # update ham/spam count
  1268.     $self->tok_sync_nspam_nham ($1+0, $2+0);
  1269.     $count++;
  1270.       } elsif (/^m ([hsf]) (.+)$/) { # update msgid seen database
  1271.     if ($1 eq "f") {
  1272.       $self->_seen_delete_direct($2);
  1273.     }
  1274.     else {
  1275.       $self->_seen_put_direct($2,$1);
  1276.     }
  1277.     $count++;
  1278.       } else {
  1279.     warn "bayes: gibberish entry found in journal: $_";
  1280.       }
  1281.     }
  1282.     close JOURNAL;
  1283.  
  1284.     # Now that we've determined what tokens we need to update and their
  1285.     # final values, update the DB.  Should be much smaller than the full
  1286.     # journal entries.
  1287.     while (my ($k,$v) = each %tokens) {
  1288.       $self->tok_touch_token ($v, $k);
  1289.  
  1290.       if ((++$count % 1000) == 0) {
  1291.     if ($showdots) { print STDERR "."; }
  1292.     $self->set_running_expire_tok();
  1293.       }
  1294.     }
  1295.  
  1296.     if ($showdots) { print STDERR "\n"; }
  1297.  
  1298.     # we're all done, so unlink the old journal file
  1299.     unlink ($retirepath) || warn "bayes: can't unlink $retirepath: $!\n";
  1300.  
  1301.     $self->{db_toks}->{$LAST_JOURNAL_SYNC_MAGIC_TOKEN} = $started;
  1302.  
  1303.     my $done = time();
  1304.     my $msg = ("bayes: synced databases from journal in " .
  1305.            ($done - $started) .
  1306.            " seconds: $count unique entries ($total_count total entries)");
  1307.  
  1308.     if ($opts->{verbose}) {
  1309.       print $msg,"\n";
  1310.     } else {
  1311.       dbg($msg);
  1312.     }
  1313.   }
  1314.  
  1315.   # else, that's the lot, we're synced.  return
  1316.   return 1;
  1317. }
  1318.  
  1319. sub tok_touch_token {
  1320.   my ($self, $atime, $tok) = @_;
  1321.   my ($ts, $th, $oldatime) = $self->tok_get ($tok);
  1322.  
  1323.   # If the new atime is < the old atime, ignore the update
  1324.   # We figure that we'll never want to lower a token atime, so abort if
  1325.   # we try.  (journal out of sync, etc.)
  1326.   return if ($oldatime >= $atime);
  1327.  
  1328.   $self->tok_put ($tok, $ts, $th, $atime);
  1329. }
  1330.  
  1331. sub tok_sync_counters {
  1332.   my ($self, $ds, $dh, $atime, $tok) = @_;
  1333.   my ($ts, $th, $oldatime) = $self->tok_get ($tok);
  1334.   $ts += $ds; if ($ts < 0) { $ts = 0; }
  1335.   $th += $dh; if ($th < 0) { $th = 0; }
  1336.  
  1337.   # Don't roll the atime of tokens backwards ...
  1338.   $atime = $oldatime if ($oldatime > $atime);
  1339.  
  1340.   $self->tok_put ($tok, $ts, $th, $atime);
  1341. }
  1342.  
  1343. sub tok_put {
  1344.   my ($self, $tok, $ts, $th, $atime) = @_;
  1345.   $ts ||= 0;
  1346.   $th ||= 0;
  1347.  
  1348.   # Ignore magic tokens, the don't go in this way ...
  1349.   return if ($tok =~ MAGIC_RE);
  1350.  
  1351.   # use defined() rather than exists(); the latter is not supported
  1352.   # by NDBM_File, believe it or not.  Using defined() did not
  1353.   # indicate any noticeable speed hit in my testing. (Mar 31 2003 jm)
  1354.   my $exists_already = defined $self->{db_toks}->{$tok};
  1355.  
  1356.   if ($ts == 0 && $th == 0) {
  1357.     return if (!$exists_already); # If the token doesn't exist, just return
  1358.     $self->{db_toks}->{$NTOKENS_MAGIC_TOKEN}--;
  1359.     delete $self->{db_toks}->{$tok};
  1360.   } else {
  1361.     if (!$exists_already) { # If the token doesn't exist, raise the token count
  1362.       $self->{db_toks}->{$NTOKENS_MAGIC_TOKEN}++;
  1363.     }
  1364.  
  1365.     $self->{db_toks}->{$tok} = $self->tok_pack ($ts, $th, $atime);
  1366.  
  1367.     my $newmagic = $self->{db_toks}->{$NEWEST_TOKEN_AGE_MAGIC_TOKEN};
  1368.     if (!defined ($newmagic) || $atime > $newmagic) {
  1369.       $self->{db_toks}->{$NEWEST_TOKEN_AGE_MAGIC_TOKEN} = $atime;
  1370.     }
  1371.  
  1372.     # Make sure to check for either !defined or "" ...  Apparently
  1373.     # sometimes the DB module doesn't return the value correctly. :(
  1374.     my $oldmagic = $self->{db_toks}->{$OLDEST_TOKEN_AGE_MAGIC_TOKEN};
  1375.     if (!defined ($oldmagic) || $oldmagic eq "" || $atime < $oldmagic) {
  1376.       $self->{db_toks}->{$OLDEST_TOKEN_AGE_MAGIC_TOKEN} = $atime;
  1377.     }
  1378.   }
  1379. }
  1380.  
  1381. sub tok_sync_nspam_nham {
  1382.   my ($self, $ds, $dh) = @_;
  1383.   my ($ns, $nh) = ($self->get_storage_variables())[1,2];
  1384.   if ($ds) { $ns += $ds; } if ($ns < 0) { $ns = 0; }
  1385.   if ($dh) { $nh += $dh; } if ($nh < 0) { $nh = 0; }
  1386.   $self->{db_toks}->{$NSPAM_MAGIC_TOKEN} = $ns;
  1387.   $self->{db_toks}->{$NHAM_MAGIC_TOKEN} = $nh;
  1388. }
  1389.  
  1390. ###########################################################################
  1391.  
  1392. sub _get_journal_filename {
  1393.   my ($self) = @_;
  1394.  
  1395.   my $main = $self->{bayes}->{main};
  1396.   return $main->sed_path($main->{conf}->{bayes_path}."_journal");
  1397. }
  1398.  
  1399. ###########################################################################
  1400.  
  1401. # this is called directly from sa-learn(1).
  1402. sub perform_upgrade {
  1403.   my ($self, $opts) = @_;
  1404.   my $ret = 0;
  1405.  
  1406.   eval {
  1407.     local $SIG{'__DIE__'};    # do not run user die() traps in here
  1408.  
  1409.     use File::Basename;
  1410.     use File::Copy;
  1411.  
  1412.     # bayes directory
  1413.     my $main = $self->{bayes}->{main};
  1414.     my $path = $main->sed_path($main->{conf}->{bayes_path});
  1415.     my $dir = dirname($path);
  1416.  
  1417.     # make temporary copy since old dbm and new dbm may have same name
  1418.     opendir(DIR, $dir) || die "bayes: can't opendir $dir: $!";
  1419.     my @files = grep { /^bayes_(?:seen|toks)(?:\.\w+)?$/ } readdir(DIR);
  1420.     closedir(DIR);
  1421.     if (@files < 2 || !grep(/bayes_seen/,@files) || !grep(/bayes_toks/,@files))
  1422.     {
  1423.       die "bayes: unable to find bayes_toks and bayes_seen, stopping\n";
  1424.     }
  1425.     # untaint @files (already safe after grep)
  1426.     @files = map { /(.*)/, $1 } @files;
  1427.       
  1428.     for (@files) {
  1429.       my $src = "$dir/$_";
  1430.       my $dst = "$dir/old_$_";
  1431.       copy($src, $dst) || die "bayes: can't copy $src to $dst: $!\n";
  1432.     }
  1433.  
  1434.     # delete previous to make way for import
  1435.     for (@files) { unlink("$dir/$_"); }
  1436.  
  1437.     # import
  1438.     if ($self->tie_db_writable()) {
  1439.       $ret += $self->upgrade_old_dbm_files_trapped("$dir/old_bayes_seen",
  1440.                            $self->{db_seen});
  1441.       $ret += $self->upgrade_old_dbm_files_trapped("$dir/old_bayes_toks",
  1442.                            $self->{db_toks});
  1443.     }
  1444.  
  1445.     if ($ret == 2) {
  1446.       print "import successful, original files saved with \"old\" prefix\n";
  1447.     }
  1448.     else {
  1449.       print "import failed, original files saved with \"old\" prefix\n";
  1450.     }
  1451.   };
  1452.   my $err = $@;
  1453.  
  1454.   $self->untie_db();
  1455.  
  1456.   # if we died, untie the dbm files
  1457.   if ($err) {
  1458.     warn "bayes: perform_upgrade: $err\n";
  1459.     return 0;
  1460.   }
  1461.   $ret;
  1462. }
  1463.  
  1464. sub upgrade_old_dbm_files_trapped {
  1465.   my ($self, $filename, $output) = @_;
  1466.  
  1467.   my $count;
  1468.   my %in;
  1469.  
  1470.   print "upgrading to " . $self->DBM_MODULE . ", please be patient: $filename\n";
  1471.  
  1472.   # try each type of file until we find one with > 0 entries
  1473.   for my $dbm ('DB_File', 'GDBM_File', 'NDBM_File', 'SDBM_File') {
  1474.     $count = 0;
  1475.     # wrap in eval so it doesn't run in general use.  This accesses db
  1476.     # modules directly.
  1477.     # Note: (bug 2390), the 'use' needs to be on the same line as the eval
  1478.     # for RPM dependency checks to work properly.  It's lame, but...
  1479.     eval 'use ' . $dbm . ';
  1480.       tie %in, "' . $dbm . '", $filename, O_RDONLY, 0600;
  1481.       %{ $output } = %in;
  1482.       $count = scalar keys %{ $output };
  1483.       untie %in;
  1484.     ';
  1485.     if ($@) {
  1486.       print "$dbm: $dbm module not installed, nothing copied\n";
  1487.       dbg("bayes: error was: $@");
  1488.     }
  1489.     elsif ($count == 0) {
  1490.       print "$dbm: no database of that kind found, nothing copied\n";
  1491.     }
  1492.     else {
  1493.       print "$dbm: copied $count entries\n";
  1494.       return 1;
  1495.     }
  1496.   }
  1497.  
  1498.   return 0;
  1499. }
  1500.  
  1501. sub clear_database {
  1502.   my ($self) = @_;
  1503.  
  1504.   return 0 unless ($self->tie_db_writable());
  1505.  
  1506.   dbg("bayes: untie-ing in preparation for removal.");
  1507.  
  1508.   foreach my $dbname (@DBNAMES) {
  1509.     my $db_var = 'db_'.$dbname;
  1510.  
  1511.     if (exists $self->{$db_var}) {
  1512.       dbg("bayes: untie-ing $db_var");
  1513.       untie %{$self->{$db_var}};
  1514.       delete $self->{$db_var};
  1515.     }
  1516.   }
  1517.  
  1518.   my $path = $self->{bayes}->{main}->sed_path($self->{bayes}->{main}->{conf}->{bayes_path});
  1519.  
  1520.   foreach my $dbname (@DBNAMES, 'journal') {
  1521.     foreach my $ext ($self->DB_EXTENSIONS) {
  1522.       my $name = $path.'_'.$dbname.$ext;
  1523.       my $ret = unlink $name;
  1524.       dbg("bayes: clear_database: " . ($ret ? 'removed' : 'tried to remove') . " $name");
  1525.     }
  1526.   }
  1527.  
  1528.   # the journal file needs to be done separately since it has no extension
  1529.   foreach my $dbname ('journal') {
  1530.     my $name = $path.'_'.$dbname;
  1531.     my $ret = unlink $name;
  1532.     dbg("bayes: clear_database: " . ($ret ? 'removed' : 'tried to remove') . " $name");
  1533.   }
  1534.  
  1535.   $self->untie_db();
  1536.  
  1537.   return 1;
  1538. }
  1539.  
  1540. sub backup_database {
  1541.   my ($self) = @_;
  1542.  
  1543.   # we tie writable because we want the upgrade code to kick in if needed
  1544.   return 0 unless ($self->tie_db_writable());
  1545.  
  1546.   my @vars = $self->get_storage_variables();
  1547.  
  1548.   print "v\t$vars[6]\tdb_version # this must be the first line!!!\n";
  1549.   print "v\t$vars[1]\tnum_spam\n";
  1550.   print "v\t$vars[2]\tnum_nonspam\n";
  1551.  
  1552.   while (my ($tok, $packed) = each %{$self->{db_toks}}) {
  1553.     next if ($tok =~ MAGIC_RE); # skip magic tokens
  1554.  
  1555.     my ($ts, $th, $atime) = $self->tok_unpack($packed);
  1556.     my $encoded_token = unpack("H*",$tok);
  1557.     print "t\t$ts\t$th\t$atime\t$encoded_token\n";
  1558.   }
  1559.  
  1560.   while (my ($msgid, $flag) = each %{$self->{db_seen}}) {
  1561.     print "s\t$flag\t$msgid\n";
  1562.   }
  1563.  
  1564.   $self->untie_db();
  1565.  
  1566.   return 1;
  1567. }
  1568.  
  1569. sub restore_database {
  1570.   my ($self, $filename, $showdots) = @_;
  1571.  
  1572.   if (!open(DUMPFILE, '<', $filename)) {
  1573.     dbg("bayes: unable to open backup file $filename: $!");
  1574.     return 0;
  1575.   }
  1576.    
  1577.   if (!$self->tie_db_writable()) {
  1578.     dbg("bayes: failed to tie db writable");
  1579.     return 0;
  1580.   }
  1581.  
  1582.   my $main = $self->{bayes}->{main};
  1583.   my $path = $main->sed_path($main->{conf}->{bayes_path});
  1584.  
  1585.   # use a temporary PID-based suffix just in case another one was
  1586.   # created previously by an interrupted expire
  1587.   my $tmpsuffix = "convert$$";
  1588.   my $tmptoksdbname = $path.'_toks.'.$tmpsuffix;
  1589.   my $tmpseendbname = $path.'_seen.'.$tmpsuffix;
  1590.   my $toksdbname = $path.'_toks';
  1591.   my $seendbname = $path.'_seen';
  1592.  
  1593.   my %new_toks;
  1594.   my %new_seen;
  1595.   my $umask = umask 0;
  1596.   unless (tie %new_toks, $self->DBM_MODULE, $tmptoksdbname, O_RDWR|O_CREAT|O_EXCL,
  1597.       (oct ($main->{conf}->{bayes_file_mode}) & 0666)) {
  1598.     dbg("bayes: failed to tie temp toks db: $!");
  1599.     $self->untie_db();
  1600.     umask $umask;
  1601.     return 0;
  1602.   }
  1603.   unless (tie %new_seen, $self->DBM_MODULE, $tmpseendbname, O_RDWR|O_CREAT|O_EXCL,
  1604.       (oct ($main->{conf}->{bayes_file_mode}) & 0666)) {
  1605.     dbg("bayes: failed to tie temp seen db: $!");
  1606.     untie %new_toks;
  1607.     $self->_unlink_file($tmptoksdbname);
  1608.     $self->untie_db();
  1609.     umask $umask;
  1610.     return 0;
  1611.   }
  1612.   umask $umask;
  1613.  
  1614.   my $line_count = 0;
  1615.   my $db_version;
  1616.   my $token_count = 0;
  1617.   my $num_spam;
  1618.   my $num_ham;
  1619.   my $error_p = 0;
  1620.   my $newest_token_age = 0;
  1621.   # Kinda wierd I know, but we need a nice big value and we know there will be
  1622.   # no tokens > time() since we reset atime if > time(), so use that with a
  1623.   # little buffer just in case.
  1624.   my $oldest_token_age = time() + 100000;
  1625.  
  1626.   my $line = <DUMPFILE>;
  1627.   $line_count++;
  1628.  
  1629.   # We require the database version line to be the first in the file so we can
  1630.   # figure out how to properly deal with the file.  If it is not the first
  1631.   # line then fail
  1632.   if ($line =~ m/^v\s+(\d+)\s+db_version/) {
  1633.     $db_version = $1;
  1634.   }
  1635.   else {
  1636.     dbg("bayes: database version must be the first line in the backup file, correct and re-run");
  1637.     untie %new_toks;
  1638.     untie %new_seen;
  1639.     $self->_unlink_file($tmptoksdbname);
  1640.     $self->_unlink_file($tmpseendbname);
  1641.     $self->untie_db();
  1642.     return 0;
  1643.   }
  1644.  
  1645.   unless ($db_version == 2 || $db_version == 3) {
  1646.     warn("bayes: database version $db_version is unsupported, must be version 2 or 3");
  1647.     untie %new_toks;
  1648.     untie %new_seen;
  1649.     $self->_unlink_file($tmptoksdbname);
  1650.     $self->_unlink_file($tmpseendbname);
  1651.     $self->untie_db();
  1652.     return 0;
  1653.   }
  1654.  
  1655.   while (my $line = <DUMPFILE>) {
  1656.     chomp($line);
  1657.     $line_count++;
  1658.  
  1659.     if ($line_count % 1000 == 0) {
  1660.       print STDERR "." if ($showdots);
  1661.     }
  1662.  
  1663.     if ($line =~ /^v\s+/) { # variable line
  1664.       my @parsed_line = split(/\s+/, $line, 3);
  1665.       my $value = $parsed_line[1] + 0;
  1666.       if ($parsed_line[2] eq 'num_spam') {
  1667.     $num_spam = $value;
  1668.       }
  1669.       elsif ($parsed_line[2] eq 'num_nonspam') {
  1670.     $num_ham = $value;
  1671.       }
  1672.       else {
  1673.     dbg("bayes: restore_database: skipping unknown line: $line");
  1674.       }
  1675.     }
  1676.     elsif ($line =~ /^t\s+/) { # token line
  1677.       my @parsed_line = split(/\s+/, $line, 5);
  1678.       my $spam_count = $parsed_line[1] + 0;
  1679.       my $ham_count = $parsed_line[2] + 0;
  1680.       my $atime = $parsed_line[3] + 0;
  1681.       my $token = $parsed_line[4];
  1682.  
  1683.       my $token_warn_p = 0;
  1684.       my @warnings;
  1685.  
  1686.       if ($spam_count < 0) {
  1687.     $spam_count = 0;
  1688.     push(@warnings, 'spam count < 0, resetting');
  1689.     $token_warn_p = 1;
  1690.       }
  1691.       if ($ham_count < 0) {
  1692.     $ham_count = 0;
  1693.     push(@warnings, 'ham count < 0, resetting');
  1694.     $token_warn_p = 1;
  1695.       }
  1696.  
  1697.       if ($spam_count == 0 && $ham_count == 0) {
  1698.     dbg("bayes: token has zero spam and ham count, skipping");
  1699.     next;
  1700.       }
  1701.  
  1702.       if ($atime > time()) {
  1703.     $atime = time();
  1704.     push(@warnings, 'atime > current time, resetting');
  1705.     $token_warn_p = 1;
  1706.       }
  1707.  
  1708.       if ($token_warn_p) {
  1709.     dbg("bayes: token ($token) has the following warnings:\n".join("\n",@warnings));
  1710.       }
  1711.  
  1712.       # database versions < 3 did not encode their token values
  1713.       if ($db_version < 3) {
  1714.     $token = substr(sha1($token), -5);
  1715.       }
  1716.       else {
  1717.     # turn unpacked binary token back into binary value
  1718.     $token = pack("H*",$token);
  1719.       }
  1720.  
  1721.       $new_toks{$token} = $self->tok_pack($spam_count, $ham_count, $atime);
  1722.       if ($atime < $oldest_token_age) {
  1723.     $oldest_token_age = $atime;
  1724.       }
  1725.       if ($atime > $newest_token_age) {
  1726.     $newest_token_age = $atime;
  1727.       }
  1728.       $token_count++;
  1729.     }
  1730.     elsif ($line =~ /^s\s+/) { # seen line
  1731.       my @parsed_line = split(/\s+/, $line, 3);
  1732.       my $flag = $parsed_line[1];
  1733.       my $msgid = $parsed_line[2];
  1734.  
  1735.       unless ($flag eq 'h' || $flag eq 's') {
  1736.     dbg("bayes: unknown seen flag ($flag) for line: $line, skipping");
  1737.     next;
  1738.       }
  1739.  
  1740.       unless ($msgid) {
  1741.     dbg("bayes: blank msgid for line: $line, skipping");
  1742.     next;
  1743.       }
  1744.  
  1745.       $new_seen{$msgid} = $flag;
  1746.     }
  1747.     else {
  1748.       dbg("bayes: skipping unknown line: $line");
  1749.       next;
  1750.     }
  1751.   }
  1752.   close(DUMPFILE);
  1753.  
  1754.   print STDERR "\n" if ($showdots);
  1755.  
  1756.   unless (defined($num_spam)) {
  1757.     dbg("bayes: unable to find num spam, please check file");
  1758.     $error_p = 1;
  1759.   }
  1760.  
  1761.   unless (defined($num_ham)) {
  1762.     dbg("bayes: unable to find num ham, please check file");
  1763.     $error_p = 1;
  1764.   }
  1765.  
  1766.   if ($error_p) {
  1767.     dbg("bayes: error(s) while attempting to load $filename, correct and re-run");
  1768.  
  1769.     untie %new_toks;
  1770.     untie %new_seen;
  1771.     $self->_unlink_file($tmptoksdbname);
  1772.     $self->_unlink_file($tmpseendbname);
  1773.     $self->untie_db();
  1774.     return 0;
  1775.   }
  1776.  
  1777.   # set the calculated magic tokens
  1778.   $new_toks{$DB_VERSION_MAGIC_TOKEN} = $self->DB_VERSION();
  1779.   $new_toks{$NTOKENS_MAGIC_TOKEN} = $token_count;
  1780.   $new_toks{$NSPAM_MAGIC_TOKEN} = $num_spam;
  1781.   $new_toks{$NHAM_MAGIC_TOKEN} = $num_ham;
  1782.   $new_toks{$NEWEST_TOKEN_AGE_MAGIC_TOKEN} = $newest_token_age;
  1783.   $new_toks{$OLDEST_TOKEN_AGE_MAGIC_TOKEN} = $oldest_token_age;
  1784.  
  1785.   # go ahead and zero out these, chances are good that they are bogus anyway.
  1786.   $new_toks{$LAST_EXPIRE_MAGIC_TOKEN} = 0;
  1787.   $new_toks{$LAST_JOURNAL_SYNC_MAGIC_TOKEN} = 0;
  1788.   $new_toks{$LAST_ATIME_DELTA_MAGIC_TOKEN} = 0;
  1789.   $new_toks{$LAST_EXPIRE_REDUCE_MAGIC_TOKEN} = 0;
  1790.  
  1791.   local $SIG{'INT'} = 'IGNORE';
  1792.   local $SIG{'TERM'} = 'IGNORE';
  1793.   local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
  1794.  
  1795.   untie %new_toks;
  1796.   untie %new_seen;
  1797.   $self->untie_db();
  1798.  
  1799.   # Here is where something can go horribly wrong and screw up the bayes
  1800.   # database files.  If we are able to copy one and not the other then it
  1801.   # will leave the database in an inconsistent state.  Since this is an
  1802.   # edge case, and they're trying to replace the DB anyway we should be ok.
  1803.   unless ($self->_rename_file($tmptoksdbname, $toksdbname)) {
  1804.     dbg("bayes: error while renaming $tmptoksdbname to $toksdbname: $!");
  1805.     return 0;
  1806.   }
  1807.   unless ($self->_rename_file($tmpseendbname, $seendbname)) {
  1808.     dbg("bayes: error while renaming $tmpseendbname to $seendbname: $!");
  1809.     dbg("bayes: database now in inconsistent state");
  1810.     return 0;
  1811.   }
  1812.  
  1813.   dbg("bayes: parsed $line_count lines");
  1814.   dbg("bayes: created database with $token_count tokens based on $num_spam spam messages and $num_ham ham messages");
  1815.  
  1816.   return 1;
  1817. }
  1818.  
  1819. ###########################################################################
  1820.  
  1821. # token marshalling format for db_toks.
  1822.  
  1823. # Since we may have many entries with few hits, especially thousands of hapaxes
  1824. # (1-occurrence entries), use a flexible entry format, instead of simply "2
  1825. # packed ints", to keep the memory and disk space usage down.  In my
  1826. # 18k-message test corpus, only 8.9% have >= 8 hits in either counter, so we
  1827. # can use a 1-byte representation for the other 91% of low-hitting entries
  1828. # and save masses of space.
  1829.  
  1830. # This looks like: XXSSSHHH (XX = format bits, SSS = 3 spam-count bits, HHH = 3
  1831. # ham-count bits).  If XX in the first byte is 11, it's packed as this 1-byte
  1832. # representation; otherwise, if XX in the first byte is 00, it's packed as
  1833. # "CLL", ie. 1 byte and 2 32-bit "longs" in perl pack format.
  1834.  
  1835. # Savings: roughly halves size of toks db, at the cost of a ~10% slowdown.
  1836.  
  1837. use constant FORMAT_FLAG    => 0xc0;    # 11000000
  1838. use constant ONE_BYTE_FORMAT    => 0xc0;    # 11000000
  1839. use constant TWO_LONGS_FORMAT    => 0x00;    # 00000000
  1840.  
  1841. use constant ONE_BYTE_SSS_BITS    => 0x38;    # 00111000
  1842. use constant ONE_BYTE_HHH_BITS    => 0x07;    # 00000111
  1843.  
  1844. sub tok_unpack {
  1845.   my ($self, $value) = @_;
  1846.   $value ||= 0;
  1847.  
  1848.   my ($packed, $atime);
  1849.   if ($self->{db_version} >= 1) {
  1850.     ($packed, $atime) = unpack("CV", $value);
  1851.   }
  1852.   elsif ($self->{db_version} == 0) {
  1853.     ($packed, $atime) = unpack("CS", $value);
  1854.   }
  1855.  
  1856.   if (($packed & FORMAT_FLAG) == ONE_BYTE_FORMAT) {
  1857.     return (($packed & ONE_BYTE_SSS_BITS) >> 3,
  1858.         $packed & ONE_BYTE_HHH_BITS,
  1859.         $atime || 0);
  1860.   }
  1861.   elsif (($packed & FORMAT_FLAG) == TWO_LONGS_FORMAT) {
  1862.     my ($packed, $ts, $th, $atime);
  1863.     if ($self->{db_version} >= 1) {
  1864.       ($packed, $ts, $th, $atime) = unpack("CVVV", $value);
  1865.     }
  1866.     elsif ($self->{db_version} == 0) {
  1867.       ($packed, $ts, $th, $atime) = unpack("CLLS", $value);
  1868.     }
  1869.     return ($ts || 0, $th || 0, $atime || 0);
  1870.   }
  1871.   # other formats would go here...
  1872.   else {
  1873.     warn "bayes: unknown packing format for bayes db, please re-learn: $packed";
  1874.     return (0, 0, 0);
  1875.   }
  1876. }
  1877.  
  1878. sub tok_pack {
  1879.   my ($self, $ts, $th, $atime) = @_;
  1880.   $ts ||= 0; $th ||= 0; $atime ||= 0;
  1881.   if ($ts < 8 && $th < 8) {
  1882.     return pack ("CV", ONE_BYTE_FORMAT | ($ts << 3) | $th, $atime);
  1883.   } else {
  1884.     return pack ("CVVV", TWO_LONGS_FORMAT, $ts, $th, $atime);
  1885.   }
  1886. }
  1887.  
  1888. ###########################################################################
  1889.  
  1890. sub db_readable {
  1891.   my ($self) = @_;
  1892.   return $self->{already_tied};
  1893. }
  1894.  
  1895. sub db_writable {
  1896.   my ($self) = @_;
  1897.   return $self->{already_tied} && $self->{is_locked};
  1898. }
  1899.  
  1900. ###########################################################################
  1901.  
  1902. sub _unlink_file {
  1903.   my ($self, $filename) = @_;
  1904.  
  1905.   unlink $filename;
  1906. }
  1907.  
  1908. sub _rename_file {
  1909.   my ($self, $sourcefilename, $targetfilename) = @_;
  1910.  
  1911.   return 0 unless (rename($sourcefilename, $targetfilename));
  1912.  
  1913.   return 1;
  1914. }
  1915.  
  1916. sub sa_die { Mail::SpamAssassin::sa_die(@_); }
  1917.  
  1918. 1;
  1919.