sympa_msg.pl.in 72.4 KB
Newer Older
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
#!--PERL--
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
# Copyright (c) 2011, 2012, 2013, 2014, 2015 GIP RENATER
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use lib split(/:/, $ENV{SYMPALIB} || ''), '--modulesdir--';
use strict;
use warnings;
use English qw(-no_match_vars);
use File::Copy qw();
use Getopt::Long;
use Pod::Usage;
use POSIX qw();

35
use Sympa;
36
37
38
39
40
41
42
43
44
use Sympa::Alarm;
use Sympa::Commands;
use Conf;
use Sympa::Constants;
use Sympa::Crash;    # Show traceback.
use Sympa::DatabaseManager;
use Sympa::Language;
use Sympa::List;
use Sympa::LockedFile;
45
use Sympa::Log;
46
47
48
49
50
use Sympa::Mailer;
use Sympa::Message;
use Sympa::Regexps;
use Sympa::Report;
use Sympa::Scenario;
51
use Sympa::Spool;
52
53
54
55
56
57
58
59
60
61
62
63
64
use tools;
use Sympa::Tools::Daemon;
use Sympa::Tools::Data;
use Sympa::Tools::File;
use Sympa::Tools::Password;

## Internal tuning
# delay between each read of the digestqueue
my $digestsleep = 5;

## Init random engine
srand(time());

65
66
# Default is to launch process as master daemon.
my $daemon_usage = 'DAEMON_MASTER';
67

68
# Check options.
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
my %options;
unless (
    GetOptions(
        \%main::options, 'debug|d',  'log_level=s', 'foreground',
        'config|f=s',    'lang|l=s', 'mail|m',      'keepcopy|k=s',
        'help|h',        'version|v',
    )
    ) {
    pod2usage(-exitval => 1, -output => \*STDERR);
}
if ($main::options{'help'}) {
    pod2usage(0);
} elsif ($main::options{'version'}) {
    printf "Sympa %s\n", Sympa::Constants::VERSION;
    exit 0;
}

86
87
88
89
90
91
92
93
if ($main::options{'debug'}) {
    $main::options{'log_level'} = 2 unless $main::options{'log_level'};
    $main::options{'foreground'} = 1;
}

my $log = Sympa::Log->instance;
$log->{log_to_stderr} = 'all' if $main::options{'foreground'};

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
my $default_lang;

my $language = Sympa::Language->instance;
my $mailer   = Sympa::Mailer->instance;

_load();

## Put ourselves in background if we're not in debug mode. That method
## works on many systems, although, it seems that Unix conceptors have
## decided that there won't be a single and easy way to detach a
## process from its controlling TTY.
unless ($main::options{'foreground'}) {
    if (open(TTY, "/dev/tty")) {
        ioctl(TTY, 0x20007471, 0);    # XXX s/b TIOCNOTTY()
        close(TTY);
    }
    open(STDIN,  ">> /dev/null");
    open(STDOUT, ">> /dev/null");
    open(STDERR, ">> /dev/null");

    setpgrp 0, 0;

    my $child_pid = fork;
    if ($child_pid) {
118
        $log->syslog('notice', 'Starting sympa/msg daemon, PID %d',
119
            $child_pid);
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        exit 0;
    } elsif (not defined $child_pid) {
        die sprintf 'Cannot fork: %s', $ERRNO;
    }

    # Fork a new process dedicated to automatic list creation, if required.
    if ($Conf::Conf{'automatic_list_feature'} eq 'on') {
        my $child_pid = fork;
        if ($child_pid) {
            waitpid $child_pid, 0;
            $CHILD_ERROR and die;
        } elsif (not defined $child_pid) {
            die sprintf 'Cannot fork: %s', $ERRNO;
        } else {
            # We're in the specialized child process:
            # automatic lists creation.
            exec q{--sbindir--/sympa_automatic.pl}, map {
                defined $main::options{$_}
                    ? ("--$_", $main::options{$_})
                    : ()
sikeda's avatar
sikeda committed
140
            } qw(config log_level mail);
141
142
143
144
145
            die sprintf 'Cannot exec: %s', $ERRNO;
        }
    }
}

sikeda's avatar
sikeda committed
146
147
my $pidfile = 'sympa_msg';

