ProcessOutgoing.pm 17.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- 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
10
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
11
12
# Copyright 2017, 2019, 2020 The Sympa Community. See the AUTHORS.md
# file at the top-level directory of this distribution and at
13
# <https://github.com/sympa-community/sympa.git>.
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
#
# 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/>.

package Sympa::Spindle::ProcessOutgoing;

use strict;
use warnings;
use English qw(-no_match_vars);

use Sympa;
use Conf;
use Sympa::DatabaseManager;
use Sympa::List;
use Sympa::Log;
use Sympa::Mailer;
40
use Sympa::Message::Template;
41
use Sympa::Process;
42
use Sympa::Spool::Listmaster;
43
44
45
46
47
48
49
50
51
52
use Sympa::Tools::Data;
use Sympa::Tools::DKIM;
use Sympa::Tracking;

use base qw(Sympa::Spindle);

my $log     = Sympa::Log->instance;
my $mailer  = Sympa::Mailer->instance;
my $process = Sympa::Process->instance;

53
use constant _distaff => 'Sympa::Spool::Outgoing';
54
55
56
57
58
59
60
61
62
63

sub _init {
    my $self  = shift;
    my $state = shift;

    if ($state == 0) {
        $self->{_last_activity} = time;
        $self->{_last_check}    = 0;
        $self->{_pids}          = {};
    } elsif ($state == 1) {
sikeda's avatar
sikeda committed
64
65
66
67
68
69
70
71
        # Enable SMTP logging if required.
        $mailer->{log_smtp} = $self->{log_smtp}
            || Sympa::Tools::Data::smart_eq($Conf::Conf{'log_smtp'}, 'on');
        # setting log_level using conf unless it is set by calling option
        $log->{level} =
            (defined $self->{log_level})
            ? $self->{log_level}
            : $Conf::Conf{'log_level'};
72

73
        # Process grouped notifications.
74
        Sympa::Spool::Listmaster->instance->flush;
75
76
77
78

        unless ($process->{detached}) {
            ;
        } elsif (0 == $process->{generation}) {
sikeda's avatar
sikeda committed
79
80
81
82
83
84
            # Create child bulks if too much packets are waiting to be sent in
            # the bulk_mailer table.
            # Only the main bulk process ({generation} is 0) can create child
            # processes.
            # Check if we need to run new child processes every
            # 'bulk_wait_to_fork' (sympa.conf parameter) seconds.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
            $self->_fork_children;
        } elsif (0 < $process->{generation}) {
            # If a child bulk process is running for long enough, stop it (if
            # the number of remaining packets to send is modest).
            $self->_finish_child;
            return 0 if $self->{finish};
        }
    } elsif ($state == 2) {
        $self->{_last_activity} = time;
    }

    1;
}

# Private subroutine.
sub _fork_children {
    my $self = shift;

sikeda's avatar
sikeda committed
103
104
    if ($Conf::Conf{'bulk_wait_to_fork'} < time - $self->{_last_check}) {
        # Clean up PID file (in case some child bulks would have died)
105
        $process->sync_child(hash => $self->{_pids}, file => 1);
sikeda's avatar
sikeda committed
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

        # Start new processes if there remain at least
        # 'bulk_fork_threshold' packets to send in the bulk spool.
        my $spare_children =
            $Conf::Conf{'bulk_max_count'} - scalar keys %{$self->{_pids}};
        if (my $r_packets = $self->{distaff}->too_much_remaining_packets
            and 0 < $spare_children) {
            # Disconnect from database before fork to prevent DB handles
            # to be shared by different processes.  Sharing database
            # handles may crash bulk.pl.
            Sympa::DatabaseManager->disconnect;

            if ($Conf::Conf{'bulk_max_count'} > 1) {
                $log->syslog(
                    'info',
                    'Important workload: %s packets to process. Creating %s child bulks to increase sending rate',
                    $r_packets,
                    $spare_children
                );
                for my $process_count (1 .. $spare_children) {
                    $log->syslog('info', "Will fork: %s", $process_count);
                    my $child_pid = $process->fork;
                    if ($child_pid) {
                        $log->syslog('info',
                            'Starting bulk child daemon, PID %s', $child_pid);
                        # Save the PID number.
                        $process->write_pid(pid => $child_pid);
                        $self->{_pids}->{$child_pid} = 1;
                        sleep 1;
                    } elsif (not defined $child_pid) {
                        $log->syslog('err', 'Cannot fork: %m');
                        last;
                    } else {
                        # We're in a child bulk process.
                        close STDERR;
                        $process->direct_stderr_to_file;
                        $self->{_last_activity} = time;
                        $log->openlog($Conf::Conf{'syslog'},
                            $Conf::Conf{'log_socket_type'});
                        $log->syslog('info',
                            'Bulk slave daemon started with PID %s', $PID);
                        last;
148
149
150
                    }
                }
            }
sikeda's avatar
sikeda committed
151
152
153
154

            # Restore persistent connection.
            Sympa::DatabaseManager->instance
                or die 'Reconnecting database failed';
155
        }
sikeda's avatar
sikeda committed
156
157
        $self->{_last_check} = time;
    }
158
159
160
161
162
163
}

