~mailman-coders/mailman/2.1

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
#! @PYTHON@
#
# Copyright (C) 2001-2018 by the Free Software Foundation, Inc.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.

"""Process disabled members, recommended once per day.

This script cruises through every mailing list looking for members whose
delivery is disabled.  If they have been disabled due to bounces, they will
receive another notification, or they may be removed if they've received the
maximum number of notifications.

Use the --byadmin, --byuser, and --unknown flags to also send notifications to
members whose accounts have been disabled for those reasons.  Use --all to
send the notification to all disabled members.

Usage: %(PROGRAM)s [options]

Options:
    -h / --help
        Print this message and exit.

    -o / --byadmin
        Also send notifications to any member disabled by the list
        owner/administrator.

    -m / --byuser
        Also send notifications to any member disabled by themselves.

    -u / --unknown
        Also send notifications to any member disabled for unknown reasons
        (usually a legacy disabled address).

    -b / --notbybounce
        Don't send notifications to members disabled because of bounces (the
        default is to notify bounce disabled members).

    -a / --all
        Send notifications to all disabled members.

    -f / --force
        Send notifications to disabled members even if they're not due a new
        notification yet.

    -l listname
    --listname=listname
        Process only the given list, otherwise do all lists.
"""

import sys
import time
import getopt

import paths
# mm_cfg must be imported before the other modules, due to the side-effect of
# it hacking sys.paths to include site-packages.  Without this, running this
# script from cron with python -S will fail.
from Mailman import mm_cfg
from Mailman import Utils
from Mailman import MailList
from Mailman import Pending
from Mailman import MemberAdaptor
from Mailman import Errors
from Mailman.Bouncer import _BounceInfo
from Mailman.Logging.Syslog import syslog
from Mailman.i18n import _

# Work around known problems with some RedHat cron daemons
import signal
signal.signal(signal.SIGCHLD, signal.SIG_DFL)

PROGRAM = sys.argv[0]



def usage(code, msg=''):
    if code:
        fd = sys.stderr
    else:
        fd = sys.stdout
    print >> fd, _(__doc__)
    if msg:
        print >> fd, msg
    sys.exit(code)



def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], 'hl:omubaf',
            ['byadmin', 'byuser', 'unknown', 'notbybounce', 'all',
             'listname=', 'help', 'force'])
    except getopt.error, msg:
        usage(1, msg)

    if args:
        usage(1)

    force = 0
    listnames = []
    who = [MemberAdaptor.BYBOUNCE]
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-l', '--list'):
            listnames.append(arg)
        elif opt in ('-o', '--byadmin'):
            who.append(MemberAdaptor.BYADMIN)
        elif opt in ('-m', '--byuser'):
            who.append(MemberAdaptor.BYUSER)
        elif opt in ('-u', '--unknown'):
            who.append(MemberAdaptor.UNKNOWN)
        elif opt in ('-b', '--notbybounce'):
            try:
                who.remove(MemberAdaptor.BYBOUNCE)
            except ValueError:
                # Already removed
                pass
        elif opt in ('-a', '--all'):
            who = [MemberAdaptor.BYBOUNCE, MemberAdaptor.BYADMIN,
                   MemberAdaptor.BYUSER, MemberAdaptor.UNKNOWN]
        elif opt in ('-f', '--force'):
            force = 1

    who = tuple(who)

    if not listnames:
        listnames = Utils.list_names()

    msg = _('[disabled by periodic sweep and cull, no message available]')
    today = time.mktime(time.localtime()[:3] + (0,) * 6)
    for listname in listnames:
        # List of members to notify
        notify = []
        mlist = MailList.MailList(listname)
        try:
            interval = mlist.bounce_you_are_disabled_warnings_interval
            # Find all the members who are currently bouncing and see if
            # they've reached the disable threshold but haven't yet been
            # disabled.  This is a sweep through the membership catching
            # situations where they've bounced a bunch, then the list admin
            # lowered the threshold, but we haven't (yet) seen more bounces
            # from the member.
            disables = []
            for member in mlist.getBouncingMembers():
                if mlist.getDeliveryStatus(member) <> MemberAdaptor.ENABLED:
                    continue
                info = mlist.getBounceInfo(member)
                if (Utils.midnight(info.date) + mlist.bounce_info_stale_after
                        < Utils.midnight()):
                    # Bounce info is stale; reset it.
                    mlist.setBounceInfo(member, None)
                    continue
                if info.score >= mlist.bounce_score_threshold:
                    disables.append((member, info))
            if disables:
                for member, info in disables:
                    mlist.disableBouncingMember(member, info, msg)
            # Go through all the members who have delivery disabled, and find
            # those that are due to have another notification.  If they are
            # disabled for another reason than bouncing, and we're processing
            # them (because of the command line switch) then they won't have a
            # bounce info record.  We can piggyback on that for all disable
            # purposes.
            members = mlist.getDeliveryStatusMembers(who)
            for member in members:
                info = mlist.getBounceInfo(member)
                if not info:
                    # See if they are bounce disabled, or disabled for some
                    # other reason.
                    status = mlist.getDeliveryStatus(member)
                    if status == MemberAdaptor.BYBOUNCE:
                        # Bouncing member with no bounce info.  Just log it and continue.
                        syslog(
                            'error',
                            '%s disabled BYBOUNCE lacks bounce info, list: %s',
                            member, mlist.internal_name())
                        continue
                    # Disabled other than by bounce.  Create bounce info (why?)
                    info = _BounceInfo(
                        member, 0, today,
                        mlist.bounce_you_are_disabled_warnings)
                lastnotice = time.mktime(info.lastnotice + (0,) * 6)
                if force or today >= lastnotice + interval:
                    notify.append(member)
                # Get a fresh re-enable cookie and set it.
                info.cookie = mlist.pend_new(Pending.RE_ENABLE,
                                       mlist.internal_name(),
                                       member)
                mlist.setBounceInfo(member, info)
            # Now, send notifications to anyone who is due
            for member in notify:
                syslog('bounce', 'Notifying disabled member %s for list: %s',
                       member, mlist.internal_name())
                try:
                    mlist.sendNextNotification(member)
                except Errors.NotAMemberError:
                    # There must have been some problem with the data we have
                    # on this member.  Most likely it's that they don't have a
                    # password assigned.  Log this and delete the member.
                    syslog('bounce',
                           'NotAMemberError when sending disabled notice: %s',
                           member)
                    mlist.ApprovedDeleteMember(member, 'cron/disabled')
            mlist.Save()
        finally:
            mlist.Unlock()



if __name__ == '__main__':
    main()