148
$log->openlog($Conf::Conf{'syslog'}, $Conf::Conf{'log_socket_type'});
149

sikeda's avatar
sikeda committed
150
151
# If process is running in foreground, don't write STDERR to a
# dedicated file
152
153
my $options;
$options->{'stderr_to_tty'} = 1 if $main::options{'foreground'};
154
155
156
$options->{'multiple_process'} = 0;

# Save the PID number
sikeda's avatar
sikeda committed
157
Sympa::Tools::Daemon::write_pid($pidfile, $PID, $options);
158
unless ($options->{'stderr_to_tty'}) {
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
    Sympa::Tools::Daemon::direct_stderr_to_file(pid => $PID);
}

# Start multiple processes if required.
unless ($main::options{'foreground'}) {
    if ($daemon_usage eq 'DAEMON_MASTER'
        and ($Conf::Conf{'incoming_max_count'} || 0) > 1) {
        $options->{'multiple_process'} = 1;

        # Disconnect from database before fork to prevent DB handles
        # to be shared by different processes.  Sharing database
        # handles may crash sympa_msg.pl.
        Sympa::DatabaseManager->disconnect;

        for my $process_count (2 .. $Conf::Conf{'incoming_max_count'}) {
            my $child_pid = fork;
            if ($child_pid) {
176
                $log->syslog('info', 'Starting child daemon, PID %s',
177
178
179
180
181
182
183
                    $child_pid);
                # Saves the PID number
                Sympa::Tools::Daemon::write_pid($pidfile, $child_pid,
                    $options);
                #$created_children{$child_pid} = 1;
                sleep 1;
            } elsif (not defined $child_pid) {
184
                $log->syslog('err', 'Cannot fork: %m');
185
186
187
188
189
190
                last;
            } else {
                # We're in a child process
                close STDERR;
                Sympa::Tools::Daemon::direct_stderr_to_file(pid => $PID);
                $daemon_usage = 'DAEMON_SLAVE';    # child
191
                $log->openlog($Conf::Conf{'syslog'},
192
                    $Conf::Conf{'log_socket_type'});
193
194
                $log->syslog('info', 'Slave daemon started with PID %s',
                    $PID);
195
196
197
198
199
200
201
202
                last;
            }
        }

        # Restore persistent connection.
        Sympa::DatabaseManager->instance
            or die 'Reconnecting database failed';
    }
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
}

# Set the User ID & Group ID for the process
$GID = $EGID = (getgrnam(Sympa::Constants::GROUP))[2];
$UID = $EUID = (getpwnam(Sympa::Constants::USER))[2];

## Required on FreeBSD to change ALL IDs
## (effective UID + real UID + saved UID)
POSIX::setuid((getpwnam(Sympa::Constants::USER))[2]);
POSIX::setgid((getgrnam(Sympa::Constants::GROUP))[2]);

## Check if the UID has correctly been set (useful on OS X)
unless (($GID == (getgrnam(Sympa::Constants::GROUP))[2])
    && ($UID == (getpwnam(Sympa::Constants::USER))[2])) {
    die
        "Failed to change process user ID and group ID. Note that on some OS Perl scripts can't change their real UID. In such circumstances Sympa should be run via sudo.\n";
}

# Sets the UMASK
umask(oct($Conf::Conf{'umask'}));

## Most initializations have now been done.
225
$log->syslog('notice', 'Sympa/msg %s Started', Sympa::Constants::VERSION());
226
227
228
229
230
231
232
233
234
235
236
237

# Check for several files.
# Prevent that 2 processes perform checks at the same time...
#FIXME: This would be done in --health_check mode.
unless (Conf::checkfiles()) {
    die "Missing files.\n";
    ## No return.
}

## Do we have right access in the directory
if ($main::options{'keepcopy'}) {
    if (!-d $main::options{'keepcopy'}) {
238
        $log->syslog(
239
240
241
242
243
244
            'notice',
            'Cannot keep a copy of incoming messages: %s is not a directory',
            $main::options{'keepcopy'}
        );
        delete $main::options{'keepcopy'};
    } elsif (!-w $main::options{'keepcopy'}) {
245
        $log->syslog(
246
247
248
249
250
251
252
253
254
255
256
            'notice',
            'Cannot keep a copy of incoming messages: no write access to %s',
            $main::options{'keepcopy'}
        );
        delete $main::options{'keepcopy'};
    }
}

