Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 527 lines (431 sloc) 14.893 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
package Qpsmtpd;
use strict;
use vars qw($VERSION $Logger $TraceLevel $Spool_dir $Size_threshold);

use Sys::Hostname;
use Qpsmtpd::Constants;

$VERSION = "0.40";

sub version { $VERSION };

sub TRACE_LEVEL { $TraceLevel }; # leave for plugin compatibility

sub load_logging {
  # need to do this differently that other plugins so as to
  # not trigger logging activity
  my $self = shift;
  return if $self->{hooks}->{"logging"};
  my $configdir = $self->config_dir("logging");
  my $configfile = "$configdir/logging";
  my @loggers = $self->_config_from_file($configfile,'logging');

  $configdir = $self->config_dir('plugin_dirs');
  $configfile = "$configdir/plugin_dirs";
  my @plugin_dirs = $self->_config_from_file($configfile,'plugin_dirs');
  unless (@plugin_dirs) {
    my ($name) = ($0 =~ m!(.*?)/([^/]+)$!);
    @plugin_dirs = ( "$name/plugins" );
  }
  
  my @loaded;
  for my $logger (@loggers) {
    push @loaded, $self->_load_plugin($logger, @plugin_dirs);
  }

  foreach my $logger (@loaded) {
    $self->log(LOGINFO, "Loaded $logger");
  }

  return @loggers;
}
  
sub trace_level {
  my $self = shift;
  return $TraceLevel if $TraceLevel;

  my $configdir = $self->config_dir("loglevel");
  my $configfile = "$configdir/loglevel";
  $TraceLevel = $self->_config_from_file($configfile,'loglevel');

  unless (defined($TraceLevel) and $TraceLevel =~ /^\d+$/) {
    $TraceLevel = LOGWARN; # Default if no loglevel file found.
  }

  return $TraceLevel;
}

sub init_logger { # needed for compatibility purposes
  shift->trace_level();
}

sub log {
  my ($self, $trace, @log) = @_;
  $self->varlog($trace,join(" ",@log));
}

sub varlog {
  my ($self, $trace) = (shift,shift);
  my ($hook, $plugin, @log);
  if ( $#_ == 0 ) { # log itself
    (@log) = @_;
  }
  elsif ( $#_ == 1 ) { # plus the hook
    ($hook, @log) = @_;
  }
  else { # called from plugin
    ($hook, $plugin, @log) = @_;
  }

  $self->load_logging; # in case we already don't have this loaded yet

  my ($rc) = $self->run_hooks("logging", $trace, $hook, $plugin, @log);

  unless ( $rc and $rc == DECLINED or $rc == OK ) {
    # no logging plugins registered so fall back to STDERR
    warn join(" ", $$ .
      (defined $plugin ? " $plugin plugin:" :
       defined $hook ? " running plugin ($hook):" : ""),
      @log), "\n"
    if $trace <= $self->trace_level();
  }
}

#
# method to get the configuration. It just calls get_qmail_config by
# default, but it could be overwritten to look configuration up in a
# database or whatever.
#
sub config {
  my ($self, $c, $type) = @_;

  #warn "SELF->config($c) ", ref $self;

  my %defaults = (
me => hostname,
timeout => 1200,
);

  my ($rc, @config) = $self->run_hooks("config", $c);
  @config = () unless $rc == OK;

  if (wantarray) {
      @config = $self->get_qmail_config($c, $type) unless @config;
      @config = $defaults{$c} if (!@config and $defaults{$c});
      return @config;
  }
  else {
      return ($config[0] || $self->get_qmail_config($c, $type) || $defaults{$c});
   }
}

sub config_dir {
  my ($self, $config) = @_;
  my $configdir = ($ENV{QMAIL} || '/var/qmail') . '/control';
  my ($path) = ($ENV{PROCESS} ? $ENV{PROCESS} : $0) =~ m!(.*?)/([^/]+)$!;
  $configdir = "$path/config" if (-e "$path/config/$config");
  if (exists $ENV{QPSMTPD_CONFIG}) {
    $ENV{QPSMTPD_CONFIG} =~ /^(.*)$/; # detaint
    $configdir = $1 if -e "$1/$config";
  }
  return $configdir;
}

