ToList.pm 16.2 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, 2018, 2019, 2020, 2021 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
#
# 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::ToList;

use strict;
use warnings;
use Time::HiRes qw();

use Sympa;
use Conf;
use Sympa::Log;
37
38
use Sympa::Spool::Outgoing;
use Sympa::Spool::Topic;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use Sympa::Tools::Data;
use Sympa::Tracking;

use base qw(Sympa::Spindle);

my $log = Sympa::Log->instance;

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

    my $list      = $message->{context};
    my $messageid = $message->{message_id};
    my $sender =
           $self->{confirmed_by}
        || $self->{distributed_by}
55
        || $self->{resent_by}
56
57
        || $message->{sender};

58
59
    my $numstored = _send_msg($message, $self->{resent_by});
    unless (defined $numstored) {
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
        $log->syslog('err', 'Unable to send message %s to list %s',
            $message, $list);
        Sympa::send_notify_to_listmaster(
            $list,
            'mail_intern_error',
            {   error  => '',
                who    => $sender,
                msg_id => $messageid,
            }
        );
        Sympa::send_dsn($list, $message, {}, '5.3.0');
        $log->db_log(
            'robot'        => $list->{'domain'},
            'list'         => $list->{'name'},
            'action'       => 'DoMessage',
            'parameters'   => $message->get_id,
            'target_email' => '',
            'msg_id'       => $messageid,
            'status'       => 'error',
            'error_type'   => 'internal',
            'user_email'   => $sender
        );
        return undef;
    } elsif (not $self->{quiet}) {
        if ($self->{confirmed_by}) {
85
86
87
88
89
            # Ensure 1 second elapsed since last message.
            Sympa::send_file(
                $list,
                'message_report',
                $self->{confirmed_by},
90
                {   type           => 'success',             # Compat<=6.2.12.
91
92
93
94
95
96
                    entry          => 'message_confirmed',
                    auto_submitted => 'auto-replied',
                    key            => $self->{authkey}
                },
                date => time + 1
            );
97
        } elsif ($self->{distributed_by}) {
98
99
100
101
102
            # Ensure 1 second elapsed since last message.
            Sympa::send_file(
                $list,
                'message_report',
                $self->{distributed_by},
103
                {   type           => 'success',             # Compat<=6.2.12.
104
105
106
107
108
109
                    entry          => 'message_distributed',
                    auto_submitted => 'auto-replied',
                    key            => $self->{authkey}
                },
                date => time + 1
            );
110
        }
111
        # No notification sent to {resent_by} user.
112
113
114
115
116
117
118
119
120
    }

    $log->syslog(
        'info',
        'Message %s for %s from %s accepted (%.2f seconds, %d sessions, %d subscribers), message ID=%s, size=%d',
        $message,
        $list,
        $sender,
        Time::HiRes::time() - $self->{start_time},
121
        $numstored,
122
123
124
125
        $list->get_total,
        $messageid,
        $message->{'size'}
    );
126
127
128
129
130
131
132
133
134
135
136
    $log->db_log(
        'robot'        => $list->{'domain'},
        'list'         => $list->{'name'},
        'action'       => 'DoMessage',
        'parameters'   => $message->get_id,
        'target_email' => '',
        'msg_id'       => $messageid,
        'status'       => 'success',
        'error_type'   => '',
        'user_email'   => $sender
    );
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

    return 1;
}

# Private subroutines.