# Catch signals, in order to exit cleanly, whenever possible.
my $signal = 0;
$SIG{'TERM'} = 'sigterm';
257
$SIG{'INT'}  = 'sigterm';    # Interrupt from terminal.
258
$SIG{'HUP'}  = 'sighup';
259
$SIG{'PIPE'} = 'IGNORE';     # Ignore SIGPIPE ; prevents process from dying
260
261
262
263
264
265
266
267
268
269

# Main loop.
# This loop is run foreach HUP signal received.

my %loop_info;
my %msgid_table;
my $latest_msgid_table_cleanup = time;
my $index_queuedigest          = 0;      # verify the digest queue
my $index_cleanqueue           = 0;

270
271
# This is the main loop : look for files in the directory, handles
# them, sleeps a while and continues the good job.
272

273
my $spool = $Conf::Conf{'queue'};
274

275
276
277
278
279
280
281
282
while ($signal ne 'term') {
    Sympa::List::init_list_cache();
    # Process grouped notifications
    Sympa::Alarm->instance->flush;

    my $dh;
    unless (opendir $dh, $spool) {
        die sprintf 'Can\'t open dir %s: %s', $spool, $ERRNO;
283
        # No return.
284
285
286
287
288
    }
    my @qfile =
        grep { !/,lock/ and !/\A(?:\.|T\.|BAD-)/ and -f ($spool . '/' . $_) }
        readdir $dh;
    closedir $dh;
289
290
291
292
    my %mtime =
        map { ($_ => Sympa::Tools::File::get_mtime($spool . '/' . $_)) }
        @qfile;
    @qfile = sort { $mtime{$a} <=> $mtime{$b} } @qfile;
293
294
295

    # process digest only in distribution mode.
    # Scan queuedigest.
296
297
    if (    $daemon_usage eq 'DAEMON_MASTER'
        and $index_queuedigest++ >= $digestsleep) {
298
299
300
        $index_queuedigest = 0;
        SendDigest();
    }
301

302
303
304
305
306
307
    # Cleanup in-memory msgid table, only in a while.
    if (time > $latest_msgid_table_cleanup +
        $Conf::Conf{'msgid_table_cleanup_frequency'}) {
        clean_msgid_table();
        $latest_msgid_table_cleanup = time;
    }
308

309
310
311
312
313
314
    my $highest_priority = 'z';
    my $numprocessed     = 0;
    foreach my $filename (@qfile) {
        last if $signal;

        $language->set_lang($default_lang);
315
316
317

        $mailer->reaper();    # finish terminated process

318
319
320
321
        my $lock_fh =
            Sympa::LockedFile->new($spool . '/' . $filename, -1, '+<');
        next unless $lock_fh;

322
        my $metadata = Sympa::Spool::unmarshal_metadata(
323
324
325
326
327
            $spool, $filename,
            qr{\A([^\s\@]+)(?:\@([\w\.\-]+))?\.(\d+)\.\w+(?:,.*)?\z},
            [qw(localpart domainpart date)]
        );
        next unless $metadata;
328
329
330

        # z and Z are a null priority, so file stay in queue and are
        # processed only if renamed by administrator
331
332
333
334
335
336
337
338
        next
            if $metadata->{'priority'} and lc($metadata->{'priority'}) eq 'z';

        # Lazily seek highest priority: Messages with lower priority than
        # those already found are skipped.
        if (defined $metadata->{priority} and length $metadata->{priority}) {
            next if $highest_priority lt $metadata->{priority};
            $highest_priority = $metadata->{priority};
339
340
341
342
343
344
345
        }

        my $msg_string = do { local $RS; <$lock_fh> };
        my $message = Sympa::Message->new($msg_string, %$metadata);

        # Compatibility: Message with checksum by Sympa <=6.2a.40
        # They should be migrated.
346
        if ($message and $message->{checksum}) {
347
            $log->syslog('err',
348
349
350
351
352
                '%s: Message with old format.  Run upgrade_send_spool.pl',
                $message);
            next;
        }

353
354
        $numprocessed++;

355
356
357
358
        # Appel de la fonction de traitement des mails entrants
        my $status = process_message($message);

        if (defined $status) {
359
            $log->syslog('debug', "Finished %s", "$spool/$filename");
360
361
362
363

            if ($main::options{'keepcopy'}) {
                unless (
                    File::Copy::copy(
364
                        $spool . '/' . $filename,
365
366
367
                        $main::options{'keepcopy'} . '/' . $filename
                    )
                    ) {
368
                    $log->syslog(
369
370
                        'notice',
                        'Could not rename %s/%s to %s/%s: %m',
371
                        $spool,
372
373
374
375
376
377
378
379
                        $filename,
                        $main::options{'keepcopy'},
                        $filename
                    );
                }
            }
            $lock_fh->unlink;
        } else {
380
            my $bad_dir = "$spool/bad";
381
382
383
384
385
386
387

            if (-d $bad_dir) {
                unless ($lock_fh->rename($bad_dir . '/' . $filename)) {
                    die sprintf
                        'Unable to rename bad file %s to %s/%s: %s',
                        $filename, $bad_dir, $filename, $lock_fh->last_error;
                }
388
                $log->syslog('notice', "Moving bad file %s to bad/",
389
390
                    $filename);
            } else {
391
                $log->syslog('notice', 'Missing directory "%s"', $bad_dir);
392
                unless ($lock_fh->rename($spool . '/BAD-' . $filename)) {
393
394
395
396
                    die sprintf
                        'Unable to rename bad file %s to BAD-%s: %s',
                        $filename, $filename, $lock_fh->last_error;
                }
397
                $log->syslog('notice', "Renaming bad file %s to BAD-%s",
398
399
400
401
402
403
404
405
406
407
408
409
410
                    $filename, $filename);
            }
        }

    }    ## END of infinite loop

    # Purge grouped notifications
    Sympa::Alarm->instance->flush(purge => 1);

    if ($signal eq 'hup') {
        # Disconnect from Database
        Sympa::DatabaseManager->disconnect;

411
        $log->syslog('notice', "Sympa %s reload config",
412
413
414
415
            Sympa::Constants::VERSION);
        _load();
        $signal = 0;
    }
416
417
418
419
420

    # If the spool was empty, sleep for a while.
    unless ($numprocessed) {
        sleep $Conf::Conf{'sleep'};
    }
421
422
}    #end of block while ($signal ne 'term'){