# Private subroutine.
sub _finish_child {
    my $self = shift;

sikeda's avatar
sikeda committed
164
165
    if (time - $self->{_last_activity} > $Conf::Conf{'bulk_lazytime'}
        and !$self->{distaff}->too_much_remaining_packets) {
166
167
168
169
        $log->syslog('info',
            'Process %s didn\'t send any message since %s seconds, exiting',
            $PID, $Conf::Conf{'bulk_lazytime'});

sikeda's avatar
sikeda committed
170
171
        $self->{finish} = 'exit';
    }
172
173
174
175
176
177
}

sub _twist {
    my $self    = shift;
    my $message = shift;

sikeda's avatar
sikeda committed
178
179
180
181
182
183
184
185
186
187
188
    # Get list/robot context.
    my ($list, $robot, $listname);
    if (ref($message->{context}) eq 'Sympa::List') {
        $list     = $message->{context};
        $robot    = $message->{context}->{'domain'};
        $listname = $list->{'name'};
    } elsif ($message->{context} and $message->{context} ne '*') {
        $robot = $message->{context};
    } else {
        $robot = '*';
    }
189

sikeda's avatar
sikeda committed
190
191
192
193
194
195
196
197
198
199
200
    if ($message->{serial} eq '0' or $message->{serial} eq 's') {
        $log->syslog(
            'notice',
            'Start sending message %s to %s (priority %s) (starting %s seconds after scheduled expedition date)',
            $message,
            $message->{context},
            $message->{'priority'},
            time() - $message->{'date'}
        );
        # trace_smime($message, 'init');
    }
201

sikeda's avatar
sikeda committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    # Enable SMTP logging if required.
    $mailer->{log_smtp} = $self->{log_smtp}
        || Sympa::Tools::Data::smart_eq(
        Conf::get_robot_conf($robot, 'log_smtp'), 'on');
    # setting log_level using conf unless it is set by calling option
    $log->{level} =
        (defined $self->{log_level})
        ? $self->{log_level}
        : Conf::get_robot_conf($robot, 'log_level');

    # Contain all the subscribers
    my @rcpts = @{$message->{rcpt}};

    # Message transformation should be done in the folowing order:
    #  -1 headers modifications (done in sympa.pl)
    #  -2 DMARC protection
218
    #  -3 personalization ("merge") and decoration (adding footer/header)
sikeda's avatar
sikeda committed
219
220
221
222
    #  -4 S/MIME signing
    #  -5 S/MIME encryption
    #  -6 remove existing signature if altered
    #  -7 DKIM signing
John Levine's avatar
John Levine committed
223
    #  -8 ARC seal
Luc Didry's avatar
Luc Didry committed
224

sikeda's avatar
sikeda committed
225
226
227
    if ($message->{shelved}{dmarc_protect}) {
        $message->dmarc_protect;
    }
228

John Levine's avatar
John Levine committed
229
    my ($dkim, $arc);
sikeda's avatar
sikeda committed
230
231
    if ($message->{shelved}{dkim_sign}) {
        $dkim = Sympa::Tools::DKIM::get_dkim_parameters($message->{context});
Luc Didry's avatar
Luc Didry committed
232
233
        $arc  = Sympa::Tools::DKIM::get_arc_parameters($message->{context})
            if $message->{shelved}->{arc_cv};
sikeda's avatar
sikeda committed
234
    }
235

sikeda's avatar
sikeda committed
236
237
238
239
240
    if (   $message->{shelved}{merge}
        or $message->{shelved}{smime_encrypt}
        or $message->{shelved}{tracking}) {
        # message needs personalization
        my $key;
241

sikeda's avatar
sikeda committed
242
        foreach my $rcpt (@rcpts) {
243
244
            my $new_message = $message->dup;

sikeda's avatar
sikeda committed
245
            my $envid;
246
247
            my $return_path;

sikeda's avatar
sikeda committed
248
249
250
            if (Sympa::Tools::Data::smart_eq(
                    $new_message->{shelved}{tracking}, qr/dsn|mdn/
                )
Luc Didry's avatar
Luc Didry committed
251
            ) {
sikeda's avatar
sikeda committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                # tracking by MDN required tracking by DSN to
                my $msgid = $new_message->{'message_id'};
                $envid =
                    Sympa::Tracking::find_notification_id_by_message($rcpt,
                    $msgid, $listname, $robot);
                $return_path = $list->get_bounce_address($rcpt, $envid);
                $new_message->replace_header('Disposition-Notification-To',
                    $return_path)
                    if $new_message->{shelved}{tracking} =~ /mdn/;
                # trace_smime($new_message, 'tracking');
            } elsif (
                Sympa::Tools::Data::smart_eq(
                    $new_message->{shelved}{tracking}, 'w'
                )
Luc Didry's avatar
Luc Didry committed
266
            ) {
sikeda's avatar
sikeda committed
267
268
269
270
271
                $return_path = $list->get_bounce_address($rcpt, 'w');
            } elsif (
                Sympa::Tools::Data::smart_eq(
                    $new_message->{shelved}{tracking}, 'r'
                )
Luc Didry's avatar
Luc Didry committed
272
            ) {
sikeda's avatar
sikeda committed
273
274
275
276
                $return_path = $list->get_bounce_address($rcpt, 'r');
            } elsif ($new_message->{shelved}{tracking}) {    # simple VERP
                $return_path = $list->get_bounce_address($rcpt);
            } elsif ($new_message->{envelope_sender}) {
277
278
                $return_path = $new_message->{envelope_sender};
            } elsif ($list) {
279
                $return_path = Sympa::get_address($list, 'return_path');
280
            } else {
281
                $return_path = Sympa::get_address($robot, 'owner');
282
283
            }

Sympa authors's avatar
Sympa authors committed
284
            if (    $new_message->{shelved}{merge}
285
                and $new_message->{shelved}{merge} ne 'footer') {
sikeda's avatar
sikeda committed
286
287
288
289
290
291
292
293
294
                unless ($new_message->personalize($list, $rcpt)) {
                    $log->syslog('err', 'Erreur d appel personalize()');
                    Sympa::send_notify_to_listmaster($list, 'bulk_failed',
                        {'message_id' => $message->get_id});
                    # Quarantine packet into bad spool.
                    return undef;
                }
                delete $new_message->{shelved}{merge};
            }
295
            if ($new_message->{shelved}{decorate}) {
Sympa authors's avatar
Sympa authors committed
296
297
                $new_message->decorate($list, $rcpt,
                    mode => $new_message->{shelved}{merge});
298
299
                delete $new_message->{shelved}{decorate};
            }
sikeda's avatar
sikeda committed
300

301
302
303
304
305
            if ($new_message->{shelved}{smime_sign}) {
                $new_message->smime_sign;
                delete $new_message->{shelved}{smime_sign};
            }

sikeda's avatar
sikeda committed
306
307
308
309
310
311
312
313
314
            if ($new_message->{shelved}{smime_encrypt}) {
                unless ($new_message->smime_encrypt($rcpt)) {
                    $log->syslog(
                        'err',
                        'Unable to encrypt message %s from %s for recipient %s',
                        $new_message,
                        $list,
                        $rcpt
                    );
315
316
                    # If encryption failed, send a generic error message:
                    # X509 cert missing.
317
318
319
320
321
322
                    my $entity = Sympa::Message::Template->new(
                        context  => $list,
                        template => 'x509-user-cert-missing',
                        rcpt     => $rcpt,
                        data     => {
                            'mail' => {
323
324
325
326
327
328
                                'sender'  => $new_message->{sender},
                                'subject' => $new_message->{decoded_subject},
                            },
                        }
                    )->as_entity;
                    $new_message->set_entity($entity);
sikeda's avatar
sikeda committed
329
330
331
332
                }
                delete $new_message->{shelved}{smime_encrypt};
            }

333
            if ($dkim) {
334
335
336
                $new_message->remove_invalid_dkim_signature;
            }
            if ($new_message->{shelved}{dkim_sign} and $dkim) {
sikeda's avatar
sikeda committed
337
338
                # apply DKIM signature AFTER any other message
                # transformation.
339
340
341
342
343
344
                $new_message->dkim_sign(
                    'dkim_d'          => $dkim->{'d'},
                    'dkim_i'          => $dkim->{'i'},
                    'dkim_selector'   => $dkim->{'selector'},
                    'dkim_privatekey' => $dkim->{'private_key'},
                );
John Levine's avatar
John Levine committed
345
346
347
348
349
350
351

                $new_message->arc_seal(
                    'arc_d'          => $arc->{'d'},
                    'arc_selector'   => $arc->{'selector'},
                    'arc_srvid'      => $arc->{'srvid'},
                    'arc_privatekey' => $arc->{'private_key'},
                    'arc_cv'         => $message->{shelved}->{arc_cv}
Luc Didry's avatar
Luc Didry committed
352

John Levine's avatar
John Levine committed
353
354
                ) if $arc;

355
356
357
                delete $new_message->{shelved}{dkim_sign};
            }

sikeda's avatar
sikeda committed
358
            # trace_smime($new_message, 'dkim');
359
360
361
362

            $new_message->{envelope_sender} = $return_path;
            unless (
                defined $mailer->store(
sikeda's avatar
sikeda committed
363
364
365
                    $new_message, $rcpt,
                    envid => $envid,
                    tag   => $new_message->{serial}
366
                )
Luc Didry's avatar
Luc Didry committed
367
            ) {
368
369
370
371
372
373
                $log->syslog('err', 'Failed to store message %s into mailer',
                    $new_message);
                # Quarantine packet into bad spool.
                return undef;
            }
        }
sikeda's avatar
sikeda committed
374
375
376
377
378
379
380
381
382
    } else {
        # message doesn't need personalization, so can be sent by packet.
        my $new_message = $message->dup;

        my $return_path;

        if ($new_message->{envelope_sender}) {
            $return_path = $new_message->{envelope_sender};
        } elsif ($list) {
383
            $return_path = Sympa::get_address($list, 'return_path');
sikeda's avatar
sikeda committed
384
        } else {
385
            $return_path = Sympa::get_address($robot, 'owner');
sikeda's avatar
sikeda committed
386
387
        }

388
389
390
391
392
        if ($new_message->{shelved}{decorate}) {
            $new_message->decorate($list, undef);
            delete $new_message->{shelved}{decorate};
        }

sikeda's avatar
sikeda committed
393
394
395
396
397
        if ($new_message->{shelved}{smime_sign}) {
            $new_message->smime_sign;
            delete $new_message->{shelved}{smime_sign};
        }

398
        if ($dkim) {
sikeda's avatar
sikeda committed
399
400
401
402
403
404
405
406
407
408
            $new_message->remove_invalid_dkim_signature;
        }
        # Initial message
        if ($new_message->{shelved}{dkim_sign} and $dkim) {
            $new_message->dkim_sign(
                'dkim_d'          => $dkim->{'d'},
                'dkim_i'          => $dkim->{'i'},
                'dkim_selector'   => $dkim->{'selector'},
                'dkim_privatekey' => $dkim->{'private_key'},
            );
John Levine's avatar
John Levine committed
409
410
411
412
413
414
415
416
            $new_message->arc_seal(
                'arc_d'          => $arc->{'d'},
                'arc_selector'   => $arc->{'selector'},
                'arc_srvid'      => $arc->{'srvid'},
                'arc_privatekey' => $arc->{'private_key'},
                'arc_cv'         => $message->{shelved}->{arc_cv}
            ) if $arc;

sikeda's avatar
sikeda committed
417
418
419
420
421
422
423
424
425
426
            delete $new_message->{shelved}{dkim_sign};
        }

        # trace_smime($new_message,'dkim 2');

        $new_message->{envelope_sender} = $return_path;
        unless (
            defined $mailer->store(
                $new_message, [@rcpts], tag => $new_message->{serial}
            )
Luc Didry's avatar
Luc Didry committed
427
        ) {
sikeda's avatar
sikeda committed
428
429
430
431
432
433
            $log->syslog('err', 'Failed to store message %s into mailer',
                $new_message);
            # Quarantine packet into bad spool.
            return undef;
        }
    }
434
435
436
437
438

    1;
}