# Extract a set of rcpt for which VERP must be use from a rcpt_tab.
# Input  :  percent : the rate of subscribers that must be threaded using VERP
#           xseq    : the message sequence number
#           @rcpt   : a tab of emails
# return :  a tab of recipients for which recipients must be used depending on
#           the message sequence number, this way every subscriber is "VERPed"
#           from time to time input table @rcpt is spliced: recipients for
#           which VERP must be used are extracted from this table
# Old name: List::extract_verp_rcpt(), Sympa::List::_extract_verp_rcpt().
sub _extract_verp_rcpt {
    $log->syslog('debug3', '(%s, %s, %s, %s)', @_);
    my $percent     = shift;
    my $xsequence   = shift;
    my $refrcpt     = shift;
    my $refrcptverp = shift;

    my @result;

    if ($percent ne '0%') {
        my $nbpart;
        if ($percent =~ /^(\d+)\%/) {
            $nbpart = 100 / $1;
        } else {
            $log->syslog('err',
                'Wrong format for parameter: %s. Can\'t process VERP',
                $percent);
            return undef;
        }

        my $modulo = $xsequence % $nbpart;
        my $length = int(scalar(@$refrcpt) / $nbpart) + 1;

        @result = splice @$refrcpt, $length * $modulo, $length;
    }
    foreach my $verprcpt (@$refrcptverp) {
        push @result, $verprcpt;
    }
    return (@result);
}