423
$log->syslog('notice', 'Sympa/msg exited normally due to signal');
424
Sympa::Tools::Daemon::remove_pid($pidfile, $PID, $options);
425
426
427
428
429
430
431
432
433
434
435
436
437

exit(0);

# Load configuration.
sub _load {
    ## Load sympa.conf.
    unless (Conf::load(Conf::get_sympa_conf(), 'no_db')) {    #Site and Robot
        die sprintf
            "Unable to load sympa configuration, file %s or one of the vhost robot.conf files contain errors. Exiting.\n",
            Conf::get_sympa_conf();
    }

    ## Open the syslog and say we're read out stuff.
438
    $log->openlog($Conf::Conf{'syslog'}, $Conf::Conf{'log_socket_type'});
439
440
441
442
443
444
445

    # Enable SMTP logging if required
    $mailer->{log_smtp} = $main::options{'mail'}
        || Sympa::Tools::Data::smart_eq($Conf::Conf{'log_smtp'}, 'on');

    # setting log_level using conf unless it is set by calling option
    if (defined $main::options{'log_level'}) {
446
447
        $log->{level} = $main::options{'log_level'};
        $log->syslog(
448
449
450
451
452
            'info',
            'Configuration file read, log level set using options: %s',
            $main::options{'log_level'}
        );
    } else {
453
454
        $log->{level} = $Conf::Conf{'log_level'};
        $log->syslog(
455
456
457
458
459
460
461
462
            'info',
            'Configuration file read, default log level %s',
            $Conf::Conf{'log_level'}
        );
    }

    Sympa::Tools::Password::ciphersaber_installed();

463
    if (Conf::cookie_changed()) {
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
        die sprintf
            'sympa.conf/cookie parameter has changed. You may have severe inconsitencies into password storage. Restore previous cookie or write some tool to re-encrypt password in database and check spools contents (look at %s/cookies.history file).',
            $Conf::Conf{'etc'};
    }

    # Check database connectivity.
    unless (Sympa::DatabaseManager->instance) {
        die sprintf
            "Database %s defined in sympa.conf is unreachable. verify db_xxx parameters in sympa.conf\n",
            $Conf::Conf{'db_name'};
    }

    # Now trying to load full config (including database)
    unless (Conf::load()) {    #FIXME: load Site, then robot cache
        die sprintf
            "Unable to load Sympa configuration, file %s or any of the virtual host robot.conf files contain errors. Exiting.\n",
            Conf::get_sympa_conf();
    }

    ## Set locale configuration
    ## Compatibility with version < 2.3.3
    $main::options{'lang'} =~ s/\.cat$//
        if defined $main::options{'lang'};
    $default_lang =
        $language->set_lang($main::options{'lang'}, $Conf::Conf{'lang'},
        'en');

    ## Main program
    if (!chdir($Conf::Conf{'home'})) {
        die sprintf 'Can\'t chdir to %s: %s', $Conf::Conf{'home'}, $ERRNO;
        ## Function never returns.
    }

    ## Check for several files.
    unless (Conf::checkfiles_as_root()) {
        die "Missing files\n";
    }
}