# Old name: trace_smime() in bulk.pl.
IKEDA Soji's avatar
IKEDA Soji committed
439
440
# No longer used.
#sub _trace_smime;
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Spindle::ProcessOutgoing - Workflow of message distribution

=head1 SYNOPSIS

  use Sympa::Spindle::ProcessOutgoing;

  my $spindle = Sympa::Spindle::ProcessOutgoing->new;
  $spindle->spin;

=head1 DESCRIPTION

L<Sympa::Spindle::ProcessOutgoing> defines workflow to distribute messages
in outgoing spool using mailer.

If messages are stored into incoming spool, sooner or later
464
L<Sympa::Spindle::ProcessIncoming> fetches them, modifies header and body of
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
them, shelves several transformations, and at last stores altered messages
into outgoing spool.

When spin() method of this class is invoked, it reads the messages in outgoing
spool and executes shelved transformations.
Message transformations are done in the following order:

=over

=item *

DMARC protection

=item *

Processing for tracking and VERP (see also <Sympa::Tracking>)

=item *

Personalization (a.k.a. "merge")
485
and decoration (adding footer/header)
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

=item *

S/MIME signing

=item *

S/MIME encryption

=item *

Removal of existing DKIM signature(s) which are invalidated by
preceding transformations.

=item *

DKIM signing

=back

Then spin() method stores transformed message into mailer
(See L<Sympa::Mailer>).

=head2 Public methods

See also L<Sympa::Spindle/"Public methods">.

=over

=item new ( [ log_level =E<gt> $level ], [ log_smtp =E<gt> 0|1 ] )

=item spin ( )

new() may take following options:

=over

=item log_level =E<gt> $level

Overwrites log_level parameter in configuration.

=item log_smtp =E<gt> 0|1

Overwrites log_smtp parameter in configuration.

=back

=back

=head2 Properties

See also L<Sympa::Spindle/"Properties">.

=over

=item {distaff}

543
Instance of L<Sympa::Spool::Outgoing> class.
544
545
546
547
548

=back

=head1 SEE ALSO

549
550
L<Sympa::Mailer>, L<Sympa::Message>, L<Sympa::Spindle>,
L<Sympa::Spool::Outgoing>.
551
552
553
554
555
556

=head1 HISTORY

L<Sympa::Spindle::ProcessOutgoing> appeared on Sympa 6.2.13.

=cut