# Old names: List::send_msg(), (part of) Sympa::List::distribute_msg().
sub _send_msg {
185
186
    my $message   = shift;
    my $resent_by = shift;
187
188
189

    my $list = $message->{context};

sikeda's avatar
sikeda committed
190
191
192
193
194
195
    my $verp_rate;
    my $tags_to_use;
    my $available_recipients;
    unless ($resent_by) {    # Not in ResendArchive spindle.
        # Synchronize list members, required if list uses include sources
        # unless sync_include has been performed recently.
196
197
198
        my $delay = $list->{'admin'}{'distribution_ttl'}
            // $list->{'admin'}{'ttl'};
        unless (defined $list->sync_include('member', delay => $delay)) {
IKEDA Soji's avatar
IKEDA Soji committed
199
200
            $log->syslog('notice', 'Unable to synchronize list %s', $list);
            #FIXME: Might be better to abort if synchronization failed.
201
202
        }

sikeda's avatar
sikeda committed
203
        # Blindly send the message to all users.
204

sikeda's avatar
sikeda committed
205
206
207
208
209
        my $total = $list->get_total('nocache');
        unless ($total and 0 < $total) {
            $log->syslog('info', 'No subscriber in list %s', $list);
            return 0;
        }
210

sikeda's avatar
sikeda committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
        # Postpone delivery if delivery time is specified.
        my $delivery_date = $list->get_next_delivery_date;
        $message->{date} = $delivery_date if defined $delivery_date;

        # Bounce rate.
        my $rate = $list->get_total_bouncing() * 100 / $total;
        if ($rate > $list->{'admin'}{'bounce'}{'warn_rate'}) {
            $list->send_notify_to_owner('bounce_rate', {'rate' => $rate});
            if (100 <= $rate) {
                Sympa::send_notify_to_user($list, 'hundred_percent_error',
                    $message->{sender});
                Sympa::send_notify_to_listmaster($list,
                    'hundred_percent_error', {sender => $message->{sender}});
            }
225
226
        }

sikeda's avatar
sikeda committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        # Prepare verp parameter.
        $verp_rate = $list->{'admin'}{'verp_rate'};
        # Force VERP if tracking is requested.
        $verp_rate = '100%'
            if Sympa::Tools::Data::smart_eq($message->{shelved}{tracking},
            qr/dsn|mdn/);

        # Define messages which can be tagged as first or last according to the
        # VERP rate.
        # If the VERP is 100%, then all the messages are VERP. Don't try to tag
        # not VERP messages as they won't even exist.
        if ($verp_rate eq '0%') {
            $tags_to_use = {tag_verp => '0', tag_noverp => 'z'};
        } else {
            $tags_to_use = {tag_verp => 'z', tag_noverp => '0'};
        }
243

sikeda's avatar
sikeda committed
244
245
246
247
248
249
250
251
252
253
254
255
256
        # Separate subscribers depending on user reception option and also if
        # VERP a dicovered some bounce for them.
        # Storing the not empty subscribers' arrays into a hash.
        $available_recipients = $list->get_recipients_per_mode($message);
        unless ($available_recipients) {
            $log->syslog('info', 'No subscriber for sending msg in list %s',
                $list);
            return 0;
        }
    } else {
        $verp_rate            = '0%';
        $tags_to_use          = {tag_verp => '0', tag_noverp => 'z',};
        $available_recipients = {mail => {noverp => [$resent_by]}};
257
    }
258
259

    my $numstored = 0;
260
261

    foreach my $mode (sort keys %$available_recipients) {
262
        # Save the message before modifying it.
263
264
265
266
267
268
269
        my $new_message = $message->dup;
        unless ($new_message->prepare_message_according_to_mode($mode, $list))
        {
            $log->syslog('err', "Failed to create Message object");
            return undef;
        }

270
        # Topics.
271
272
        my @selected_tabrcpt;
        my @possible_verptabrcpt;
273
274
        if (not $resent_by    # Not in ResendArchive spindle.
            and $list->is_there_msg_topic
Luc Didry's avatar
Luc Didry committed
275
        ) {
276
            my $topic = Sympa::Spool::Topic->load($message);
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
            my $topic_list = $topic ? $topic->{topic} : '';

            @selected_tabrcpt =
                $list->select_list_members_for_topic($topic_list,
                $available_recipients->{$mode}{'noverp'} || []);
            @possible_verptabrcpt =
                $list->select_list_members_for_topic($topic_list,
                $available_recipients->{$mode}{'verp'} || []);
        } else {
            @selected_tabrcpt =
                @{$available_recipients->{$mode}{'noverp'} || []};
            @possible_verptabrcpt =
                @{$available_recipients->{$mode}{'verp'} || []};
        }

        ## Preparing VERP recipients.
        my @verp_selected_tabrcpt = _extract_verp_rcpt(
            $verp_rate,         $message->{xsequence},
            \@selected_tabrcpt, \@possible_verptabrcpt
        );

        # Prepare non-VERP sending.
        if (@selected_tabrcpt) {
            my $result =
                _mail_message($new_message, \@selected_tabrcpt,
                tag => $tags_to_use->{'tag_noverp'});
            unless (defined $result) {
                $log->syslog(
                    'err',
                    'Could not send message to distribute to list %s (VERP disabled)',
                    $list
                );
                return undef;
            }
            $tags_to_use->{'tag_noverp'} = '0' if $result;
312
            $numstored += $result->{total_packets};
313
314
315
316

            # Add number and size of messages sent to total in stats file.
            my $numsent = scalar @selected_tabrcpt;
            my $bytes   = length $new_message->as_string;
317
            $list->update_stats(0, $numsent, $bytes, $bytes * $numsent);
318
319
320
321
322
323
324
325
326
327
328
        } else {
            $log->syslog(
                'notice',
                'No non VERP subscribers left to distribute message to list %s',
                $list
            );
        }

        $new_message->{shelved}{tracking} ||= 'verp';

        if ($new_message->{shelved}{tracking} =~ /dsn|mdn/) {
329
            my $tracking = Sympa::Tracking->new(context => $list);
330
331
332
333
334
335
336
337

            $tracking->register($new_message, [@verp_selected_tabrcpt],
                'reception_option' => $mode);
        }

        # Ignore those reception option where mail must not ne sent.
        next
            if $mode eq 'digest'
338
339
340
            or $mode eq 'digestplain'
            or $mode eq 'summary'
            or $mode eq 'nomail';
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

        ## prepare VERP sending.
        if (@verp_selected_tabrcpt) {
            my $result =
                _mail_message($new_message, \@verp_selected_tabrcpt,
                tag => $tags_to_use->{'tag_verp'});
            unless (defined $result) {
                $log->syslog(
                    'err',
                    'Could not send message to distribute to list %s (VERP enabled)',
                    $list
                );
                return undef;
            }
            $tags_to_use->{'tag_verp'} = '0' if $result;
356
            $numstored += $result->{total_packets};
357
358
359
360

            # Add number and size of messages sent to total in stats file.
            my $numsent = scalar @verp_selected_tabrcpt;
            my $bytes   = length $new_message->as_string;
361
            $list->update_stats(0, $numsent, $bytes, $bytes * $numsent);
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
        } else {
            $log->syslog('notice',
                'No VERP subscribers left to distribute message to list %s',
                $list);
        }
    }

    #log in stat_table to make statistics...
    unless ($message->{sender} =~ /($Conf::Conf{'email'})\@/) {
        #ignore messages sent by robot
        unless ($message->{sender} =~ /($list->{name})-request/) {
            #ignore messages of requests
            $log->add_stat(
                'robot'     => $list->{'domain'},
                'list'      => $list->{'name'},
                'operation' => 'send_mail',
                'parameter' => $message->{size},
                'mail'      => $message->{sender},
            );
        }
    }
383
    return $numstored;
384
385
386
387
388
389
}