############################################################
# sigterm
############################################################
#  When we catch signal, just changes the value of the $signal
#  loop variable.
#
# IN : -
#
# OUT : -
#
############################################################
sub sigterm {
    my ($sig) = @_;
516
517
    $log->syslog('notice',
        'Signal %s received, still processing current task', $sig);
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
    $signal = 'term';
}

############################################################
# sighup
############################################################
#  When we catch SIGHUP, changes the value of the $signal
#  loop variable and puts the "-mail" logging option
#
# IN : -
#
# OUT : -
#
###########################################################
sub sighup {
    if ($mailer->{log_smtp}) {
534
        $log->syslog('notice',
535
536
537
538
            'signal HUP received, switch of the "-mail" logging option and continue current task'
        );
        $mailer->{log_smtp} = undef;
    } else {
539
        $log->syslog('notice',
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
            'signal HUP received, switch on the "-mail" logging option and continue current task'
        );
        $mailer->{log_smtp} = 1;
    }
    $signal = 'hup';
}

############################################################
#  process_message
############################################################
#  Handles a file received and files in the queue directory.
#  This will read the file, separate the header and the body
#  of the message and call the adequate function wether we
#  have received a command or a message to be redistributed
#  to a list.
#
# IN : -$file (+): the file to handle
#
# OUT : $status
#     | undef
#
##############################################################
sub process_message {
563
    $log->syslog('debug', '(%s)', @_);
564
565
566
567
568
    my $message = shift;

    my $status;

    unless (defined $message) {
569
570
571
572
573
574
575
576
577
578
579
        $log->syslog('err', 'Unable to create Sympa::Message object');
        $log->db_log(
            #'robot'        => $robot,
            #'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => '',
            'target_email' => "",
            'msg_id'       => '',
            'status'       => 'error',
            'error_type'   => 'unable_create_message',
            'user_email'   => ''
580
581
582
583
584
585
        );
        return undef;
    }

    unless (defined $message->{'message_id'}
        and length $message->{'message_id'}) {
586
587
588
589
590
591
592
593
594
595
596
        $log->syslog('err', 'Message %s has no message ID', $message);
        $log->db_log(
            #'robot'        => $robot,
            #'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => $message->get_id,
            'target_email' => "",
            'msg_id'       => "",
            'status'       => 'error',
            'error_type'   => 'no_message_id',
            'user_email'   => $message->{'sender'}
597
598
599
600
        );
        return undef;
    }

601
    my $msg_id = $message->{message_id};
602

603
    $log->syslog(
604
605
606
607
608
609
610
        'notice',
        'Processing %s; envelope_sender=%s; message_id=%s; sender=%s',
        $message,
        $message->{envelope_sender},
        $message->{message_id},
        $message->{sender}
    );
611
612
613
614
615
616
617
618
619
620
621
622
623

    my $robot;
    my $listname;

    $robot =
        (ref $message->{context} eq 'Sympa::List')
        ? $message->{context}->{'domain'}
        : $message->{context};
    $listname = $message->{'listname'};

    ## Ignoring messages with no sender
    my $sender = $message->{'sender'};
    unless ($message->{'md5_check'} or $sender) {
624
625
626
627
628
629
630
631
632
633
634
        $log->syslog('err', 'No sender found in message %s', $message);
        $log->db_log(
            'robot'        => $robot,
            'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => "",
            'target_email' => "",
            'msg_id'       => $msg_id,
            'status'       => 'error',
            'error_type'   => 'no_sender',
            'user_email'   => $sender
635
636
637
638
639
640
        );
        return undef;
    }

    ## Unknown robot
    unless ($message->{'md5_check'} or Conf::valid_robot($robot)) {
641
        $log->syslog('err', 'Robot %s does not exist', $robot);
642
643
644
        Sympa::Report::reject_report_msg('user', 'list_unknown', $sender,
            {'listname' => $listname, 'message' => $message},
            '*', $message->as_string, '');
645
646
647
648
649
650
651
652
653
654
        $log->db_log(
            'robot'        => $robot,
            'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => "",
            'target_email' => "",
            'msg_id'       => $msg_id,
            'status'       => 'error',
            'error_type'   => 'unknown_robot',
            'user_email'   => $sender
655
656
657
658
        );
        return undef;
    }

659
660
    $language->set_lang(Conf::get_robot_conf($robot, 'lang'), $default_lang);

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
    # Load spam status.
    $message->check_spam_status;
    # Check DKIM signatures.
    $message->check_dkim_signature;
    # Check S/MIME signature.
    $message->check_smime_signature;
    # Decrypt message.  On success, check nested S/MIME signature.
    if ($message->smime_decrypt and not $message->{'smime_signed'}) {
        $message->check_smime_signature;
    }

    # *** Now message content may be altered. ***

    # Enable SMTP logging if required.
    $mailer->{log_smtp} = $main::options{'mail'}
        || Conf::get_robot_conf($robot, 'log_smtp');
    # setting log_level using conf unless it is set by calling option
    unless (defined $main::options{'log_level'}) {
679
680
        $log->{level} = Conf::get_robot_conf($robot, 'log_level');
        $log->syslog('debug',
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
            'Setting log level with %s configuration (or sympa.conf): %d',
            $robot, Conf::get_robot_conf($robot, 'log_level'));
    }

    ## Strip of the initial X-Sympa-To and X-Sympa-Checksum internal headers
    delete $message->{'rcpt'};
    delete $message->{'checksum'};

    ## Initialize command report
    Sympa::Report::init_report_cmd();

    my $list =
        (ref $message->{context} eq 'Sympa::List')
        ? $message->{context}
        : undef;
    my $type = $message->{'listtype'} || '';
    my $list_address;

    if ($type eq 'listmaster' or $type eq 'sympa') {
        $list_address =
            $message->{'localpart'} . '@'
            . Conf::get_robot_conf($robot, 'host');
    } else {
        unless (ref $list eq 'Sympa::List') {
705
            $log->syslog('err', 'List %s does not exist', $listname);
706
707
708
709
710
711
712
713
714
715
716
            Sympa::Report::reject_report_msg(
                'user',
                'list_unknown',
                $sender,
                {   'listname' => $listname,
                    'message'  => $message
                },
                $robot,
                $message->as_string,
                ''
            );
717
718
719
720
721
722
723
724
725
726
            $log->db_log(
                'robot'        => $robot,
                'list'         => $listname,
                'action'       => 'process_message',
                'parameters'   => "",
                'target_email' => "",
                'msg_id'       => $msg_id,
                'status'       => 'error',
                'error_type'   => 'unknown_list',
                'user_email'   => $sender
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
            );
            return undef;
        }
        $list_address = $list->get_list_address();
    }

    ## Loop prevention
    if (ref $list eq 'Sympa::List'
        and Sympa::Tools::Data::smart_eq(
            $list->{'admin'}{'reject_mail_from_automates_feature'}, 'on'
        )
        ) {
        my $conf_loop_prevention_regex;
        $conf_loop_prevention_regex =
            $list->{'admin'}{'loop_prevention_regex'};
        $conf_loop_prevention_regex ||=
            Conf::get_robot_conf($robot, 'loop_prevention_regex');
        if ($sender =~ /^($conf_loop_prevention_regex)(\@|$)/mi) {
745
            $log->syslog(
746
747
748
749
750
751
752
753
754
755
756
757
758
759
                'err',
                'Ignoring message which would cause a loop, sent by %s; matches loop_prevention_regex',
                $sender
            );
            return undef;
        }

        ## Ignore messages that would cause a loop
        ## Content-Identifier: Auto-replied is generated by some non standard
        ## X400 mailer
        if (grep {/Auto-replied/i} $message->get_header('Content-Identifier')
            or grep {/Auto Reply to/i}
            $message->get_header('X400-Content-Identifier')
            or grep { !/^no$/i } $message->get_header('Auto-Submitted')) {
760
            $log->syslog('err',
761
762
763
764
765
766
767
768
769
770
771
772
773
                "Ignoring message which would cause a loop; message appears to be an auto-reply"
            );
            return undef;
        }
    }

    ## Q- and B-decode subject
    my $subject_field = $message->{'decoded_subject'};

    ## Loop prevention
    my $loop;
    foreach $loop ($message->get_header('X-Loop')) {
        chomp $loop;
774
        $log->syslog('debug2', 'X-Loop: %s', $loop);
775
776
        #foreach my $l (split(/[\s,]+/, lc($loop))) {
        if ($loop eq lc($list_address)) {
777
            $log->syslog('err',
778
779
780
781
782
783
784
785
786
787
788
789
790
                'Ignoring message which would cause a loop (X-Loop: %s)',
                $loop);
            return undef;
        }
        #}
    }

    # Anti-virus
    my $rc = $message->check_virus_infection;
    if ($rc) {
        my $antivirus_notify =
            Conf::get_robot_conf($robot, 'antivirus_notify') || 'none';
        if ($antivirus_notify eq 'sender') {
791
            Sympa::send_file(
792
793
794
795
796
797
798
799
800
801
                $robot,
                'your_infected_msg',
                $sender,
                {   'virus_name'     => $rc,
                    'recipient'      => $list_address,
                    'lang'           => Conf::get_robot_conf($robot, 'lang'),
                    'auto_submitted' => 'auto-replied'
                }
            );
        } elsif ($antivirus_notify eq 'delivery_status') {
802
            Sympa::send_dsn(
803
804
805
806
807
808
809
810
811
                $message->{context},
                $message,
                {   'virus_name' => $rc,
                    'recipient'  => $list_address,
                    'from'       => $message->{sender}
                },
                '5.7.0'
            );
        }
812
        $log->syslog('notice',
813
814
            "Message for %s from %s ignored, virus %s found",
            $list_address, $sender, $rc);
815
816
817
818
819
820
821
822
823
824
        $log->db_log(
            'robot'        => $robot,
            'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => "",
            'target_email' => "",
            'msg_id'       => $msg_id,
            'status'       => 'error',
            'error_type'   => 'virus',
            'user_email'   => $sender
825
826
827
        );
        return undef;
    } elsif (!defined($rc)) {
828
        Sympa::send_notify_to_listmaster(
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
            $robot,
            'antivirus_failed',
            [   sprintf
                    "Could not scan message %s; The message has been saved as BAD.",
                $message->get_id
            ]
        );

        return undef;
    }

    if ($type eq 'listmaster') {
        $status = DoForward('sympa', 'listmaster', $robot, $message);
    } elsif ($type eq 'sympa') {
        # Mail addressed to the robot is command.
        $status = DoCommand('sympa', $robot, $message);
    } elsif ($type eq 'subscribe' or $type eq 'unsubscribe') {
        # Mail to <list>-subscribe or <list>-unsubscribe is command.
        $status = DoCommand("$listname-$type", $robot, $message);
    } elsif ($type eq 'owner') {    # -request
        # Forward mails to <list>-request.
        # Simulate Smartlist behaviour with command in subject
        if (    $subject_field
            and $subject_field =~
            /^\s*(subscribe|unsubscribe)(\s*$listname)?\s*$/i) {
            my $command = $1;
            $status = DoCommand("$listname-$command", $robot, $message);
        } else {
            $status = DoForward($listname, 'owner', $robot, $message);
        }
    } elsif ($type eq 'return_path' or $type eq 'editor') {
        # Forward mails to <list>-owner etc.
        $status = DoForward($listname, $type, $robot, $message);
    } else {
        $status = DoMessage($message);
    }

    ## Mail back the result.
    if (Sympa::Report::is_there_any_report_cmd()) {
        ## Loop prevention

        ## Count reports sent to $sender
        $loop_info{$sender}{'count'}++;

        ## Sampling delay
        if ((time - ($loop_info{$sender}{'date_init'} || 0)) <
            $Conf::Conf{'loop_command_sampling_delay'}) {

            ## Notify listmaster of first rejection
            if ($loop_info{$sender}{'count'} ==
                $Conf::Conf{'loop_command_max'}) {
                ## Notify listmaster
881
                Sympa::send_notify_to_listmaster($robot, 'loop_command',
882
883
884
885
886
887
                    {'msg' => $message});
            }

            ## Too many reports sent => message skipped !!
            if ($loop_info{$sender}{'count'} >=
                $Conf::Conf{'loop_command_max'}) {
888
                $log->syslog(
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
                    'err',
                    'Ignoring message which would cause a loop, %d messages sent to %s; loop_command_max exceeded',
                    $loop_info{$sender}{'count'},
                    $sender
                );

                return undef;
            }
        } else {
            ## Sampling delay is over, reinit
            $loop_info{$sender}{'date_init'} = time;

            ## We apply Decrease factor if a loop occurred
            $loop_info{$sender}{'count'} *=
                $Conf::Conf{'loop_command_decrease_factor'};
        }

        ## Send the reply message
        Sympa::Report::send_report_cmd($sender, $robot);
908
909
910
911
912
913
914
915
916
917
        $log->db_log(
            'robot'        => $robot,
            'list'         => $listname,
            'action'       => 'process_message',
            'parameters'   => "",
            'target_email' => "",
            'msg_id'       => $msg_id,
            'status'       => 'success',
            'error_type'   => '',
            'user_email'   => $sender
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
        );

    }

    return $status;
}