sub plugin_dirs {
    my $self = shift;
    my @plugin_dirs = $self->config('plugin_dirs');
    
    unless (@plugin_dirs) {
        my ($path) = ($ENV{PROCESS} ? $ENV{PROCESS} : $0) =~ m!(.*?)/([^/]+)$!;
        @plugin_dirs = ( "$path/plugins" );
    }
    return @plugin_dirs;
}

sub get_qmail_config {
  my ($self, $config, $type) = @_;
  $self->log(LOGDEBUG, "trying to get config for $config");
  if ($self->{_config_cache}->{$config}) {
    return wantarray ? @{$self->{_config_cache}->{$config}} : $self->{_config_cache}->{$config}->[0];
  }
  my $configdir = $self->config_dir($config);

  my $configfile = "$configdir/$config";

  if ($type and $type eq "map") {
    return +{} unless -e $configfile . ".cdb";
    eval { require CDB_File };

    if ($@) {
      $self->log(LOGERROR, "No CDB Support! Did NOT read $configfile.cdb, could not load CDB_File module: $@");
      return +{};
    }

    my %h;
    unless (tie(%h, 'CDB_File', "$configfile.cdb")) {
      $self->log(LOGERROR, "tie of $configfile.cdb failed: $!");
      return +{};
    }
    #warn Data::Dumper->Dump([\%h], [qw(h)]);
    # should we cache this?
    return \%h;
  }

  return $self->_config_from_file($configfile, $config);
}