# Distribute a message to a list, shelving encryption if needed.
#
# IN : -$message(+) : ref(Sympa::Message)
#      -\@rcpt(+) : recipients
390
# Returns: Marshalled metadata (file name) or undef
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#
# Old name: Sympa::Mail::mail_message(), Sympa::List::_mail_message().
sub _mail_message {
    $log->syslog('debug2', '(%s, %s, %s => %s)', @_);
    my $message = shift;
    my $rcpt    = shift;
    my %params  = @_;

    my $tag = $params{tag};

    my $list = $message->{context};

    # Shelve DMARC protection, unless anonymization feature is enabled.
    $message->{shelved}{dmarc_protect} = 1
        if $list->{'admin'}{'dmarc_protection'}
406
407
        and $list->{'admin'}{'dmarc_protection'}{'mode'}
        and not $list->{'admin'}{'anonymous_sender'};
408

409
410
    # Shelve personalization if not yet shelved.
    # Note that only 'footer' mode will be allowed unless otherwise requested.
IKEDA Soji's avatar
IKEDA Soji committed
411
412
    $message->shelve_personalization(type => 'mail')
        unless $message->{shelved}{merge};
413

414
415
416
417
418
    # Shelve re-encryption with S/MIME.
    $message->{shelved}{smime_encrypt} = 1
        if $message->{'smime_crypted'};

    # Overwrite original envelope sender.  It is REQUIRED for delivery.
419
    $message->{envelope_sender} = Sympa::get_address($list, 'return_path');
420

421
    return Sympa::Spool::Outgoing->new->store($message, $rcpt, tag => $tag)
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        || undef;
}

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Spindle::ToList - Process to distribute messages to list members

=head1 DESCRIPTION

436
437
438
439
440
441
442
443
444
This class executes the last stage of message transformation to be sent
through the list.
Transformation processes by this class are done in the following order:

=over

=item *

Classifies recipients for whom message is delivered by each reception mode,
445
filters recipients by topics (see also L<Sympa::Spool::Topic>), and choose
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
message tracking modes if necessary.

=item *

Transforms message by each reception mode.

=item *

Enables DMARC protection (according to
L<C<dmarc_protection>|list_config(5)/dmarc_protection>
list configuration parameter),
message personalization (according to
L<C<merge_feature>|list_config(5)/merge_feature>
list configuration parameter) and/or
re-encryption by S/MIME (if original message was encrypted).

=item *

Alters envelope sender of the message to I<list>C<-owner> address.

=back

468
Then stores message into outgoing spool (see L<Sympa::Spool::Outgoing>)
469
with classified packets of recipients.
470

IKEDA Soji's avatar
IKEDA Soji committed
471
472
473
474
This cass updates statistics information of the list (with digest delivery,
L<Sympa::Spindle::ToOutgoing> will update it).


475
476
=head1 SEE ALSO

477
L<Sympa::Internals::Workflow>.
478

479
480
L<Sympa::Message>,
L<Sympa::Spindle>, L<Sympa::Spindle::DistributeMessage>,
481
482
L<Sympa::Spool::Outgoing>,
L<Sympa::Spool::Topic>, L<Sympa::Tracking>.
483
484
485
486
487
488

=head1 HISTORY

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

=cut