#sub DoSendMessage($message);
#DEPRECATED: Run upgrade_send_spool.pl to migrate message with old format.

############################################################
#  DoForward
############################################################
#  Handles a message sent to [list]-editor : the list editor,
#  [list]-request : the list owner or the listmaster.
#  Message is forwarded according to $function
#
# IN : -$name : list name (+) if ($function <> 'listmaster')
#      -$function (+): 'listmaster'|'owner'|'editor'
#      -$robot (+): robot
#      -$msg (+): ref(message object).
#
# OUT : 1
#     | undef
#
############################################################
sub DoForward {
    my ($name, $function, $robot, $message) = @_;
946
    $log->syslog('debug', '(%s, %s)', $name, $function);
947
948
949
950
951
952
953
954

    my $msg        = $message->as_entity;        #FIXME: not required.
    my $messageid  = $message->{'message_id'};
    my $msg_string = $message->as_string;        #FIMXE: not required.
    my $sender     = $message->{'sender'};
    chomp $sender;

    if ($message->{'spam_status'} eq 'spam') {
955
        $log->syslog(
956
957
958
959
960
961
962
963
964
965
            'notice',
            'Message for %s-%s ignored, because tagued as spam (message ID: %s)',
            $name,
            $function,
            $messageid
        );
        return undef;
    }

    ##  Search for the list
966
    my ($list, $admin, $host, $recipient, $priority);
967
968

    if ($function eq 'listmaster') {
969
        $recipient =
970
971
972
973
974
975
            $Conf::Conf{'listmaster_email'} . '@'
            . Conf::get_robot_conf($robot, 'host');
        $priority = 0;
    } else {
        $list = $message->{context};
        unless (ref $list eq 'Sympa::List') {
976
            $log->syslog(
977
978
979
980
981
982
983
984
985
                'notice',
                'Message for %s function %s ignored, unknown list %s (message ID: %s)',
                $name,
                $function,
                $name,
                $messageid
            );
            my $sympa_email = Conf::get_robot_conf($robot, 'sympa');
            unless (
986
                Sympa::send_file(
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                    $robot,
                    'list_unknown',
                    $sender,
                    {   'list' => $name,
                        'date' => POSIX::strftime(
                            "%d %b %Y  %H:%M",
                            localtime(time)
                        ),
                        'boundary'       => $sympa_email . time,
                        'header'         => $message->header_as_string,
                        'auto_submitted' => 'auto-replied'
                    }
                )
                ) {
For faster browsing, not all history is shown. View entire blame