sub _config_from_file {
  my ($self, $configfile, $config, $visited) = @_;
  return unless -e $configfile;

  $visited ||= [];
  push @{$visited}, $configfile;

  open CF, "<$configfile" or warn "$$ could not open configfile $configfile: $!" and return;
  my @config = <CF>;
  chomp @config;
  @config = grep { length($_) and $_ !~ m/^\s*#/ and $_ =~ m/\S/} @config;
  close CF;

  my $pos = 0;
  while ($pos < @config) {
    # recursively pursue an $include reference, if found. An inclusion which
    # begins with a leading slash is interpreted as a path to a file and will
    # supercede the usual config path resolution. Otherwise, the normal
    # config_dir() lookup is employed (the location in which the inclusion
    # appeared receives no special precedence; possibly it should, but it'd
    # be complicated beyond justifiability for so simple a config system.
    if ($config[$pos] =~ /^\s*\$include\s+(\S+)\s*$/) {
      my ($includedir, $inclusion) = ('', $1);

      splice @config, $pos, 1; # remove the $include line
      if ($inclusion !~ /^\//) {
        $includedir = $self->config_dir($inclusion);
        $inclusion = "$includedir/$inclusion";
      }

      if (grep($_ eq $inclusion, @{$visited})) {
        $self->log(LOGERROR, "Circular \$include reference in config $config:");
        $self->log(LOGERROR, "From $visited->[0]:");
        $self->log(LOGERROR, " includes $_")
          for (@{$visited}[1..$#{$visited}], $inclusion);
        return wantarray ? () : undef;
      }
      push @{$visited}, $inclusion;

      for my $inc ($self->expand_inclusion_($inclusion, $configfile)) {
        my @insertion = $self->_config_from_file($inc, $config, $visited);
        splice @config, $pos, 0, @insertion; # insert the inclusion
        $pos += @insertion;
      }
    } else {
      $pos++;
    }
  }

  $self->{_config_cache}->{$config} = \@config;

  return wantarray ? @config : $config[0];
}

sub expand_inclusion_ {
  my $self = shift;
  my $inclusion = shift;
  my $context = shift;
  my @includes;

  if (-d $inclusion) {
    $self->log(LOGDEBUG, "inclusion of directory $inclusion from $context");

    if (opendir(INCD, $inclusion)) {
      @includes = map { "$inclusion/$_" }
        (grep { -f "$inclusion/$_" and !/^\./ } readdir INCD);
      closedir INCD;
    } else {
      $self->log(LOGERROR, "Couldn't open directory $inclusion,".
                           " referenced from $context ($!)");
    }
  } else {
    $self->log(LOGDEBUG, "inclusion of file $inclusion from $context");
    @includes = ( $inclusion );
  }
  return @includes;
}


sub load_plugins {
  my $self = shift;
  
  $self->log(LOGWARN, "Plugins already loaded") if $self->{hooks};
  $self->{hooks} = {};
  
  my @plugins = $self->config('plugins');
  my @loaded;

  for my $plugin_line (@plugins) {
    my $this_plugin = $self->_load_plugin($plugin_line, $self->plugin_dirs);
    push @loaded, $this_plugin if $this_plugin;
  }

  return @loaded;
}

sub _load_plugin {
  my $self = shift;
  my ($plugin_line, @plugin_dirs) = @_;

  my ($plugin, @args) = split ' ', $plugin_line;

  my $package;

  if ($plugin =~ m/::/) {
    # "full" package plugin (My::Plugin)
    $package = $plugin;
    $package =~ s/[^_a-z0-9:]+//gi;
    my $eval = qq[require $package;\n]
              .qq[sub ${plugin}::plugin_name { '$plugin' }];
    $eval =~ m/(.*)/s;
    $eval = $1;
    eval $eval;
    die "Failed loading $package - eval $@" if $@;
    $self->log(LOGDEBUG, "Loading $package ($plugin_line)")
      unless $plugin_line =~ /logging/;
  }
  else {
    # regular plugins/$plugin plugin
    my $plugin_name = $plugin;
    $plugin =~ s/:\d+$//; # after this point, only used for filename

    # Escape everything into valid perl identifiers
    $plugin_name =~ s/([^A-Za-z0-9_\/])/sprintf("_%2x",unpack("C",$1))/eg;
    
    # second pass cares for slashes and words starting with a digit
    $plugin_name =~ s{
(/+) # directory
(\d?) # package's first character
}[
"::" . (length $2 ? sprintf("_%2x",unpack("C",$2)) : "")
]egx;
    
    $package = "Qpsmtpd::Plugin::$plugin_name";
    
    # don't reload plugins if they are already loaded
    unless ( defined &{"${package}::plugin_name"} ) {
      PLUGIN_DIR: for my $dir (@plugin_dirs) {
        if (-e "$dir/$plugin") {
          Qpsmtpd::Plugin->compile($plugin_name, $package,
            "$dir/$plugin", $self->{_test_mode}, $plugin);
          $self->log(LOGDEBUG, "Loading $plugin_line from $dir/$plugin")
            unless $plugin_line =~ /logging/;
          last PLUGIN_DIR;
        }
      }
    }
  }

  my $plug = $package->new();
  $plug->_register($self, @args);
  
  return $plug;
}

sub transaction {
    return {}; # base class implements empty transaction
}

sub run_hooks {
  my ($self, $hook) = (shift, shift);
  my $hooks = $self->{hooks};
  if ($hooks->{$hook}) {
    my @r;
    my @local_hooks = @{$hooks->{$hook}};
    $self->{_continuation} = [$hook, [@_], @local_hooks];
    return $self->run_continuation();
  }
  return $self->hook_responder($hook, [0, ''], [@_]);
}

sub run_continuation {
  my $self = shift;
  die "No continuation in progress" unless $self->{_continuation};
  $self->continue_read() if $self->isa('Danga::Client');
  my $todo = $self->{_continuation};
  $self->{_continuation} = undef;
  my $hook = shift @$todo || die "No hook in the continuation";
  my $args = shift @$todo || die "No hook args in the continuation";
  my @r;
  while (@$todo) {
    my $code = shift @$todo;
    if ( $hook eq 'logging' ) { # without calling $self->log()
      eval { (@r) = $code->{code}->($self, $self->transaction, @$args); };
      $@ and warn("FATAL LOGGING PLUGIN ERROR: ", $@) and next;
    }
    else {
      $self->varlog(LOGDEBUG, $hook, $code->{name});
      eval { (@r) = $code->{code}->($self, $self->transaction, @$args); };
      $@ and $self->log(LOGCRIT, "FATAL PLUGIN ERROR: ", $@) and next;

      !defined $r[0]
        and $self->log(LOGERROR, "plugin ".$code->{name}
                       ." running the $hook hook returned undef!")
        and next;

      if ($self->transaction) {
        my $tnotes = $self->transaction->notes( $code->{name} );
        $tnotes->{"hook_$hook"}->{'return'} = $r[0]
          if (!defined $tnotes || ref $tnotes eq "HASH");
      }
      else {
        my $cnotes = $self->connection->notes( $code->{name} );
        $cnotes->{"hook_$hook"}->{'return'} = $r[0]
          if (!defined $cnotes || ref $cnotes eq "HASH");
      }
      
      if ($r[0] == YIELD) {
        $self->pause_read() if $self->isa('Danga::Client');
        $self->{_continuation} = [$hook, $args, @$todo];
        return @r;
      }
      elsif ($r[0] == DENY or $r[0] == DENYSOFT or
          $r[0] == DENY_DISCONNECT or $r[0] == DENYSOFT_DISCONNECT)
      {
        $r[1] = "" if not defined $r[1];
        $self->log(LOGDEBUG, "Plugin ".$code->{name}.
", hook $hook returned ".return_code($r[0]).", $r[1]");
        $self->run_hooks("deny", $code->{name}, $r[0], $r[1]) unless ($hook eq "deny");
      }
      else {
        $r[1] = "" if not defined $r[1];
        $self->log(LOGDEBUG, "Plugin ".$code->{name}.
", hook $hook returned ".return_code($r[0]).", $r[1]");
        $self->run_hooks("ok", $code->{name}, $r[0], $r[1]) unless ($hook eq "ok");
      }

    }

    last unless $r[0] == DECLINED;
  }
  $r[0] = DECLINED if not defined $r[0];
  @r = map { split /\n/ } @r;
  return $self->hook_responder($hook, \@r, $args);
}

sub hook_responder {
  my ($self, $hook, $msg, $args) = @_;
  
  my $code = shift @$msg;
  
  my $responder = $hook . '_respond';
  if (my $meth = $self->can($responder)) {
    return $meth->($self, $code, $msg, $args);
  }
  return $code, @$msg;
}

sub _register_hook {
  my $self = shift;
  my ($hook, $code, $unshift) = @_;

  my $hooks = $self->{hooks};
  if ($unshift) {
    unshift @{$hooks->{$hook}}, $code;
  }
  else {
    push @{$hooks->{$hook}}, $code;
  }
}

sub spool_dir {
  my $self = shift;

  unless ( $Spool_dir ) { # first time through
    $self->log(LOGINFO, "Initializing spool_dir");
    $Spool_dir = $self->config('spool_dir')
               || Qpsmtpd::Utils::tildeexp('~/tmp/');

    $Spool_dir .= "/" unless ($Spool_dir =~ m!/$!);
  
    $Spool_dir =~ /^(.+)$/ or die "spool_dir not configured properly";
    $Spool_dir = $1; # cleanse the taint

    # Make sure the spool dir has appropriate rights
    if (-e $Spool_dir) {
      my $mode = (stat($Spool_dir))[2];
      $self->log(LOGWARN,
          "Permissions on spool_dir $Spool_dir are not 0700")
        if $mode & 07077;
    }

    # And finally, create it if it doesn't already exist
    -d $Spool_dir or mkdir($Spool_dir, 0700)
      or die "Could not create spool_dir $Spool_dir: $!";
  }
    
  return $Spool_dir;
}

# For unique filenames. We write to a local tmp dir so we don't need
# to make them unpredictable.
my $transaction_counter = 0;

sub temp_file {
  my $self = shift;
  my $filename = $self->spool_dir()
    . join(":", time, $$, $transaction_counter++);
  return $filename;
}

sub temp_dir {
  my $self = shift;
  my $mask = shift || 0700;
  my $dirname = $self->temp_file();
  -d $dirname or mkdir($dirname, $mask)
    or die "Could not create temporary directory $dirname: $!";
  return $dirname;
}

sub size_threshold {
  my $self = shift;
  unless ( defined $Size_threshold ) {
    $Size_threshold = $self->config('size_threshold') || 0;
    $self->log(LOGNOTICE, "size_threshold set to $Size_threshold");
  }
  return $Size_threshold;
}

sub authenticated {
  my $self = shift;
  return (defined $self->{_auth} ? $self->{_auth} : "" );
}

sub auth_user {
  my $self = shift;
  return (defined $self->{_auth_user} ? $self->{_auth_user} : "" );
}

sub auth_mechanism {
  my $self = shift;
  return (defined $self->{_auth_mechanism} ? $self->{_auth_mechanism} : "" );
}
  
1;

__END__

=head1 NAME

Qpsmtpd

=head1 DESCRIPTION

This is the base class for the qpsmtpd mail server. See
L<http://smtpd.develooper.com/> and the I<README> file for more information.

=head1 COPYRIGHT

Copyright 2001-2005 Ask Bjoern Hansen, Develooper LLC. See the
LICENSE file for more information.
Something went wrong with that request. Please try again.